text:
Q: Form abrindo popup JS em branco Preciso que retornar o resultado da submissão de um form em um popup(tentei lightbox mas penei pra conseguir usar, seria até melhor, recomendações?) no centro da tela do usuário, o único problema é que o popup tá retornando uma página em branco e eu não consegui identificar onde está o erro no código.
Se eu colocar 'include/verifica.php' no window.open ele dá várias mensagens de erro, não resolve.
Form:
<form action="include/verifica.php" onsubmit="return abrirPopup('this', 400, 120)" method="POST">

JS:
function abrirPopup(form, w, h) {
  var newW = w + 100;
  var newH = h + 100;
  var left = (screen.width - newW) / 2;
  var top = (screen.height - newH) / 2;
  var newwindow = window.open('', 'formpopup', 'width=' + newW + ',height=' + newH + ',left=' + left + ',top=' + top);
  form.target = 'formpopup';
  newwindow.resizeTo(newW, newH);

  //posiciona o popup no centro da tela
  newwindow.moveTo(left, top);
  newwindow.focus();
  return false;
}

O formulário tá na minha index, ele verifica se todos os dados foram inseridos na verifica.php em caso positivo ele inclui a insere.php que é quem joga os dados pro banco de dados e me retorna um número de protocolo, que é a id da nova linha na table.
Desculpa a bagunça do código mas isso se dá na maior parte pela quantidade de vezes que eu já alterei ele no desespero de tentar arrumar haha

A: está faltando colocar o endereço da popup em
var newwindow = window.open('ENDEREÇODAPOP', 'formpopup', 'width=' + newW + ',height=' + newH + ',left=' + left + ',top=' + top);


text:
Q: Is there a way to open a page in the browser in the background, UNFOCUSED, from the command line? For those familiar with OSX, the behavior I'm looking for is open -g http://google.com, which will open a google webpage in the default browser in the background, without switching focus to it at all.
I've been testing on stock Natty (Gnome, Unity...) with Chrome and then Firefox set to the default browser. I've tried both gnome-open http://google.com and xdg-open http://google.com, and with or without appending &>/dev/null & to the end, the browser window always gets focused. The only case where the browser doesn't get focus is when the default is Firefox and there is already a Firefox window open. I've also tried just calling firefox or google-chrome directly, and neither of them work.
Is there some combination of commands or a package I could use to get the desired behavior more reliably, regardless of whether the default browser is Chrome or Firefox, or whether there's already a window open? This is for software to be installed on others' machines, so modifying their browser profiles is not really a solution...

A: From what I understand most applications that run under X accept options on the command line that allow you to modify the behavior, I've found two options that may be of use:

-xrm resourcestring
Resources  can  also  be  specified from the command line.  The
resourcestring is a single resource name  and  value  as  shown
above.  Note that if the string contains characters interpreted
by the shell (e.g., asterisk), they must be quoted.
-iconic
This option indicates that the user would prefer that the application's windows initially not be visible as if the windows had
be immediately iconified by the user. Window managers may choose not
to honor the application's request.

The first option will allow you to set properties on the command line, the only issue is I can't find the right string to use that would prevent focus or minimize the window.
The second option should start the program minimized however in my limited set of trials I was unable to get Firefox to honor the iconic option under XFCE leading me to believe that implementation of that flag is dependent on the program.
Your best option is to look into setting Xresources using xrm, I will update this post if I find a good option for xrm.
Sidenote:
From a UI/UX standpoint there is a good article on focus stealing, Please Don't Steal My Focus by Jeff Atwood if you haven't read it already it presents a good approach to focusing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to backup a GlassFish server 2.1.1 domain without stopping or suspending the server? We are using JCAPS 6.3 with a build-in GlassFish 2.1.1 app server, we'd like to create a replication of the default domain (C:\JavaCAPS63\appserver\domains\domain1).
Is that possible to perform the backup by just copying everything inside "domain1" folder and pasting into a folder in another server?
We don't really want to stop/suspend the current server.
Thanks a lot if anyone would help.


text:
Q: Resize image From url objective c I return an image from an url with
 NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:Result]];

and i store it to google map marker i want to resize it to half size

A: Try with below code:
UIImage *actualImage = [UIImage imageWithData:imageData];
UIGraphicsBeginImageContext(CGSizeMake(actualImage.size.width/2, actualImage.size.height/2);
[actualImage drawInRect:CGRectMake(0,0,actualImage.size.width/2, actualImage.size.height/2)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *smallData = UIImagePNGRepresentation(newImage);

A: To resize the image after it has been downloaded from an URL, you can use mainly 2 methods:

*

*Use Core Graphics (as suggested), but pay attention about the aspect ratio

*Use ImageIO

In the first case you should create a space in memory to redraw the downloaded image at a small size, that's a brief description of the snippet posted.
Those are 2 frameworks available both for OSX and iOS, my suggestion is to use NYXImagesKit if using third party library is not a problem. It has very helpful method to handle images also one to download images from a URL in a correct way.
What you are doing can be bad for the user experience, the way you are download data from a URL creates a synchronous connection that will block the main thread until the method has finished. The main thread manages most of  the UI interactions. This is not good, because imagine that the server is not responding and the timeout is set to 60 seconds, the user will have to wait 60 seconds before make an further action on the app. the same happen if th image is too big and the connection poor.
To correctly download data you should use an asynchronous method, the library above has what you are looking for.


text:
Q: Extending namespaced JS imports This is a general ES6 question, but I've encountered it in the context of React Native. The basic problem is that I want to override some components that I usually import from the 'react-native' module with my own components. My method for doing this looks like the following:

Instead of requiring components with import { Text, View, etc } from 'react-native'
require them like this: import { Text, View, etc } from './ui_components'
where ui_components.js looks something like:
export * from 'react-native'

The issue is, how do I add my own components to this export? Ideally I'd be able to add them in ui_components.js by doing something like this:
import * as RN from 'react-native'
RN.Text = myTextComponent
RN.View = myViewComponent
export * from RN

But this doesn't quite work. Any ideas?

A: You need to import React Native's component and reexport it, with or without extensions from your side - it's up to you.
But remember - don't ever override React's internals (or any other's internals). Components are composable, yay!
For example, here, I am creating my custom Text component cause I want all texts in my app to be red by default. Also I want it to be configurable if I need different color for title/subtitle/whatever...
import React from 'react';
import { Text as NativeText } from 'react-native';

export default function Text({ style, ...props}) {
    return <NativeText style={[ { color: 'red' }, style]} {...props} />
}

Got an idea?
Good, now to folder structure...
ui_components
| - index.js
| - Text.js

// Text.js
// See example above...

// index.js
export { default as Text } from './Text';

// In your app
import { Text } from './ui_components';


text:
Q: Access: cannot move to next record with the code Private Sub btn_Next_Click()
'Creating Connection to database
Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "SELECT * FROM Tbl_Author"
Set rs = CurrentDb.OpenRecordset(strSQL)

    If Not rs.BOF And Not rs.EOF Then
        While (Not rs.EOF)
            Me.txtID = rs.Fields("Author_id")
            Me.txtFName = rs.Fields("AFirst_Name")
            Me.txtLName = rs.Fields("ALast_Name")
            Me.txtAddress = rs.Fields("Address")
            Me.txtEAddress = rs.Fields("Email_Address")
            Me.txtMNum = rs.Fields("Mobile_Number")
            Me.txtPNum = rs.Fields("Phone_Number")
            Me.cmbStatus = rs.Fields("Status")
            rs.MoveNext
        Wend
    End If
    rs.Close
End Sub

A: Found the answer. i wrote the query based on the current record displayed in the form, then no need of a loop, every time you click on next, it gets the next value from the database and post it in the textboxes.


text:
Q: What PCB fabrication methods for *prototypes* are used by professional engineering departments today? Ten years ago, I worked at a small engineering department within Philips Semiconductors that prototyped all designs before getting them professionally fabricated outside. The method was pretty standard:

*

*Print artwork using a cheap laser printer onto semi-transparent film

*Tape down top artwork onto bottom artwork and visually align them.

*Cut a PCB to approx size, drill a hole at edge where a wire can be inserted to hold the PCB between insertions in chemicals.

*Insert PCB between artworks, and expose using a homemade UV light box.

*Hook wire into hole on PCB and dunk in a vertical tank containing Sodium Hydroxide and wait until developed

*Put in spray tank and spray with clean water.

*put in vertical tank containing Ferric Chloride etch and leave until etched.

*put in spray tank and spray with clean water

*put in etch remover until etch removed

*Put in vertical tin tank for tinning.

The results were beautiful looking PCBs that were very easy to solder and professional looking, despite a lack of solder mask and screen.
Is this the standard method still used by professional engineering departments when making prototype PCBs today, or are there other methods that give similar great results?

A: Time has definitely moved on from those days and I endorse what the other answers say/imply about the cost of getting proper multilayer PCBs made externally but I'll add something else.
In my experience the use of circuit simulation tools means that you can reduce the number of PCB iterations to get a design correct. Add this to the almost insignificant cost of multilayer boards and there is no real need for in-house prototyping any more.

A: I work at a small laboratory at colege. Here you have to make a gerber file (usually using Altium), and then send to the person responsible for prototyping (me), who will use a LPKF S42 to make the board. Sadly it looks pretty homemade.
I attached this picture from one of our prototypes. The left one (multilevel green) is made in some Board House; the right one (kind of brown) I made by myself.

A: So this is what we follow in our Lab. Only for a two layer board. More than two layer boards end up going to the vendor.

*

*Take a print out of the board image (original size) and make sure only the bottom, drills, pads, via and dimension layers are on the image. We use Eagle for this. Use photographic pages of GSM less than 140.

*Tear the page suitably to place over a PCB of certain size and iron (yes using an Electric Iron) the board keeping the printed side on the copper. Do this for atleast 15 minutes till you are sure that the tracks would have transferred onto the board.

*Put the board in water and remove the excess paper and etch the board using Ferric Chloride as you mentioned. Once etched see the original design and using a compass make holes on all places where drills need to be done. Use appropriate bits for drilling (depending on the size of the component you wish to fit). Also, drill all the vias and add jumpers on the top layer (if applicable).
So, This is the final result. :)
Edit: A few parts, which i thought were self explanatory, added now.

A: None that I know of. 15+ years ago I also worked for a small engineering firm that did what you described above. Today, in my basement, I can layout PC boards with free or low cost software, generate a Gerber file, email those files to a circuit board house and have boards made for less than $3/sq in with better quality that I can dream of doing. Mask and silkscreen are typically included for the same price. Turnaround is between 5-15 working days depending on how much you want to pay.
It's no longer reasonable to make PC boards yourself unless you need turnaround time measured in minutes. It's so cheap that if you place a reasonable value on your time, you lose money doing it onsite.

A: About 15 years ago I hired an EE straight out of U.C. Santa Barbra.  His first week on the job he asked me, "How do you prototype PCB's?  Wire wrap, breadboards, or what?"  My answer then is just as valid now.  We design a normal PCB, have it professionally made, and if they work we ship the product.  If it doesn't work, we fix it, build new ones, and try again.
There are PCB shops and contract manufacturers that specialize in making prototype quantities of bare PCB's.
The vast majority of companies make their prototypes in the same way.  There are exceptions, of course.  Some companies etch their own PCB's.  Some use something like a milling machine for PCB's.  Some will do wire wrap.  And some will use breadboards or perf. board.  But for anything but the simplest of boards probably 95+% of companies just get prototype PCB's made from a professional PCB fab shop.
While this method seems to cost more, in the end it is cheaper.  We spend less time debugging, building, and futzing around with potentially low-quality and unreliable prototypes.  Plus, we are able to use 4+ layer PCB's with plated holes-- which is HUGE.  In the past 15 years I've designed maybe FOUR 2-layer boards and 40+ more complex boards.

A: I'm not sure how professional we'd count as being, as we're a small design house rather than a huge multinational electronics corp...
Generally, very basic prototypes are done with a scalpel & copper-clad board if needed, or if more complex, we just send it out to Seeedstudio / Iteadstudio for $20, it's a no-brainer. If we need something done quick, we pay a more local "proper" PCB house to do a one-off or very short run. It costs, but that's business.

A: I feel like someone should mention PCB milling as a prototyping method. Quicker and less messy than a chemical process, and the same machine that does the milling can also drill holes and rout the the board edges.
Two-sided boards are accomplished by drilling a few registration holes in the board that drop on to pins on the milling machine. Mill one side, flip, mill other side.
Still probably not very common in professional environments since prototype runs are so cheap, but for times when faster turnaround than a prototype run can provide is needed, milling is pretty great.

A: Typically, we send our stuff out to be printed for us, even for prototypes. Sometimes this can get expensive - 10 revisions of our work and there's over $10k. But for an initial investment of $7k, you can buy a CNC mill that will cut out dual layer PCBs very nicely. This isn't bad for prototyping, but not the best answer for mass production. We tend to steer away from chemical etch because it has a tendency to etch unevenly, and when your PCB has over a pound of copper on a small board (power supplies) you can create hotspots. For LV projects, chemical etch isn't too bad.

A: I use the cold method of DIY PCB creation.  I have a cheap Brother laser printer than can do 1200x, I use this mode for most 48pin and 62pin MCU boards.  If I don't need the resolution, I use the standard 600x and double the toner print.
I don't get fancy as far as via's go, I drill a 1mm hole where ever I need one, slide a wire just a little smaller and solder both sides(I'll also use old solder wick to tie top and bottom layers together if I poured a top ground).  The paper I use is Fedex-Kinko's light glossy paper, works like a charm.
Pre-step, cut board to correct size using a high speed rotary tool.

*

*Clean board using very fine grit sandpaper.  Then wipe down with the same mix I'll use apply the toner mask.  5 parts 80% alcohol to 3 acetone, with no added water due to the alcohol not being 99%.
2.Cut the reversed toner mask to correct size.  Apply a decent bubble of the above mixture to the board, apply mask, aligning at least one edge on both board and mask.
Use a simple rubber roller to get most of the air out from between board and mask.
Then put the board down on an old piece of prototype board paper up, add another old board and apply one or more clamps depending on size.  After about 10 min, remove clamps and board, and let air dry.
2a Now I'll put the board into a shallow dish with some water and give it at least an hour to loosen up and then remove the paper.  Wipe down the board with water. Ensure clean.
++ Next I'll take my hot air wand to it, making sure to soften the toner everywhere.  You should only heat it enough to cause the toner to become slightly softened and fill any holes left by the transfer.  Since I started doing this, after etching and removal of the toner, you can easily see any pattern left over from the initial sanding.
-+- If I have signal traces on the bottom, I'll cover up the top mask using painters tape(That's the blue tape that really does not stick to much).  This is just to keep any of the mix from being able to reach the front.
I'll now repeat steps 2 and 2a and remove any blue tape.
++ Next I'll take it outside and etch using a combo of Hydrogen Perioxide and Muratic Acid(aka weak Hydrochloric). Etch until it looks good and flush with water.  I'll pour all of the etchent (Unless I'm planning on making more in the next hour) into an old apple cider bottle.  That goes back on a shelf in the shed; I live in Arizona and in less than a week all the water is gone.

*Remove all toner using 100% acetone and napkins.  Wipe down with mix.

*Drill required through holes, vias, etc.
If it's small I'll just hand assemble using a tooth pick to lay down some refurbed paste(I add a little flux to it and mix), spot the part and use my hot air wand to reflow.  If it's big, I use some of my good paste and a mask to lay it down.  Carefully using tweezers, bright light and a head mag, I'll put all the parts on, put it carefully in the toaster oven, attach temp probe and reflow that way.

I've used this method to make all kind of boards including RF boards up to 2.5G.
Hope I did not forget anything...

A: We scarcely need yet another go-around of this question, but since it is here, for completeness the clothes iron & junk mail paper laser toner transfer method is a useful and faster alternative to the photo etch method for those same-day one-off experiments.


text:
Q: Partial sorting: nth elements having preseved order The task is to partially sort a vector with duplicates s.t. the median (nth-element) is at the position it would be, if the vector were sorted. All smaller elements should be on the left, all larger elements on the right. All elements with value same as median have to be in original order - but only these not the rest of the elements.
How would you solve this?
My initial solution:

*

*Use std::nth_element() to find median element

*traverse vector and sort only the elements with same value as median with respect to their index. How would I do this efficiently?

A: Use partition or stable_partition (to preserve original order).
class Predicate{
    int median_value;
    public:
    Predicate(int med) : median_value(med) {}
    bool operator()(int x){
    return x < median_value;
    }
};

int main(){

vector<int> v{ 10, 20, 30, 10, 30};

int median = 20;

cout << "median  = " << median << endl;

stable_partition(v.begin(), v.end(), Predicate(median));

for ( auto i : v)
    cout << i << " ";
}


text:
Q: rle for finding rectangles in matrix I'm following this approach to find rectangles of 1's  in a (0,1) matrix
Find 5 consecutive numbers >= 3 for each row of a matrix
but there's a problem when I try to find 1x4 rectangles (1 row and 4 columns) like in this matrix
m <- matrix(c(0,1,1,1,1,0,0,0,1,0,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,0), nrow = 6, ncol = 5, byrow = TRUE)

There are four rectangles: 1st row, 4th row, 5th row and 6th row
   [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    1    1    1
[2,]    0    0    0    1    0
[3,]    1    0    0    1    0
[4,]    1    1    1    1    0
[5,]    0    1    1    1    1
[6,]    1    1    1    1    0

when I run the code for this case I get the 4 results, but two of them (4th and 6th row) both results start at first column but in the result I get as starting column the 5th and ending column the 8th when the matrix is 6x5 and can't find out which is the problem.
b<-m

for (j in 1:5){
cont<-1
 for (i in 6:1) {
 if (m[i,j]==0){
cont<-1
b[i,j]<-NA}
 else {b[i,j]<-cont
cont<-cont+1}
}
}

mdat<-b

apply(mdat, 1, function(x) {
  r <- rle(x >= 1)
  w <- which(!is.na(r$values) & r$values & r$lengths >=4)
  if (length(w) > 0) {
    before <- sum(r$lengths[1:(w[1]-1)])
    c(before+1,before+ r$lengths[w[1]])
  } else
    NULL
})

[[1]]
[1] 2 5

[[2]]
NULL

[[3]]
NULL

[[4]]
[1] 5 8

[[5]]
[1] 2 5

[[6]]
[1] 5 8

A: You need to change the calculation of before variable since it does not work if the row starts with the sequence of 1's :
apply(mdat, 1, function(x) {
  r <- rle(x >= 1)
  w <- which(!is.na(r$values) & r$values & r$lengths >=4)
  if (length(w) > 0) {
    before <- sum(r$lengths[1:w[1]]) - r$lengths[w[1]]
    c(before+1,before+r$lengths[w[1]])
  } else
    NULL
})

Problem was the following line :
before <- sum(r$lengths[1:(w[1]-1)])

that works properly only if the sequence of ones is not at the first position (i.e. w > 1).
BTW, note that your code only consider the first sequence in the row, ignoring other sequences (if present).
e.g. supposing to have one matrix row = c(0,1,1,1,1,0,1,1,1,1), it will return only c(2,5) and not c(2,5), c(7,10)
If you want something returning all the sequences, you can use this code :
apply(mdat, 1, function(x) {
  r <- rle(x >= 1)
  w <- which(!is.na(r$values) & r$values & r$lengths >=4)
  if (length(w) > 0) {
    lapply(w,FUN=function(w1){ before <- sum(r$lengths[1:w1]) - r$lengths[w1];
                               c(before+1,before+r$lengths[w1]) })
  } else
    NULL
})

N.B. it returns a list where each element is a list containing the pairs


text:
Q: Does this count as an Insertion-Sort? And why does a random number show at the end? I've been asked to create an insertion sort for an array. My program ended differently from the teacher's, but it sorts the array. However, I'm curious if it truly counts as a proper insertion sort. Also, at the end of the sorting, some random numbers appear. I would appreciate some help with this.
#include <iostream>
#define size  6
using namespace std;
void insertion(int v[size]){
    int i,temp;
    for(i=0;i<size;i++){
       while(v[i+1] < v[i]){
            temp = v[i+1];
            v[i+1] = v[i];
            v[i] = temp;
            printArr(v);
            i = 0;
            }
      }
}
int main(){
    int vet[size] = {34,12,15,21,5,88};
    printArr(vet);
    insertion(vet);

    return 0;

}

Here is the output, one line at a time:
34,12,15,21,5,88,
12,34,15,21,5,88,
12,15,34,21,5,88,
12,15,21,34,5,88,
12,15,21,5,34,88,
12,15,5,21,34,88,
12,5,15,21,34,88,
5,12,15,21,34,88,
5,12,15,21,34,44,

Notice the 44 at the end there. I don't know why it's there since the code works nicely up until the end.
Edit: Fixed a damn typo. My PC turns any lowercase i into uppercase, just forgot to adjust it, but it's not wrong in code.

A: For starters there is a typo in this statement
v[i+1] = v[I];
         ^^^^

It seems you mean
v[i+1] = v[i];
         ^^^^

The while loop
   while(v[i+1] < v[i]){
        temp = v[i+1];
        v[i+1] = v[I];
        v[i] = temp;
        printArr(v);
        i = 0;
        }

can invoke undefined behavior due to accessing memory beyond the array when i is equal to size - 1.
In any case the approach with the while loop is incorrect and inefficient. The outer for loop again starts from 0 when a swap of adjacent elements occurred.
And moreover the function depends on the magic named number 6. That is it is unable to sort arrays of different sizes.

A: There is a variable mismatch.
Change the capital I to small i.


text:
Q: Expander Style questions iam a newby in WPF and i need help again...
I have an expander with Round Corners, but i don't like this and i want rectangular corners. Can anyone tell me how i can solve this problem?
This is my expander
.. Style:
<Style x:Key="exp_AInfo_Style" TargetType="Expander">
        <Setter Property="IsExpanded" Value="True"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
        <Setter Property="VerticalAlignment" Value="Top"/>
        <Setter Property="Margin" Value="18,5,0,0"/>
        <Setter Property="Width" Value="259"/>
        <Setter Property="Height" Value="29"/>
        <Setter Property="FontSize" Value="14"/>

        <Style.Triggers>
            <Trigger Property="IsExpanded" Value="True">
                <Setter Property="Height" Value="155"/>
            </Trigger>
        </Style.Triggers>
    </Style>

and the Object:
       <Expander x:Name="exp_AInfo" Header="Allgemeine Info's"
            Style="{StaticResource exp_AInfo_Style}" Height="116"
            >
            <Expander.Background>
                <ImageBrush ImageSource="pct/expander.png" Opacity="0.9"/>
            </Expander.Background>
            <Grid Height="112">
                <!--many many objects-->
            </Grid>
        </Expander>

Thanks 4 help

A: It's all about the CornerRadius of the ToggleButton ControlTemplate.
There you go:
  <ControlTemplate x:Key="ExpanderToggleButton"
             TargetType="{x:Type ToggleButton}">
        <Border x:Name="Border"
              CornerRadius="0,0,0,0"
              BorderThickness="1" Background="White" BorderBrush="Black">

            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="MouseOver">
                    </VisualState>
                    <VisualState x:Name="Pressed">
                    </VisualState>
                    <VisualState x:Name="Disabled">
                    </VisualState>
                </VisualStateGroup>
                <VisualStateGroup x:Name="CheckStates">
                    <VisualState x:Name="Checked">
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                       Storyboard.TargetName="CollapsedArrow">
                                <DiscreteObjectKeyFrame KeyTime="0"
                                  Value="{x:Static Visibility.Hidden}" />
                            </ObjectAnimationUsingKeyFrames>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                       Storyboard.TargetName="ExpandededArrow">
                                <DiscreteObjectKeyFrame KeyTime="0"
                                  Value="{x:Static Visibility.Visible}" />
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="Unchecked" />
                    <VisualState x:Name="Indeterminate" />
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
            <Grid>
                <Path x:Name="CollapsedArrow"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Data="M 0 0 L 4 4 L 8 0 Z">
                    <Path.Fill>
                        <SolidColorBrush Color="Black" />
                    </Path.Fill>
                </Path>
                <Path x:Name="ExpandededArrow"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Visibility="Collapsed"
                    Data="M 0 4 L 4 0 L 8 4 Z">
                    <Path.Fill>
                        <SolidColorBrush Color="Black" />
                    </Path.Fill>
                </Path>
            </Grid>
        </Border>
    </ControlTemplate>

    <Style TargetType="{x:Type Expander}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Expander}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition x:Name="ContentRow"
                       Height="0" />
                        </Grid.RowDefinitions>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver" />
                                <VisualState x:Name="Disabled"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="Border"
                              Grid.Row="0"
                              BorderThickness="1"
                              CornerRadius="2,2,0,0">
                            <Border.BorderBrush>
                                <LinearGradientBrush EndPoint="0,1"
                               StartPoint="0,0">
                                    <GradientStop Color="White" Offset="0" />
                                    <GradientStop Color="White" Offset="1" />
                                </LinearGradientBrush>
                            </Border.BorderBrush>
                            <Border.Background>
                                <LinearGradientBrush StartPoint="0,0"
                               EndPoint="0,1">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStopCollection>
                                            <GradientStop Color="White" Offset="0.0" />
                                            <GradientStop Color="White" Offset="1.0" />
                                        </GradientStopCollection>
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>

                            </Border.Background>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="20" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <ToggleButton OverridesDefaultStyle="True"
                                        Template="{StaticResource ExpanderToggleButton}"
                                        IsChecked="{Binding IsExpanded, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
                                    <ToggleButton.Background>
                                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                            <GradientStop Color="White" Offset="0" />
                                            <GradientStop Color="White" Offset="1" />
                                        </LinearGradientBrush>
                                    </ToggleButton.Background>
                                </ToggleButton>
                                <ContentPresenter Grid.Column="1"
                                    Margin="4"
                                    ContentSource="Header"
                                    RecognizesAccessKey="True" />
                            </Grid>
                        </Border>
                        <Border x:Name="Content"
                                  Grid.Row="1"
                                  BorderThickness="1,0,1,1"
                                  CornerRadius="0,0,0,0">
                            <ContentPresenter Margin="4" />
                        </Border>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsExpanded" Value="True">
                            <Setter TargetName="ContentRow"
                                Property="Height"
                                Value="{Binding DesiredHeight, ElementName=Content}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


text:
Q: Type 'WebAPI.Controllers.ValuesController' does not have a default constructor in Web API I have started working on ASP.NET Web API but I am new for this technology. here what I have tried to set up my project.
Step 1
Create Web API project

Can someone please help me that why I am getting this error?

A: You have to install Unity.WebAPI nuget package too.
https://www.nuget.org/packages/Unity.WebAPI/
http://www.devtrends.co.uk/blog/using-unity.mvc5-and-unity.webapi-together-in-a-project


text:
Q: Iterate through map with tuple I am trying to iterate through a map, that has a tuple. The below fails
std::map<int, std::tuple<int,       double, double, double>> database;

for (auto d : database){
        if (std::get<3>(d) > temp){
            json tmp;
            tmp = {
            { "result", "ok" },
            { "id", id },
            { "timestamp", std::get<0>(d) },
            { "x", std::get<1>(d) },
            { "y", std::get<2>(d) },
            { "temperature", std::get<3>(d) }
            };
            result+=tmp;
        }
        id++;
}

The error message is massive, this is the first part
temperature_server.cc:83:30: error: no matching function for call to 'get(std::pair<const int, std::tuple<int, double, double, double> >&)'
         if (std::get<3>(d) > temp){

A: Change to:
for (const auto& p : database){
    const auto& d = p.second; // std::tuple<int, double, double, double>
    // ...


text:
Q: How to not execute a stubbed method in RSpec I am testing that a controller calls a certain method in a module that it includes. I don't want the method to actually execute, just to verify that it is called. What I have right now is:
it 'calls create_show_and_tickets' do
  sign_in create :admin
  expect(subject).to receive(:create_show_and_tickets)

  post :create, show: valid_attributes
end

In the test I am not putting proper parameters in, so it is throwing an error when I tries to iterate over an object that doesn't exist. Is there a way to make sure that create_show_and_tickets does not execute?

A:
Is there a way to make sure that create_show_and_tickets does not execute?

You have done just that by calling
expect(subject).to receive(:create_show_and_tickets)

... before the post. allow would have the same effect. In either case the underlying code is replaced by your mock or stub, and will not get called.
You can put a debugging statement within create_show_and_tickets to confirm this.


text:
Q: ThunderBird fail to receive some mails A couple of days ago, I switched from Outlook to ThunderBird, at first I thought it was ok, until today I found that Outlook can receive some mails but ThunderBird cannot! What the heck?
It's like this, say 10 mails to sent by different people, Outlook can receive them all, but ThunderBird can only got 3 or 4 of them, which is wired that how could ThunderBird misses some of those mails? This really drives me crazy, and I decided to give ThunderBird one last shot before I switch back to Outlook.
About my ThunderBird configuration, sending server and receiving server are the same, email.my_company.com.
sending protocol is SMTP, receiving protocol is POP3.
Any idea, bros?

A: Thunderbird has got a weird way to check emails. If it does not get all the emails in 60 seconds, it declares that it fails to receive the emails. So if you get an enough big mail with heavy attached documents, 60 seconds will not be enough for Thunderbird to get it and it will not be able to receive emails until you see the big email with an other program like a webmail or Outlook (since it cannot see it). More than 12 MB of attachments can cause this. I don't know why 60 seconds and how to change it.


text:
Q: VARIANT type punkVal gives undefined values? I am using few CComVariant type variables to store interface pointers.However, sometime I need to pass interface pointer as NULL.In this case when I do this:
CComVariant vAData,vBData;
......
....
CComQIPtr<IBData> pAData = vAData.punkVal; //vAData is {0, VT_I4} when I pass NULL

CComQIPtr<IBData>pBData = vBData.punkVal;  //vBData is {0, VT_I4} when I pass NULL

The first line fails and throws exception since the vAData.punkVal = 0xffffffff00000000
But the second line passes fine with no error and it has valid vBData.punkVal value(0x0000000000000000).
I am wondering why the two punkVal are different when both are NULL??
Does anybody has any idea why this is happening??
This throws exception only on 64bit machines.

A: Some additional information about VARIANTs: they're somewhat weird in that they are compound types: it's basically a union of several types, with the fields for each type (bstrVal, lVal, punkVal, etc) all occupying the same space in memory, and the vt field indicating which field is valid.
You should only attempt to access the field that matches the value of vt. So if vt is VT_BSTR, then only bstrVal is valid; punkVal is off-limits. If vt is VT_I4, then only the lVal field should be used.
VT_EMPTY means "this variant hasn't been set to any value, so doesn't represent anything"; when vt is VT_EMPTY, all fields are off-limits - they might be whatever garbage just happened to be on the stack before - which is what you are seeing here.
In Win64, integers are still 32-bits, but pointers are 64 bits. A variant that is of type VT_I4 with value 0 will have the 32 bits that represent the integer all set to 0, but the rest of the memory in the variant could be any leftover garbage. If you try to treat that memory as a 64-bit pointer - by accessing punkVal - then you'll end up with a pointer made from those 32 0 bits, but also from an adjacent 32bits that have never been properly initialized - that's likely why you're seeing differences between the two cases here.
In Win32, you get lucky: the pointer is the same size as the int, so if you access a VT_I4 that's 0 and read the punkVal (which you shouldn't!), you would end up getting a NULL pointer in that case.

A: CComVariant calls VariantInit() in constructor and that sets vt to VT_EMPTY, but leaves punkVal uninitialized (doesn't make it null).
What you try to do is therefore undefined behavior since you try to construct a CComQIPtr passing it an uninitialized pointer.
If you want a CComVariant holding a null IUnknown* you can do this:
CComVariant variant( static_cast<IUnknown*>( 0 ) ); // null IUnknown*, VT_UNKNOWN type

now it's perfectly legal to construct a CComQIPtr:
CComQIPtr<IWhatever> whatever( variant.punkVal ); //punknVal is null - legal


text:
Q: google OAuth Refresh Token keeps expiring Hei
I'm having trouble keeping my google OAuth Refresh Token valid for a small application I'm writing. I need to get data from a spreadsheet to a server / desktop application.
I'm trying to authorize with OAuth, which works for a week, then stops.
According to this post, this is expected behaviour:
https://stackoverflow.com/a/67966982/16509954
Another answer in the same thread posts a method how to permanently give access and not get your token expired:
https://stackoverflow.com/a/66292541/16509954
I did this but my token still keeps expiring.
Any ideas what I'm doing wrong?
I'm using the python library, my code is pretty much identical to the example given in the documentation quickstart.py:
https://developers.google.com/sheets/api/quickstart/python

A: Refresh tokens can expire for a number of reasons the main one these days being that your application is still in the testing phase.

Set your application over to production in Google cloud console and have it verified and the refresh tokens will not expire after a week.
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/drive.drive']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'

def initialize_sheets():
  """Initializes an sheets service object.

  Returns:
    An authorized sheets  service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  service = build('sheets', 'v4', credentials=creds)

  return service


text:
Q: Is it possible to enable Windows Mixed Reality on Windows Server 2019? Windows Mixed Reality (WMR) isn't shipped with Windows Server 2019, which I'm currently running at version 1809.
Is there an update or a PowerShell command that will allow a Windows Mixed Reality (WMR) device to be recognised on this system?

A: Windows Server 2019 is not part of the Windows Mixed Reality supported versions
Seems like Windows Server 2019 does not support Windows Mixed Reality as of yet. As explained in this official Microsoft document for Windows Mixed Reality:

Make sure you have the Windows 10 Version 1709 or newer installed
You must be running the Windows 10 Version 1903 or newer to use Windows Mixed Reality. Compatible versions of Windows 10 include:

*

*Windows 10 Version 1903

*Windows 10 Version 1909

*Windows 10 Version 2004

*Windows 10 Version 20H2

To see which version of Windows 10 your device is currently running, select the Start button, then select Settings > System > About.
To ensure that Windows 10 is up to date on your PC, select the Start button, then select Settings > Update & security > Windows Update. Select Check for updates. If updates are available, install them.


text:
Q: Java EE servlet error - duplicate URL pattern I'm in the process of making a prototype banking application for one of my assignments. I've successfully created the persistence API, EJBs, and all required tables. However, when I create the WebClient for my application and integrate that with the Enterprise application and try to run it, I get the following error:

java.lang.IllegalArgumentException: Servlet [RegistrationPortImpl] and
  Servlet [RegistrationRequesterPortImpl] have the same url pattern

The WebClient only has the default index.xhtml file on it and I have not yet integrated to managed beans with it.
I just wanted to check if my application would run after the integration with enterprise application before I make any advances.

A: You can add the entry metadata-complete=true in the web-app tag like this:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

This post suggests something similar.
This entry disabled the scan for Servlet 3.0 specific annotations and web-fragments in /WEB-INF/lib. See here, here and here.
Maybe you could check the URL patterns in your web.xml and what libraries your app use.

A: In the @WebServlet put a unique url path for example @WebServlet("/port") @WebServlet("/requestport")
Annotate each of your servlet like this and then i believe this issue will not occur.


text:
Q: Let's be printed the matter
Let's be printed the matter.

This sentence is wrong and it sounds odd.
But grammatically what is the error in this sentence? Is there any specific format for Let's? I have read on a website that "Let is followed by an infinitive without 'to' ".

A: "Let's" is a contraction for "let us."
Thus, assuming novels converse with one another before being printed, a not-yet-printed novel might say to one or more other not-yet-printed novels,

Let's be printed

That is perfectly grammatical, however odd the thought.
No one would think odd

Let's be photographed together.

Now consider the following sentence:

Let the book be printed

This sentence is in standard word order: it has an imperative verb, "let," with an implied subject, and the verb's object, "book," properly follows that verb and precedes the modifying passive infinitive "be printed."

Let be printed the book

is simply invalid word order in English.

Let the matter be printed

is grammatical but makes no sense. Matters are not books or papers that are printed.

Let's be printed the matter

mixes up "let's" and "let," violates grammatical word order, and uses the word "matter" when something else was meant. It sounds odd because it is simultaneously ungrammatical and nonsensical.


text:
Q: ld: warning: directory not found for option: -LC_ID_DYLIB=/usr/lib I'm using OSX command line gcc and attempting to build a dynamic library. when I do the build I get the following warning.  How is it it is not finding this library given /usr/lib is well known?  And /usr/lib does indeed exist on my machine
this is what I am using:
gcc -arch i386 cata/*.c -dynamiclib -o build/cata.dylib -LC_ID_DYLIB=/usr/lib

Thanks

A: the way i solved it was to make it so the string that got stuck in the library (on where to find the library at runtime) was relative to nowhere -- if that makes sense. so it would be forced to use the LD_LOAD_PATH.
I was using the other flags because someone suggested I use them.
so the gcc i ended up using is this:
# my tree is like this
# cata/*.c
# build/*.dylib
#
cd build
gcc -arch i386 ../cata/*.c -dynamiclib -o cata.dylib

Doing this compiles/makes a library in the same directory where it thinks it is 'used' (basically having no path).  I am now free to put it somewhere else.  When it is later linked at compile time by a different program and then examined using
otool -L

it appears with no path in front of the library name.   This is apparently preferable as now when the system goes to try to find it it resorts to looking at the standard libraries and eventually finds it (because I install it to one of the standard locations).
In the original way, otool -L was showing it having a required path of
'build/cata.dylib'

This made it un-findable and which is why i was trying to use the apple documentation to get around the problem.
This doesn't really solve why LC_ID_DYLIB doesn't work.  I looked into the Loader.h file (line 643) and it has room for an identifier(0xd), a path, and a structure, so I don't really understand why my path wasn't getting picked up.  but its two different topics.  Loader.h is runtime and the other is gcc AFAIK.  I'm still learning apple.


text:
Q: Cannot pull a newly created empty docker repo: repository not found
$ sudo docker pull d33tah/afl-sid
Trying to pull repository docker.io/d33tah/afl-sid ... failed
FATA[0002] Repository not found

What am I doing wrong here?

A: Apparently I needed to tag and push the repo first.


text:
Q: Find the matrix of T with respect to the standard bases for M2x2 and P2 Let $T$: $M_{2x2}$ → $P_2$ be defined by $T$$\bigl( \begin{smallmatrix} a & b \\ c & d \end{smallmatrix} \bigr)$ = $(a+b-c-d)t^2+(c+d)t+(a+b)$.
Find the matrix of $T$ with respect to the standard bases for $M_{2x2}$ and $P_2$.
To start, one thing that confuses me about this problem is the format that T is in. Can anyone help me interpret T before continuing to solve this?

A: Perhaps better notation would be $T\left( \begin{bmatrix} a & b \\ c & d \end{bmatrix} \right) = (a+b-c-d)t^2 + (c+d)t + (a+b) $.
$T$ is a function. The matrix $\begin{bmatrix} a & b \\ c & d\end{bmatrix}$ is the input of $T$. The output of $T$ is the polynomial $(a+b-c-d)t^2 + (c+d)t + (a+b)$.

A: Let $T(A)$  can be defined in the following form
$$ \begin{bmatrix} t^2 + 1 &&-t^2 -t \\\end{bmatrix} A \begin{bmatrix} 1 \\ 1\end{bmatrix}$$

A: The standard basis of $\mathcal M_{2,2}$ is
$$E_{1,1}=\begin{bmatrix}1&0\\0&0\end{bmatrix},\enspace E_{1,2}=\begin{bmatrix}0&1\\0&0\end{bmatrix},\enspace E_{2,1}=\begin{bmatrix}0&0\\1&0\end{bmatrix}, \enspace E_{2,2}=\begin{bmatrix}0&0\\0&1\end{bmatrix}. $$
You have to find the  $3\times4$ matrix with first column the coordinates of $T(E_{1,1})$, second column the coordinates of $T(E_{1,2})$, &c.


text:
Q: Circulation around a self-intersecting curve
Is computing circulation around this curve sensible? In a circuit, electric current flows through intersecting paths - but I haven't seen an instance where it flows within a closed, self-intersecting loop such as that above. If it is sensible, what is its interpretation? Also, let me know whether the following statement is accurate:
"Using the fluid interpretation, circulation is a constant value which indicates the rate at which a fluid immersed in the vector force field would flow."


text:
Q: "Error Creating Control" when using Microsoft Office SharePoint Designer 2007 I am designing a form using the SP designer 2007. I am getting the following error on of my control

Is there any fix for this please?

A: Did you try the solutions in the links -
http://blogs.msdn.com/b/jjameson/archive/2007/03/22/error-creating-control-when-using-microsoft-office-sharepoint-designer-2007.aspx
http://social.msdn.microsoft.com/forums/en-US/sharepointcustomization/thread/2b837df5-0c83-4401-8cbd-51dacf0dd0f2/

A: I'm pretty sure I've seen this before and that it was caused by including a column in the form where the user doesn't have permission to the list for a lookup. Since you haven't included
any  information about your list, I can only guess that this the the cause here as well.


text:
Q: Xamarin android .axml file loading error : This item doesn't support previewing I have installed Xamarin today & when I create a project, everything goes right but when I want to open the .axml file in layout folder, visual studio crashes! nothing happens & speed of the visual studio reduces the PCs performance. the only error that I get is: This item doesn't support previewing!
What should I do? Please help... . Thanks

A: The xamarin android designer has a lot of problems and a lot of community discussions which can be found :
https://forums.xamarin.com/discussion/118384/android-designer-does-not-work-well
https://forums.xamarin.com/discussion/125879/designer-not-loading-layout-at-all
https://forums.xamarin.com/discussion/76851/visual-studio-2015-android-designer-not-working
https://forums.xamarin.com/discussion/82082/android-designer-not-working-in-visual-studio-enterprise-2015
https://forums.xamarin.com/discussion/6258/android-designer-doesnt-work-in-vs-2012
https://developercommunity.visualstudio.com/content/problem/99268/xamarin-android-designer-not-working.html
After reading all this discussion I could not understand the actual core reason of the issue and I was actually frustrated to the point where I repaired my Visual studio, now I could see the AXML file as XML when I opened it with the designer(crash stopped). But I could still not open the designer, So what I did was as I had experience with working with the android studio and I never faced this issue, I started working on Android studio for the AXML and copy-pasted that to xamarin and it worked like a charm.
Revert in case of queries


text:
Q: WM_NCCALCSIZE, custom client area, and scroll bars I have an MFC app that embeds a Scintilla text edit control. I want to customize the Scintilla control to display some custom controls next to the vertical scrollbar. Essentially, I want to  render some controls in the orange area below, where the green area represent the scroll bars:

I tried overriding the WM_NCCALCSIZE message of the Scintilla window and subtracting an offset from the right side of the client rectangle. Here is the code:
void CScintillaCtrl::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp)
{
    CWnd::OnNcCalcSize(bCalcValidRects, lpncsp);
    lpncsp->rgrc[0].right -= 100;
}

However, this causes the vertical and horizontal scroll bars to reposition themselves to account for the smaller client width, as shown below:

I'm not sure if this behavior is caused by Scintilla or Windows. Is there a way I can adjust the client area and preserve the positions of the scroll bars?

A: I found a Scintilla specific solution. I can use the SCI_SETMARGINRIGHT command to add a margin to the right side of the client area, and then render my controls inside that.


text:
Q: Does locking in this situation guarantee that multiple modifications are atomic across threads? I am trying to determine a solution to a problem I am facing outlined in this Programmers.SE question. The specific problem I am facing right now is that I need someway to make multiple atomic modifications to collections from the System.Collections.Concurrent namespace. From what I can tell there is no mechanism in place to do so; concurrent collections only guarantee that single operations are atomic.
One solution to the problem I do not wish to have to implement is to create my own concurrent collection that provides some mechanism or method for multiple atomic operations. I'd like to think I am experienced enough to write my own concurrent collection to allow multiple atomic modifications, though I would much rather use out of the box, well developed classes.
In light of this I have thought of another possible solution using the out of the box collections provided. My solution is to use a lock to control access to parts of code that perform multiple modifications so that they do not interleave each other.
public interface IWork { }
public interface IResource { }

public sealed class WorkPerformer
{
    public static WorkPerformer Instance { get { return lazyInstance.Value; } }
    public static readonly Lazy<WorkPerformer> lazyInstance = new Lazy<WorkPerformer>(() => new WorkPerformer());

    private ConcurrentDictionary<IResource, ConcurrentQueue<Guid>> IResourceWaitQueues { get; set; }
    private ConcurrentDictionary<IWork, ConcurrentDictionary<IResource, Guid>> IWorkToPerform { get; set; }

    private readonly object _LockObj = new object();

    private WorkPerformer()
    {
        IResourceWaitQueues = new ConcurrentDictionary<IResource, ConcurrentQueue<Guid>>();
        IWorkToPerform = new ConcurrentDictionary<IWork, ConcurrentDictionary<IResource, Guid>>();
    }

    private void ModifierTask_MultipleAdds(IWork workToDo)
    {
        Task.Run(() =>
        {
            lock(_LockObj)
            {
                // -- The point is here I am making multiple additions to IResourceWaitQueues and IWorkToPerform
                // Find all IResource this IWork uses and generate a Guid for each
                // Enqueue these Guid into their respective ConcurrentQueue's within IResourceWaitQueues
                // Add this IWork and IResource -> Guid mapping into IWorkToPerform
            }
        });
    }

    public void ModifierTask_MultipleRemoves(IWork workThatsDone)
    {
        Task.Run(() =>
        {
            lock (_LockObj)
            {
                // -- The point is here I am making multiple deletions to IResourceWaitQueues and IWorkToPerform
                // Find all IResource that this IWork used to perform its work
                // Dequeue from the ConcurrentQueue respective to each IResource used from IResourceWaitQueues
                // Remove this ITask KeyValuePair from IWorkToPerform
            }
        });
    }
}

I was wondering if this solution would work to allow multiple atomic operations to IResourceWaitQueues and IWorkToPerform in the example code above?
I would have to assume that it could turn out to be slow sometimes if there are multiple contentions for the lock. But other than that if I understand lock correctly these the multiple modifications I wish to perform should not interleave each other because only one thread should be allowed in the locked code at a time.
The only other issue I see is that I think I would have to lock on every other access to IResourceWaitQueues and IWorkToPerform in the example code above? Unless of course it is ok for the accesses to be interleaved with the locked portions of code.

EDIT: Here is a much more complete code example with some, hopefully, helpful comments on the exact problem I am trying to solve. Again for reference an alternatively worded explanation of the problem and solution is outlined in this Programmers.SE question I asked.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace WorkProcessorSandbox
{
    public interface IResource { }

    public interface IWork
    {
        void ProcessWork();
        List<IResource> NeededResources { get; set; }
    }

    // This classes purpose is to process IWork objects by calling their ProcessWork methods when it is found that
    // the IResources they need to process are free. The nature of IResource objects is that they are not threadsafe
    // (though some may be; some must be if an IResource appears in NeededResources multiple times). As a result
    // care must be taken to make sure two IWork do not try to use a distinct IResource simultaneously.

    // This is done by a sort of signalling/ticketing system. Each time a new IWork comes in to be processed it "lines
    // up" for the IResources it needs. Only when it is at the front of the line for all IResource it needs will it
    // move on to process. By forcing atomicity on the "lining up" of the IWork for IResources deadlocks and race conditions
    // can be prevented because the order of an IWork "ticket" in a line can never interleave anothers.
    public sealed class WorkProcessor
    {
        // Singleton class
        public static WorkProcessor Instance { get { return lazyInstance.Value; } }
        public static readonly Lazy<WorkProcessor> lazyInstance = new Lazy<WorkProcessor>(() => new WorkProcessor());

        // ResourceWaitQueues holds a Queue of Guids mapped to distinct
        // IResources representing the next IWork that is in line to use it
        private readonly object _Lock_ResourceDict = new object();
        private Dictionary<IResource, Queue<Guid>> ResourceWaitQueues { get; set; }

        // WorkToProcess holds a Dictionary of Guid mapped to IResources representing
        // the place in line this IWork (that said Dictionary is mapped to) is in for use of the IResources.
        private readonly object _Lock_WorkDict = new object();
        private Dictionary<IWork, Dictionary<IResource, Guid>> WorkToProcess { get; set; }

        private WorkProcessor()
        {
            Running = false;
        }

        private bool Running { get; set; }
        private CancellationToken ProcessingToken { get; set; }
        private CancellationTokenSource ProcessingTokenSource { get; set; }

        // Stops the processing of IWork from the WorkToProcess Dictionary
        public void StopProcessing()
        {
            if (Running)
            {
                ProcessingTokenSource.Cancel();
                Running = false;
            }
        }

        // Starts (Allows) the processing of IWork from the WorkToProcess Dictionary
        public void StartProcessing()
        {
            if (!Running)
            {
                // Instantiate to Empty
                ResourceWaitQueues = new Dictionary<IResource, Queue<Guid>>();
                WorkToProcess = new Dictionary<IWork, Dictionary<IResource, Guid>>();

                // Create CancellationToken for use in controlling Tasks
                ProcessingTokenSource = new CancellationTokenSource();
                ProcessingToken = ProcessingTokenSource.Token;
                Running = true;
            }
        }

        // The purpose of this method is to compare the list of Guids at the front of the Queues in ResourceWaitQueues
        // to the list of Guids that each IWork is waiting on for it to start processing.
        // If the Guids that an IWork needs to start processing is present in the list of Guids at the front of the Queues
        // then the IWork can start processing, otherwise it cannot.
        private void TryProcessWork()
        {
            if(Running)
            {
                // A Task that will go through all of the IWork waiting to be
                // processed and start processing the IWork objects that are ready.
                Task.Run(() =>
                {
                    // Here we need to lock on both the ResourceWaitQueues and WorkToProcess locks
                    lock (_Lock_ResourceDict) {
                    lock (_Lock_WorkDict)
                    {
                        // Go through the Dictionary of IWork waiting to be processed
                        foreach (var waitingWork in WorkToProcess)
                        {
                            // Find the List<Guid> that are needed for this IWork to be processed
                            var worksGuids = waitingWork.Value.Select(x => x.Value).ToList();

                            // Find the List<Guid> that are currently ready to be processed
                            var guidsReadyToProcess = ResourceWaitQueues.Values.Select(x =>
                            {
                                // If a Queue<T> is Empty when it is Peek'd it throws and Exception!
                                if (x.Count > 0)
                                    return x.Peek();
                                return Guid.Empty;
                            }).ToList();

                            // If the List<Guid> needed by this IWork is contained within the List<Guid> ready to be processed
                            if (worksGuids.All(x => guidsReadyToProcess.Contains(x)))
                            {
                                // This IWork is ready to be processed!
                                ProcessWork(waitingWork);

                                // Remove this IWork from WorkToProcess
                                if (!WorkToProcess.Remove(waitingWork.Key))
                                {
                                    Console.Out.WriteLine("Fatal error! Stopping work processing. Could not remove IWork from Dictionary that should contain it.");
                                    StopProcessing();
                                    break;
                                }
                            }
                        }
                    }
                    }
                }, ProcessingToken);
            }
        }

        // The purpose of this function is to "enqueue" IWork for processing. First a list of all the IResources
        // that the IWork needs to process is created along with a Guid for each unique IResource it uses.
        // These Guids are then enqueued into the respective Queue in ResourceWaitQueues representing this IWork's
        // "spot in line" to use those specific IResources. Finally the IWork and its Guids are then added to the
        // WorkToPerform Dictionary so that TryProcessWork can determine if it is ready to run or not.
        // TryProcess is called at the end to see if this IWork is possibly ready to process right away.
        public void EnqueueWork(IWork workToDo)
        {
            if (Running)
            {
                // Get all distinct IResource in the IWork's NeededResources
                var worksResources = workToDo.NeededResources.Distinct().ToList();

                // Create the Guids this IWork object will wait on to start processing
                Dictionary<IResource, Guid> worksGuidResourceMap = new Dictionary<IResource, Guid>();
                worksResources.ForEach(x => worksGuidResourceMap.Add(x, Guid.NewGuid()));

                // Here we need to lock on both the ResourceWaitQueues and WorkToProcess locks
                lock (_Lock_ResourceDict) {
                lock (_Lock_WorkDict)
                {
                    // Find all of the IResources that are not currently present in the ResourceWaitQueues Dictionary
                    var toAddResources = worksResources.Where(x => !ResourceWaitQueues.Keys.Contains(x)).ToList();

                    // Create a new entry in ResourceWaitQueues for these IResources
                    toAddResources.ForEach(x => ResourceWaitQueues.Add(x, new Queue<Guid>()));

                    // Add each Guid for this works IResources into the Queues in ResourceWaitQueues
                    foreach (var aGuidResourceMap in worksGuidResourceMap)
                    {
                        foreach (var resourceQueue in ResourceWaitQueues)
                        {
                            if (aGuidResourceMap.Key == resourceQueue.Key)
                                resourceQueue.Value.Enqueue(aGuidResourceMap.Value);
                        }
                    }

                    // Add this IWork and its processing info to the Dictionary of awaiting IWork to be processed
                    WorkToProcess.Add(workToDo, worksGuidResourceMap);
                }
                }

                // Go through the list of IWork waiting to be processed and start processing IWork that is ready
                TryProcessWork();
            }
        }

        // The purpose of this function is to create a Task in which the IWork passed to it can be processed.
        // Once the processing is complete the Task then dequeues a single Guid from the Queue respective to
        // each IResource it needed to process. It then calls TryProcessWork because it is most likely possible
        // there is some IWork that is now ready to process.
        private void ProcessWork(KeyValuePair<IWork, Dictionary<IResource, Guid>> workToProcess)
        {
            Task.Run(() =>
            {
                // Actually perform the work to be processed.
                workToProcess.Key.ProcessWork();

                // Get the list of the IResources that were used during processing
                var usedResources = workToProcess.Value.Select(x => x.Key).ToList();

                // We are removing multiple Guids from the ResourceWaitQueues. They must be atomic.
                // The ResourceWaitQueues could become incoherent if any other operations are performed on it during the dequeueing.
                // It is ok for WorkToProcess to be modified while this is happening.
                lock (_Lock_ResourceDict)
                {
                    // Get the Queues corresponding to these IResources
                    var resourceQueues = ResourceWaitQueues.Where(x => usedResources.Contains(x.Key)).Select(x => x.Value).ToList();

                    try
                    {
                        // Dequeue a Guid from each of these Queues exposing the next Guid to be processed on each
                        resourceQueues.ForEach(x => x.Dequeue());
                    }
                    catch (InvalidOperationException ex)
                    {
                        Console.Out.WriteLine("Fatal error! Stopping work processing. Could not dequeue a Guid that should exist: " + ex.Message);
                        StopProcessing();
                    }
                }

                // Go through the list of IWork waiting to be processed and start processing IWork that is ready
                TryProcessWork();

            }, ProcessingToken);
        }
    }
}

A: Without a good Minimal, Complete, and Verifiable code example that accurately illustrates your scenario, it's impossible to say for sure. But based on your description so far, it seems reasonably clear that using lock will address your primary issue (atomicity of some grouped series of operations)
Whether you need to also use lock on all other accesses of the same objects depends on what those accesses are and how they relate to the grouped operations you're protecting with lock. For sure, there is no need to use lock just to make sure that the collections remain coherent. Their internal synchronization will ensure that.
But if your grouped operations represent some type of coherency in and of itself, where other accesses to the objects would be incorrect if they were allowed to take place while a grouped operation was in progress then, yes, you would need to also use lock, with the same _LockObj reference, to ensure that the grouped operation could not take place at the same time any other access was taking place which depended on the coherency of the data structure in aggregate.
If you need more specific advice than that, please improve the question so that it's clear how all of these operations actually relate.

Aside: you may want to consider following normal .NET coding conventions: restricting your use of Pascal casing to methods and properties, and using camel-casing for fields. This will make it easier for readers to follow your code.
I would say that for sure, it's a very bad choice to use for fields the .NET convention for interface naming (i.e. Pascal-cased identifiers which always start with I). You are sure to make it very difficult for people to understand your code when you do that.

A: To maximise performance you should avoid locking X number of IResource objects for the duration of the IWork.ProcessWork method. The problem is if you have an IWork object that requires 10 IResource objects, 9 of those resources may take only a few milliseconds to process while the 10th could take minutes, in this scenario, all 10 of the resource objects will be locked so that no other IWork object can use them for the full time it takes to complete the work.
By creating a LockResource method and a ReleaseResource method, you can use the ConcurrentDictionary as it's designed without the need of wrapping it in a lock as you will only be performing atomic operations, i.e. add IResource to ResourceWaitQueue and remove IResource from ResourceWaitQueue. This will allow your IWork objects to execute in an efficient way where the only bottle neck is the actual resources rather than the code.


text:
Q: shinydashboard menuItem with widgets not showing results I'm building an app with shinydashboard which incorporates a side bar menu with menuItem / tabItems, but i can't get the 2nd tab (which includes widgets) to display the result.  The body is only displaying the 1st tab.  It must be something very simple but i can't see what i'm doing wrong...
here's a reproducible example:
## app.R ##
library(shiny)
library(shinydashboard)

ui <- dashboardPage(

  dashboardHeader(),

  dashboardSidebar(

    sidebarMenu(

      menuItem("SomeText",
               tabName = "sometext"
               ),

      menuItem("Histogram",
               tabName = "histogram",

            # input1: number of observations:
            sliderInput(
              inputId = "n",
              label = "Number of observations",
              min = 10, max = 100, value = 30
            )

      ) # end menuItem

    ) # end sidebarMenu

  ), # end dashboardSidebar

  dashboardBody(
     tabItems(

         tabItem(tabName = "sometext",
            h2("blah blah blah")
         ),

        tabItem(tabName = "histogram",
            plotOutput("my_histogram")
        )
    )
  )
)

server <- function(input, output) {
  output$my_histogram <- renderPlot({
    hist(input$n, col = "red" )
  })

  }

shinyApp(ui, server)

Why can i not see the histogram plot on the 2nd tab item?

A: shinydashboard's sidebar distinguishes "childless" and "childfull" menuItems. By placing the sliderInput inside the menuItem "histogram" it becomes "childfull", which means one or more sub categories are available for navigation, accordingly there is no need to display content in the body, as the user is expected to navigate to one of the childs. Please read this for further information.
Therefore, if you want to display content in the body for the "histogram"-tab it needs to be "childless".
Here is a solution placing the slider outside of the "histogram"-tab, but only displaying it when "histogram" is selected:
## app.R ##
library(shiny)
library(shinydashboard)

ui <- dashboardPage(dashboardHeader(),
                    dashboardSidebar(
                      sidebarMenu(
                        id = "mySidebar",
                        menuItem("SomeText", tabName = "sometext"),
                        menuItem("Histogram", tabName = "histogram"),# end menuItem
                        conditionalPanel(condition = "input.mySidebar == 'histogram'", {
                          # input1: number of observations:
                          sliderInput(
                            inputId = "n",
                            label = "Number of observations",
                            min = 10,
                            max = 100,
                            value = 30
                          )
                        })
                      ) # end sidebarMenu
                    ), # end dashboardSidebar
                    dashboardBody(tabItems(
                      tabItem(tabName = "sometext",
                              h2("blah blah blah")),
                      tabItem(tabName = "histogram",
                              plotOutput("my_histogram"))
                    )))

server <- function(input, output) {
  output$my_histogram <- renderPlot({
    hist(round(runif(input$n, 1, 10), digits = 0), col = "red")
  })
}

shinyApp(ui, server)


text:
Q: static file not found after deploy not in a root dir (nextjs) I deploy my nextjs web in a not root dir like '/next' not '/';
after that the static files in public floder can not be found.
Because the url that request is not http://example.com/next/a.png but the
http://example.com/a.png
how can i config it to make it request 'http://example.com/next/a.png'
pls help me

A: You can use assetPrefix feature to specify your additional dir.
// next.config.js

module.exports = {
  // Use the CDN in production and localhost for development.
  assetPrefix: process.env.NODE_ENV === 'production' ? '/next/' : '',
}


text:
Q: JetBrains MPS - Constrain ClassifierType reference to subclasses of a given type I'm writing a DSL in MPS to define event producer/consumers, like this:
on FooEventProducer
    then FooEventConsumer

where:
class FooEventProducer implements Producer<FooEvent> {}
class FooEventConsumer implements Consumer<FooEvent> {}

I have an On concept containing a ClassifierType reference.
How do I constrain the ClassifierType reference to subclasses of Producer?

A: I recommend that you create and use your own sub-concept of ClassifierType, which specifies constraints on the "classifier" reference, something like:
concepts constraints MyClassifierType {
  can be child <none>

  can be parent <none>

  can be ancestor <none>

  <<property constraints>>

  link {classifier}
    referent set handler:<none>
    scope:
      (exists, referenceNode, contextNode, containingLink, linkTarget, operationContext, enclosingNode, model, position, contextRole)->Scope {

        sequence<node<Classifier>> candidates = model.nodesIncludingImported(Classifier).where({~it => it.getExtendedClassifierTypes().any({~clazz => clazz.classifier :eq: node/Runnable/; }); });
        new ListScope(candidates) {
          public string getName(node<> child) {
            child : INamedConcept.name;
          }
        };
      }
    presentation :
      <no presentation>
  ;

  default scope
    <no default scope>

}


text:
Q: Insert tipo timestamp em banco de dados firebird Erro no insert em banco de dados firebird, field DataCadastro de tipo timestamp não aceita string.
INSERT INTO VENDA(CODIGO, NRO_VENDA, DATA_VENDA, VALOR_TOTAL_PRODUTOS, VALOR_ACRESCIMO,
VALOR_DESCONTO, VALOR_TOTAL_VENDA, CODIGO_CLIENTE)
VALUES (1, 1, '14/12/2016', 5, 2, 3, 2, 1)

Overflow occurred during data type conversion.

A: Tente substituir a data de '14/12/2016'por '12/14/2016'
A data no firebird segue o seguinte formato: MM/DD/YYYY.


text:
Q: Unused variable warning in XCode 6 I see this warning while compiling within the Mixpanel framework used in my project.

It was not showing when I compiled some moment back. Is it a bug in XCode 6? How the variable k is unused here?

A: You must be compiling with the constant NS_BLOCK_ASSERTIONS set, so those NSAssert() statements are disabled.
From the documentation:

Assertions are disabled if the preprocessor macro NS_BLOCK_ASSERTIONS
  is defined.


text:
Q: efficient date comparison in data table I have a data frame (actually a data table) that looks like
id  hire.date   survey.year
1   15-04-2003  2003
2   16-07-2001  2001
3   06-06-1980  2002
4   17-08-1981  2001

I need to check if hire.date is less than say 31st March of survey.year. So I would end up with something like
id  hire.date   survey.year   emp31mar
1   15-04-2003  2003          FALSE
2   16-07-2001  2001          FALSE
3   06-06-1980  2002          TRUE
4   17-08-1981  2001          TRUE

I could always create an object holding March 31st of survey.year and then make the appropriate comparison like so
mar31 = as.Date(paste0("31-03-", as.character(myData$survey.year)), "%d-%m-%Y")

myData$emp31 = myData$hiredate < mar31

but creating the object mar31 is consuming too much time because myData is large-ish (think tens of millions of rows).
I wonder if there is a more efficient way of doing this -- a way that doesn't involve creating an object such as mar31?

A: You could try the data.table methods for creating the column.
library(data.table)
setDT(df1)[,  emp31mar:= as.Date(hire.date, '%d-%m-%Y') <
             paste(survey.year, '03-31', sep="-")][]
#     id  hire.date survey.year emp31mar
#1:  1 15-04-2003        2003    FALSE
#2:  2 16-07-2001        2001    FALSE
#3:  3 06-06-1980        2002     TRUE
#4:  4 17-08-1981        2001     TRUE


text:
Q: Runtime Error Cannot read property 'remove' of undefined I am using import { Storage } from '@ionic/storage' storage
give Runtime error Cannot read property 'remove' of undefined when use this.storage.remove('key');

this is my function code where i used:this.storage.remove
logout(): void {
            this.storage.remove(this.HAS_LOGGED_IN);
            this.storage.remove('email');
            this.events.publish('user:logout');
          };

A: You have to inject a storage object in the constructor:
import { Storage } from '@ionic/storage';

constructor(private storage: Storage) {

}

logout(): void {
    this.storage.remove(this.HAS_LOGGED_IN);
    this.storage.remove('email');
    this.events.publish('user:logout');
};

Note that you also have to register the storage module in your app:
import { IonicStorageModule } from '@ionic/storage';

@NgModule({
    declarations: [
        // ...
    ],
    imports: [
        IonicModule.forRoot(MyApp),
        IonicStorageModule.forRoot()
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        // ...
    ],
    providers: []
})
export class AppModule {}

See this documentation

A: install ionic-native package > $ npm install ionic-native --save
and use it like:
import { Storage } from 'ionic-native

//and in component class call it like this

Storage.remove('email');

you dont need to inject it if you are not using wrapper


text:
Q: What can cause a C variable to be initialized on 1? I am making a basic x86 operating system with a group using C and NASM for college. We have to make a simple game using VGA Mode 3 to display the 'graphics' on a 80x50 characters grid. We are using bochs to simulate the OS.
Some time ago we had to make a procedure that, whenever a key is pressed, displays it on the top right of the screen. The teachers gave us some pre-made functions to interact with the PIC, and map the keyboard interrupt to entry 33 on the IDT. We had no problem with the implementation.
Now, recently, we added functionality to the necesary keys, while still displaying the pressed key on the top right. The difference is that now, for some reason, whenever you release the key, or press another one (i.e. you generate a scan code that isn't for a key that does something in-game), a smiley face is printed on the top right.
This is the code for the interrupt handler for the keyboard:
global _isr33

_isr33:
pushad
    xor eax,eax
    in al, 0x60
    push eax
    call manejo_teclado
    pop eax
    call fin_intr_pic1
popad
iret

This is the 'manejo_teclado' (handle_keyboard):
char manejo_teclado(char scanCode){
    char valor;
    int player;
    direccion dir;

    if(scanCode == 0x2a){
        valor = '1';

    }
    if(scanCode == 0x36){
        valor = '2';

    }
    if(scanCode == 0x1f){
        valor = 's';
        dir = ABA;
        player = 0;
        game_mover_cursor(player,dir);

    }
    //1e (A), 1f (S), 20
    if(scanCode == 0x1e){
        valor = 'a';
        dir = IZQ;
        player = 0;
        game_mover_cursor(player,dir);

    }
    if(scanCode == 0x20){
        valor = 'd';
        dir = DER;
        player = 0;
        game_mover_cursor(player,dir);

    }
    if(scanCode == 0x11){
        valor = 'w';
        dir = ARB;
        player = 0;
        game_mover_cursor(player,dir);

    }
    //24 (J), 25 (K), 26 (L)
    if(scanCode ==0x17 ){
        valor = 'i';
        dir = ARB;
        player = 1;
        game_mover_cursor(player,dir);

    }
    if(scanCode == 0x24){
        valor = 'j';
        dir = IZQ;
        player = 1;
        game_mover_cursor(player,dir);

    }
    if(scanCode == 0x25){
        valor ='k' ;
        dir = ABA;
        player = 1;
        game_mover_cursor(player,dir);

    }
    if(scanCode == 0x26 ){
        valor = 'l';
        dir = DER;
        player = 1;
        game_mover_cursor(player,dir);
    }
    if(scanCode == 0x15){
        //modo debug
        valor = 'y';
        //lanzar_modo_debug();
    }

    print_char(valor, 79, 0, (unsigned short)0x0E);
    return valor;
}

And the 'print_char' (VIDEO_SCREEN is 0xB8000 and 'ca' is a struct that holds a byte for character and a byte for formatting)
void print_char(char  text, unsigned int x, unsigned int y, unsigned short attr) {
    ca (*p)[VIDEO_COLS] = (ca (*)[VIDEO_COLS]) VIDEO_SCREEN;
    p[y][x].c = (unsigned char) text;
    p[y][x].a = (unsigned char) attr;
}

The 'valor' variable, that is the one that gets printed to the screen, is never initialized when the scanCode isn't one of the defined ones, but still is being initialized with the value of 1 (the code for the face).
I have changed the 'manejo_teclado' function, replacing the chain of ifs for a single if-else if-else if-.. chain. This gets rid of the smiley face.
The face is also consistent, it has happened on all the computers we have compiled this in. We didn't make the makefile (teachers provided one for us), and the gcc version is 4.8.4.
So for the questions: Is this something that is caused by the compiling process? Is gcc misinterpreting something on the function? Are we missing something else?
Sorry for any typos and/or mistakes, here's a pic of the perpetrator:


text:
Q: How to find a button within
* and
* via Proctractor? I am new to automation, and my previous experiences were with non-Angular apps, thus i start to use Protractor.
I want to navigate throught the website, though cannot find the right selector.
The button is highlighted in red on the bottom of the screen:
I've tried below code among many:
element(by.name('Flota')).click()
or
element(by.css('.ng-tns-c11-5')).click()
element(by.css('div[title=Flota]'));

A: maybe you should target the <a> or <nb-icon> element instead?
Try the following locators:
using a:
element(by.css('.ng-tns-c11-16.ng-star-inserted.active'));

or nb-icon:
element(by.css('.menu-icon.ng-tns-c11-16.ng-star-inserted'));

Additionally, if you need to target the <span> element:
element(by.css('.ng-tns-c11-16.ng-star-inserted.active span'));

A: I suggest
by.css("a[title='Flota']") //if this is the button you are looking for
Since the shorter is locator - the better

A: your help was much appreciated!
Unfortunately, i tried all options you provided and didn't work, though i made additional trial and error runs.
The code i worked out is below, maybe it will help another newbie like me:
element.all(by.css('#menu-item ng-tns-c11-4 ng-star-inserted li')).click()


text:
Q: Prove that a relation R on A is antisymmetric if and only if $R∘R^{-1} \subseteq I_A$ If: I tried to take some element $(a,b)∈R∘R^{-1}$ and show that we have some $c∈A$ s.t. $(a,c)∈R^{-1}$ and $(c,b)∈R$, and use the fact that $R∘R^{-1} \subseteq I_A$ which gives that $a=b$.  I then tried to show that $(b,c)∈R$ with $b≠c$ and find a contradiction but couldn't get anything.
I didn't get to the only if yet because I've been very stuck.  Any help is appreciated.
Also note we have our standard definition of antisymmetry: A relation $R$ on a set $A$ is said to be antisymmetric if, for all $x∈A$ and $y∈A$, whenever $(x,y)∈R$ and $(y,x)∈R$, then $x=y$.

A: I think you really want to prove the correct

The relation $R$ on $A$ is antisymmetric iff $R \cap R^{-1} \subseteq I_A$.

So not composition of relations, but intersection!
To show the original statement is false, let $R$ be $\le$ on $A=\mathbb{N}$, say (classically antisymmetric). Then $(1,2) \in R$, $(3,1) \in R^{-1}$ so $(3,2) \in R \circ R^{-1}$ but $(3,2) \notin I_A$.
The corrected statement is really a restatement of the definition of antisymmetricity of $R$, try it.


text:
Q: why does not toggle work on click if the element has a class JS I do animation of cards using css and js. It seems that almost everything worked out. I just can't figure out why this.classList.toggle ('is-active');
does not remove the class on the second click on the element. Help fix the error. What is the problem here. Why does toggle work like add in this situation? What's my mistake.

window.addEventListener('load', function() {
  const cardsLst = document.querySelectorAll(".card");
  for (let card of cardsLst) {
    card.addEventListener("click", function() {
      for (let card of cardsLst) {
        card.classList.remove('is-active');
      }
      this.classList.toggle('is-active');
    });

  }
})
.cards {
  display: grid;
  grid-template-columns: repeat(3, 33.33%);
  grid-auto-rows: 70vh;
}

.card {
  position: relative;
  overflow: hidden;
}

.card img {
  transition: 2s;
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

.card .card__title {
  color: #fff;
  position: relative;
  z-index: 2;
}

.card__text {
  position: absolute;
  padding: 50px 100px;
  font-size: 15px;
  transform: translate(0px, 70vh);
  transition: transform .5s ease 0s;
  z-index: 2;
  color: #fff;
}

.card:hover img {
  transform: scale(1.2);
  /* Увеличиваем масштаб */
}

.card.is-active .card__text {
  transform: translate(0px, 0px);
  transition: transform .5s ease .5s;
  top: 50%;
  /* 3 */
  transform: translate(0, -50%);
}

.card:after {
  content: "";
  margin: 0;
  background: red;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
  border-radius: 100%;
  width: 0;
  height: 0;
  transition: all 1.3s;
}

.card.is-active:after {
  width: max(100vh, 100vw);
  height: max(100vh, 100vw);
}

Lorem

ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla?

Lorem

ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla?

Lorem

ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla?

A: The is-active has already been removed in the for loop. Hence toggle will add it back.
As a fix, skip removing the class in the for loop.
for (let card of cardsLst) {
  if(card === this) { continue; }
  card.classList.remove('is-active');
}


text:
Q: How do I do this query in postgres? We have a json column 'passed_states_data' in table party_procedures
The column data looks like this:

[{"state":"documents","passed_at":"2016-02-04 13:16:51
  +0100"},{"state":"problems","passed_at":"2016-02-04 16:10:07 +0100"},{"state":"waiting_for_physical_documents","passed_at":"2016-02-08
  13:50:17
  +0100"},{"state":"customer_acceptance","passed_at":"2016-02-08 13:50:19
  +0100"},{"state":"customer_identifier","passed_at":"2016-02-08 13:50:54 +0100"},{"state":"checking_account","passed_at":"2016-02-08
  13:51:45
  +0100"},{"state":"transfer_money_to_savings_account","passed_at":"2016-02-10
  09:12:18 +0100"}]

I need to build query that only returns rows where 'transfer_money_to_savings_account' exists and then get the passed_at date.
so the query should return something like this:
select blah as "date passed" from party_procedures pp
  where json_array_elements(pp.passed_states_data)->>'state'='transfer_money_to_savings_account' = 't'

or something like that.

A: json_array_elements() function returns set of json, therefore, you cannot use ->> for that; in other words, you need to iterate over the set of json array elements and check if state has a value you a looking for.
WITH t(passed_states_data) AS ( VALUES
  ('[{"state":"documents","passed_at":"2016-02-04 13:16:51 +0100"},
     {"state":"problems","passed_at":"2016-02-04 16:10:07 +0100"},
     {"state":"waiting_for_physical_documents","passed_at":"2016-02-08 13:50:17 +0100"},
     {"state":"customer_acceptance","passed_at":"2016-02-08 13:50:19 +0100"},
     {"state":"customer_identifier","passed_at":"2016-02-08 13:50:54 +0100"},
     {"state":"checking_account","passed_at":"2016-02-08 13:51:45 +0100"},
     {"state":"transfer_money_to_savings_account","passed_at":"2016-02-10 09:12:18 +0100"}]'::JSON)
)
SELECT j->>'passed_at' as "date passed" FROM t, json_array_elements(t.passed_states_data) j
WHERE j->>'state' = 'transfer_money_to_savings_account';

Result:
        date passed
---------------------------
 2016-02-10 09:12:18 +0100
(1 row)


text:
Q: unrecognized selector sent to instance on ios table view cell click I'm a very beginner to iOs. I'm going to view a list in table view controller. My application is a story board application. I did the following code to go to the next view.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   LawyerViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"LawyerViewController"];
   dvc.lawyer = @"Thisara";//[self.myObject objectAtIndex:indexPath.row];
   [self.navigationController pushViewController:dvc animated:YES];
}

in my LawyerViewController header file I defined the following property.
@property (nonatomic, strong) NSString *lawyer;

When I'm clicking on the cell, I've got following error.
2014-07-26 23:56:14.420 lawyerapp[3626:60b] -[UIViewController setLawyer:]: unrecognized        selector sent to instance 0x8cdd1f0
2014-07-26 23:56:14.424 lawyerapp[3626:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setLawyer:]:
unrecognized selector sent to instance 0x8cdd1f0'

How do I fix this.
Thanks in Advance!

A: You have not defined the class in storyBoard.
Go to your viewController in StoryBoard ->
 than identity Inspector -> class -> Put the class LawyerViewController.

Clean,build and run


text:
Q: Swift: Rotate UIImageView from fixed position to full screen I want to rotate a view. Tried different things but can not make it
I use autolayout.
As a result I have imageView in the top of the screen with share almost as a square
        func presentPortrait() {
        coverImageView.layer.transform = CATransform3DIdentity
        coverImageView.snp.remakeConstraints { (make) in
        make.leading.trailing.top.equalToSuperview()
        make.width.equalTo(coverImageView.snp.height).multipliedBy(375.0/211.0)
    }

    func presentLandscape() {
    coverImageView.layer.transform = CATransform3DMakeRotation(CGFloat(.pi/2), 0.0, 0.0, 1.0)
    coverImageView.snp.remakeConstraints { (make) in
    make.leading.trailing.top.bottom.equalToSuperview()


text:
Q: Sorting Algorithm that minimizes the maximum number of comparisons in which individual items are involved I'm interested in finding a comparison sorting algorithm that minimizes the number of times each single element is compared with others during the run of the algorithm.
For a randomly sorted list, I'm interested in two distributions: the number of comparisons that are needed to sort a list (this is the traditional criterion) and the number of comparisons in which each single element of the list is involved.
Among the algorithms that have a good performance in terms of the number of comparisons, say achieving O(n log(n)) on average, I would like to find out the one for which, on average, the number of times a single element is compared with others is minimized.
I supposed that the theoretical minimum is O(log(n)) which is obtained by dividing the above figure on the total number of comparisons by n.
I'm also interested in the case where data are likely to be already ordered to some extent.
Is perhaps a simulation the best way to go about finding an answer?
(My previous question has been put on hold - This is now a very clear question, if you can't understand it then please explain why)

A: Yes you definitely should do simulations.
There you will implicitely set the size and pre-ordering constraints in a way that may allow more specific statements than the general question you rose.
There can, however, not be a clear answer to such question in general.
Big-O deals with asymptotic behaviour while your question
seem to target smaller problem sizes. So Big-O could hint on the best candidates for sufficiently large input sets to a sort run. (But, e.g. if you are interested in size<=5 the results may be completely different!)
For getting proper estimate on comparison operations you would need
to analyze each individual algorithm.
At the end, the result (for a given algorithm) will necesarily be specific to the dataset being sorted.
Also, on avarage is not well defined in your context. I'd assume you intend to refer to the number of comparisions on the participating objects for a given sort and not avarage over a (sufficiently large) set of sort runs.
Even within a single algorithm the distribution of comparisions an individual object is taking place in may show a large standard deviation in one case and be (nearly) equally distributed in another case.
As complexity of a sorting algorithm is determined by the total number of comparisons (and position changes thereof), I do not assume there will be much from therotical analysis contributing to an answer.
Maybe you can add some background on what would make an answer to your question "interesting" in a practical sense?


text:
Q: Drawing method flow I have tried to draw noDuplicate method for array, but I couldn't completed it. Ay help with that:
public void noDups(){

    int size = elementsSize - 1;
    long duplicated = 0;

    for(int i = 0; i <= size; i++){
        duplicated = longArray[i];

        for (int j = i+1; j <= size; j++) {
            if(longArray[j] == duplicated){

                for (int k = j; k < size; k++) {
                    longArray[k] = longArray[k+1];
                }
                elementsSize--;
                j--;
                size--;
                System.out.println("Duplicated Deleted using noDups " + duplicated);
            }
        }
    }
}

please see attached file for drawing ref.

A: Can you create a set and put all your element into it.It will retain only unique value.


text:
Q: symlink in ubuntu I'am newbie I want to add a symbolic link to another folder
I want to say ln -sf / var / www / html to
/home / var / exemple / public
This is good.
/ home / var / example / public belongs to a user who creates.
in any case this is fine to do in production

A: To create a symbolic link of /var/www/html in /home/var/example/public, you can
ln -s /var/www/html /home/var/example/public

maybe you meant the destination folder as ~/public which will be in the same user.


text:
Q: How to make a table with many checkboxes I have a question regarding selectManyCheckboxes. And by that I mean, many. I have in the bean a list of 85 options which I have to display in 4 columns, and every column should have around 25 options. My snipet of code is this:
<p:selectManyCheckbox id="groups" value="#{shareOfferBean.selectedGroupIds}" layout="pageDirection" label="#{amsg.groups}"
                                          converter="groupConverter">
    <f:selectItems value="#{shareOfferBean.groups}" var="g" itemValue="#{g.id}" itemLabel="#{g.name}"/>
</p:selectManyCheckbox>

With this, I get only all of the checkboxes in 1 column and 85 rows which is really really ugly on the page. How can I make the rows limited, so they break and go in another column? Thanks to everyone that tries helping!

A: How about using an UI:repeat to loop through.
<ui:repeat var="x" value="#{tableBean.kList}">
   <p:selectManyCheckbox id="groups" value="#{shareOfferBean.selectedGroupIds}" layout="pageDirection" label="#{amsg.groups}"
                                      converter="groupConverter">
<f:selectItems value="#{shareOfferBean.groups}" var="g" itemValue="#{g.id}" itemLabel="#{g.name}"/>
</p:selectManyCheckbox>
 </ui:repeat>

you could do something like this. i dint test it. you could give it a try