text:
Q: How come you cannot catch Code Contract exceptions? System.Diagnostics.Contracts.ContractException is not accessible in my test project. Note this code is purely myself messing around with my shiney new copy of Visual Studio, but I'd like to know what I'm doing wrong.
I'm using the professional edition of VS, therefore I do not have static checking. In order to still use code contracts (which I like) I figured the only way my method can work is to catch the exception that is thrown at runtime, but I'm not finding this possible.
TestMethod
[TestMethod, ExpectedException(typeof(System.Diagnostics.Contracts.ContractException))]
public void returning_a_value_less_than_one_throws_exception()
{
    var person = new Person();
    person.Number();
}

Method
public int Number()
{
    Contract.Ensures(Contract.Result<int>() >= 0);
    return -1;
}

Error
Error 1 'System.Diagnostics.Contracts.ContractException' is inaccessible
due to its protection level.
Edit
After some more thought I've come to the conclusion discussed in the comments, as well as the following. Given a method, if this had a requirement which could be expressed in Code Contract form, I'd write tests as such.
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void value_input_must_be_greater_than_zero()
{
    // Arrange
    var person = new Person();
    // Act
    person.Number(-1);
}

This would ensure the contract is part of the code, and will not be removed. This would require the Code Contract to actually throw the specified exception however. In some cases this would not be required however.

A: EDIT: I have had a conversion and no longer use either ExpectedException or this attribute below, but rather have coded some extension methods:
AssertEx.Throws<T>(Action action);
AssertEx.ThrowsExact<T>(Action action);
AssertEx.ContractFailure(Action action);

These allow me to be more precise about where the exception is raised.
Example of ContractFailure method:
    [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Cannot catch ContractException")]
    public static void ContractFailure(Action operation)
    {
        try
        {
            operation();
        }
        catch (Exception ex)
        {
            if (ex.GetType().FullName == "System.Diagnostics.Contracts.__ContractsRuntime+ContractException")
                return;

            throw;
        }

        Assert.Fail("Operation did not result in a code contract failure");
    }

I created an attribute for MSTest, that behaves similarly to the
  ExpectedExceptionAttribute:
public sealed class ExpectContractFailureAttribute : ExpectedExceptionBaseAttribute
{
    const string ContractExceptionName = "System.Diagnostics.Contracts.__ContractsRuntime+ContractException";

    protected override void Verify(Exception exception)
    {
        if (exception.GetType().FullName != ContractExceptionName)
        {
            base.RethrowIfAssertException(exception);
            throw new Exception(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Test method {0}.{1} threw exception {2}, but contract exception was expected. Exception message: {3}",
                    base.TestContext.FullyQualifiedTestClassName,
                    base.TestContext.TestName,
                    exception.GetType().FullName,
                    exception.Message
                )
            );
        }
    }
}

And this can be used similarly:
    [TestMethod, ExpectContractFailure]
    public void Test_Constructor2_NullArg()
    {
        IEnumerable arg = null;

        MyClass mc = new MyClass(arg);
    }

A: This is deliberate - although a slight pain for testing.
The point is that in production code you should never want to catch a contract exception; it indicates a bug in your code, so you shouldn't be expecting that any more than arbitrary unexpected exceptions which you may want to catch right at the top of your call stack so you can move onto the next request. Basically you shouldn't view contract exceptions as ones which can be "handled" as such.
Now, for testing that's a pain... but do you really want to test your contracts anyway? Isn't that a bit like testing that the compiler stops you from passing in a string to a method which has an int parameter? You've declared the contract, it can be documented appropriately, and enforced appropriately (based on settings, anyway).
If you do want to test contract exceptions, you can either catch a bare Exception in the test and check its full name, or you can mess around with the Contract.ContractFailed event. I would expect unit testing frameworks to have built-in support for this over time - but it'll take a little while to get there. In the meantime you probably want to have a utility method to expect a contract violation. One possible implementation:
const string ContractExceptionName =
    "System.Diagnostics.Contracts.__ContractsRuntime.ContractException";

public static void ExpectContractFailure(Action action)
{
    try
    {
        action();
        Assert.Fail("Expected contract failure");
    }
    catch (Exception e)
    {
        if (e.GetType().FullName != ContractExceptionName)
        {
            throw;
        }
        // Correct exception was thrown. Fine.
    }
}

A: in the vs2010 rtm, the full name has been changed to "System.Diagnostics.Contracts.__ContractsRuntime+ContractException". HTH

A: Though this question is getting old, and an answer has already been supplied, I feel like I have a nice solution that keeps things simple and readable.
In the end, it allows us to write tests on preconditions as simple as:
[Test]
public void Test()
{
    Assert.That(FailingPrecondition, Violates.Precondition);
}

public void FailingPrecondition() {
    Contracts.Require(false);
}

Okay, so the idea is to provide the Code Contracts rewriter with a custom contract runtime class.
This can be setup in the assembly's properties under "Custom Rewriter Methods" (see the Code Contracts User Manual section 7.7):

Remember to also check Call-site Requires Checking!
The custom class looks something like this:
public static class TestFailureMethods
{
    public static void Requires(bool condition, string userMessage, string conditionText)
    {
        if (!condition)
        {
            throw new PreconditionException(userMessage, conditionText);
        }
    }

    public static void Requires<TException>(bool condition, string userMessage, string conditionText) where TException : Exception
    {
        if (!condition)
        {
            throw new PreconditionException(userMessage, conditionText, typeof(TException));
        }
    }
}

Using a custom PreconditionException class (it contains nothing fancy!).
We furthermore add a small helper class:
public static class Violates
{
    public static ExactTypeConstraint Precondition => Throws.TypeOf<PreconditionException>();
}

This allows us to write simple, readable tests on precondition violations, as shown above.


text:
Q: unfortunately test1 has stopped help please i want to run my app on the emulator but it doesn't run and keeps showing me unfortunately
package com.example.test1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

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

        Button kh = (Button)findViewById(R.id.imageButton3);
        kh.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent kh = new Intent(MainActivity.this , kh.class);
                startActivity(kh);
            }
        });
    }
}

A: you have Button kh...in the onClick() you send the intent to that button! Intent kh = new Intent(MainActivity.this , kh.class);
i think you want something else.

A: In your code, kh.class should be replaced with <Target_Activity>.class the activity which you want to launch..
Intent kh = new Intent(MainActivity.this , <Target_Activity>.class);
startActivity(kh);

Also make sure your <Target_Activity> is available in <activity /> tag of Android Application's manifest file.

A: Create Activity same like MainActivity with different name say for example SampleActivity and call that
Intent kh = new Intent(MainActivity.this , SampleActivity.class);
startActivity(kh);

And include that activity in AndroidManifest.xml
<activity android:name=".SampleActivity"
        android:label="@string/yourlabel"></activity>

It should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to create a second Laravel "api route" with a separate API KEY? I'm new to Laravel and I am handed an existing application that is composed of two parts:
1 - An admin backend built on Laravel and uses Vueify
2 - The frontend website built on next.js and uses react components
The admin part communicates with Laravel using the "web routes" but also uses the "api routes" as well since the vue components make AJAX requests using those "api routes".
I am now tasked with "connecting" the frontend part to the laravel app. The frontend part will be using AJAX as well to communicate with laravel but I was told I should not use the same "api route" that is used by the admin backend because that has a lot more privileges that should not be accessible by the frontend. Basically it's a security risk and that I should somehow separate the two.
I'm not actually sure which term to use.. I initially thought it was called "channel" but I see that channel is one of the 4 "ways" of connecting to laravel (the other 3 being web, api and console). So I think routes is the term to use and forgive me for the double-quotes.
I have made a simple diagram to show the structure I mean. What I need to know is is there a way to create a second api route that would be used exclusively by the frontend and would include only a limited set of priviledges. I imagine something like /frontapi/ or /webapi/ as opposed to /api/ which is used now by the backend.

Thanks a lot for your help and please correct me if I am using wrong terminology.
EDIT
Thank you all for answering the part regarding separating the route prefix and the api route files.
One part of the question that I realized late that I hadn't made clear was the importance of separating the API Keys for both APIs since I think that is the main security issue and what would really make then two individual API "Channels or ways". I think that is one reason why I was confusing about the terminology because "way" sounded to me more separate that just a "route". I've also edited the question to reflect that. Thank you again for taking the time to help.

A: You can decompose routes in as many files as you want, you can also give each file its own prefix (like how api.php routes start with /api)
The modification need to be done in App\Providers\RouteServiceProvider
//in map() add $this->mapApiTwoRoutes()
public function map()
{
    $this->mapApiRoutes();
    $this->mapApiTwoRoutes();//<---this one
    $this->mapWebRoutes();
}

//now add the method mapApiTwoRoutes
protected function mapApiTwoRoutes()
{
    Route::prefix('api2')//<-- prefix in the url
         ->middleware('api')//<-- api middleware (throttle and such check App\Http\Kernal.php)
         ->namespace('App\Http\Controllers') //<-- you can modify the namespace of the controllers
         ->group(base_path('routes/apiTwo.php'));//<-- file containing the routes
}

And that's it.

A: You need to define a new route file, firstly add a new entry $this->mapApi2Routes(); in the map() function in app\Providers\RouteServiceProvider.
Then add a new function in that file, basically copying the mapApiRoutes() function, call it mapApi2Routes(). You can use different middleware etc. for the new file.
The last step would be adding a new file api2.php in the routes folder.


text:
Q: 404 error after migration of WP site I have this url, where I have my site now, but I migrate it to this one. I have a custom permalink structure:
/%category%/%postname%/
In the first link (old site) al works fine, but in the new one, only the default option (?p=123) structure works.
It's important to say that the second link, the URL's points to another server, it means the second url is an CNAME in my server. I also import the .htaccess file.
How can I make work my custom structure in the new server?

A: That did it for me:
Try flushing your mod_rewrite rules:
Dashboard -> Settings -> Permalinks
Save settings (no need to make any changes)
https://wordpress.stackexchange.com/questions/14685/after-server-migration-only-the-homepage-works


text:
Q: NSG module for creating multiple NSGs with NSG rules I have created a NSG module for creating multiple nsgs. Below is the code:
main.tf
resource "azurerm_network_security_group" "nsgcreation" {
  for_each = var.network_security_groups
  name = each.value["name"]
  location = var.location
  resource_group_name = var.resource_group_name
}

resource "azurerm_subnet_network_security_group_association" "associate" {
    for_each = {
        for key,value in var.network_security_groups : key => value
    }
    subnet_id = data.azurerm_subnet.snet[each.key].id
    network_security_group_id = azurerm_network_security_group.nsgcreation[each.key].id
}

resource "azurerm_network_security_rule" "nsgrules" {
    for_each = var.nsg_rules
    name = each.value["name"]
    direction = each.value["direction"]
    access = each.value["access"]
    priority = each.value["priority"]
    protocol = each.value["protocol"]
    source_port_ranges = lookup(each.value, "source_port_ranges", null)
    source_port_range = lookup(each.value, "source_port_range", null)
    destination_port_ranges = lookup(each.value, "destination_port_ranges", null)
    destination_port_range = lookup(each.value, "destination_port_range", null)
    source_address_prefixes = lookup(each.value, "source_address_prefixes", null)
    source_address_prefix = lookup(each.value, "source_address_prefix", null)
    destination_address_prefixes = lookup(each.value, "destination_address_prefixes", null)
    destination_address_prefix = lookup(each.value, "destination_address_prefix", null)
    resource_group_name = var.resource_group_name
    network_security_group_name = each.value["network_security_group_name"]
    depends_on = [
        azurerm_network_security_group.nsgcreation
    ]
}

variables.tf
variable "network_security_groups" {
    description = "Details of network security groups to be created"
    default = {}
}

variable "nsg_rules" {
 default     = {}
}

variable "resource_group_name" {
  description = "Name of the resource group to be imported."
  #type        = string
}

variable "location" {
  description = "The location of the vnet to create. Defaults to the location of the resource group."
  type        = string
}

data.tf
data "azurerm_subnet" "snet" {
    for_each = {
         for key,value in var.network_security_groups : key => value
    }
    name = each.value["subnet_name"]
    virtual_network_name = each.value["vnet_name"]
    resource_group_name = each.value["vnet_rgname"]
}

Currently I am calling the module as per the below code and using tfvars for input.
Given below is the code for tfvars and module
Module Code:
module "nsgs" {
  source = "./nsgs"
  network_security_groups = var.nsgs_aks_dev
  nsg_rules = var.nsg_rules_aks_dev
  resource_group_name = azurerm_resource_group.rg1.name
  location = azurerm_resource_group.rg1.location
}

vnet.auto.tfvars
nsgs_aks_dev = {
    nsg_aks1 = {
        name = "nsg_subnet-mel-dev-aks-pa1-ext-10.80.200.0"
        vnet_name = "bupaanz-mel-dev-caas-vnet01"
        vnet_rgname = "caas-dev-rg01"
        subnet_name = "subnet-mel-dev-aks-pa1-ext-10.80.200.0"
    },
    nsg_aks2 = {
        name = "nsg_subnet-mel-dev-aks-internal01-10.80.192.0"
        vnet_name = "anz-mel-dev-caas-vnet01"
        vnet_rgname = "caas-dev-rg01"
        subnet_name = "subnet-mel-dev-aks-internal01-10.80.192.0"
    },
}

nsg_rules_aks_dev = {
    nsg_aks1 = {
      name                   = "DenyAllIn"
      priority               = 4096
      network_security_group_name = "nsg_subnet-mel-dev-aks-pa1-ext-10.80.200.0"
      direction              = "Inbound"
      access                 = "Deny"
      protocol               = "tcp"
      source_port_range      = "*"
      destination_port_range = "*"
      source_address_prefix  = "*"
      destination_address_prefix = "*"
      description            = "Deny all inbound ports"
    },
    nsg_aks2 = {
      name                   = "DenyAllOut"
      priority               = 4096
      network_security_group_name = "nsg_subnet-mel-dev-aks-pa1-ext-10.80.200.0"
      direction              = "Outbound"
      access                 = "Deny"
      protocol               = "tcp"
      source_port_range      = "*"
      destination_port_range = "*"
      source_address_prefix  = "*"
      destination_address_prefix = "*"
      description            = "Deny all outbound ports"
    },
    nsg_aks3 =  {
     name                    = "AllowSCOMOutbound"
     priority                = 100
     network_security_group_name = "nsg_subnet-mel-dev-aks-pa1-ext-10.80.200.0"
     direction               = "Outbound"
     access                  = "Allow"
     protocol                = "tcp"
     source_port_range       = "*"
     source_port_ranges      = null
     source_address_prefix   = "*"
     source_address_prefixes = null
     destination_port_range  = "5723"
     destination_port_ranges = null
     destination_address_prefix   = null
     destination_address_prefixes = ["10.68.100.168","10.64.150.162","10.68.100.169","10.64.150.164"]
     description                  = "Allow outbound connection to SCOM"
   },
   nsg_aks4 =  {
     name                    = "AllowSCCMOutbound"
     priority                = 200
     network_security_group_name = "nsg_subnet-mel-dev-aks-pa1-ext-10.80.200.0"
     direction               = "Outbound"
     access                  = "Allow"
     protocol                = "tcp"
     source_port_range       = "*"
     source_port_ranges      = null
     source_address_prefix   = "*"
     source_address_prefixes = null
     source_address_prefixes = null
     destination_port_ranges = [
      "80",
      "443",
      "445",
      "8530",
      "8531"
    ]
     destination_address_prefix   = null
     destination_address_prefixes = ["10.68.100.129","10.68.100.130","10.64.150.177"]
     description                  = "Allow outbound connection to SCCM"
  },
    nsg_aks5 = {
      name                   = "DenyAllIn"
      priority               = 4096
      network_security_group_name = "nsg_subnet-mel-dev-aks-internal01-10.80.192.0"
      direction              = "Inbound"
      access                 = "Deny"
      protocol               = "tcp"
      source_port_range      = "*"
      destination_port_range = "*"
      source_address_prefix  = "*"
      destination_address_prefix = "*"
      description            = "Deny all inbound ports"
    },
    nsg_aks6 = {
      name                   = "DenyAllOut"
      priority               = 4096
      network_security_group_name = "nsg_subnet-mel-dev-aks-internal01-10.80.192.0"
      direction              = "Outbound"
      access                 = "Deny"
      protocol               = "tcp"
      source_port_range      = "*"
      destination_port_range = "*"
      source_address_prefix  = "*"
      destination_address_prefix = "*"
      description            = "Deny all outbound ports"
    },
    nsg_aks7 =  {
      name                    = "AllowSCOMOutbound"
      priority                = 100
      network_security_group_name = "nsg_subnet-mel-dev-aks-internal01-10.80.192.0"
      direction               = "Outbound"
      access                  = "Allow"
      protocol                = "tcp"
      source_port_range       = "*"
      source_port_ranges      = null
      source_address_prefix   = "*"
      source_address_prefixes = null
      destination_port_range  = "5723"
      destination_port_ranges = null
      destination_address_prefix   = null
      destination_address_prefixes = ["10.68.100.168","10.64.150.162","10.68.100.169","10.64.150.164"]
      description                  = "Allow outbound connection to SCOM"
    },
     nsg_aks8 =  {
      name                    = "AllowSCCMOutbound"
      priority                = 200
      network_security_group_name = "nsg_subnet-mel-dev-aks-internal01-10.80.192.0"
      direction               = "Outbound"
      access                  = "Allow"
      protocol                = "tcp"
      source_port_range       = "*"
      source_port_ranges      = null
      source_address_prefix   = "*"
      source_address_prefixes = null
      destination_port_range  = null
      destination_port_ranges = [
      "80",
      "443",
      "445",
      "8530",
      "8531"
      ]
      destination_address_prefix   = null
      destination_address_prefixes = ["10.68.100.129","10.68.100.130","10.64.150.177"]
      description                  = "Allow outbound connection to SCCM"
  },
}

Now as per the tfvars file, I am creating the same four rules for two nsgs but I writing each nsg rule code twice(each time for one nsg). Please can you let me know if we can reduce the tfvars so that the same rules have to be defined only once and not multiple times.


text:
Q: Stack Layout layout nightmare with Xamarin XAML forms I have the following code:
  <StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" Margin="0,10,0,10" BackgroundColor="Green" Padding="5,5,5,5">
        <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" Margin="0,0,0,0" BackgroundColor="Blue">
              <Label Text="SHOW COMPLETED TASKS" BackgroundColor="Red" Style="{StaticResource lblSubHeading_Black}" />
        </StackLayout>
        <Switch x:Name="CompletedJobsSwitch" Toggled="CompletedJobsSwitch_Toggled" HorizontalOptions="EndAndExpand" IsToggled="{Binding isOn}" BackgroundColor="Yellow"/>
  </StackLayout>

It all loads fine but when the app loads it is showing, but the Switch is not flush right. Why? It's really annoying, seems really inconsistent
I've looked at http://forums.xamarin.com/discussion/21226/how-to-right-align-a-view-inside-a-list-item but this doesn't work for me.
Any ideas?

A: This is well-known issue with combination of StackLayout and Label:

*

*Bugzilla #28650

*Bugzilla #31128

*Bugzilla #33841
You could use workaround described by JamesMontemagno. The point is to use Grid instead of StackLayout in that case.

A: Use this
<Grid BackgroundColor="Green">
  <Grid.RowDefinitions>
    <RowDefinition Height="auto" />
  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="auto" />
  </Grid.ColumnDefinitions>
  <Label Text="SHOW COMPLETED TASKS" BackgroundColor="Red" />
  <Switch x:Name="CompletedJobsSwitch" BackgroundColor="Yellow" Grid.Column="1" />
</Grid>

A: Maybe I'm just too late to the party and some bugs have been fixed, but for others that arrive here through searching:
For the lefthand item use HorizontalOptions="StartAndExpand"
For the right align item use HorizontalOptions="End"
The switch is a fixed length component, so you don't want to use expand.If you do use EndAndExpand, it will add some padding to the right, ruining your right alignment.
The label wants to fill the remaining space, so tell it to expand.
 <StackLayout VerticalOptions="Start" Orientation="Horizontal" Margin="0,10,0,10" BackgroundColor="Green" Padding="5,5,5,5">
            <Label Text="SHOW COMPLETED TASKS" BackgroundColor="Red"  HorizontalOptions="StartAndExpand"  />
            <Switch x:Name="CompletedJobsSwitch"  HorizontalOptions="End" IsToggled="false" BackgroundColor="Yellow"/>
</StackLayout>


text:
Q: PHP/MySQL - how to combine variables from separate forms to build a query? Please see the code in this pastebin: http://pastebin.com/5gKwb7gi
It is quite a lot of code but I think all you gurus on here will understand it!
Basically what I have just confused myself is, I had a search form, and I then created an advanced search form which is dynamic.
I just got it finished and now I am attempting to include the simple search criteria (if it is filled out) in the advanced search query but obviously these variables are never set because the simple search form is never submitted :S
Does anyone have any hints, tips or ideas on what to do? Not sure if I want to combine the forms or not so I would appreciate some advice and opinions.
Thanks.

A: If anyone reads this question and would like to know how I solved it, I used hidden inputs and some JQuery to copy the values from the simple search form to the hidden inputs like so:
<input type="hidden" name="hiddenfilename" id="hiddenfilename"/>
<input type="hidden" name="hiddenfilesize_min" id="hiddenfilesize_min"/>
<input type="hidden" name="hiddenfilesize_max" id="hiddenfilesize_max"/>
//etc

<script type="text/javascript">
$("#filename").change(copyFilename);
$("#filesize_min").change(copyFileSizeMin);
$("#filesize_max").change(copyFileSizeMax);

function copyFilename()
{
   var valueToCopy=$("#filename").val();
   $("#hiddenfilename").val(valueToCopy);
}

function copyFileSizeMin()
{
   var valueToCopy=$("#filesize_min").val();
   $("#hiddenfilesize_min").val(valueToCopy);
}

function copyFileSizeMax()
{
   var valueToCopy=$("#filesize_max").val();
   $("#hiddenfilesize_max").val(valueToCopy);
}
</script>

A: I will not read 600 lines of code to help you. Make the example smaller that you can express it with some words and less then 50 lines. That is always possible! Anyway, I answer from what I read here without the code.
If you want to get Data for a multipage form you have several options. You can evaluate each page of your form server side, and then just put them back where you want to have them in the second step (use hidden import tags for variables, which should not be rendered). Another choice is to put the values into a cookie and take it from there when you need it. Also you can change the structure of your form with Javascript according to the user inputs and then just send the whole thing, when he is finished (maybe per AJAX). The most basic but often also most elegant one is the first one. For learning purposes I advice that one. Combining cookies and AJAX should be the highest level and the one used most often, but also the most complicated one, because you need to learn how your server and your php code handles cookies and also how to apply Javascript correctly.


text:
Q: Incorrect Vulkan UniformBuffer Memory Alignment As per the specification Variables declared inside a Uniform Buffer must be properly aligned.
I have the following GLM variables in my structure:
struct UniformBufferObject_PointLights {
    glm::f32 constant[64]{};
    glm::f32 linear[64]{};
    glm::f32 quadratic[64]{};

    glm::vec3 position[64]{};

    glm::vec3 ambient[64]{};
    glm::vec3 diffuse[64]{};

    glm::int32 count{};
};

*

*Attempting to access any of the variables from within the shader acts
as if their values are all 0. The issue is centered around the
glm::f32 and glm::uint32 declarations.

The glm::vec3's are all accessible by simply declaring them above the glm::f32's and glm::uint32, however, the glm::uint32 and glm::f32's are still inaccessible. At this point I figure it must be an alignment issue.
//  After rearrangement.
struct UniformBufferObject_PointLights {
    glm::vec3 position[64]{};

    glm::vec3 ambient[64]{};
    glm::vec3 diffuse[64]{};

    glm::f32 constant[64]{};
    glm::f32 linear[64]{};
    glm::f32 quadratic[64]{};

    glm::uint32 count{};
};

*

*position,ambient, and diffuse are all accessible after moving
them to the top of the struct.

I have set #define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES but it doesn't appear to work for glm::f32 and glm::uint32 and probably others. What do I need to do to get these variables working in my uniform buffer? I've tried placing alignas(4),alignas(8),alignas(16), and alignas(32) before their declarations but no combination works.

A: Arrays in uniform buffers must be aligned as per std140 which basically states vec4 alignment.
That means your uniform buffer is too small. As for the shader the float foo[64] is actually the same size as vec4 foo[64]. alignas qualifier won't allow you to change that.
Either use storage buffers, which could be slower, or just use vec4's in arrays.


text:
Q: Can we have some text passed as variables in a text file to validate the result in Ruby Cucumber framework I have a XML file(Input file) which I use to generate a PDF file(Output file) which is basically a letter sent to the customers. I have to automate the validation of PDF content. I am able to get the text in PDF using PDF-Reader gem. Now I have to validate this text.
This PDF contains some static text(Text that will remain same for every customer) like, the Heading of the letter, sender address, part of the text in body of the letter, but things like Recipient address and name, Account number payment amount in the body of the letter will change for every customer.
These changing values I can get from XML. So to automate the validation I want to  use a text file that has the static text and for the dynamic text I want to pass a the value from the XML using Nokogiri gem.
Then compare this text file with the PDF text.
I need some help in creating this text file with the variables.
Or if any one has any other suggestion please suggest ?
Example:
Sample XML:
<RealTimeLetter>
<Customer>
<RTLtr_LetterNumber>00510</RTLtr_LetterNumber>
<RTLtr_CustomerAddress1>Recipient address1</RTLtr_CustomerAddress1>
<RTLtr_CustomerAddress2>*</RTLtr_CustomerAddress2>
<RTLtr_CustomerCity>CITY</RTLtr_CustomerCity>
<RTLtr_CustomerState>STATE</RTLtr_CustomerState>
<RTLtr_CustomerZip>221501020</RTLtr_CustomerZip>
<RTLtr_CustomerName>Recipient name1</RTLtr_CustomerName>
<RTLtr_CustomerSSN>111111111</RTLtr_CustomerSSN>
<RTLtr_ActNum>1111111</RTLtr_ActNum>
</Customer>
<Customer>
<RTLtr_LetterNumber>00510</RTLtr_LetterNumber>
<RTLtr_CustomerAddress1>Recipient address2</RTLtr_CustomerAddress1>
<RTLtr_CustomerAddress2>*</RTLtr_CustomerAddress2>
<RTLtr_CustomerCity>CITY</RTLtr_CustomerCity>
<RTLtr_CustomerState>STATE</RTLtr_CustomerState>
<RTLtr_CustomerZip>221501020</RTLtr_CustomerZip>
<RTLtr_CustomerName>Recipient name2</RTLtr_CustomerName>
<RTLtr_CustomerSSN>111111111</RTLtr_CustomerSSN>
<RTLtr_ActNum>2222222</RTLtr_ActNum>
</Customer>
</RealTimeLetter>

Sample PDF Text:
Sender Name                                                            Letter Send Date
Sender Address                                                         Letter Heading
Sender City, State zip

Recipient name                                                        Account #: 1111111
Recipient address
Recipient City, state zip

Dear Recipient name,
Body of the letter. Some text in this will not change. Payment amount $1234. The amount will keep chenge.

Paragraph 2. XXXXXXXXXXXX.yyyyyyyy.

Sincerely,

Customer Care Department
Sender Signature

I want to be able to put the value of the tag
<RTLtr_CustomerAddress1>Recipient address1</RTLtr_CustomerAddress1>

as a variable in the text file that also has the other static text in it. and be able to compare it with the text extracted from PDF.


text:
Q: Which ways should I go Front-End firs or Back-end first in Project development? I want build an application by using the framework.
the application contains two parts: the Back-End and the Front-End.
Everybody who have experiences can suggest me which ways should I do?:
Develop the Front-End first Or Develop the Back-End first
Or give more tips on the start up project?
thanks

A: I usually start with the backend to get the major functionality implemented, but even so, it's pretty much inevitable that the frontend and backend will have to be developed at the same time at some point in the project.
People can say what they want about separating presentation and functionality, and that's a good principle, but the reality is that the presentation influences the functionality and vice versa.
You might get the backend mostly written, and then you make the frontend, but you will probably decide to change some things and end up working on both together.


text:
Q: TDD basics - do I add or replace tests? I'm completely new to TDD and am working my way through this article.
It's all very clear except for a basic thing that probably seems too obvious to mention:
Having run the first test (module exists), what do I do with my code before running the next one? Do I keep it so the next test includes results from the first one? Do I delete the original code? Or do I comment it out and only leave the current test uncommented?
Put another way, does my spec file end up as long list of tests which are run every time, or should it just contain the current test?

A: Quoting the same article linked to in the question.

Since I don't have a failing test though, I won't write any module
  code. The rule is: No module code until there's a failing test. So
  what do I do? I write another test—which means thinking again.

Spec will end up with list of tests which are run every time to check for regression errors for every additional feature. If adding a new feature breaks something that was added before then the previous tests will indicate by failing the test.


text:
Q: guidelines for large Unix data center setup? Are there any blogs/ recommended readings on how to setup/configure/manage large ( 500 + ) unix servers in a single / multiple data center ?
I am trying to understand best practices, network design suggestions as well.
Thanks

A: I'm not aware of any A-to-Z guides for this as usually people responsible for the design and build of a 500+ server environment have already gained significant experience in these basics. I'd be worried if you're being asked to do so yet asking for such basic, non-specific, help. Feel free to ask more specific questions here though.

A: Infrastructures.org has a good checklist of best practices and general guidelines. The information looks a little bit outdated, but most of the things they suggest are still to be considered when setting up a large data center environment.
Some of the topics covered:

*

*Version Control

*Gold Server

*Directory/Authentication Servers

*Network File Servers

*Configuration/Application management

*Monitoring

*...


text:
Q: jQuery get real margin if assigned by 2 classes I have the following issue:
I have some inline-block elements and I want to get the margin of the elements.
At the moment I do it like this methods.settings.items.first().css('marginLeft') which works like a charm, BUT I have assigned the margin using the class .card however on the tablet view I have .tablet .card{ margin: 5px; } which works fine and the browser inspector shows margin: 5px jQuery however still shows margin: 10px.
Any idea how to fix that?
Edit

Okay, problem solved: I left an unneeded css animation on the items which animated the margin, this of course caused the jquery to pickup the value before it was done animating.


text:
Q: No module named pyinotify Traceback (most recent call last):
  File "mitmf.py", line 29, in <module>
    import core.responder.settings as settings
  File "/home/hacklab/Downloads/MITMf-master/MITMf/core/responder/settings.py", line 24, in <module>
    from core.configwatcher import ConfigWatcher
  File "/home/hacklab/Downloads/MITMf-master/MITMf/core/configwatcher.py", line 20, in <module>
    import pyinotify
ImportError: No module named pyinotify

I cannot open mitmf. I wonder if I should use another program?

A: Double check that you have installed the correct package. There are two packages available, pynotify and pyinotify. Please note the additional letter i in the second one.
The error message says that pyinotify is missing.
So check the output of pip list (or maybe pip3 list, depending on your environment).


text:
Q: xmlformatter ignore less than in quotes I am trying to format the following xml
<block formula="MY_VAR < 3"><set-variable name="OTHER_VAR"></set-variable></block>

into
<block formula="MY_VAR < 3">
  <set-variable name="OTHER_VAR">
  </set-variable>
</block>

using xmlformatter and getting an error because of the < in my formula. Specifically the error is

ExpatError: not well-formed (invalid token)

when I try the code
my_xml = '<block formula="MY_VAR < 3"><set-variable name="OTHER_VAR"></set-variable></block>'
formatter = xmlformatter.Formatter(indent="1", indent_char="  ", encoding_output="UTF-8", preserve=["literal"])
pretty_xml = formatter.format_string(my_xml)

How do I include the less than in my formula and be able to format my XML?

A: You can use xml.sax.saxutils.quoteattr to escape the attribute value when constructing the xml string.
>>> my_xml = '<block formula=%s><set-variable name="OTHER_VAR"></set-variable></block>' % su.quoteattr('MY_VAR < 3')
>>> my_xml
'<block formula="MY_VAR < 3"><set-variable name="OTHER_VAR"></set-variable></block>'

If you don't control construction of the xml this hack will fix the xml in the  example:
stack = []

out = []
brackets = '<>'

for c in bad_xml:
    if c in brackets:
        try:
            prev = stack[-1]
        except IndexError:
            stack.append(c)
            out.append(c)
        else:
            if prev == c:
                escaped = '>' if c == '>' else '<'
                out.append(escaped)
            else:
                stack.append(c)
                out.append(c)
    else:
        out.append(c)
my_xml = ''.join(out)


text:
Q: Rxjs Retry with Delay function I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.
I expect there 16:22:48, 16:22:59 ...
canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }

and console result is :

A: All of this is RxJS 6+

TL;DR
You could use the fully tested operator from this package, or scroll down to see the source :)
npm i rxjs-boost

import { retryWithDelay } from 'rxjs-boost/operators';

obs$.pipe(
  // will retry 4 times with a 1s delay before each try:
  retryWithDelay(1000, 4)
);

Criteria
As most (or maybe none) of the other answer didn't meet all of my criteria, I'll list my solution below. Goals:

*

*Emits & completes regularly if no error is thrown. ✅

*Retries x times if an error is thrown. ✅

*Has a delay of y before each retry. ✅

*Returns the last emitted error. (A lot of other answers were struggling with this.) ✅

*Correct typing with strict: true – but this was quite difficult to mess up.  ✅

Solution
As every other answer we'll use the retryWhen operator to catch the errors. To track the amount of repetitions can use the scan operator. To limit the amount of repetitions we'll simply throw an error inside a map operator.

The original source uses throwIf, but in that case we could simply use retryWithDelay from rxjs-boost.

Last we'll use the delay operator to add the delay between the different executions:
import { MonoTypeOperatorFunction } from 'rxjs';
import { delay as delayOperator, map, retryWhen, scan } from 'rxjs/operators';

export function retryWithDelay<T>(
  delay: number,
  count = 1
): MonoTypeOperatorFunction<T> {
  return (input) =>
    input.pipe(
      retryWhen((errors) =>
        errors.pipe(
          scan((acc, error) => ({ count: acc.count + 1, error }), {
            count: 0,
            error: undefined as any,
          }),
          map((current) => {
            if (current.count > count) {
              throw current.error;
            }
            return current;
          }),
          delayOperator(delay)
        )
      )
    );
}

Sources

*

*rxjs-boost

*Original Source

*Spec File with Tests – probably comes in handy

A: I came to this conclusion, in order to retry with other operations in the http pipe
import {delay as _delay, map, retryWhen} from 'rxjs/operators';

export const delayedRetry = (delay, retries = 1) => retryWhen(result => {
    let _retries = 0;
    return result.pipe(
      _delay(delay),
      map(error => {
        if (_retries++ === retries) {
          throw error;
        }
        return error;
      }),
    );
  },
);

Usage
    http.pipe(
      delayedRetry(1500, 2),
      catchError((err) => {
        this.toasterService.error($localize`:@@not-saved:Could not save`);
        return of(false);
      }),
      finalize(() => this.sending = false),
    ).subscribe((success: boolean) => {
        if (success === true) {
           this.toasterService.success($localize`:@@saved:Saved`);
        }
      }
    });

A: Retry 5 times with a delay of 500ms:
RxJS 6.x

*

*Use index to count

*Transform retryWhen 's error Observable to timer or throwError
retryWhen(concatMap((err, index) => index < 5 ? timer(500) : throwError(err)))

RxJS 6.3 ⬆

*

*Use index to count

*In retryWhen 's error Observable, use delayWhen to wait timer or throwError
retryWhen(delayWhen((err, index) => index < 5 ? timer(500) : throwError(err)))

or you can do this :
const delayFn = (delay = 0, count = Infinity) => {
    return (err, index) => index < count ? timer(delay) : throwError(err);
};

retryWhen(concatMap(delayFn(500, 5))) // RxJS 6.x

retryWhen(delayWhen(delayFn(500, 5))) // RxJS 6.3 ⬆

RxJS 7.3 ⬆

*

*Just retry
retry({ count: 5, delay: 500 })

A: For ngrx5+ we could create operator:

function retryRequest(constructor: () => Observable, count: number, delayTime: number) {
  let index = 0;
  return of(1) // we need to repeat not the result of constructor(), but the call of constructor() itself
    .pipe(
      switchMap(constructor),
      retryWhen(errors => errors.pipe(
        delay(delayTime),
        mergeMap(error => {
          if (++index > count) {
            return throwError(error);
          }
          return of(error);
        })
      ))
    );
}

A:
Works on rxjs version 6.3.3

https://stackblitz.com/edit/http-basics-8swzpy

Open Console and see the retries
Sample Code

import { map, catchError, retryWhen, take, delay, concat } from 'rxjs/operators';
import { throwError } from 'rxjs';

export class ApiEXT {

    static get apiURL(): string { return 'http://localhost:57886/api'; };
    static httpCLIENT: HttpClient;

 static POST(postOBJ: any, retryCOUNT: number = 0, retryINTERVAL: number = 1000) {
        return this.httpCLIENT
            .post(this.apiURL, JSON.stringify(postOBJ))
            .pipe(
                map(this.handleSUCCESS),
                retryWhen(errors => errors.pipe(delay(retryINTERVAL), take(retryCOUNT), concat(throwError("Giving up Retry.!")))),
                catchError(this.handleERROR));
    }

  private static handleSUCCESS(json_response: string): any {
        //TODO: cast_and_return
        return JSON.parse(json_response);

    }

 private static handleERROR(error: Response) {
        let errorMSG: string;
        switch (error.status) {
            case -1: errorMSG = "(" + error.status + "/" + error.statusText + ")" + " Server Not Reachable.!"; break;
            default: errorMSG = "(" + error.status + "/" + error.statusText + ")" + " Unknown Error while connecting with server.!"; break;
        }
        console.error(errorMSG);
        return throwError(errorMSG);
    }

}

A: I recently had this problem, and found that the accepted solution could be improved.
Observable.pipe(
     retryWhen(errors => errors.pipe(
      delay(1000),
      take(10))),
    first(v => true),
    timeout(10000))

What it essentially does is to retry as mentioned, but this finishes right away without adding any (erroneous) value using the 'first' operator.
If it cannot find a value within the timeout timeframe, an error is raised.

A: To add on to @JB Nizet's answer. If you're writing this in rxjs 5+ with lettable operators, structure it as
retryWhen(errors => errors.pipe(delay(1000), take(5)))

A: As the accepted answer's suggestion to use retryWhen() was ok at that time, now, as we can see on the provided link for retryWhen(), this operator is deprecated and will be removed as from the RxJS version 9 or 10. So all solutions with retryWhen() are deprecated as well.
Now a solution that is suggested by the RxJS dev team and the docs is to use retry() operator, which is also an error handling operator, with the retryConfig param.
Now, to achieve the same logic, with less code, you would use the following:
// A custom method to check should retry a request or not
shouldRetry(error: HttpErrorResponse) {
    // Example for catching specific error code as well
    if (error.status === 503) {
      return timer(1000); // Adding a timer from RxJS to return observable to delay param.
    }

    throw error;
  }

// Retry operator somewhere in your code
retry({ count: 2, delay: this.shouldRetry })

As you could see from the example above, we have used less code and less RxJS operators to achieve some logic for which we needed a lot more using the retryWhen() operator. This is also the case why the team is deprecating this operator, as the same logic can be achieved using the retry() with this config.
Note: you would have to adopt the code I provided as per your needs, but this is an example of how to use the retry() operator instead of retryWhen().

A: delay() is used to introduce a delay between events emitted by the observable. But the observable never emits any event. It just errors immediately.
What you're looking for is retryWhen(), which allows deciding after how long to retry:
RxJS 5:
  .retryWhen(errors => errors.delay(1000).take(10))

RxJS 6:
import { retryWhen, delay, take } from 'rxjs/operators'
someFunction().pipe(
  // ...
  retryWhen(errors => errors.pipe(delay(1000), take(10)))
)

This will complete the whole observable after 10 attempts. If you want to error the whole observable after 10 attempts, the observable returned by the retryWhen callback must throw:
RxJS 5:
  .retryWhen(errors => errors.delay(1000).take(10).concat(Observable.throw()))

RxJS 6:
import { retryWhen, delay, take, concatMap, throwError } from 'rxjs/operators'
someFunction().pipe(
  // ...
  retryWhen(errors => errors.pipe(delay(1000), take(10), concatMap(throwError)))
)

A: This may help you
let values$ = Rx.Observable.interval(1000).take(5);
let errorFixed = false;

values$
.map((val) => {
   if(errorFixed) { return val; }
   else if( val > 0 && val % 2 === 0) {
      errorFixed = true;
      throw { error : 'error' };

   } else {
      return val;
   }
})
.retryWhen((err) => {
    console.log('retrying again');
    return err.delay(1000).take(3); // 3 times
})
.subscribe((val) => { console.log('value',val) });

A: RxJS provides retry operator that resubscribes the Observable for the given number of count when there is an error. Before throwing error Observable is resubscribed for the given number of count by retry operator and if still there is an error, then error is thrown. retry is useful to hit the URL many times. It is possible that because of network bandwidth, URL does not return successful data in one time and when it reties, it may return data successfully. If after retying still there is error in Observable then catchError can be used to return Observable with user defined default data.
getBook(id: number): Observable<Book> {
  return this.http.get<Book>(this.bookUrl + "/" + id).pipe(
     retry(3),
     catchError(err => {
      console.log(err);
      return of(null);
     })
  );
}

A: As accepted answer rethrow didn't  work for me, I ended up with this:
Retry 3 times with 2 seconds delay and if no success throw an error.

Observable.pipe(
  retryWhen(errors => errors.pipe(
    mergeMap((error, i) =>
      iif(() => i >= 3, throwError(() => error), timer(2000))
    )
  ))
);

A: I come up with following solution using retryWhen and Observable.Interval, but in this solution, error function of subscribe never calls,
this.branchService.getCanCreate()
  .do((value) => {
    this.cCreate = value;
  }, (error) => {
    console.log('do', error + new Date().toTimeString());
  })
  .retryWhen(errors => {
    return Observable.interval(1000).take(3).concat(Observable.throw('error')));
  })
  .subscribe(
    value => {
      this.cCreate = !!value
      console.log('success', new Date().toTimeString());
    },
    error => {
      console.log('subscribe', error + new Date().toTimeString());
      this.cCreate = false;
    },
    () => {
      console.log('finally', new Date().toTimeString());
    }
  );

A: 1. Using Concat
getPosts()
      {
        return this.httpClient
        .get<any[]>('https://jsonplaceholder.typicode.com/postss')
        .pipe(
          retryWhen(errors =>{
            return concat(
              errors.pipe(
                delay(2000),
                take(2),
              ),
              throwError("Max Retries Exceeded!")
            )
          }),
          catchError(()=>of(["Angular","Rxjs"])))
      }

2. Using ConcatMap
return this.httpClient
    .get<any[]>('https://jsonplaceholder.typicode.com/postss')
    .pipe(
      retryWhen(errors =>{
        return errors.pipe(
          concatMap((error,index)=> {
            if(index>=2) return throwError(error);
            else return of(error).pipe(delay(2000))
          })
        )
      }),
      catchError(()=>of("Angular","Rxjs"])))

3. Using Scan
return this.httpClient
    .get<any[]>('https://jsonplaceholder.typicode.com/postss')
    .pipe(
      retryWhen(errors =>{
        return errors.pipe(
         scan( (acc, error) => {
           if(acc>2) throw error;
           return acc+1;
         }, 1),
          delayWhen(val => timer(val * 1000)),
        )
      }),
      catchError(()=>of("Angular","Rxjs"])))
    }


text:
Q: How does one read from stdin when no characters remain? I am writing a basic Scanner class similar to Java's. Here is what I have (well, the relevant parts):
using System.Text;
using System.Collections.Generic;

namespace System.IO
{
    /// <summary>
    ///     <remarks>
    ///         Scanner is a wrapper for a <see cref="System.IO.TextReader" />
    ///         instance, making it easier to read values of certain types. It
    ///         also takes advantage of the
    ///         <see cref="System.IO.EndOfStreamException" /> class.
    ///     </remarks>
    ///     <seealso cref="System.IO.TextReader" />
    /// </summary>
    public class Scanner
    {
        private TextReader Reader;
        private Queue<char> CharacterBuffer = new Queue<char>();

        /// <summary>
        ///     <remarks>
        ///         Defaults to reading from <see cref="Console.In"/>
        ///     </remarks>
        /// </summary>
        public Scanner() : this(Console.In)
        {
        }

        public Scanner(TextReader reader)
        {
            this.Reader = reader;
        }

        public char Peek()
        {
            if (this.CharacterBuffer.Count > 0)
                return this.CharacterBuffer.Peek();

            try
            {
                return Convert.ToChar(this.Reader.Peek());
            }
            catch (OverflowException)
            {
                throw new EndOfStreamException();
            }
        }

        public char ReadChar()
        {
            if (this.CharacterBuffer.Count > 0)
                return this.CharacterBuffer.Dequeue();

            try
            {
                return Convert.ToChar(this.Reader.Read());
            }
            catch (OverflowException)
            {
                throw new EndOfStreamException();
            }
        }
    }
}

From the few tests that I ran, this works great with real files, but it doesn't quite work as expected with stdin. If I use Scanner.Peek or Scanner.ReadChar, after a newline is sent, the TextReader instance thinks it is at the end of the file (I think) and throws an EndOfStreamException instance since this.Reader.Read and this.Reader.Peek returns -1.
How can I force it to request a new character while still supporting true files and StringReader instances?

A: I changed Peek to reflect the following code. I'm not sure if this is 100% because I typed this from memory directly here.
public char Peek()
{
    if (this.CharacterBuffer.Count > 0)
        return this.CharacterBuffer.Peek();

    char Character
    try
    {
        Character = Convert.ToChar(this.Reader.Read());
    }
    catch (OverflowException)
    {
        throw new EndOfStreamException();
    }

    this.CharacterBuffer.Enqueue(Character);
    return Character;
}


text:
Q: ActionRequest vs RenderRequest I've read here that actionrequest is only valid during the action phase and RenderRequest is only valid during the render phase. However if I set actionREquest.setAttribute("object", myobject) I can access this object from my JSP, which I understand is the render phase right? How is this possible and how does this fit with the answer I link?

A: While ActionRequest and RenderRequest are distinct classes/objects, they all relate to the same request handling cycle. The main difference is that ActionRequest allows you to change state, RenderRequest does not any more.
While only one portlet on the page can handle an action (per single HTTP request), all portlets on the page typically render to make up the whole markup of the page. That's what the separation of action/render brings you in the portlet world. Servlets didn't have this because one servlet was always meant to render the whole page on every single request anyway. Portlets can render (which they most often do) and they can change state (which they typically do in the action phase)

A: You shouldn't forget that after an action-phase, portlet lifecycles proceed toward render-phase.
Try to watch the image in this blog post (the first I found by a google search): http://haitaoblog.blogspot.it/2011/05/portlets-portal.html
So JSP can access to both attributes in request.
On the other hand, if you need to access in the render phase to an action RENDER parameter, you have to set it inside your action code
actionResponse.setRenderParameter("parameter-name", "value");


text:
Q: Grub2 boots into prompt instead of menu after grub2-install This all starts when one day out of pure curiosity I ran "grub2-install" and it finished with no errors, although I expected no change either since I had in no way messed with grub modules. I had added an option to grub.cfg the legitimate way using 40_custom and then grub2-mkconfig but it had nothing to do with this, right? Well next time I boot into grub I see a prompt instead of a menu. After messing around a little I figure out that all I have to do is type "normal" to get to the menu and then I can continue as usual, this fixes my panic but I don't get what grub2-install did and how to fix it permanently! Every time I reboot now I see the prompt and have to enter the normal command for it to take me to the menu. I don't even know what normal does but it works. Is it a command that should execute by default but it somehow got removed from the auto execute list? Is there a grub configuration file I have to edit??
I know that this seems more like a complaint than a technical question, I apologise in advance. Also I'm running CentOS 7 with grub2 here. Thanks!

A: Without seeing the configuration file you changed it is hard to figure out what actually happened.
Here are the details on the grub2 normal command:
Command: normal [file]
Enter normal mode and display the GRUB menu.
In normal mode, commands, filesystem modules, and cryptography modules are automatically loaded, and the full GRUB script parser is available. Other modules may be explicitly loaded using insmod (see insmod).
If a file is given, then commands will be read from that file. Otherwise, they will be read from $prefix/grub.cfg if it exists.
normal may be called from within normal mode, creating a nested environment. It is more usual to use configfile (see configfile) for this.


text:
Q: Query a DataFrame with another DataFrame I want to filter a main DataFrame by values in multiple columns and rows of a second DataFrame. We could say the second is the search condition.
The initial data looks like this
   a  b  c
0  A  0  b
1  A  1  b
2  A  2  b
3  B  3  a
4  B  4  x

I want to filter/search for all rows where a=='B' and c=='a' | c=='x'. This can be represented as a DataFrame.
search_for = df.loc[:, ['a', 'c']].iloc[3:5]

   a  c
3  B  a
4  B  x

The point is that I do not know the concret search values because they are a result of another "query" and stored in a DataFrame.
It can be done like this and the result is correct.
search_for = df.loc[:, ['a', 'c']].iloc[3:5]
query_mask = (df.a.isin(search_for.a) & df.c.isin(search_for.c))
result_a = df[query_mask]

But because I have much more then just two columns in the real data I would prefer something like this Pseudocode:
df[search_for]

Here es an approach which does not fully work.
search_for = df.loc[:, ['a', 'c']].iloc[3:5]
query_mask = df.loc[:, search_for.columns].isin(search_for)
result_b = df[query_mask]

Result is
     a   b    c
0  NaN NaN  NaN
1  NaN NaN  NaN
2  NaN NaN  NaN
3    B NaN    a
4    B NaN    x

This is the full MWE
#!/usr/bin/env python3
import pandas as pd

print(pd.__version__)

# initial data
df = pd.DataFrame({
    'a': list('AAABB'),
    'b': range(5),
    'c': list('bbbax')
})
print(f'\nPrimary data:\n{df}')

# the values I need to search for
search_for = df.loc[:, ['a', 'c']].iloc[3:5]
print(f'\nSearch for:\n{search_for}')

# IMHO bad solution
result_a = df[df.a.isin(search_for.a) & df.c.isin(search_for.c)]
print(f'Result-A\n{result_a}')  # correct result

# An approach not fully working
search_for = df.loc[:, ['a', 'c']].iloc[3:5]
query_mask = df.loc[:, search_for.columns].isin(search_for)
result_b = df[query_mask]
print(f'Result-B\n{result_b}')

The full MWE output
1.2.5

Primary data:
   a  b  c
0  A  0  b
1  A  1  b
2  A  2  b
3  B  3  a
4  B  4  x

Search for:
   a  c
3  B  a
4  B  x
Result-A
   a  b  c
3  B  3  a
4  B  4  x
Result-B
     a   b    c
0  NaN NaN  NaN
1  NaN NaN  NaN
2  NaN NaN  NaN
3    B NaN    a
4    B NaN    x

A: The pandas way would be to use DataFrame.merge().
df.merge(search_for)[search_for.columns]


text:
Q: Tensorflow Eigen/Freeze_graph issue I've got a trained model that I want to put on my iPhone for inference. I've used Tensorflow, and obtained the necessary graph.pb and a checkpoint file. I use the freeze_graph.py script to freeze the graph with weights but I get the error:
google.protobuf.text_format.ParseError: 2:1 : Expected identifier or number. On the line where the script tries to read in the graph.
I tried using the method which is mentioned here and installed bazel. However when I do a bazel build tensorflow/python:freeze_graph, it gives me the error that Eigen was not found in the deps. This is right since the Eigen is in another folder.
I understand there's two things I'm asking here:

*

*How to freeze a graph properly given my error.

*If bazel is required for using freeze_graph how to get around the Eigen dependency.

I've also referenced this issue as well, but it didn't help since I'm using a Mac and configured tensorflow to build without CUDA support.
Any help will be appreciated. Thanks.


text:
Q: Ordering bookmarks c# i have a template word file with 4 different bookmarks, i want to add them to the form.
foreach (Bookmark bookmark in WordDocument.Bookmarks)
{
    dataGridView1.Rows.Add(bookmark.Name);
 }

But in the grid they are ordered by name, though i want them ordered by location, ive tried this construction:
var orderedBoomarks = WordDocument.Bookmarks.Cast<Bookmark>()
                          .OrderBy(d => d.Start).ToList();

How can i use this variable and insert it to my grid?(I barely understand what means this construction). Thanks!!

A: var orderedBoomarks = WordDocument.Bookmarks.Cast<Bookmark>().OrderBy(d => d.Start);
foreach (var bookmark in orderedBoomarks)
    dataGridView1.Rows.Add(bookmark.Name);


text:
Q: recursive array not working properly okay, so i have written some basic code that is supposed to test various sorting methods (only testing one sorting method at the moment) and find the most efficient. In order for the results to be considered accurate i am planning on running the tests several times on different sized arrays. Rather than manually running the same test over and over again i tried to create a recursive function but what i have so far doesn't work (the base case doesn't quite work and it goes on forever). Could someone please help me so that i can run the test several times using a working recursive method?
Side note, i have writtten about 5 different sorting methods (like selectionSort shown below) and was wondering if anyone has any ideas on what would be the best way to rotate through them in the test method so that i dont have to change selectionSort to something else each time i want to test a different sorting method. Cheers.
public void testSorts(){

    int size = 100;
    if(size < 1000000){
        String[] data;
        long start;
        long time;

        UI.println("\n\n======Selection Sort=======\n");

        data = createArray(size);
        start = System.currentTimeMillis();
        selectionSort(data);
        time =  System.currentTimeMillis() - start;

        UI.printf("Number of items:  %,d\n", data.length);
        UI.printf("Sorted correcetly: %b\n", testSorted(data));
        UI.printf("Time taken:       %.2f s\n", time/1000.0);

        UI.println("\n=======DONE=========\n");

        size = size*10;
        testSorts();

    }

A: You could fix this if you passed in the "size" parameter to your testSorts function.  As it stands now, you are just calling the same function within itself with no change, so you will get an infinite loop (in practice a stack overflow).
As a bigger picture comment, I don't see any reason to use recursion for this.

A: Why don't you just create a method 'test()' containing a for loop which calls your actual test method? Your for loop could increment by 100, like you 'testSorts' method does.
for(int size = 0; size < 1000000; size += 100) {
  testSort(size);
}

A: The problem is that your variable size is local to the method, so when you increase the size and then call testSorts again, a "new size" variable is created inside the scope of the recursive call.
To use this recursively, you'd have to:
public void testSorts(int size){

    if(size < 1000000){
        ....
        size = size*10;
        testSorts(size);
    }
}

However, I would use a simple loop to increase the size by an order of magnitude each step:
for (int size = 100; size < 1000000; size = size * 10){
    String[] data;
    long start;
    long time;

    UI.println("\n\n======Selection Sort=======\n");

    data = createArray(size);
    start = System.currentTimeMillis();
    selectionSort(data);
    time =  System.currentTimeMillis() - start;

    UI.printf("Number of items:  %,d\n", data.length);
    UI.printf("Sorted correcetly: %b\n", testSorted(data));
    UI.printf("Time taken:       %.2f s\n", time/1000.0);

    UI.println("\n=======DONE=========\n");
}

A: I agree with the other answerers that there is no need to use recursion here, @Rein suggests more or less what I would do.
Regarding trying different types of sort 'automatically', you could:

*

*Define an interface containing the public String[] sort(String[] data) method

*Populate a List in your testing class with the various implementations which implement the sort interface.

*Have another loop either inside or outside the existing loop in your test class iterate the object you delegate search to (depending on whether you want all algorithms at one size or all sizes for one algorithm order)

This would mean that your search algorithms are nicely separated from your 'test harness' class.


text:
Q: React 17 Deprecate "module pattern" components React 17
Вот тут:
https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md#deprecate-module-pattern-components
описан Deprecate "module pattern" components
Я так и не смог понять предлагаемый паттерн.
Описание типа в React 17 говорит что можно вернуть объект,
содержащий функцию, propTypes, contextTypes, defaultProps, displayName
В типе не сказано ни про какой onClick И предлагаемый паттерн вызывает ошибку.
Ранее я нигде (в том числе и в документации) не встречал возврата объекта и предлагаемая документом конструкция дает ошибку типа:
interface someProps {
  props1: string;
}
function Foo(props): React.FC<someProps> {
  return {
    onClick() {
      console.log("aa");
    },
    render() {
      return
;
    },
  };
}
Foo.prototype = { isReactComponent: true };

Поясните пожалуйста - кто разобрался с Deprecate "module pattern" components - как правильно ныне писать React.FC ?
Второй вопрос в связи с этим - ОК, свои компоненты я перепишу - а что делать со сторонними библиотеками ?

A: Вот один из вариантов написания функциональных компонентов на React. (Мне нравится больше всего, поэтому я везде предпочитаю его использовать)

type Props = {
  myProp?: string
}

const MyComponent: React.FC<Props> = ({children, myProp}) => {
  ...some logic
  return

    {children}

}

export default MyComponent

Так компонент получает displayName, что помогает при дебаге.
Если пользоваться записью описанной у вас, то это будет уже не функциональный компонент, т.е. тип React.FC не подойдет. Раньше такая запись работала, но в 17 реакте придется дополнительно указывать Foo.prototype = { isReactComponent: true };, что делает такую запись неудобной для большинства компонентов. Конечно могут быть случаи, когда в компоненте захочется иметь дополнительные методы или свойства (например, чтобы потом использовать их с помощью ref), тогда можно использовать такую запись, но тип скорее всего придется писать самому(React.FC не подойдет)


text:
Q: Run Cron Job On Specific Minute? I need to run a cron job on the 3rd minute of every hour, every day.
Here's what I currently have:
3 * * * *

Is that how you correctly do it or would that run it every 3 minutes instead?

A: That is correct!
If you would like to run a job every third minute you could do like this:
*/3 * * * *


text:
Q: Read Outlook Shared Calendars via Python Using Python, how do you read Outlook's Shared Calendar events, and hopefully, also using a time filter?

A: Here is a relevant post, but to answer this fully:
import win32com.client  # for outlook
import datetime

"""This code reads shared calendars."""

# set variables
days = 3
begin = datetime.date.today()
end = begin + datetime.timedelta(days=days)
events = []  # to write results from calendar loop

# begin importing calendar
Outlook = win32com.client.Dispatch("Outlook.Application")
ns = Outlook.GetNamespace("MAPI")

# turn this into a list to read more calendars
recipient = ns.CreateRecipient("username")  # cmd whoami to find this
resolved = recipient.Resolve()  # checks for username in address book

# olFolderCalendar = 9
# appointments = ns.GetDefaultFolder(9).Items  # for personal calendar
appointments = ns.GetSharedDefaultFolder(recipient, 9).Items

# filtering criteria
# https://learn.microsoft.com/en-us/office/vba/api/outlook.items.includerecurrences
appointments.Sort("[Start]")  # suspect problem
appointments.IncludeRecurrences = "True"
restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") \
            + "' AND [End] <= '" + end.strftime("%m/%d/%Y") + "'"

# list of appointments
restrictedItems = appointments.Restrict(restriction)

# loop through all calendar events, and add elements to list
count = 0
for app in restrictedItems:
    count += 1  # no len(range(restrictedItems)) allowed

#   display values
    print()
    print("item: " + str(count))
    print("start: \t\t" + str(app.Start))
    print("subject: \t" + app.Subject)
    print("end: \t\t" + str(app.End))
    print("recurring: \t" + str(app.IsRecurring))
    print("status: \t" + str(app.MeetingStatus))

    # collect values
    app_instance = [app.Subject,
                    app.Start,
                    app.End,
                    app.BusyStatus]
    events.append(app_instance)


text:
Q: Is there a "null" printf code that doesn't print anything, used to skip a parameter? If I want a program to have multiple text output formats, I could do something like this:
const char *fmtDefault = "%u x %s ($%.2f each)\n";
const char *fmtMultiLine = "Qty: %3u\nItem: %s\nPrice per item: $%.2f\n\n";
const char *fmtCSV = "%u,%s,%.2f\n";

const char *fmt;
switch (which_format) {
    case 1: fmt = fmtMultiLine; break;
    case 2: fmt = fmtCSV; break;
    default: fmt = fmtDefault;
}

printf(fmt, quantity, item_description, price);

Since the price is specified last, I could also add one that doesn't list prices:
const char *fmtNoPrices = "%u x %s\n";

But what if I want to omit the quantity instead? If I did this:
const char *fmtNoQuantity = "The price of %s is $%.2f each.\n";

then undefined behavior (most likely a segfault) will occur rather than what I want. This is because it will treat the first parameter as a pointer to a string, even though it's actually an unsigned int. This unsigned int will most likely point to something other than valid string data, or (much more likely, especially if you're not buying hundreds of millions of the same item) an invalid memory location, resulting in a segmentation fault.
What I want to know is if there's a code I can put somewhere (%Z in this example) to tell it to skip that parameter, like this:
const char *fmtNoQuantity = "%ZThe price of %s is $%.2f each.";

A: For %s values, there is a "null" printf() code: %.0s.
You could reach a general solution via:
When possible, re-arrange so that non-%s values are last, and then under specify the format string.
My favorite for you is to have 3 separate printf() calls, one for each value using its own format.  When the value is not needed, simply supply a format string with no specifiers.
const char * Format1q   = "";
const char * Format1id  = "The price of %s";
const char * Format1p   = " is $%.2f each.\n";
...
printf(Format1q,  quantity);
printf(Format1id, item_description);
printf(Format1p,  price);

Weird solutions:
For other values that are the same size you could attempt the Undefined Behavior of also using %.0s.  (worked with some samples in gcc 4.5.3, who knows in other compilers or the future.)
For other values that are the N x the same size as a pointer size you could attempt the Undefined Behavior of also using %.0s N times.  (worked with some samples in gcc 4.5.3, who knows in other compilers or the future.)

A: I actually figured this out on my own while looking something up for my question. You can prepend a parameter number, followed by a $ to the format code, after the %. So it would be like this:
const char *fmtNoQuantity = "The price of %2$s is $%3$.2f each.";

That is, the string would use the 2nd parameter, and the float would use the 3rd parameter.
Note, however, that this is a POSIX extension, not a standard feature of C.
A better method would probably be to define a custom printing function. Something like this:

typedef enum {fmtDefault, fmtMultiLine, fmtCSV, fmtNoPrices, fmtNoQuantity} fmt_id;

void print_record(fmt_id fmt, unsigned int qty, const char *item, float price)
{
    switch (fmt) {
    case fmtMultiLine:
        printf("Qty: %3u\n", qty);
        printf("Item: %s\n", item);
        printf("Price per item: $%.2f\n\n", price);
        break;
    case fmtCSV:
        printf("%u,%s,%.2f\n", qty, item, price);
        break;
    case fmtNoPrices:
        printf("%u x %s\n", qty, item);
        break;
    case fmtNoQuantity:
        printf("The price of %s is $%.2f each.\n", item, price);
        break;
    default:
        printf("%u x %s ($%.2f each)\n", qty, item, price);
        break;
    }
}


text:
Q: How should I terminate long run scripts without any data generated, I tried pressing Ctrl+C in a windows console via paramiko module This is really interesting.
I have following scripts on my linux machine:
sleep.py
import time
from datetime import datetime
print(datetime.now())
time.sleep(20)
print('Over!')
print(datetime.now())

loop.py
import time
for i in range(20):
    time.sleep(1)
    print(i)

I can terminate them directly by ctrl+c if I login through PuTTY or git-bash.
But when I trying to run the Python scripts on Windows console:
test.py
def ssh_pty_command(cmd, ip, username, passwd=None, key_filename=None):
    """run ssh.exec_command with realtime output and return exit_code."""
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        logging.debug('Connecting to remote server {}...'.format(ip))
        ssh.connect(ip, 22, username, password=passwd,
                    key_filename=key_filename, timeout=5)
        stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
        logging.info('ssh_In: {}'.format(cmd))
        # print '$: {}'.format(cmd)
        for line in iter(stdout.readline, ""):
            logging.info('ssh_Out: {}'.format(
                line.rstrip('\n').encode('utf-8')))
        for err in iter(stderr.readline, ""):
            logging.error('ssh_Error: {}'.format(
                err.rstrip().encode('utf-8')))
        exit_code = stdout.channel.recv_exit_status()
        logging.debug('Task exit with code {}.\n'.format(exit_code))
        return exit_code
    except Exception as err:
        logging.error('*** Caught SSH exception: %s: %s' %
                      (err.__class__, err))
        raise
    finally:
        ssh.close()

  ssh_pty_command('python loop.py',ip,username)
  ssh_pty_command('python sleep.py',ip,username)

When I press ctrl+c , the loop.py terminated immediately, but the sleep.py waits until the time.sleep(20) is finished and then terminate the execution.
How can I terminate the sleep.py immediately?
Note I did try to use get_pty=True in my exec_command method in my function, but it didn't help.
I guess it should have something to do with the signal sent by Paramiko, but not sure where to dig in...

A: Ctrl+C signals an interrupt. Python interpreter checks for the interrupt regularly, and raises KeyboardInterrupt exception, when it detects one.
When Paramiko is waiting for an incoming data on a socket, the checking for interrupts is probably suspended (just guessing). So if a remote command is not producing any output, you cannot break the local script.
Your loop.py produces an output using print(i), so your local Python script can be interrupted at the moment it's processing the output.
In any case, it's not the remote script that cannot be interrupted, it's the local script. So it has probably nothing to do with time.sleep as such.
See also:

*

*Stopping python using ctrl+c

*https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt

If you actually do not want to wait for the command to finish, your question is not really about Python (nor Paramiko), but about Linux. See Execute remote commands, completely detaching from the ssh connection.


text:
Q: White iPhone 4 vs. black iPhone 4 Other than the color, what exactly are the difference between the black and the white iPhone 4?

A: Check out this gallery for some comparison photos.

A: There are two changes that I've read about, both related to the color change but not just that the color is different:

*

*The rear camera positioning has been slightly modified to reduce the amount of light that leaks into the area; it's said to be recessed slightly deeper into the device, though other reports indicate a slightly different casing. Makes sense, since the black glass and plastic would absorb light that the white glass and plastic would let through, likely causing washed-out pictures (or the software adjusting the white balance incorrectly, losing details in lighter and/or darker areas of the image).

*Reports also indicate that the proximity sensor has been modified. Though it's quite possible, if the iPhone uses a capacitive proximity sensor such a change shouldn't be necessary (if it uses an infrared proximity sensor then the same light change issue would require a change). It seems more likely that the change was made for the ambient light sensor which is right next to the proximity sensor, since the ambient light sensor would have light change differences as well.
Other than the the phones are identical. The new one is no faster, for example.

A: Its supposed to be identical, but 0.2mm thicker

A: There is only a Color Difference between both devices.


text:
Q: Findout Data trasfer rate & Battery consumption in Android app? I'm working on android app development in which how get profiling information like

*

*Data transfer during app running

*Battery consumption

Is there possible done by code or any API or sample API
Thanks in Advance - sri

A: Please go through below link for battery consumtion and data transfer rate . It might helps you.
Battery consumption.
Data Transfer rate.


text:
Q: Showing when a button has been pushed in Qt I'm using Qt with C++, and I want to make a button that keeps looking pushed down after it is pushed and released.  I'm currently making buttons on a QToolBar and doing something like toolBar->addAction (icon, tr("Text"));.  This makes buttons on the toolbar that display the QIcon named icon and display "Text" on hover-over.  They also look pushed down as the user is pushing them, but stop looking pushed down when they are released (as is reasonable for most uses of buttons).  I need something different, however: I would simply like the buttons to remain looking pushed down after they are released, perhaps until they are clicked again.  It would be best if I could just call some function on a button or on the toolbar that could give me the capacity to control whether a button will look pushed down or not pushed down when it is displayed.  That way I could just control this aspect of button appearance programmatically.
What's the easiest way to do this in Qt? I've seen fancy ways of doing it involving borders and very complicated setups, but I was wondering whether there might be an easy way to do it.

A: Add QPushButton to the toolbar using addWidget and then make the button checkable.


text:
Q: How to submit the form with div ids as values in jquery php how to send div name with id as name and value to php on form submit without using ajax
    foreach ($_SESSION['companyuser']['roles'] as $key => $value){
       echo "

           <form action='controller/fileName.php' method='POST' id='formID'>

".$value['cmp_name']."

                    <button class='btn btn-default btndefault' type='submit' name='action' value='validatecompanyid'></button>

            </form>

        ";
    }

Generating HTML code using PHP foreach
How to send the data with div id on form submit when click on div
Here is my jquery code
    $(".choosecmp").click(function(e){
        var cmpId = this.id;
        $(this).find('.btndefault').click();
        // $('form#formID').submit();  // with direct form submit

    });

I tried with above code to submit form using button and direct form submition.
But here there is no input elements, so i want to send div id as post name and values.

A: You can add hidden fields in your form to send the data you want :
<?php
foreach ($_SESSION['companyuser']['roles'] as $key => $value){
   echo "

       <form action='controller/fileName.php' method='POST' id='formID'>
            <input type='hidden' name='divId' value='".$value['cmp_id']."' />

".$value['cmp_name']."

                <button class='btn btn-default btndefault' type='submit' name='action' value='validatecompanyid'></button>

        </form>

    ";
}

I add the following line :
<input type='hidden' name='divId' value='".$value['cmp_id']."' />

Just after your form opening to carry the div id as well
An other way would be to add the company id in the form url :
<form action='controller/fileName.php?companyId=" . $value['cmp_id'] . "' method='POST' id='formID'>

So that you can retrieve this value with a get :
$companyId = (int) $_GET['companyId'];

A: Add a hidden input field in your form with the value you want to commit and manage the submmision with jQuery:
    foreach ($_SESSION['companyuser']['roles'] as $key => $value){
       echo "

           <form action='controller/fileName.php' method='POST' id='formID'>

".$value['cmp_name']."

                    <input type='hidden' name='companyId' value='" . $value['cmp_id'] . "' />
                    <button class='btn btn-default btndefault' type='submit' name='action' value='validatecompanyid'></button>

            </form>

        ";
    }

jQuery:
$(".choosecmp").click(function(e){
    $('#formID').submit();
});

A: Without using ajax there aren't many options, you will need to submit actual input fields. One way to do this would be to add hidden input fields to the div that contain the variable. You could do this in the PHP:
foreach ($_SESSION['companyuser']['roles'] as $key => $value){
    echo "

       <form action='controller/fileName.php' method='POST' id='formID'>

".$value['cmp_name']."

                <button class='btn btn-default btndefault' type='submit' name='action' value='validatecompanyid'></button>

            <input type='hidden' name='companyId' value='".$value['cmp_id']."' />
        </form>

    ";
}

Or you could dynamically add them using javascript when the div is clicked:
$(".choosecmp").click(function(e){
    var form = $('form#formID');

    // Loop through the divs that have a name and id, and add the input
    form.find('div[name][id]').each(function(element) {
        var id = element.attr('id');
        var name = element.attr('name');
        var input = $('<input />');

        input.attr({'type': 'hidden', 'name': name, 'value': id});
        element.after(input);
    });

    form.submit();
});


text:
Q: Proof by Induction of a recurrence relation I am stuck with following proof which I am not able to get.
One such code is a list of $2n$ $n$-bit strings in which each string (except the first) differs from
the previous one in exactly one bit. Let us call such a list a twiddling list since we go from
one string to the next by just flipping one bit.
Consider the following recursive algorithm for listing the $n$-bit strings of a twiddling list. If $n = 1$, the list is $0,1$. If $n > 1$, first take a twiddling list of $(n − 1)$-bit strings and place
a $0$ in front of each string. Then, take a second copy of the twiddling list of $(n − 1)$-bit
strings, place a $1$ in front of each string, reverse the order of the strings and place it after
the first list. So, for example, for $n = 2$, the list is $00,01,11,10$, and for $n = 3$, we get
$000,001,011,010,110,111,101,100$.
I need to prove it by induction on n such that every n-bit string appears exactly once in the list generated
by the algorithm. Also, what will be the worst case time complexity of this recurrence relation.


text:
Q: UIWebView - What load times should I expect? I have had a look through lots of posts but can't seem to find anything on UIWebView load times and the kind of performance to expect.
I have an app that calls in a cached html page which is about 4.2KB in size. The view takes around 3.5 seconds to render through a wi-fi connection. How good or bad is this?
I'm trying to get the page as quick as possible but I can't really find anything more I can do. So I guess the question is, should I be getting better performance than this?
Any useful links would be appreciated.

A: It really doesn't have much to do with the size of the HTML. Although 4.2Kb is rather big. Rendering performance is mostly related to "what" it renders. For example, if you have lots of tables, or even worse -- nested tables --, then the rendering will be really slow. If you're HTML uses bad recursive entity definitions, it'll be horribly slow too. I would recommend taking full advantage of HTML5 for complex rendering.


text:
Q: How can I install CodeIgniter core (system) files using Composer? How can I install just the codeigniter core (system) code using Composer?

A: This might not be what you are after, but the obvious answer is to create a composer.json file and require "ellislab/codeigniter" - this will install whatever is offered, as a complete package.
I have no experience with CodeIgniter, but I think this will install more than you need. I have not seen and way to just install the system directory. This would only be possible if CodeIgniter would offer this as a separate package - and they don't.

A: I've just stumbled over the project that does just that - codeigniter-composer. Never used it though, simply was searching for a similar thing and this popped out.


text:
Q: Grab Data ID Value I'm trying to get the value of data-id in this a tag to be stored in the var filterValue
Some Page

By using the script below as I need the value of the data-id ID to be used by the Handlebars Helper
The Javascript is
    var filterValue = $("body").on('click', 'a.link-item', function (e) {
    e.preventDefault();
    $(this).data("id");

    alert("Data ID: " + $(this).data("id"));

    console.log(filterValue);

    Handlebars.registerHelper('filter', function (fValue, options) {
        if (fValue == filterValue) {
            return options.fn(this);
        } else {
            return options.inverse(this);
        }
    });

});

The alert is returning the value of data-id but somehow its not being stored in the var filterValue
I've created a JS bin here http://jsbin.com/fesejo/1/edit?html,js,output
Thanks & Regards

A: you are doing it wrong, you have to change it to this:
 var filterValue;
   $("body").on('click', 'a.link-item', function (e) {
    e.preventDefault();
    filterValue =$(this).data("id");//<-- store data-id value in variable
    ....................
    ....................
});

or:
   $("body").on('click', 'a.link-item', function (e) {
    e.preventDefault();
    var filterValue =$(this).data("id");//<-- store data-id value in variable
    ....................
    ....................
});

UPDATED JS BIN


text:
Q: How to remove zero columns/rows from a matrix while keeping row/column headings The following code (by @kglr) correctly works if mat1 does not have any row/column headings. However, I am working with a matrix with row/column headings.
How can I adjust the code given below to remove the zero rows/columns without dropping the headings?
mat1 =
{{0, c1s1, c1s2, c1s3, c2s1, c2s2, c2s3, c3s1, c3s2, c3s3,
c1d1, c1d2, c2d1, c2d2, c2d3, c3d1, c3d2}, {c1s1, 1, 3, 0, 2, 2,
2, 3, 2, 0, 3, 1, 2, 0, 3, 3, 0}, {c1s2, 2, 2, 0, 0, 3, 0, 0, 0,
0, 0, 0, 3, 0, 1, 2, 0}, {c1s3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0}, {c2s1, 2, 1, 0, 0, 2, 0, 2, 3, 0, 2, 3, 1, 0, 2,
2, 1}, {c2s2, 1, 3, 0, 0, 2, 1, 3, 0, 0, 3, 3, 2, 0, 1, 2,
3}, {c2s3, 3, 3, 0, 0, 2, 2, 3, 1, 0, 2, 2, 2, 0, 0, 2, 3}, {c3s1,
1, 2, 0, 0, 2, 0, 3, 0, 0, 1, 0, 1, 0, 2, 3, 1}, {c3s2, 2, 0, 0,
2, 2, 0, 3, 0, 0, 3, 1, 1, 0, 1, 3, 3}, {c3s3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {c1t, 3, 1, 0, 0, 0, 3, 1, 0, 0, 0,
1, 2, 0, 2, 0, 0}, {c2t, 2, 1, 0, 0, 3, 3, 3, 0, 0, 2, 1, 0, 0,
3, 1, 2}, {c3t, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0}, {va, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 3, 2, 0, 3, 3, 1}};

nonzerorows = Flatten@Position[mat1, Except@{0 ..}, 1, Heads -> False]
nonzerocols = Flatten@Position[Transpose@mat1, Except@{0 ..}, 1, Heads -> False]
mat1NZ = mat1[[nonzerorows, nonzerocols]]
{zerorows, zerocols} = MapThread[
  Complement[Range@#@Dimensions[mat1], #2] &, {{First,
  Last}, {nonzerorows, nonzerocols}}]

A: With minimal change in your code:
nonzerorows = Flatten@Position[Rest /@ mat1, Except@{0 ..}, 1, Heads -> False]

{1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 14}

nonzerocols = Flatten@Position[Rest /@ Transpose@mat1, Except@{0 ..}, 1,
   Heads -> False]

{1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 15, 16, 17}

{zerorows, zerocols} = MapThread[Complement[Range@#@Dimensions[mat1], #2] &,
  {{First, Last}, {nonzerorows, nonzerocols}}]

 {{4, 10, 13}, {4, 10, 14}}

mat1NZ = mat1[[nonzerorows, nonzerocols]];

MatrixForm[mat1NZ]

MapAt[Highlighted, mat1,
  Join[Thread[{zerorows, All}], Thread[{All, zerocols}]]] /.
    Highlighted[Highlighted[a_]] :> Highlighted[a] // MatrixForm


text: Q: How to change defaulte localhost port in my angular app I am just starting to learn angular js. I have two apps both with deafault port of 4200, I want to have different port for each of my apps, and I don't know how to change default port.


text:
Q: Joining 2 primary key columns to 1 foreign key column in the same table I have a jobs table with a projectmanagerid and a projectdirectorid e.g
jobs
----------------
pk jobid
pk projectmanagerid
pk projectdirectorid

Both these id columns need to link to an employees table using the employeeid pk as the link. Is this good practice or is there a better way?
employees
------------------
pk employeeid
   other stuff

A: This seems OK as long as you're only going to have those two types: Manager and Director. But think about whether you might need to add another employee type, for example Coordinator, in the future. If that's a possibility then you've got a many-to-many relationship between jobs and employees that you should resolve by using an intermediary junction table, perhaps also adding a third table to describe the employee's role on the job (Manager, Director, ...).

A: Nothing wrong with it and it's perfectly acceptable. The field names are descriptive and thereby signify that you do actually need to have two different FKs pointing at the users table. if it was x and y, then it'd look weird.

A: Seems quite reasonable -- and common in many heirarchies -- to have two relationships to the same table. As with all foreign keys, but perhaps even more so in this case, use cascading carefully. I'm guessing that deletion of the manager or director should not result in deletion of the job record.

A: There is a rule of thumb that states a table models an entity/class or the relationship between entities/classes but not both. Therefore, consider creating two relationship tables to model the two relationships, project managers and project directors respectively. I don't recommend Joe Stefanelli's employee_role_id approach. I think you will find that the attributes for each role (yes, relationships do indeed have attributes too) will be too different to make the generic table approach to add value.


text:
Q: Why are extra 92 pixel square thumbnails created? Disabling this WordPress feature which automatically generates various sizes of an uploaded image, is normally as simple as going to WordPress Dashboard > Settings > Media screen and changing all image-size options to 0 (zero).
Unless I am missing something, this is not the case with my blog. Any image I upload gets a 92 pixel square thumbnail cousin.
I have searched through all the theme files for any and all occurrences of the number '92', but there's none! So I am guessing it's WordPress core?
PS:

*

*This WordPress Codex page says that the default sizes for thumbnail, medium, and large resolution images are 150 px, 300 px, and 640 px (squares) respectively. A 92 px square is clearly not among the defaults.

*I read here that WordPress creates "one additional thumb for Dashboard interface needs". I am not sure where. Is this why the 92px thumb is being generated? (I don't think so.)

*In case it helps, I am using a WordPress.com theme called "Reddle" on my self-hosted blog. It looks like the theme was developed by Automattic Theme Wranglers.

A: Take a look at the output of get_intermediate_image_sizes(). If there are any image sizes listed other than 'thumbnail', 'medium' or 'large', a plugin or a theme has added a custom size.
From our chat discussion I know it was WPtouch Pro. :) But it could have been any plugin. There are also sometimes plugins in the directory mu-plugins.


text:
Q: static variable size comparison Consider the following 3 programs:

*

*static1.c
 int main(int argc, char * argv[])
 {
     return 0;
 }

*static2.c
 int main(int argc, char * argv[])
 {
     static int i;
     return 0;
 }

*static3.c
 int main(int argc, char * argv[])
 {
     static int i = 2;
     return 0;
 }

Now the size for each program is invoked:

*

*size static1.out
text    data     bss     dec     hex filename
1418     544       8    1970     7b2 static1.out

*size static2.out
text    data     bss     dec     hex filename
1418     544       8    1970     7b2 static2.out

*size static3.out
text    data     bss     dec     hex filename
1418     548       4    1970     7b2 static3.out

Why is the size output same for static1.c and static2.c, even if there is an uninitialised/zero initialised static variable in static2.out, which must go to .bss segment?
In all 3 programs the variable is never used. If the compiler is smart enough to deduce that, then why did the size information in static3.c different from other two?
If the .data and .bss are 544 and 8 respectively(without any variables), then only .data segment should change in the static3.c but from the output we can see that the int moved from .bss to .data(because the variable has an initial value now)


text:
Q: Pointers in C not working as desired I'm trying to work through Harvard's CS50 problem set and I find myself stuck on a very basic greedy problem of finding the least number of coins for given change if the coins are only available in denominations of 25c, 10c, 5c and 1c. While pointers are not really needed for this problem and even having a separate function is an overkill probably, I'm trying to get a better understanding of pointers by implementing it here, however, I don't get the desired output for 'coins' for some reason. The printf statements after before and after function calls are for debugging purposes. A sample output is given after the code.
Here's the code:
#include <stdio.h>
#include <cs50.h>

void denomination(float* change, int* coins, int den);

int main(void){

    float change;
    do{
        printf("How much change is owed?\n");
        change = GetFloat();
    }while(change < 0);

    int coins; //number of coins in total to be given in change

    if(change == 0){
        coins = 0;
        printf("%d\n", coins);
    }else{
        change = change * 100; //converting to cents
        denomination(&change, &coins, 25);
        printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
        denomination(&change, &coins, 10);
        printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
        denomination(&change, &coins, 5);
        printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
        denomination(&change, &coins, 1);
        printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
        printf("%d\n", coins);
    }
    return 0;
}

void denomination(float* change, int* coins, int den){
    int tmp;
    tmp = (*change/den);
    printf("Temp: %d\n", tmp);
    *coins = *coins + tmp;
    *change = *change - (tmp*den);
}

Here's the output:
How much change is owed?
0.41
Temp: 1
Inside else:: Change: 16.000000, Coins: 134516108
Temp: 1
Inside else:: Change: 6.000000, Coins: 134516109
Temp: 1
Inside else:: Change: 1.000000, Coins: 134516110
Temp: 1
Inside else:: Change: 0.000000, Coins: 134516111
134516111

I don't understand why 'change' works as desired but 'coins' does not.

A: The while loop must be left with a nonzero value of change (as the else branch is reached), but coins is initialized only in the if branch above. In total, the behaviour is undefined.

A: First of remove the while loop in function.
void denomination(float* change, int* coins, int den)
{
    int tmp;
    tmp = (*change/den);
    printf("Temp: %d\n", tmp);
    *coins = *coins + tmp;
    *change = *change - (tmp*den);
}

Because you are already dividing so getting the total number of coins only in one time.
So first of all there is no need of loop.
Then instead of only removinf one den you have to remove total amount which will be multiple of tmp coins to be given.
So Corrected the following statement in your function.
*change=(*change-(tmp*den));

Second thing initialize the coins variable.
As i think it is giving somewhat garbage value.
So initialize it with zero in main.
int Coins=0;

A: I don't see anywhere that coins is initialized and its new value is always dependent on the previous value I could that would be the problem it look to me like its not a pointer problem


text:
Q: split the url from the / with php What would be the best way to split URL http://www.mysite.com/?name
How to split the /?name from the above url and be able to put in a id from the server.  The ids are already on the server I just need to change this so that someone with that id could put in:
http://www.mysite.com/username.

A: First, you should use URL rewriting to convert all the virtual addresses into script calls. Like www.mysite.com/username is actually served as www.mysite.com/?name=username. Inside the script, you would simply access the name variable from GET parameters.
There are thousands of tutorials available on the net, this one seems good enough : http://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/

A: use parse_url output is

scheme - e.g. http
host
port
user
pass
path
query - after the question mark ?
fragment - after the hashmark #

like
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

output
Array
(
   [scheme] => http
   [host] => hostname
   [user] => username
   [pass] => password
   [path] => /path
   [query] => arg=value
   [fragment] => anchor
)