text:
Q: Trailhead : Variable Scope Issue (Compiler Error) This is my class
global class ProjectCalloutService1  {

String OppId;

@InvocableMethod
public static void postOpportunityToPMS(List<Id> oids)
{

     OppId = oids[0];

}

global class QueueablePMSCall implements Queueable, Database.AllowsCallouts
{
   public void execute(QueueableContext context)
   {

    Opportunity o = [SELECT ID,Name,Account.Name,CloseDate,Amount FROM Opportunity WHERE Id = '1'];

    ServiceTokens__c s = ServiceTokens__c.getValues('ProjectServiceToken');
    System.debug(s.Token__c);

    String jsonInput = '{\n' +
    ' "opportunityId" : "'+o.Id+'",\n'+
    ' "opportunityName" : "'+o.Name+'",\n'+
    ' "accountName" : "'+o.Account.Name+'",\n'+
    ' "closeDate" : "'+String.ValueOf(o.CloseDate).mid(0,10)+'",\n'+
    ' "amount" : '+o.Amount+'\n'+
    '}';

    HTTPRequest req = new HTTPRequest();
    req.setEndPoint('callout:ProjectService');
    req.setMethod('POST');
    req.setHeader('Content-Type', 'application/json');
    req.setHeader('Token', s.Token__c);
    req.setBody(jsonInput);

    HTTP h = new HTTP();
    HTTPResponse res = h.send(req);
    System.debug('~~~ REQ BODY '+req.getBody());
    System.debug('~~~ REQUEST '+req.toString());
    System.debug('~~~ RESPONSE '+res);

    if(res.getStatusCode() == 201)
    {
      o.Type = 'Submitted Project';
      update o;
    }

   }

}

}

I still have not finished developing this class so kindly excuse if it does not make sense.
My concern is with respect to compiler error that I am getting which says below
Error: Compile Error: Variable does not exist: OppId at line 9 column 6

I have tried adding global and public access modifiers in front of "String OppId" without success.
I thought as per OO principles a member variable can be accessed by all member methods within the same class.
When that being the case why my method "postOpportunityToPMS" complains that the variable "OppId" does not exist ?

A: You are trying to reference instance variable inside a static method, which is not allowed.
This is Instance variable:
String OppId;

This is static variable:(this variable now can be used in static methods.)
Static String OppId;


text:
Q: Why is ItemsControl in the following WPF XAML not showing anything? When I run the app, I expect to see 5 buttons (see ItemsControl\DataTemplate\Button in my XAML below) each with a content like "55/42" denoting max ad min temperature. However, the window is blank. I know this has to do with ItemsControl because I can display the data without using the ItemsControl. Can someone catch my mistake?
<Window x:Class="Embed_WeatherSummaryAsItemsControl_ToMain.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    FocusManager.FocusedElement="{Binding ElementName=InputCity}"
    Title="Weather App" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox x:Name="InputCity" Grid.Row="0" Width="200" Text="{Binding CityAndOptionalCountry}"></TextBox>
    <Button Grid.Row="0" Width="50" Content="Go" Margin="260,0,0,0" Command="{Binding GetWeatherReportCommand}"></Button>
    <ItemsControl Grid.Row="1" ItemsSource="{Binding WeatherForecastSummaryCollection}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Path=MaxMinTemperature}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

As shown below, "WeatherForecastSummaryCollection" is a collection property on ViewModel class and "MaxMinTemperature" is a property of item in collection.
public class MainWindowViewModel : ViewModelBase
{
    ....

    private List<WeatherForecastSummary> mWeatherForecastSummaryCollection;
    public List<WeatherForecastSummary> WeatherForecastSummaryCollection
    {
        get { return mWeatherForecastSummaryCollection; }
        set
        {
            mWeatherForecastSummaryCollection = value;
            OnPropertyChanged("WeatherForecastSummaryCollection");
        }
    }
    .....
}

public class WeatherForecastSummary
{
    public string MaxMinTemperature { get; set; }
}

Thanks for helping!

A: I think you are missing the DataContext here.
Even if you are using the codebehind of the View, you need to write
this.DataContext = this;

or if you are using someother class as viewmodel you might want to point the datacontext to that class. Just replace "this" in the above code with your viewmodels object.
In this case it would be ,
this.DataContext = new MainWindowViewModel();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Javascript run perfectly inline, but not if referenced externally? I am trying to populate a dropdown form field created with:

    Province

    <select id="provinces"></select>

using the following JavaScript:
var provinces = ['Gauteng', 'Limpopo', 'Western Cape','Northern Cape','Mpumalanga','Kwazulu Natal','North West','Eastern Cape','Free State'],
select = document.getElementById( 'provinces' );
for( province in provinces ) {
    select.add( new Option( provinces[province] ) );
};

This works perfectly if I place the script in the HTML document but nothing happens if I remove the script tags and place it in an external file.  I have referenced the js file from within the HTML file with

and I have confirmed that I am referencing the correct field.
I'm obviously making some other stupid mistake. Would any of you experts be kind enough to show me where I am going wrong?

A: You are Calling Script Before it's Element Created in DOM Structure.
JavaScript Code:

This works perfectly if I place the script in the HTML document (you are placing the script after Select Element Created, That's why it is working)
but nothing happens if I remove the script tags and place it in an external file (You are adding external file in html head section top, the script will be execute instant head section load. It will not wait to load entire body, and thus your script will not get Select Element & you will get JavaScript error in your browser "Uncaught TypeError: Cannot read property 'add' of null at ..."). I have referenced the js file from within the HTML file with

and I have confirmed that I am referencing the correct field.
I'm obviously making some other stupid mistake (You are not stupid, it happens with everyone who are beginners even it happened lots of time with me even... Well, that time I was kid :D). Would any of you experts be kind enough to show me where I am going wrong? (Off course dear, Stackers are everywhere and willing to help each and every person on SO :) :))

The Correct Way is add script or external javascript always at the end of html body, So then your script will get all required elements
  from body.

Working Script: Inline (No matter it's before  or before )

External Script Code: (No matter it's before  or before )
window.onload = function() {
    var provinces = ['Gauteng', 'Limpopo', 'Western Cape', 'Northern Cape', 'Mpumalanga', 'Kwazulu Natal', 'North West', 'Eastern Cape', 'Free State'],
        select = document.getElementById('provinces');
    for (province in provinces) {
        select.add(new Option(provinces[province]));
    };
};

A: Check if
1) The script file is referenced correctly (open the src location) and
2) The script tag is within the body (ideally after the section element). It may be that the javascript code is executing before the element is rendered

A: You must execute your code after the dom is loaded, you have some options how to do it:

*

*load your js at the end of your page;

*use defer attribute on your script tag;

*pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it


text:
Q: Add a new column to dataframe and add unique values to each row I have a dataframe with two columns: id_code & diagnosis
I have a folder with images with filename same as id_code. I want to add a new columns to the dataframe: Image, height and width
I have the following code:
for idx, row in df_train.iterrows():
    img = Image.open('train_images/{}.png'.format(row['id_code']))
    height, width = img.size
    row['image'] = img
    row['height'] = height
    row['width'] = width

I tried using df_train.iloc[idx]['image'] = img instead of row['image'] = img and so on for the rest of the lines of code but that would give me an error.
But this code updates the row but doesn't update the dataframe itself.

A: We should assign it cell by cell
l=[]
for idx, row in df_train.iterrows():
    img = Image.open('train_images/{}.png'.format(row['id_code']))
    l.append(img)
    height, width = img.size
    df.loc[idx,'height'] = height
    df.loc[idx,'width'] = width

df['img']=l


text:
Q: JMeter. How to add dependencies for variables in different requests? I have request for logging users via JSON Body and .csv file such as:
JSON Body:
 {
  "data": {
    "email": "${user_email}",
    "password": "${user_password}"
  }
}

.csv:
load_testing_0000@example.com,load_testing_0000
load_testing_0001@example.com,load_testing_0001
...
load_testing_0004@example.com,load_testing_1999

And second request that has variable ${user_id} into the path /en/api/v1/user/${user_id}/tickets?page=0&per_page=20
which get data from another .csv file
699
700
...
2698

The request will be succesfull only when first user will be use path with first variable (699), second user with second variable(700) etc.
But now I have situation when first user can take second variable, and for example second user can take first variable. That's why my request has response code: 403 Access denied for current user.
How can I add this dependency (or implement this behavior using JMeter)?

A: I would suggest to merge your 2 CSV files into one like
load_testing_0000@example.com,load_testing_0000,699

And configure CSV Data Set Config Variable Names section as:
user_email, user_password, user_id

So there will be a match between user email and user id.
See Using CSV DATA SET CONFIG guide to learn how to define and use multiple variables.


text:
Q: How to send a string to other application including Microsoft Word I was trying to accomplish this but did not get good results. I used GetForegroundWindow(), AttachThreadInput(uint,uint,bool) and GetFocus() functions to send the strings to another window. It works with Notepad, Wordpad and other applications, but not with Microsoft Word.
int foregroundWindowHandle = GetForegroundWindow();
uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
uint currentThreadId = GetCurrentThreadId();
bool b = AttachThreadInput(remoteThreadId, currentThreadId, true);
int focused = GetFocus();
int d = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
b = AttachThreadInput(remoteThreadId, currentThreadId, false);
SendMessage(focused , WM_GETTEXT, builder.Capacity, builder);
clip = builder.ToString();

//Text operations...

SendMessage(focused, WM_SETTEXT, 0, builder);

That's the code I have, but it doesn't work with Word. I know that Word uses Custom Controls, but I think there should be another way to handle this.
For example:
Windows Speech Recognition sends text to every application which has focus even if it is Word. I don't think they made the inputs manually.
I thought to use the SendInputs function but I don't know how to make that.

A: Check whether the following works; you just need to call SendString. This should work for any application that can receive text whose window is currently active.
All code except the first method is courtesy of pinvoke.net.
/// <summary>
/// Synthesizes keystrokes corresponding to the specified Unicode string,
/// sending them to the currently active window.
/// </summary>
/// <param name="s">The string to send.</param>
public static void SendString(string s)
{
    // Construct list of inputs in order to send them through a single SendInput call at the end.
    List<INPUT> inputs = new List<INPUT>();

    // Loop through each Unicode character in the string.
    foreach (char c in s)
    {
        // First send a key down, then a key up.
        foreach (bool keyUp in new bool[] { false, true })
        {
            // INPUT is a multi-purpose structure which can be used
            // for synthesizing keystrokes, mouse motions, and button clicks.
            INPUT input = new INPUT
            {
                // Need a keyboard event.
                type = INPUT_KEYBOARD,
                u = new InputUnion
                {
                    // KEYBDINPUT will contain all the information for a single keyboard event
                    // (more precisely, for a single key-down or key-up).
                    ki = new KEYBDINPUT
                    {
                        // Virtual-key code must be 0 since we are sending Unicode characters.
                        wVk = 0,

                        // The Unicode character to be sent.
                        wScan = c,

                        // Indicate that we are sending a Unicode character.
                        // Also indicate key-up on the second iteration.
                        dwFlags = KEYEVENTF_UNICODE | (keyUp ? KEYEVENTF_KEYUP : 0),

                        dwExtraInfo = GetMessageExtraInfo(),
                    }
                }
            };

            // Add to the list (to be sent later).
            inputs.Add(input);
        }
    }

    // Send all inputs together using a Windows API call.
    SendInput((uint)inputs.Count, inputs.ToArray(), Marshal.SizeOf(typeof(INPUT)));
}

const int INPUT_MOUSE = 0;
const int INPUT_KEYBOARD = 1;
const int INPUT_HARDWARE = 2;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_UNICODE = 0x0004;
const uint KEYEVENTF_SCANCODE = 0x0008;
const uint XBUTTON1 = 0x0001;
const uint XBUTTON2 = 0x0002;
const uint MOUSEEVENTF_MOVE = 0x0001;
const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
const uint MOUSEEVENTF_LEFTUP = 0x0004;
const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
const uint MOUSEEVENTF_RIGHTUP = 0x0010;
const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
const uint MOUSEEVENTF_XDOWN = 0x0080;
const uint MOUSEEVENTF_XUP = 0x0100;
const uint MOUSEEVENTF_WHEEL = 0x0800;
const uint MOUSEEVENTF_VIRTUALDESK = 0x4000;
const uint MOUSEEVENTF_ABSOLUTE = 0x8000;

struct INPUT
{
    public int type;
    public InputUnion u;
}

[StructLayout(LayoutKind.Explicit)]
struct InputUnion
{
    [FieldOffset(0)]
    public MOUSEINPUT mi;
    [FieldOffset(0)]
    public KEYBDINPUT ki;
    [FieldOffset(0)]
    public HARDWAREINPUT hi;
}

[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
    public int dx;
    public int dy;
    public uint mouseData;
    public uint dwFlags;
    public uint time;
    public IntPtr dwExtraInfo;
}

[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
    /*Virtual Key code.  Must be from 1-254.  If the dwFlags member specifies KEYEVENTF_UNICODE, wVk must be 0.*/
    public ushort wVk;
    /*A hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE, wScan specifies a Unicode character which is to be sent to the foreground application.*/
    public ushort wScan;
    /*Specifies various aspects of a keystroke.  See the KEYEVENTF_ constants for more information.*/
    public uint dwFlags;
    /*The time stamp for the event, in milliseconds. If this parameter is zero, the system will provide its own time stamp.*/
    public uint time;
    /*An additional value associated with the keystroke. Use the GetMessageExtraInfo function to obtain this information.*/
    public IntPtr dwExtraInfo;
}

[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
    public uint uMsg;
    public ushort wParamL;
    public ushort wParamH;
}

[DllImport("user32.dll")]
static extern IntPtr GetMessageExtraInfo();

[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);

A: Word doesn't use a standard edit control that responds to WM_TEXT. To poke text into Word you could use SendInput to fake input, or COM automation, or UI Automation.
The last of these options, UI Automation, would be my choice and is the way MS intend you to do this nowadays.


text:
Q: Unsigned and signed division in C In my program two variables are declared as signed long (let say X and Y on 32 bit machine) and these divided one by other(X/Y).
The final value is assigned to a unsigned long variable(Let say Z). I am not sure whether this is right or wrong assignment. I am just debugging a code that was written by some one. I guess this may lead to overflow or undefined state.
What happens in below four scenarios,
Z =+X/+Y
Z =+X/-Y
Z =-X/+Y
Z =-X/-Y

I know that %u for unsigned and %d for integer. My question is regarding what value would be stored in Z in the above four scenarios.
Any help would be greatly appreciated.

A: If your variables are signed, all is fine. Perhaps there is a (unwanted?) conversion afterwards if you gert a negative division result.
Working with expressions containing unsigned values is more painful, e.g.
(1U-2)/10

gives unexpected results.

A: Z would store the value of the integer division, but as Z is unsigned, all values will be positive, and thus the sign bit will not be processed as such, but as part of the number, and also there will be no two's complement conversion. For example, if unsigned int is 32-bit wide:
X = 1, Y = 1 -> Z = 1
X = -1, Y = 1 -> Z = 4294967295 = 0xFFFFFFFF (this would be -1 -two's complement- if Z was signed)

A: You'll get garbage if result of division is negative.
For example:
unsigned z;
int a = 10;
int b = -2;
z = a/b;

then z == 4294967291.


text:
Q: Get undefined when stripe return result Hello guy I am doing payment with stripe, I am already success payment (checked on dashboard.striped.com) but i can't get the result return. Below is my code

Node
app.post('/payment', async (req, res) => {
  const { token,
    totalPrice } = req.body
  const idempontencyKey = uuidv4()
  return stripe.customers.create({
    email:token.email,
    source:token.id
  }).then(customer => {
    stripe.charges.create({
      amount: Math.ceil(totalPrice),
      currency: 'usd',
      customer:customer.id,
    },{idempotencyKey: idempontencyKey})
  }).then(result => {
    res.status(200).json(result) // result in here is undefined
  }).catch(err => console.log(err))
});

Here is my checkout component
<StripeCheckout stripeKey='pk_test_51KU0KNHzr2aPULLHERi1fWVBHp2Oxy1BTeBG0gfJ6O9DeRwuiGN1csKbpJMMPLvZjHTv5bo2qKguE8RQZnpCekjD00KDxRcNhm' token={makePayment} name='Buy product' amount={order.totalPrice} >
   <ButtonComponent>Pay ${order.totalPrice}</ButtonComponent>
</StripeCheckout>

And this is makePayment
const makePayment = async (token) => {
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    const data = await axios.post('/payment', {
      token,
      totalPrice: order.totalPrice
    }, config)
    console.log('data',data.data) // this return empty string
  }

Anyone have any ideas? Thank you!!!

A: The part
}).then(customer => {
  stripe.charges.create({
    amount: Math.ceil(totalPrice),
    currency: 'usd',
    customer:customer.id,
  },{idempotencyKey: idempontencyKey})
})

does not return anything, so the next .then will receive undefined.
Change it to
}).then(customer => {
  return stripe.charges.create({
    amount: Math.ceil(totalPrice),
    currency: 'usd',
    customer:customer.id,
  },{idempotencyKey: idempontencyKey})
})

A: In this then, you just call create charges function but return nothing. So that in the next then, it receive nothing.
}).then(customer => {
  return stripe.charges.create({
    amount: Math.ceil(totalPrice),
    currency: 'usd',
    customer:customer.id,
  },{idempotencyKey: idempontencyKey})
})


text:
Q: Database Name Change I read it was more secure to use something else besides wp_ as the database prefix, so I downloaded my .sql file replaced all instances of wp_ with tsi_ and then dropped the wp_ tables and imported my .sql file.
The prefix is now correct, so then I went to my wp_config file and changed the prefix table from wp_ to tsi_ and I thought everything was good.
Well, all my posts were still there, but the images are missing. I say missing because when you look in the uploads folder they are there, correctly sorted and everything, but in the media library, they appear as grey icons instead of the previews and they are missing from all my posts. Is there any way to get the images to display correctly?
*The domain name did not change or any of my settings, I just changed the database prefix and that's it.
The grey icons in the media library:

The posts without images:

Thanks,
Josh

A: Ok...
So after some more research I found: http://andrewapeterson.com/2012/08/fix-wordpress-media-library-and-attachments-broken-after-movingcloning-site/ which explains that you can't just do a find and replace in a text editor and be good to go.
Fortunately, I still had the original database, so I dropped all the tables in the tsi_ database and restored the original wp_ database.
All my images were restored and the site was back to normal, now to change the database prefix properly...
I found a plugin called Change DB Prefix: https://wordpress.org/plugins/db-prefix-change/ it allows you to put in the old prefix wp_ and replace it with a new one tsi_.
The plugin safely changed my database prefix and updated my wp_config file in less than a second! All my images are fine and everything is now up and running correctly with the new database prefix!!
Hope this helps someone!
Thanks,
Josh

A: This is not related to DB prefix, this is an option for uploads folder commonly this folder is  mydomain.com/wp-content/uploads, but sometimes WP confuses this directory, you can solve changing this to empty, so WP will browse the files in the proper directory.
 This option can be changed on settings - Media or using phpmyAdmin looking for the option uploads folder.
:)


text:
Q: changing size of Widget from QStyle I am writting a QStyle Here I am changing the QProgressBar to a Slim single line, no text. So Height will also be reduced to 5px. However Widget Width will be determined by layout. what should I do in My Style's drawControl to change widget height ?

A: I've never actually written a QStyle but I would consider it odd if you were supposed to resize anything inside drawControl. I could be wrong on this by a quick review of the documentation would seem to suggest that you would override subElementRect and return a rect based on current width and your preferred height. I assume this would be called by layout activities and would be sorted out by the time drawControl gets called.

A: Do you need the height for the widget to be fixed?  Or just the drawn height to never go past 5 pixels?  For the first, set the height and resize policy on the polish function.  For the second, override the drawing in the QStyle to only use 5 pixels.  The functions that do the drawing generally take rects; you can call the base class's draw with a modified rect if you properly override the appropriate functions.  Unfortunately, it's been years since I've done any QStyle work, so I'm not sure exactly what those functions are.


text:
Q: alternative to a number of if else loop in r I have a table of conditions and coformula to be used based on the condition:
MTR                 CLD                     AF                 PI
AA                  AA                     AB                   0.5/a      (cond1)
AA                  AB                     AB                  0.5/a      (cond2)
AB                  AA                     AB                   0.5 /a     (cond3)
AA                  AA                     AA                    1/a   (cond4)
AB                  AA                     AA                     1/a   (cond5)
BB                  AB                     AA                    1/a  (cond6)
AB                  AB                     AA                    1/(a+b) (cond7)
AB                  AB                     AB                    1/(a+b)  (cond8)

If there is not match of conditions should yield "NA".
 # table of conditions
MTR <- c("AA",  "AA",   "AB",   "AA",   "AB",   "BB",   "AB",   "AB")
CLD <- c("AA",  "AB",   "AA",   "AA",   "AA",   "AB",   "AB",   "AB")
AF <- c("AB",   "AB",   "AB",   "AA",   "AA",   "AA",   "AA",   "AB")
PI <- c("0.5/a",    "0.5/a",    "0.5/a",    "1/a",  "1/a",  "1/a",
      "1/(a+b)",    "1/(a+b)")

Here are two datasets to be applied:
# the dataset to be applied to
dataf <- data.frame (MTR = c("AB", "BB", "AB", "BB", "AB", "AA"),
                     CLD= c("AA", "AB", "AA", "AB", "AB", "AB"),
                     AF = c("AA", "AB", "BB", "AB", "BB", "AB")
                     )

     MTR CLD AF
1  AB  AA AA
2  BB  AB AB
3  AB  AA BB
4  BB  AB AB
5  AB  AB BB
6  AA  AB AB

a = c(0.5, 0.4, 0.3, 0.5, 0.2, 0.4)
mapd <- data.frame(a = a, b = 1-a)

Edits: Following the suggestion down, I can combine the two dataframes into one:
newdf <- data.frame (dataf, mapd)
 MTR CLD AF   a   b
1  AB  AA AA 0.5 0.5
2  BB  AB AB 0.4 0.6
3  AB  AA BB 0.3 0.7
4  BB  AB AB 0.5 0.5
5  AB  AB BB 0.2 0.8
6  AA  AB AB 0.4 0.6

I think that I can solve this by creating if else - but there are many conditions I am not sure that this is only (good) way to do.
 PI = NULL
 if (dataf$MTR = "AA", dataf$CLD = "AA", dataf$AF = "AB") {
                          PI =  0.5/mapd$a } else {
  if (dataf$MTR = "AA", dataf$CLD = "AB", dataf$AF = "AB"){
                          PI =  0.5/mapd$a
                          } else {
         ............. so on

Is there is any alternative to this ?

A: Looks overly complex!
My suggestion would be to make the table of conditions into a data frame with three columns: The first column would be a paste of the columns MTR, CLD, and AF (so a typical entry might be "AB~AA~AB") and the other two columns would be called COEFA and COEFAB which are the coefficient multiplying 1/a and the coefficient multiplying 1/(a+b) in your PI expression... e.g. "0.5/a" would have COEFA = 0.5 and COEFAB = 0 while "1/(a+b)" would have COEFA = 0 and COEFB = 1.
To be clear, condition 1 would be represented in the form MTR_CLD_AF = "AA~AA~AB", COEFA = 0.5, COEFB = 0.
Then to work out which condition is appropriate for each row in dataf, you just need to paste MTR, CLD and AF together, match this up to column MTR_CLD_AF in the conditions dataframe, and thereby extract COEFA and COEFB for that row. The desired value for your PI variable is then COEFA*(1/a) + COEFB*(1/(a+b)).
Let me know if further explanation or code would be helpful :)
Follow up:
Here's a stab at the code I'd use here:
### first, all your object definitions...

MTR <- c("AA",  "AA",   "AB",   "AA",   "AB",   "BB",   "AB",   "AB")
CLD <- c("AA",  "AB",   "AA",   "AA",   "AA",   "AB",   "AB",   "AB")
AF <- c("AB",   "AB",   "AB",   "AA",   "AA",   "AA",   "AA",   "AB")
PI <- c("0.5/a",    "0.5/a",    "0.5/a",    "1/a",  "1/a",  "1/a",
      "1/(a+b)",    "1/(a+b)")

dataf <- data.frame (MTR = c("AB", "BB", "AB", "BB", "AB", "AA"),
                     CLD= c("AA", "AB", "AA", "AB", "AB", "AB"),
                     AF = c("AA", "AB", "BB", "AB", "BB", "AB")
                     )
a = c(0.5, 0.4, 0.3, 0.5, 0.2, 0.4)
mapd <- data.frame(a = a, b = 1-a)

### first create COEFA and COEFAB from PI (could automate but small
### enough to do manually here)

COEFA <- c(0.5, 0.5, 0.5, 1, 1, 1, 0, 0)
COEFAB <- c(0, 0, 0, 0, 0, 0, 1, 1)

### then create conditions data frame as specified in my solution

cond = data.frame(MTR_CLD_AF = paste(MTR,CLD,AF,sep="~"), COEFA, COEFAB,
                  stringsAsFactors=FALSE)

### now put all the data in dataf and mapd into one object alldata to
### keep things neat

alldata = data.frame(MTR = dataf$MTR, CLD = dataf$CLD, AF = dataf$AF,
                     a = mapd$a, b=mapd$b, stringsAsFactors=FALSE)

### now go ahead and get COEFA and COEFB for each row in alldata - first
### do the match up (look in matcond to see this) then copy coef columns
### over to alldata

matcond=cond[match(with(alldata, paste(MTR, CLD, AF, sep="~")),
                   cond$MTR_CLD_AF),]
alldata$COEFA = matcond$COEFA
alldata$COEFAB = matcond$COEFAB

### finally compute COEFA*(1/a) + COEFAB*(1/(a+b)) using the columns of
### alldata, and store the answer in column called PI

alldata$PI = with(alldata, COEFA*(1/a) + COEFAB*(1/(a+b)))

### that's it! as noted elsewhere, the value will be NA if no matching
### condition exists

A: #data.frame with conditions and functions
confun<-data.frame(c1=c("AA","AA","AB"),
                       c2=c("AA","AB","AA"),
                       c3=c("AB","AB","AB"),
                       fun=c("0.5/a","0.5/b","1/(a+b)"))
confun$fun<-as.character(confun$fun)

confun
      c1 c2 c3     fun
    1 AA AA AB   0.5/a
    2 AA AB AB   0.5/b
    3 AB AA AB   1/(a+b)

#data
test<-data.frame(c1=c("AA","AB"),c2=c("AB","AA"),c3=c("AB","AB"),a=c(2,3))
    test$b<-1-test$a

test
  c1 c2 c3 a  b
1 AA AB AB 2 -1
2 AB AA AB 3 -2

fun<-function(c1,c2,c3) as.numeric(rownames(confun[paste(confun$c1,confun$c2,confun$c3)==paste(c1,c2,c3),]))
test$i<-mapply(fun,test$c1,test$c2,test$c3)

fun2<-function(a,b,i) eval(parse(text=confun$fun[i]))

res<-mapply(fun2,test$a,test$b,test$i)

res
[1] -0.5  1.0

quick & dirty


text:
Q: Как зафиксировать AppBarLayout в свёрнутом положении Имеется CoordinatorLayout с вложенным в него AppBarLayout внутри CollapsingToolbarLayout а внутри него toolbar + картинка. Под AppBar находится ViewPager с вложенными фрагментами. ViewPager имеет поведение: appbar_scrolling_view_behavior. И соответственно при прокрутке содержимого фрагментов appbar сворачивается.
<androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@id/bottomNavViewCoreAct"
            android:fitsSystemWindows="true">

        <com.google.android.material.appbar.AppBarLayout
                style="@style/AppBarLayoutSchool"
                android:id="@+id/appBarCoreAct">
            <com.google.android.material.appbar.CollapsingToolbarLayout
                    style="@style/CollapsingToolbar"
                    android:id="@+id/collapsToolbarCoreAct"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed"
                    app:expandedTitleTextAppearance="@style/CollapsingTextAppearance.Inverse"
                    app:contentScrim="?colorPrimary">

                <ImageView
                        android:layout_width="fill_parent"
                        android:layout_height="300dp"
                        android:src="@drawable/london_flat"
                        android:tint="@color/colorWhiteAlfa"
                        android:scaleType="centerCrop"
                        android:contentDescription="@string/service_image_item"
                        android:id="@+id/imgToolbarCoreAct"/>

                <androidx.appcompat.widget.Toolbar
                        style="@style/Toolbar"
                        android:id="@+id/toolbarCoreAct"
                        app:layout_collapseMode="pin"/>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

        <androidx.viewpager.widget.ViewPager
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/viewPagerCore"
                android:layout_below="@+id/appBarCoreAct"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Однако в одном из фрагментов мне необходимо свернуть AppBar и зафиксировать его в таком положении.
val appBarCoreAct = findViewById<AppBarLayout>(R.id.appBarCoreAct)
appBarCoreAct.setExpanded(false)

Код выше просто сворачивает toolbar но он продолжает разворачиваться. Если же установить флаг для CollapsingToolbarLayout
(collapsToolbarCoreAct.layoutParams as AppBarLayout.LayoutParams).scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP

То изображение будет полного размера (примерно на пол экрана). Пробовал при установке флагов изменять размер изображения и делать его невидимым, но в таком случае пропадает title для CollapsingToolbarLayout.
Подскажите как свернуть AppBarLayout и запретить его разворачивание при прокрутке.

A: Помог ответ kris larson из поста англоязычного stack. Для моего случая, во время перехода на целевой фрагмент сделал следующее:
/*разворачиваем toolbar, чтоб изображение view pager не убегало за пределы экрана*/
appBarCoreAct.setExpanded(true)
collapsToolbarCoreAct.visibility = View.GONE //прячем toolbar

...
Получаем искомый отображаемый в данный момент на экране фрагмент и устанавливаем для него pageFragment.view?.isNestedScrollingEnabled = false готово
Однако появляется небольшая проблема. Так как nestedScroll отключен, если на фрагменте есть список то последний элемент не будет помещаться на экране ровно на столько, сколько места занимает toolbar. Можно решить эту проблему - проставив отступ.


text:
Q: Linux solution for schools? The school I'm working for as an administrator requested a system upgrade. Currently we are using a government-suggested Linux distribution called SuliXerver - it would be great, but most of the admin functions have been disabled, and are controlled by the company managing the distro. As there are major issues with it that are ignored by this company, the school board decided to switch to something else.
As our budget is limited, Windows solutions are out of the question. This leaves us with open-source and free software.
I've been looking into education-oriented distros, but the thing is, none provides (by the things I see) the level of comfort for the end-user as SuliXerver did - mostly the unified web interface, which, while being limited, had all needed features (user management, user network access control, email, etc.).
I'm still undecided though about the best choice. The distros I've checked so far:

*

*Debian Edu/Skolelinux - apparently the best choice for us. Supports a grand part of what we need be supported, BUT is limited when it comes to modifying the initial values it is preloaded with - the LDAP schemes, network setup, domain, server name, etc.

*Karoshi Server - seems limited in my opinion, and still not yet ready for prime time. Also less maintained compared to Skolelinux

*ClearOS - while not directly meant for schools, a great deal of the system can be salvaged and slightly modified to work with our setup.

*Zentyal - same as ClearOS but limited functionality in regards of the web interface. Also has better support, and the interface is easier to use.

Is there any other distribution I've missed, that would be a better match for our solution? Due to the limited timeframe I was given to complete the whole transfer (by the end of October I should have a working prototype system, and latest end of December, transition must be done), I do not feel up to the task to write our own solution.
Requirements:

*

*Unified web interface that is easy to use for students, teachers, and admins. Teachers should be able to control the rooms' internet access via proxy settings, modify students' passwords, but not core system settings. Students can change their own password.

*E-mail system - web interface is given (RoundCube or RainLoop), back-end is not yet decided (would like to have Exchange ActiveSync)

*OpenLDAP + Samba for Windows domain login and Documents storage (to store user settings, bookmarks, files). Also automatic assignment of network drives.

*Web server - either Apache or NGINX, running with PHP and MySQL.

*Print server for the offices

*DNS server for local computer name resolution

A: https://www.edubuntu.org/  seems to be popular amongst schools....
here is a list of where it is run:
==> https://wiki.edubuntu.org/Education/UbuntuSchools

A: I personally like Debian very much, but if you are happy with SuliXerver why don't you adapt it to your needs?
If there are admin functions you don't have download them and use those. If it is just a permission problem, change root password with a live CD/USB and you're ready to go.

A: The myskool server is the best solution i have ever encountered..
http://cyberorg.co.in/myscool/
check this out this has been impemented in India and Indonesia also

A: As you are not looking for desktop applications but are more concerned with the administration side - I guess what you are really looking for is an easy management interface?
No matter what distribution you choose, they will all use the standard tools to provide the sundry features you expect.
Are you specifically looking for Linux? The OSX Server does everything that you need, has strong BSD underpinnings, plus I challenge you to find a better out-of-the-box UI experience.
It does not have a per-user license; your only cost would be the physical hardware. It it is only licensed for use on apple hardware; so you are restricted to what you can afford there.  My recommendation would be to go with a couple of mac mini "server edition", that come with two hard drives and OSX Server pre-installed.
I will not pretend that there aren't ways to run it on commodity hardware but that it is a silly risk to take.

A: A french solution, out of the box is "SambaEdu", with a unifies web-interface.
http://wwdeb.crdp.ac-caen.fr/mediase3/
Francois


text:
Q: Imagine if open() method threw exception ignore then proceed to the next loop I am trying to use Imagine to batch make 250x250 thumbnail of more than 90k+ relatively small mobile images. The problem is, when I run a loop,
foreach ($images as $c) {
  $imagine = new Imagine();
  $image = $imagine->open($c);
  $image->resize(new Box(250, 250))->save($outFolder);
}

sometimes, the image is corrupted and the open() method fails, throwing exception:
Unable to open image
vendor/imagine/imagine/lib/Imagine/Gd/Imagine.php
Line: 96
and completely breaks the loop. Is there a way, to check if open failed? something like:
foreach ($images as $c) {
  $imagine = new Imagine();
  $image = $imagine->open($c);
  if ($image) {
     $image->resize(new Box(250, 250))->save($outFolder);
  } else {
     echo 'corrupted:
';
  }
}

Hope somebody can help. or if its not possible, can you suggest a PHP image library that I can pragmatically resize by batch?
Thank you

A: For handling the exception just use try-catch.
From the library documentation

The ImagineInterface::open() method may throw one of the following exceptions:

Imagine\Exception\InvalidArgumentException
Imagine\Exception\RuntimeException

Try it like this:
$imagine = new Imagine(); // Probably no need to instantiate it in every loop
foreach ($images as $c) {
    try {
        $image = $imagine->open($c);
    } catch (\Exception $e) {
        echo 'corrupted:
';
        continue;
    }
    $image->resize(new Box(250, 250))->save($outFolder);
}


text:
Q: Configure Angular to re-evaluate on blur instead of keypress By default, it seems that Angular reevaluates its binding from a particular DOM element (e.g Text Input) to the underlying scope property on keypress or paste - i.e, whenever the value in the text input changes.
Is it possible to make it only refresh the binding on blur? I.e. do something like:

        <input type="text" ng-model="base" ng-update-type="blur"/>
        <input type="text" />

Take the following JS fiddle:
http://jsfiddle.net/f76dW/
I would like the doubled span to only update when I move the focus out of the first input

A: You can use ng-blur and a dummy variable (base_ in this case) to achieve that effect: http://jsfiddle.net/f76dW/1/
Template
    <input type="text" ng-model="base_" ng-blur="updateBase()" />

Controller
function ctrl($scope) {

    $scope.base = $scope.base_ = 1000;

    $scope.updateBase = function () {
        $scope.base = $scope.base_;
    };

    $scope.doubled = function() {
        return $scope.base * 2;
    }
}

A: Use ng-model options. Using a blur hack is tricky, because a blur may not be a change.
<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options={updateOn: 'blur'}"/>


text:
Q: Query Activity to Return Number of Opens and/or Number of Clicks I am trying to pull data about a sent email into a data extension using a SQL query in the Query Activity section.
The below is my query which pulls back all information about an email using a combination of the Sent and Job objects.
However I want to pull back further information in the form of Total Clicks for this email and Total Opens for this email. The information is all available in the "My Tracking" section of the email studio I just cant seem to get the correct query.
select
j.JobID,
a.Id as AccountId,
s.subscriberKey,
s.EventDate as SentDateTime,
j.EmailID,
j.emailName,
j.EmailSubject,
s.EventDate as ModifyDateTime,
'ID_' + a.Id + '_' + convert(nvarchar(50), j.JobID) as RecordId,
s.TriggererSendDefinitionObjectID as SendID

from _sent s
join _job j on j.JobID = s.JobId
join Account_Salesforce a on a.PersonContactId = s.subscriberKey

where s.EventDate > dateadd(d, -50, getdate())

A: You need to use Open and Click data views and count the clicks/opens grouped by JobID. Instead of joining for this you need to use sub-queries, that use the count-function. These sub-queries are queries inside your query.
The subquery could look like this and would be used as a "column" of your query:
(SELECT
    count(SubscriberKey)
FROM
    _open o
WHERE
    o.JobID = s.JobId
GROUP BY JobID) as OpenCount

This is basic SQL however and not specific to Salesforce Marketing Cloud. So SQL specific questions could be asked on StackOverflow. Marketing Cloud SQL is based on Microsoft SQL Server 2005, so anything possible there should also work.
Documentation articles:

*

*Data View: Open

*Data View: Click


text:
Q: Failed to start, ddev-router failed to become ready, duplicate upstream I previously had a local drupal site working in ddev, then somehow the code got deleted with the ddev container remaining configured.
When I attempted to rebuild my local site, I set it up with a local. subdomain by setting the following in .ddev/config.yaml:
additional_hostnames:
- local.mysitename

Somehow in the process of re-configuring ddev I ended up with two ddev containers with the same name and the following error when I try to start the container.
Failed to start mysitename: ddev-router failed to become ready: logOutput=2019/03/19 22:29:32 [emerg] 15415#15415: duplicate upstream "local.mysitename.ddev.local-80" in /etc/nginx/conf.d/default.conf:198
nginx: [emerg] duplicate upstream "local.mysitename.ddev.local-80" in /etc/nginx/conf.d/default.conf:198
nginx: configuration file /etc/nginx/nginx.conf test failed, err=container /ddev-router unhealthy: 2019/03/19 22:29:32 [emerg] 15415#15415: duplicate upstream "local.mysitename.ddev.local-80" in /etc/nginx/conf.d/default.conf:198
nginx: [emerg] duplicate upstream "local.mysitename.ddev.local-80" in /etc/nginx/conf.d/default.conf:198
nginx: configuration file /etc/nginx/nginx.conf test failed

Removing the container from ddev and re-configuring it doesn't seem to help.
How can I remove both containers from ddev for good, or how do I at least resolve the error above?

A: Not sure what the official solution is, but I got it "fixed" by:

*

*Deleted the problem docker containers

*

*Ran docker ps -a to list all docker containers

*Ran docker rm -f ID where ID is the IDs of the docker containers named:

*

*ddev-mysitename-web

*ddev-mysitename-dba

*ddev-mysitename-db

*Reset Docker to factory defaults

*Re-ran the ddev installer (Note I am on Windows btw)

*Run ddev start on the site

Not ideal but what I did above is what fixed my issue.
Note: This will wipe the ddev DBs for all of your local sites

A: Removing the ddev-router container with ddev poweroff, then restarting DDEV to recreate the container worked for me.


text:
Q: Weird behavior, elements move when slider scrolls Today i got the following site from another designer, he makes the frontend, and i add the functionality to all of the websites.
There is a weird issue going on and it's happening only in Google Chrome, i have tried a lot of things but i cannot find the cause of it.
The website is made using bootstrap 3
Here is the link to the site and the section that is being affected.
Go to site
What's happening is that when the slider with the images above moves an element (right now is bxslider plugin but it was before Bootstrap own slider, and even caroufredsel, same issue) the images on the container below, and others move a bit from side to side.
I have no idea what is causing it, I wonder if any of you guys can help me.
Cheers

A: You need to set useCSS to false to solve this issue.

A: Somehow i managed to track the issue, probably something related to the bxslider, (since it's the only control on which this is happening) so i'll answer here for future references and if someone else runs on the same thing.
What was causing the movement on the images below was the boostrap class .block when added the atribute margin:0 auto; or text-align:center to the images within the parent container inside block
Removed that and the problem is gone.


text:
Q: How to select correct gradle version in React Native I never upgraded my gradle since 4.3 and now i decided to upgrade my libs. Firstly i updated my react native version to 0.63. And now thinking to upgrade gradle as well. But cannot decide which version to upgrade?
Is there any docs for that, or always it should be updated to latest version?
EDIT: Got these errors below while updating


text:
Q: Bukkit - Change the speed of a projectile I'm pretty new to bukkit plugin developing and I was wondering how I would change the speed of a snowball/any other projectile. In my code, when a player interacts with a certain object it will fire a snowball but I need to change the speed of it. Help would be appreciated.
Thanks
Code:
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
    Player player = event.getPlayer();
    if (!(event.getAction() == Action.RIGHT_CLICK_AIR)) return;
    if (!(event.getItem().getType() == Material.BLAZE_ROD)) return;
    Snowball snowball = player.launchProjectile(Snowball.class);
}

A: Right now you are only simply launching the Snowball projectile. You have to add velocity to the object to change its speed. This is done by editing the object itself.
Here's the basic outline that you should use. I have no means to test this, but it should help to point you in the right direction.
Snowball snowball = player.launchProjectile(Snowball.class);

// Get vectors
Vector i = target.getLocation().toVector();
Vector j = snowball.getLocation().toVector();

// Perform the subtraction, then normalize
Vector r = i.subtract(j);
Vector v = r.normalize();

// then, actually set the speed, in this case, by a magnitude of four
Vector velocity = v.multiply(4);

// Then, set the velocity of the snowball but updating the 'default' velocity of the snowball
snowball.setVelocity(snowball.setVelocity(velocity));

This could be condensed by writing the compound expression:
Snowball snowball = player.launchProjectile(Snowball.class);

Vector velocity = (target.getLocation().toVector().subtract(snowball.getLocation().toVector()).normalize()).multiply(4);
snowball.setVelocity(snowball.setVelocity(velocity));

Hope this helps!


text:
Q: 80s/90s book where boy stumbles on game where aliens gamble their planets I don't remember much about it other than the setting. It's about a boy who one night stumbles upon some different alien races playing a game in which their civilizations will end if they lose. He gets involved in the game somehow and is hunted.

A: First thing that pops to mind is Interstellar Pig, by William Sleator.
From the plot summary:

When Zena, Manny, and Joe move into the cinder-block cottage next door, Barney is intrigued by their glamorous, exotic lifestyle. His fascination grows when Zena introduces Barney to their favorite pastime: Interstellar Pig, a board game in which the key objective is to finish the game with the Piggy card in hand.
Zena quickly briefs him on the rules: each player picks their character from a box of cards depicting different aliens. Every alien race has their own strengths, weaknesses, and IRSC (Interstellar Relative Sapience Code, with lower numbers favorable). When the time runs out, every home planet will be obliterated except the one belonging to the holder of the Piggy. Barney is amazed when the neighbors keep choosing the same character cards: Joe repeatedly picks water-breathing Jrlb; Zena always chooses Zulma, an arachnoid nymph; and Manny always picks Moyna, an octopus-like gas bag.

A: Could this be The Homeward Bounders, by Dianna Wynne Jones? From Wikipedia:

Twelve-year-old Jamie discovers a strange place in his hometown in which mysterious and demonic entities, known only as Them, are playing a board game with the entire world. Upon his discovering Them, They are forced to make Jamie a Homeward Bounder; this means he must constantly travel from world to world until he finds his home again.


text:
Q: OpenGL: GL_FRAMEBUFFER_UNSUPPORTED on specific combinations of framebuffer attachments Im trying to attach multiple targets to a framebuffer object. I have the following problem:
There is no error, when using float texture attachments and a depth attachment.
There is also no error, when using float texture attachments and integer texture attachments. Although these combinations work, I cant use float, integer and depth attachments at the same time. This results in a GL_FRAMEBUFFER_UNSUPPORTED status.
this is my code:
//working:
Framebuffer fb = Framebuffer(
    1280,720,
    {
        //AttachmentInfo(GL_DEPTH_COMPONENT16,GL_DEPTH_ATTACHMENT),
        AttachmentInfo(GL_RG32F,GL_COLOR_ATTACHMENT0),
        AttachmentInfo(GL_RGB16UI,GL_COLOR_ATTACHMENT1),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT2),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT3),
        AttachmentInfo(GL_RGBA16F,GL_COLOR_ATTACHMENT4),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT5),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT6),
    }
);

//working:
Framebuffer fb = Framebuffer(
    1280,720,
    {
        AttachmentInfo(GL_DEPTH_COMPONENT16,GL_DEPTH_ATTACHMENT),
        AttachmentInfo(GL_RG32F,GL_COLOR_ATTACHMENT0),
        //AttachmentInfo(GL_RGB16UI,GL_COLOR_ATTACHMENT1),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT2),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT3),
        AttachmentInfo(GL_RGBA16F,GL_COLOR_ATTACHMENT4),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT5),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT6),
    }
);

//NOT working:
Framebuffer fb = Framebuffer(
    1280,720,
    {
        AttachmentInfo(GL_DEPTH_COMPONENT16,GL_DEPTH_ATTACHMENT),
        AttachmentInfo(GL_RG32F,GL_COLOR_ATTACHMENT0),
        AttachmentInfo(GL_RGB16UI,GL_COLOR_ATTACHMENT1),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT2),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT3),
        AttachmentInfo(GL_RGBA16F,GL_COLOR_ATTACHMENT4),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT5),
        AttachmentInfo(GL_RGB32F,GL_COLOR_ATTACHMENT6),
    }
);

Note: I only get this error when using my NVidia GTX 970 graphics card. On a bit older ATI card no error occured.
I use glbinding to call glGetError after every gl* function call, so I know, that no other error occured.
this is my constructor code for the Framebuffer object:
Framebuffer::Framebuffer(uint width,uint height,initializer_list<AttachmentInfo> attachments)
:width(width),height(height)
{
    glGenFramebuffers(1,&fbID);
    glBindFramebuffer(GL_FRAMEBUFFER,fbID);

    if(std::none_of(attachments.begin(),attachments.end(),[](const AttachmentInfo& a){
        return a.attachment == GL_DEPTH_ATTACHMENT;
    })){
        //depth test needs either a depth renderbuffer or depth attachment.
        unsigned int rboID=0;
        glGenRenderbuffers(1, &rboID);
        glBindRenderbuffer(GL_RENDERBUFFER, rboID);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
        glBindRenderbuffer(GL_RENDERBUFFER, 0);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,rboID);
    }

    vector<GLenum> buffers;
    glActiveTexture(GL_TEXTURE0);

    for(AttachmentInfo attachment:attachments){
        GLuint tID;
        glGenTextures(1, &tID);
        glBindTexture(GL_TEXTURE_2D,tID);

        GLint param;
        glGetInternalformativ(GL_TEXTURE_2D, attachment.internalFormat, GL_FRAMEBUFFER_RENDERABLE, 1, &param);

        if(param != GL_FULL_SUPPORT){
            _log(WARNING,"Internal format " << attachment.internalFormat << " support is " << GLenum(param) << ".");
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_LINEAR));
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_LINEAR));
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLint(GL_CLAMP_TO_EDGE));
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GLint(GL_CLAMP_TO_EDGE));

        if(attachment.attachment == GL_DEPTH_ATTACHMENT){
              glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GLint(GL_COMPARE_REF_TO_TEXTURE));
              glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GLint(GL_LESS));
        }
        glTexStorage2D(GL_TEXTURE_2D,1,attachment.internalFormat,width,height);
        glFramebufferTexture(GL_FRAMEBUFFER, attachment.attachment, tID, 0);

        if(Tools::startsWith(glbinding::Meta::getString(attachment.attachment),"GL_COLOR_ATTACHMENT")){
            buffers.push_back(attachment.attachment);
        }
        texMap[attachment.attachment]=new Texture(tID,GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D,0);
    }
    if(buffers.empty()){
        buffers.push_back(GL_NONE);
    }
    glDrawBuffers(buffers.size(),buffers.data());

    GLenum error=glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(error != GL_FRAMEBUFFER_COMPLETE){
        _log(ERROR,"Framebuffer error: " << error);
    }
    unbind();
}

Im really out of ideas what I can do to make it work...

A:
Im really out of ideas what I can do to make it work...

Your OpenGL implementation tells you, that the configuration you choose is not supported. You have to accept that. The OpenGL specification does not require that particular combination of formats to be supported by all implementation, so if you want to program to be portable and robust, if you get a GL_FRAMEBUFFER_UNSUPPORTED error you'll have to gradually step down your format requirements until a workable combination is found.
A very good hint on what's supported is enumerating all the FBConfigs supported for creating a OpenGL context; usually this is a subset of the permissible FBO configurations.

A: In case anyone else runs across this question as I did. The exact combination of supported formats vary by OpenGL implementation, but there is a set of formats that any implementation must support. If you stick to those, you won't have to worry about portability. The requirements are described in the OpenGL wiki on Framebuffer Completeness and Required Image Formats.


text:
Q: Mechanism for Save/Load+Undo/Redo with minimum boilerplate I want to make an app where a user can edit a diagram (for example), which would provide the standard mechanisms of: Save, Load, Undo, and Redo.
A simple way to do it is to have classes for the diagram and for the various shapes in it, which implement serialization via save and load methods, and where all methods to edit them return UndoableActions that can be added to an UndoManager which calls their perform method and adds them to an undo stack.
The problem with the simple way described above is that it requires a lot of error-prone boilerplate work.
I know that the serialization (save/load) part of the work can be solved by using something like Google's Protocol Buffers or Apache Thrift, which generates the boiler-plate serialization code for you, but it doesn't solve the undo+redo problem. I know that for Objective C and Swift, Apple provides Core Data which does solve serialization + undo, but I'm not familiar with anything similar for C++.
Is there a good way non-error-prone to solve save+load+undo+redo with little boilerplate?

A: Two reasonable approaches to this problem are implemented in the frameworks Flip and ODB.
Code-generation / ODB
With ODB you need to add #pragma declarations to your code, and have it's tool generate methods that you use for save/load and for editing the model, like so:
#pragma db object
class person
{
public:
    void setName (string);
    string getName();
    ...
private:
    friend class odb::access;
    person () {}

    #pragma db id
    string email_;

    string name_;
 };

Where the accessors declared in the class are auto-generated by ODB so that all changes to the model can get captured and undo-transactions may be made for them.
Reflection with minimal boilerplate / Flip
Unlike ODB, Flip doesn't generate C++ code for you, but rather it requires your program to call Model::declare to re-declare your structures like so:
class Song : public flip::Object
{
public:
    static void declare ();
    flip::Float tempo;
    flip::Array <Track> tracks;
};

void Song::declare ()
{
    Model::declare <Song> ()
    .name ("acme.product.Song")
    .member <flip::Float, &Song::tempo> ("tempo");
    .member <flip::Array <Track>, &Song::tracks> ("tracks");
}

int main()
{
    Song::declare();
    ...
}

With the structured declared like so, flip::Object's constructor can initialize all the fields so that they can point to the undo stack, and all the edits on them are recorded. It also has a list of all the members so that flip::Object can implement the serialization for you.

A:
The problem with the simple way described above is that it requires a lot of error-prone boilerplate work.

I would say that the actual problem is that your undo/redo logic is part of a component, that should ship only a bunch of data as a position, a content and so on.
A common OOP way to decouple the undo/redo logic from the data is the command design pattern.
The basic idea is that all the user interactions are converted to commands and those commands are executed on the diagram itself. They contain all the information required to perform an operation and to rollback it, as long as you maintain a sorted list of commands and undo/redo them in order (that is usually the user expectation).
Another common OOP pattern that can help you either to design a custom serialization utility or to use the most common ones is the visitor design pattern.
Here the basic idea is that your diagram should not care about the kind of components it contains. Whenever you want to serialize it, you provide a serializer and the components promote themselves to the right type when queried (see double dispatching for further details on this technique).
That being said, a minimal example is worth more than a thousand words:
#include <memory>
#include <stack>
#include <vector>
#include <utility>
#include <iostream>
#include <algorithm>
#include <string>

struct Serializer;

struct Part {
    virtual void accept(Serializer &) = 0;
    virtual void draw() = 0;
};

struct Node: Part {
    void accept(Serializer &serializer) override;
    void draw() override;
    std::string label;
    unsigned int x;
    unsigned int y;
};

struct Link: Part {
    void accept(Serializer &serializer) override;
    void draw() override;
    std::weak_ptr<Node> from;
    std::weak_ptr<Node> to;
};

struct Serializer {
    void visit(Node &node) {
        std::cout << "serializing node " << node.label << " - x: " << node.x << ", y: " << node.y << std::endl;
    }

    void visit(Link &link) {
        auto pfrom = link.from.lock();
        auto pto = link.to.lock();
       std::cout << "serializing link between " << (pfrom ? pfrom->label : "-none-") << " and " << (pto ? pto->label : "-none-") << std::endl;
    }
};

void Node::accept(Serializer &serializer) {
    serializer.visit(*this);
}

void Node::draw() {
    std::cout << "drawing node " << label << " - x: " << x << ", y: " << y << std::endl;
}

void Link::accept(Serializer &serializer) {
    serializer.visit(*this);
}

void Link::draw() {
    auto pfrom = from.lock();
    auto pto = to.lock();

    std::cout << "drawing link between " << (pfrom ? pfrom->label : "-none-") << " and " << (pto ? pto->label : "-none-") << std::endl;
}

struct TreeDiagram;

struct Command {
    virtual void execute(TreeDiagram &) = 0;
    virtual void undo(TreeDiagram &) = 0;
};

struct TreeDiagram {
    std::vector<std::shared_ptr<Part>> parts;
    std::stack<std::unique_ptr<Command>> commands;

    void execute(std::unique_ptr<Command> command) {
        command->execute(*this);
        commands.push(std::move(command));
    }

    void undo() {
        if(!commands.empty()) {
            commands.top()->undo(*this);
            commands.pop();
        }
    }

    void draw() {
        std::cout << "draw..." << std::endl;
        for(auto &part: parts) {
            part->draw();
        }
    }

    void serialize(Serializer &serializer) {
        std::cout << "serialize..." << std::endl;
        for(auto &part: parts) {
            part->accept(serializer);
        }
    }
};

struct AddNode: Command {
    AddNode(std::string label, unsigned int x, unsigned int y):
        label{label}, x{x}, y{y}, node{std::make_shared<Node>()}
    {
        node->label = label;
        node->x = x;
        node->y = y;
    }

    void execute(TreeDiagram &diagram) override {
        diagram.parts.push_back(node);
    }

    void undo(TreeDiagram &diagram) override {
        auto &parts = diagram.parts;
        parts.erase(std::remove(parts.begin(), parts.end(), node), parts.end());
    }

    std::string label;
    unsigned int x;
    unsigned int y;
    std::shared_ptr<Node> node;
};

struct AddLink: Command {
    AddLink(std::shared_ptr<Node> from, std::shared_ptr<Node> to):
        link{std::make_shared<Link>()}
    {
        link->from = from;
        link->to = to;
    }

    void execute(TreeDiagram &diagram) override {
        diagram.parts.push_back(link);
    }

    void undo(TreeDiagram &diagram) override {
        auto &parts = diagram.parts;
        parts.erase(std::remove(parts.begin(), parts.end(), link), parts.end());
    }

    std::shared_ptr<Link> link;
};

struct MoveNode: Command {
    MoveNode(unsigned int x, unsigned int y, std::shared_ptr<Node> node):
        px{node->x}, py{node->y}, x{x}, y{y}, node{node}
    {}

    void execute(TreeDiagram &) override {
        node->x = x;
        node->y = y;
    }

    void undo(TreeDiagram &) override {
        node->x = px;
        node->y = py;
    }

    unsigned int px;
    unsigned int py;
    unsigned int x;
    unsigned int y;
    std::shared_ptr<Node> node;
};

int main() {
    TreeDiagram diagram;
    Serializer serializer;

    auto addNode1 = std::make_unique<AddNode>("foo", 0, 0);
    auto addNode2 = std::make_unique<AddNode>("bar", 100, 50);
    auto moveNode2 = std::make_unique<MoveNode>(10, 10, addNode2->node);
    auto addLink = std::make_unique<AddLink>(addNode1->node, addNode2->node);

    diagram.serialize(serializer);
    diagram.execute(std::move(addNode1));
    diagram.execute(std::move(addNode2));
    diagram.execute(std::move(addLink));
    diagram.serialize(serializer);
    diagram.execute(std::move(moveNode2));
    diagram.draw();
    diagram.undo();
    diagram.undo();
    diagram.serialize(serializer);
}

I've not implemented the redo action and the code is far from being a production-ready piece of software, but it acts quite well as a starting point from which to create something more complex.
As you can see, the goal is to create a tree diagram that contains both nodes an links. A component contains a bunch of data and knows how to draw itself. Moreover, as anticipated, a component accepts a serializer in case you want to write it down on a file or whatever.
All the logic is contained in the so called commands. In the example there are three commands: add node, add link and move node. Neither the diagram nor the components know anything about what's going on under the hood. All what the diagram knows is that it's executing a set of commands and those commands can be executed back a step at the time.
A more complex undo/redo system can contain a circular buffer of commands and a few indexes that indicate the one to substitute with the next one, the one valid when going forth and the one valid when going back.
It's quite easy to implement indeed.
This approach will help you decoupling the logic from the data and it's quite common when dealing with user interfaces.
To be honest, it's not something that came up suddenly to my mind. I found something similar while looking at how open-source software solved the issue and I've used it a few years ago in a software of mine. The resulting code is really easy to maintain.

A: Another approach you might want to consider is working with inmutable data structures and objects. Then, the undo/redo stack can be implemented as a stack of versions of the scene/diagram/document. Undo() replaces the current version with an older version from the stack, and so on. Because all data is inmutable, you can keep references instead of copies, so it is fast and (relatively) cheap.
Pros:

*

*simple undo/redo

*multithread-friendly

*clean separation of "structure" and transient state (e.g. current selection)

*may simplify serialization

*caching/memoization/precomputation-friendly (e.g. bounding-box, gpu buffers)

Cons:

*

*consumes a bit more memory

*forces separation of "structure" and transient state

*probably more difficult: for example, for a typical tree-like scenegraph, to change a node you would also need to change all the nodes along the path to the root; the old and new versions can share the rest of the nodes

A:
The problem with the simple way described above is that it requires a lot of error-prone boilerplate work.

I am not convinced that this is the case. Your approach sounds reasonable and using Modern C++ features and abstractions you can implement a safe and elegant interface for it.
For starters, you could use std::variant as a sum type for "undoable actions" - this will give you a type-safe tagged union for every action. (Consider using boost::variant or other implementations that can be easily found on Google if you do not have access to C++17). Example:
namespace action
{
    // User dragged the shape to a separate position.
    struct move_shape
    {
        shape_id _id;
        offset _offset;
    };

    // User changed the color of a shape.
    struct change_shape_color
    {
        shape_id _id;
        color _previous;
        color _new;
    };

    // ...more actions...
}

using undoable_action = std::variant<
    action::move_shape,
    action::change_shape_color,
    // ...
>;

Now that you have a sum type for all your possible "undoable actions", you can define undo behavior by using pattern matching. I wrote two articles on variant "pattern matching" by overloading lambdas that you could find interesting:

*

*"visiting variants using lambdas - part 1"

*"visiting variants using lambdas - part 2"
Here's an example of how your undo function could look like:
void undo()
{
    auto action = undo_stack.pop_and_get();
    match(action, [&shapes](const move_shape& y)
                  {
                      // Revert shape movement.
                      shapes[y._id].move(-y._offset);
                  },
                  [&shapes](const change_shape_color& y)
                  {
                      // Revert shape color change.
                      shapes[y._id].set_color(y._previous);
                  },
                  [](auto)
                  {
                      // Produce a compile-time error.
                      struct undo_not_implemented;
                      undo_not_implemented{};
                  });
}

If every branch of match gets large, it could be moved to its own function for readability. Trying to instantiate undo_not_implemented or using a dependent static_assert is also a good idea: a compile-time error will be produced if you forget to implement behavior for a specific "undoable action".
That's pretty much it! If you want to save the undo_stack so that the history of actions is preserved in saved documents, you can implement a auto serialize(const undoable_action&) that, again, uses pattern matching to serialize the various actions. You could then implement a deserialize function that repopulates the undo_stack on file load.
If you find implementing serialization/deserialization for every action too tedious, consider using BOOST_HANA_DEFINE_STRUCT or similar solutions to automatically generate serialization/deserialization code.
Since you're concerned about battery and performance, I would also like to mention that using std::variant or similar tagged union constructs is on average faster and more lightweight compared to polymorphic hierarchies, as heap allocation is not required and as there is no run-time virtual dispatch.

About redo functionality: you could have a redo_stack and implement an auto invert(const undoable_action&) function that inverts the behavior of an action. Example:
void undo()
{
    auto action = undo_stack.pop_and_get();
    match(action, [&](const move_shape& y)
                  {
                      // Revert shape movement.
                      shapes[y._id].move(-y._offset);
                      redo_stack.push(invert(y));
                  },
                  // ...

auto invert(const undoable_action& x)
{
    return match(x, [&](move_shape y)
                {
                    y._offset *= -1;
                    return y;
                },
                // ...

If you follow this pattern, you can implement redo in terms of undo! Simply call undo by popping from the redo_stack instead of the undo_stack: since you "inverted" the actions it will perform the desired operation.

EDIT: here's a minimal wandbox example that implements a match function that takes in a variant and returns a variant.

*

*The example uses boost::hana::overload to generate the visitor.

*The visitor is wrapped in a lambda f that unifies the return type to the type of the variant: this is necessary as std::visit requires that the visitor always returns the same type.

*

*If returning a type which is different from the variant is desirable, std::common_type_t could be used, otherwise the user could explicitly specify it as the first template parameter of match.

A: Assuming that you're calling save() on a temporary file for each edit of the  diagram (even if user doesn't explicitly call the save action) and that you undo only the latest action, you can do as follows:
LastDiagram load(const std::string &path)
{
  /* Check for valid path (e.g. boost::filesystem here) */
  if(!found)
  {
    throw std::runtime_exception{"No diagram found"};
  }
  //read LastDiagram
  return LastDiagram;
}
LastDiagram undoLastAction()
{
    return loadLastDiagram("/tmp/tmp_diagram_file");
}

and in your main app you handle the exception if thrown. In case you want to allow more undos, then you should think to a solution like sqlite or a tmp file with more entries.
If performance in time and space are issues due large diagrams, think to implement some strategy like keeping an incremental difference for each element of a diagram in a std::vector (limit it to 3/5 if objects are big) and call the renderer with the current statuses. I'm not an OpenGL expert, but I think it's the way it's done there. Actually you could 'steal' this strategy from game development best practices, or generally graphics related ones.
One of those strategies could be something like this:
A structure for efficient update, incremental redisplay and undo in graphical editors


text:
Q: Chrome extension that replaces images with other images how can I do a Chrome extension that replaces images with other images?
Here's my manifest.json code so far:
{
  "name": "HaramB",
  "version": "69.0.420.666",
  "manifest_version": 2,
  "description": "This is HaramB's own extension!",
  "browser_action": {
    "default_icon": "images/icon.png",
    "default_popup": "popup.html",
    "default_title": "HaramB"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ],
  "icons": {
    "128": "images/icon.png"
  },
  "web_accessible_resources": [
    "images/nicolas.jpg"
  ],
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["onPage.js"],
    "css": ["onPage.css"]
  }]
}

And here's my onPage.js code:
var picture = "images/nicolas.jpg";
document.getElementsByTagName("img").setAttribute("src", picture);

Dont't care about the popup.html or the onPage.css files.
It's the onPage.js file i want  it to do it with, if it's not possible, tell me.

A: document.getElementsByTagName() returns an Array of elements. This means you need to loop through the array and call the methods you want on them individually, like so:
var picture = "images/nicolas.jpg",
    images = document.getElementsByTagName("img");

for (var i = 0; i < images.length; i++) {
    images[i].setAttribute("src", picture);
};

Note: it is preferable to use images[i].src = ... to using setAttribute as detailed in this question


text:
Q: RegEx validation? I am having some issues validating my form with RegEx, fname, lname are text only but upon testing it  does not work when I enter the regex, almost like it's not reading it on the form I get the same alert over and over as if the field is empty or filled in wrong.  Any help would be appreciated!
function validateForm(){

    var name_value =  document.getElementById("name")
    var flname = (/^[a-zA-Z]$/)

    if (!document.myForm.fname.value.match('/^[a-zA-Z]*$/') ) {

        alert("Please fill in your First name!");
        return false;
    }

    if (!document.myForm.lname.value.match('/^[a-zA-Z]*$/')) {

        alert("Please fill in your Last name!");
        return false;
    }

A: Use test function of RegExp instance and don't use strings, unless of course in RegExp constructor. BTW, you can add required attribute to make things hassle-free.
function validateForm() {
    var name_value = document.getElementById("name"), regx  = /^[a-zA-Z]$/;
    if (!regx.test(document.myForm.fname.value)) {
        alert("Please fill in your First name!");
        return false;
    }
    if (!regx.test(document.myForm.lname.value)) {
        alert("Please fill in your Last name!");
        return false;
    }
}

A: You can use HTML5 validation:

<form>
  <input id="fname" required pattern="[a-zA-Z]+" />
  <!-- Note that you can't actually submit since it's in a stack snippet -->
  <button type="submit">Submit!</button>
</form>

This will automatically tell the user that the input is invalid if it is
blank or doesn't match the regex: /[a-zA-Z]+.


text:
Q: Zend_Router_Regex and additional parameter I have no idea how realize it.
I have this router
$route = new Zend_Controller_Router_Route_Regex(
                    'category/([-\w]+)(?:/(\d+))?',
                    array('module' => 'dynamic', 'controller' => 'index', 'action' => 'show-category'),
                    array(1 => 'category', 2 => 'pageNumber'),
                    'category/%s/%d'
    );

$router->addRoute('dynamic-categories', $route);

Assembled url in view will be /category/news/1 by using $this->url(...) helper. I want that my first page of news will be /category/news. Should I use other route to do it or use router chaining. I'm frustrated. Thank you for help.

A: You can use Zend_Controller_Router_Route for straight forward mapping:
new Zend_Controller_Router_Route(
    '/category/:category/:page',
    array(
        'module' => 'dynamic',
        'controller' => 'index',
        'action' => 'show-category',
        'category' => 'news',
        'page' => 1
    )
)

Will match /category/, /category/news/, /category/othercategory or /category/news/4 (examples only of course).


text:
Q: Making CAReplicator display horizontally I was wondering if there was a way to take the CAReplicator, which in my use case creates two camera previews stacked on top of one another, and instead render these two horizontally. My ViewController:
import UIKit
import AVFoundation

class ViewController: UIViewController {

    let captureSession = AVCaptureSession()
    var previewLayer:AVCaptureVideoPreviewLayer!

    var replicatorLayer = CAReplicatorLayer()

    var captureDevice:AVCaptureDevice!

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareCamera()
    }

    func prepareCamera(){
        captureSession.sessionPreset = AVCaptureSession.Preset.photo

        let availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
        captureDevice = availableDevices.first
        beginSession()

    }

    func beginSession(){
        do {
            let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
            captureSession.addInput(captureDeviceInput)
        } catch {
            print(error.localizedDescription)
        }

        let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.previewLayer = previewLayer
        self.previewLayer.videoGravity = .resizeAspectFill
        self.previewLayer.frame = self.view.bounds//CGRect(x: 0.0, y: 0.0, width: view.bounds.size.width, height: view.bounds.size.height / 2)

        let replicatorInstances = 2

        replicatorLayer.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: CGFloat(view.bounds.size.height / CGFloat(replicatorInstances)))
        replicatorLayer.instanceCount = replicatorInstances
        replicatorLayer.instanceTransform = CATransform3DMakeTranslation(0.0, view.bounds.size.height / CGFloat(replicatorInstances), 0.0)
        replicatorLayer.addSublayer(previewLayer)
        self.view.layer.addSublayer(replicatorLayer)
        captureSession.startRunning()

        let dataOutput =  AVCaptureVideoDataOutput()
        dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)] as [String : Any]
        dataOutput.alwaysDiscardsLateVideoFrames = true

        if captureSession.canAddOutput(dataOutput) {
            captureSession.addOutput(dataOutput)
        }

        captureSession.commitConfiguration()

        let queue = DispatchQueue(label: "clockworksciencce")
        dataOutput.setSampleBufferDelegate(self as? AVCaptureVideoDataOutputSampleBufferDelegate, queue: queue)

    }

    private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) {

        layer.videoOrientation = orientation

        previewLayer.frame = self.view.bounds

    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if let connection =  self.previewLayer?.connection  {

            let currentDevice: UIDevice = UIDevice.current

            let orientation: UIDeviceOrientation = currentDevice.orientation

            let previewLayerConnection : AVCaptureConnection = connection

            if previewLayerConnection.isVideoOrientationSupported {

                switch (orientation) {
                case .portrait: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)

                    break

                case .landscapeRight: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft)

                    break

                case .landscapeLeft: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight)

                    break

                case .portraitUpsideDown: updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown)

                    break

                default: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)

                    break
                }
            }
        }
    }

}

Right now this displays two camera previews stacked vertically, I want to side-by-side, such that, when I turn the device sideways, they fill the screen (one preview on the left, the other on the right).

A: It's as simple as changing the line
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(0.0, view.bounds.size.height / CGFloat(replicatorInstances), 0.0)

to
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(view.bounds.size.height / CGFloat(replicatorInstances), 0.0, 0.0)


text:
Q: (Angular) insert an object to json array I am trying to add new item to roleList json array.
I have tried push / concat but it does not change the roleList array.
Any way to solve the issue?
// The javascript :

function RoleListCtrl($scope)
{
    $('#myTab a[href="#role"]').tab('show');

    $scope.newCompanyName ="";
    $scope.newPosition="";

    $scope.addRole = function()
    {
        var newRole = new function() {
            this.companyName = $scope.newCompanyName;
            this.position    = $scope.newPosition;
            this.id          = '';
        }

        alert("test :"+newRole.companyName);

        $scope.roleList = $scope.roleList.push(newRole);
        // I have also tried this :   $scope.roleList = $scope.roleList.concat(newRole);
    }

    $scope.roleList = [
        {"companyName": "Company 01", "id":"1", "position": "CEO"},
        {"companyName": "Company 02", "id":"2", "position": "Board of Director"},
        {"companyName": "Company 01", "id":"1", "position": "CEO"},
        {"companyName": "Company 02", "id":"2", "position": "Board of Director"}

    ];
}

Below is the button that called the addRole() :
<form class="form-horizontal">

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Role

            Company Name

                <input type="text" id="coyName" ng-model="newCompanyName" placeholder="Company Name">

            Role

                <input type="text" id="newRole" ng-model="newPosition" placeholder="Role">

        Close
        Save changes

</form>

                    Add New Role

                            company name
                            position
                            action

                            {{eachRole.companyName}}
                            {{eachRole.position}}

                                <button ng-click="deleteRole($index)">delete</button>

A: var currentList = $scope.roleList;
var newList = currentList.concat(newRoleArray);
$scope.roleList = newList;

A: This line is your problem:
$scope.roleList = $scope.roleList.push(newRole);

When you call push, it return the length (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push). You're essentially pushing the new Role into it and then replacing roleList with the length of the array, losing the array.

A: you can directly push your object by making object with key value pair.
$scope.addRole = function(){
var newRole = {
    "companyName":$scope.newCompanyName,
    "id":"",
    "position":$scope.newPosition
 }
$scope.roleList.push(newRole);
}


text:
Q: Leader mapping to toggle a vim setting There are several Vim settings I love, but are too annoying to always enable. For example:

*

*set relativenumber - annoying when scrolling

*set list - distracting when you don't need it

What is a concise leader mapping to toggle a generic Vim setting?

A: You have two ways, as described in the help:
                                                           :set-! :set-inv
:se[t] {option}!   or
:se[t] inv{option}      Toggle option: Invert value. {not in Vi}

Either
:set list!

Or
:set invlist

Will do the same.

A: Toggle options by appending ! to :set <option>

For example, to toggle relativenumber:
nnoremap <leader>r :set relativenumber!<cr>


text:
Q: TFS SQL Query to Find Merges Between Branches I would like to be able to query TFS to look for specific check-ins.    The database Tfs_Warehouse has a table called DimChangeset in it which has a good bit of data around specific changesets.   However I'd like to limit the data by only returning information that has been between a specific branch.
The [DimChangeset] table in Tfs_Warehouse shows all check-ins, but doesn't say where what they were from or too.
Is there any way via a SQL query to check for all merges between one code branch and another?  Not across projects, just between two specific branches.
The database that TFS uses has things like the ParentPath, but I can't see exactly how to find a destination path or ID?  I figure there must be something based on the fact that it knows about it in work items.

A: You have to query the FactCodeChurn table; see reference here


text:
Q: Why navigationBar's height does not change I cannot understand why navigationBar's height does not change from default to 100.
I would be happy if you have any answer.
my code is below,
let mainNavController: UINavigationController = UINavigationController(navigationBarClass: CustomNavigationBar.self, toolbarClass: nil)
    mainNavController.setViewControllers([ViewController], animated: false)

and also
class CustomNavigationBar: UINavigationBar {
override func sizeThatFits(_ size: CGSize) -> CGSize {
    var size = super.sizeThatFits(size)
    size.height = 100
    return size
    }
}


text:
Q: Display an array at the bottom of its container (ScrollView) I have a list and I want to position that at the bottom of its container. I thought I could do that with flex-end (yeah, I also tried contentContainerStyle={{justifyContent: "flex-end",}} for ScrollView), but somehow it doesn't work. Maybe because of ScrollView, I don't know. The code below is the simplified version of what I've done. So, I'd like to keep the hierarchy as it is. Is there a way to display that array starting from bottom?
import { View, StyleSheet, Text, ScrollView, Dimensions} from 'react-native';

const WindowsWidth = Dimensions.get('window').width
const WindowsHeight = Dimensions.get('window').height

export default function ExampleComponent ({navigation}){
    const ownedAudios=["First item", "Second item", "Third item", "Fourth item"]
    return (
        <View style={styles.container}>
            <View style={styles.recordingsList}>
                <ScrollView>
                    {ownedAudios? ownedAudios.map((key, index)=>{
                    return (
                        <View key={index} onTouchEnd={() => console.log("heyhey")}>
                            <Text style={{color:"#474131", fontSize:14, fontWeight:"400", }}>{key}</Text>
                        </View>
                    );
                    }):<></>}
                </ScrollView>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        width: "100%",
        height: "100%",
        backgroundColor: "#0C0A09",
        color: "#c6825a",
        zIndex: 0,
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    recordingsList: {
        flex:1,
        justifyContent: 'flex-end',
        alignItems: 'flex-start',
        position: "absolute",
        width: WindowsWidth-130,
        height: WindowsHeight - 260,
        left:0,
        bottom:355,
        padding:15,
        paddingLeft:0,
        top:170,
        backgroundColor:"pink",
    },
  });

A: flexGrow: 1 and flexShrink: 1 will do the job for you,

import { View, StyleSheet, Text, ScrollView, Dimensions } from 'react-native';

const WindowsWidth = Dimensions.get('window').width;
const WindowsHeight = Dimensions.get('window').height;

export default function App() {
  const ownedAudios = [
    'First item',
    'Second item',
    'Third item',
    'Fourth item',
  ];
  return (
    <View style={styles.container}>
      <View style={styles.recordingsList}>
        <View style={styles.spacer} />
        <View style={styles.scrollContainer}>
          <ScrollView>
            {ownedAudios ? (
              ownedAudios.map((key, index) => {
                return (
                  <View key={index} onTouchEnd={() => console.log('heyhey')}>
                    <Text
                      style={{
                        color: '#474131',
                        fontSize: 14,
                        fontWeight: '400',
                      }}>
                      {key}
                    </Text>
                  </View>
                );
              })
            ) : (
              <></>
            )}
          </ScrollView>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    backgroundColor: '#0C0A09',
    color: '#c6825a',
    flex: 1,
  },
  recordingsList: {
    width: WindowsWidth,
    height: WindowsHeight,
    backgroundColor: 'pink',
  },
  spacer: {
    flexGrow: 1,
  },
  scrollContainer: {
    flexShrink: 1,
  },
});


text:
Q: Fractional part of the product of a factorial tending to infinity and of an irrational number Let $\alpha\in\mathbb{R}\setminus\mathbb{Q}$ be an irrational number and take the limit
$$\lim_{n\to\infty}\cos^{2n}(n!2\pi \alpha).$$
Intuitively this must be zero since $n!\alpha$ will never be an integer and therefore the value or $|\cos|$ will always be less than 1, and taking an increasingly high power of values strictly less than 1 should tend to 0. That's my intuition.
But how can I be sure that in the infinite set of values of $n!x$ there will not be a sequence of values $(n_i!x)_i$ such that their fractional values are increasingly close to $0$ that even when taking the $2n$-th powers of the cosinus, the proximity to zero will compensate the effect of the power and the result will tend to something different than $0$?
Ideally I would like to find an upper bound $\eta$ such that $|\cos(n!2\pi \alpha)|<\eta<1$ for $n$ big enough, so that $\lim_{n\to\infty}\cos^{2n}(n!2\pi \alpha)\leq \lim_{n\to\infty}\eta^{2n}$ which is necessarily $0$. But does such a bound exist?
What do we know of the fractional part of $n!\alpha$ when $\alpha$ is an arbitrary irrational and $n\to\infty$?

A: You can get a counterexample by taking $\alpha$ to be Euler's number $e$. We have
$$
n!2\pi e=n!2\pi\sum_{k=0}^\infty\frac{1}{k!} = 2\pi\sum_{k=0}^n \frac{n!}{k!} + 2\pi \sum_{k=n+1}^\infty \frac{n!}{k!},
$$
which differs from an integer multiple of $2\pi$ by
$$
2\pi \sum_{k=n+1}^\infty \frac{n!}{k!} = 2\pi\sum_{k\geq 1}\frac{1}{(n+1)\cdots (n+k)}< 2\pi\sum_{k\geq 1}\frac{1}{(n+1)^k}= \frac{2\pi}{n}.
$$
Since $\cos(x) \geq 1-x^2/2$, it follows that
$$
\cos(n!2\pi e)\geq 1-\frac{4\pi^2}{n^2},
$$
and therefore
$$
\begin{align*}
1\geq \cos^{2n}(n!2\pi e)&\geq \left(1-\frac{4\pi^2}{n^2}\right)^{2n}\\
&=\left(\left(1-\frac{4\pi^2}{n^2}\right)^{n^2}\right)^{2/n}.\\
\end{align*}
$$
Finally, taking the limit as $n\to\infty$, we have
$$
\lim_{n\to\infty} \left(1-\frac{4\pi^2}{n^2}\right)^{n^2} = e^{-4\pi^2},
$$
and so
$$
1 \geq \lim_{n\to\infty}\cos^{2n}(n!2\pi e)\geq  \lim_{n\to\infty} \left(e^{-4\pi^2}\right)^{2/n} = 1.
$$


text:
Q: Register here link button is not working? I am working in asp.net C#. I have created login page in which i have used validations to check if username or password is empty or not. Bu everytime i click on register here link it shows me to enter username or password. I am attaching code and image please help. Furthermore i have used link button for register here link.
enter image description here
Here is login.aspx.cs file code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace Dots
{
    public partial class Login : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_ClickLogin(object sender, EventArgs e)
        {
            SqlConnection conn = new   SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            conn.Open();

            string checkUser = "Select count(*) from Registeration where UserName =  @username  and Password = @pass";
            SqlCommand sq = new SqlCommand(checkUser, conn);
            sq.Parameters.AddWithValue("@username", TextBoxUserName.Text);
            sq.Parameters.AddWithValue("@pass", TextBoxPassword.Text);
            SqlDataAdapter da = new SqlDataAdapter(sq);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "");
            }
            conn.Close();
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {

            Response.Redirect("Registeration.aspx");

        }

    }
}

Here is my aspx code.
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Dots.Login" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <link rel ="stylesheet" type="text/css" href="~/Styles/StyleSheet1.css" />

Secure Login

                        UserName

                            <asp:TextBox ID="TextBoxUserName" runat="server" Width="180px" CssClass="Login_un" Height="22px"></asp:TextBox>

                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter Username" ControlToValidate="TextBoxUserName" ForeColor="Red"></asp:RequiredFieldValidator>

                        Password

                            <asp:TextBox ID="TextBoxPassword" runat="server" Width="180px" CssClass="Login_un" TextMode="Password" Height="22px"></asp:TextBox>

                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter Password" ControlToValidate="TextBoxPassword" ForeColor="Red"></asp:RequiredFieldValidator>

                            <asp:Button ID="Button1" runat="server" OnClick="Button1_ClickLogin" CssClass="Login_btn" Text="Button" />

                            <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">New User? Register Here</asp:LinkButton>

</asp:Content>

A: Change:
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" >New User? Register Here</asp:LinkButton>

to
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" ValidateRequestMode="Disabled">New User? Register Here</asp:LinkButton>

Here is some additional feedback.
I would suggesting surrounding with a try/catch/finally so if you redirect you close the connection to the Database rather than leaving it open if you redirect. It is just good practice.
 SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
        try {
            conn.Open();
            string checkUser = "Select count(*) from Registeration where UserName =  @username  and Password = @pass";
            SqlCommand sq = new SqlCommand(checkUser, conn);
            sq.Parameters.AddWithValue("@username", TextBoxUserName.Text);
            sq.Parameters.AddWithValue("@pass", TextBoxPassword.Text);
            SqlDataAdapter da = new SqlDataAdapter(sq);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0) {
                Response.Redirect("default.aspx");
            } else {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "");
            }
        } finally {
            conn.Close();
        }

A: Change this code :
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">New User? Register Here</asp:LinkButton>

to :
New User? Register Here


text:
Q: Make plugin php file called directly aware of Wordpress? My plugin needs to make a POST request to another file within the plugin that will receive the request and store some of its data as a new post in wordpress.
The idea is that different sites that use this plugin as admin will be able to 'receive' posts via this file that will handle POST requests from the 'main' site.
All good but when I make a POST request with some data to a particular receiver php file, this file is not 'aware' that it's part of the plugin hence I can't use the data there within the plugin.
How do I handle this? Thanks

A: You can't load plugin files directly, you need to target either a front-end or admin URL that bootstraps WordPress. An easy way to do this is the admin_post_(action) action:
add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' );
function prefix_admin_add_foobar() {
    // your code here
}

You can then POST your data to admin_url( 'admin-post.php' ) and set action to add_foobar in this example, which will trigger your hooked function.