text:
Q: Add id to array of objects I have an array of objects. How do I add an id key to them starting from 1.
[
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
},
{
    color: "blue",
    value: "#00f"
},
{
    color: "cyan",
    value: "#0ff"
},
{
    color: "magenta",
    value: "#f0f"
},
{
    color: "yellow",
    value: "#ff0"
},
{
    color: "black",
    value: "#000"
}
]

So, it will be like
[
{
    color: "red",
    value: "#f00",
    id: 1
},
{
    color: "green",
    value: "#0f0",
    id: 2
},
{
    color: "blue",
    value: "#00f",
    id: 3
},
{
    color: "cyan",
    value: "#0ff",
    id: 4
},
{
    color: "magenta",
    value: "#f0f",
    id: 5
},
{
    color: "yellow",
    value: "#ff0",
    id: 6
},
{
    color: "black",
    value: "#000",
    id: 7
}
]

I tried using forEach but it was returning the id as the length - 1 value for all the objects inside the array.
I have a large number of objects and can use lodash too.

A: You can use .forEach() to iterate over array elements and add id:
data.forEach((o, i) => o.id = i + 1);

Demo:

let data = [{
    color: "red",
    value: "#f00"
}, {
    color: "green",
    value: "#0f0"
}, {
    color: "blue",
    value: "#00f"
}, {
    color: "cyan",
    value: "#0ff"
}, {
    color: "magenta",
    value: "#f0f"
}, {
    color: "yellow",
    value: "#ff0"
}, {
    color: "black",
    value: "#000"
}];

data.forEach((o, i) => o.id = i + 1);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use the map() function to iterate over your array of objects.
n is each of your objects and you can set the id value inside the map.
Hope this helps :)

let arr = [{
    color: "red",
    value: "#f00"
  },
  {
    color: "green",
    value: "#0f0"
  },
  {
    color: "blue",
    value: "#00f"
  },
  {
    color: "cyan",
    value: "#0ff"
  },
  {
    color: "magenta",
    value: "#f0f"
  },
  {
    color: "yellow",
    value: "#ff0"
  },
  {
    color: "black",
    value: "#000"
  }
]

let i = 0;
arr.map(n => {
  n['id'] = i;
  i++;
})

  console.log(arr);

A: ES6
You can use forEach() to get the required result.

const arr =[{color: "red",value: "#f00"},{color: "green",value: "#0f0"},{color: "blue",value: "#00f"},{color: "cyan",value: "#0ff"},{color: "magenta",value: "#f0f"},{color: "yellow",value: "#ff0"},{color: "black",value: "#000"}];

arr.forEach((o,i)=>o.id=i+1);
console.log(arr);
.as-console-wrapper {max-height: 100% !important;top: 0;}

You can also use map() to get the required result.
DEMO

const arr =[{color: "red",value: "#f00"},{color: "green",value: "#0f0"},{color: "blue",value: "#00f"},{color: "cyan",value: "#0ff"},{color: "magenta",value: "#f0f"},{color: "yellow",value: "#ff0"},{color: "black",value: "#000"}];

console.log(arr.map((o,i)=>Object.assign(o,{id:i+1})));
.as-console-wrapper {max-height: 100% !important;top: 0;}

A:   source.map((s, i)=> s.id = i+1);
   console.log(source)

A: You could use Array#forEach for this. The second argument of the callback refers to the index of the element. So you can assign the ID as index + 1.

const source = [{
    color: "red",
    value: "#f00"
  },
  {
    color: "green",
    value: "#0f0"
  },
  {
    color: "blue",
    value: "#00f"
  },
  {
    color: "cyan",
    value: "#0ff"
  },
  {
    color: "magenta",
    value: "#f0f"
  },
  {
    color: "yellow",
    value: "#ff0"
  },
  {
    color: "black",
    value: "#000"
  }
];

source.forEach((item, i) => {
  item.id = i + 1;
});

console.log(source);

A: The simples solution would be to use map function

let data = [{ color: "red", value: "#f00" }, { color: "green", value: "#0f0" }]

data = data.map((item, index) => ({ ...item, id: index + 1 }))

console.log(data)

A: No need for complex function and logic. Simply loop it over forEach which will also give you the index of each object in the array and assign that index+1 value to the id property of the object.

var arr = [
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
},
{
    color: "blue",
    value: "#00f"
},
{
    color: "cyan",
    value: "#0ff"
},
{
    color: "magenta",
    value: "#f0f"
},
{
    color: "yellow",
    value: "#ff0"
},
{
    color: "black",
    value: "#000"
}
];

arr.forEach((item, index)=>{
 item.id = index+1;
});
console.log(arr);

A: when i use this solutions my ids get one number
like this:
list = [ {
    color: "red",
    value: "#f00",
    id: 0
}, {

    color: "green",
    value: "#0f0",
    id: 4
},{
    color: "blue",
    value: "#00f",
    id: 4
},{
    color: "cyan",
    value: "#0ff",
    id: 4
},{
    color: "black",
    value: "#000",
    id: 4
}]

my code is this:
let i = 0;
list.map(n => {
        n['id'] = i;
        i++;
});

A: You can use filter() to remove duplicate and reduce() to achieve the desired output.

const colorArray = [
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]

const result = colorArray
    .filter((a, i, x) => x.findIndex((t) => t.color === a.color) === i)
    .reduce((agg, item, index) => {
        item.id = index + 1;
        agg.push(item);
        return agg;
    }, []);

console.log(result);


text:
Q: SwiftUI: Text Field getting cut off The textField on my SwiftUI app is getting cut off. But it doesn't happen every time. It seems to happen at random.

Here is the code I'm using:
var body: some View {
    VStack {
      Spacer()
      // Target row
      HStack {
        Text("Put the bullseye as close as you can to:")
        Text("\(target)")
      }
      Spacer()
      // Slider row
      HStack {
        Text("1")
        Slider(value: $sliderValue, in: 1...100) {_ in
          print(self.sliderValue)
        }
        Text("100")
      }
      Spacer()
      // Hit me button row
      Button(action: {
        print("Button pressed")
        self.alertIsVisible = true
      }) {
        Text(/*@START_MENU_TOKEN@*/"Hit Me!"/*@END_MENU_TOKEN@*/)

      }
      .alert(isPresented: $alertIsVisible) { () -> Alert in
        let roundedValue = Int(sliderValue.rounded())
        let score = pointsForCurrentRound()
        return Alert(title: Text("Hello there!"), message: Text("The slider's value is \(roundedValue)!\n" +
          "You scored \(score) points this round"
          ), dismissButton: .default(Text("Awesome")))
      }
      Spacer()
      // Score and start over button row
      HStack {
        Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
          Text("Start Over")
        }
        Spacer()
        Text("Score:")
        Text("999999")
        Spacer()
        Text("Round:")
        Text("999")
        Spacer()
        Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
          Text("Info")
        }
      }
      .padding(.bottom, 20)
    }
  }

I've tried adding padding trailing the text field and before the target. I've tried adding padding to the leading edge of the target. I've tried giving using the frame method on the text field to add a min length. None of these work.  Any ideas?
Thanks

A: I just came across this exact situation! After a few moments of searching, trial, and errors, I finally figured it out. The text view is trying to resize and one of the parent views have animations enabled. If anyone having this same issue adds .animation(nil) to the Text, this will likely solve the issue.
VStack {
    Text("\(Int(self.viewModel.ProgressPercentage * 100.0))%")
        .font(.largeTitle)
        .animation(nil)
}

Good luck!

A: You may add fixedSize() to lock the labels.
HStack {
  Text("Put the bullseye as close as you can to:").fixedSize()
  Text("\(target)").fixedSize()
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass state.params from react-navigation as props in react native I want to pass the props from
this.props.navigation.navigate('LIST_PRODUCT', { product: item.product, stock: item.stock});
but the result will be
{
 ...this.props,
 navigation: {
  ...,
  state: {
    ...,
    params: {
      product: 'Lenovo K5 Pro',
      stock: 5
    }
  }
 }
}

and the result what I want is
{
 ...this.props,
 product: 'Lenovo K5 Pro',
 stock: 5
}

is there any way to passing params from state to this.props in child component?

A: try the below solution
HomeScreen.js
class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            /* 1. Navigate to the Details route with params */
            this.props.navigation.navigate('Details', {
              itemId: 86,
              otherParam: 'anything you want here',
            });
          }}
        />
      </View>
    );
  }
}

DetailsScreen.js
class DetailsScreen extends React.Component {
  render() {
    /* 2. Get the param, provide a fallback value if not available */
    const { navigation } = this.props;
    const itemId = navigation.getParam('itemId', 'NO-ID');
    const otherParam = navigation.getParam('otherParam', 'some default value');

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Text>itemId: {JSON.stringify(itemId)}</Text>
        <Text>otherParam: {JSON.stringify(otherParam)}</Text>
        <Button
          title="Go to Details... again"
          onPress={() =>
            this.props.navigation.push('Details', {
              itemId: Math.floor(Math.random() * 100),
            })
          }
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

A: I think you could just spread the state object like this:
const { navigation, ...rest } = this.props;
{
  ...rest,
  ...navigation.state.params
}

Beware that state.params may not always be there


text:
Q: How to set the list of features which will be installed if the button was pushed? I'am using WixUI_Mondo set. I modified "CompleteButton" button in the SetupTypeDlg:
<Control Id="ServerButton" Type="PushButton" X="40" Y="120" Width="80" Height="17" ToolTip="!(loc.SetupTypeDlgServerButtonTooltip)" Text="!(loc.SetupTypeDlgServerButton)">
   <Publish Property="WixUI_InstallMode" Value="InstallServer">1</Publish>
   <Publish Property="SERVICE" Value="[SERVSTR]">1</Publish>
   <Publish Property="ADDLOCAL" Value="Feature1,Feature2,Feature3">1</Publish>
</Control>

<Property Id="ADDLOCAL" Secure="yes"></Property>

When I push ServerButton the log says:
(CLIENT)     MSI (c) (1C:88) [15:28:49:154]: PROPERTY CHANGE: Adding ADDLOCAL property. Its value is 'Feature1,Feature2,Feature3'.
(UNKNOWN)     Действие 15:28:49: ServStrDlg. Dialog created
(UNKNOWN)     Действие 15:28:53: ShortsDlg. Dialog created
(UNKNOWN)     Действие 15:28:55: VerifyReadyDlg. Dialog created
(CLIENT)     MSI (c) (1C:88) [15:28:55:966]: Note: 1: 2727 2:
(UNKNOWN)     Действие закончено 15:28:56: WelcomeDlg. Код возврата 1.
(CLIENT)     MSI (c) (1C:DC) [15:28:56:076]: Doing action: ProgressDlg
(UNKNOWN)     Действие 15:28:56: ProgressDlg.
(UNKNOWN)     Начало действия 15:28:56: ProgressDlg.
(UNKNOWN)     Действие 15:28:56: ProgressDlg. Dialog created
(UNKNOWN)     Действие закончено 15:28:56: ProgressDlg. Код возврата 1.
(CLIENT)     MSI (c) (1C:DC) [15:28:56:091]: Doing action: ExecuteAction
(UNKNOWN)     Действие 15:28:56: ExecuteAction.
(UNKNOWN)     Начало действия 15:28:56: ExecuteAction.
(CLIENT)     MSI (c) (1C:DC) [15:28:56:091]: PROPERTY CHANGE: Adding SECONDSEQUENCE property. Its value is '1'.
(CLIENT)     MSI (c) (1C:DC) [15:28:56:091]: Grabbed execution mutex.
(CLIENT)     MSI (c) (1C:DC) [15:28:56:091]: Incrementing counter to disable shutdown. Counter after increment: 0
(CLIENT)     MSI (c) (1C:DC) [15:28:56:091]: Switching to server: NETFRAMEWORK40CLIENT="#1"INSTALLLOCATION="some dir" TARGETDIR="C:\"
 MANUFACTURERDIR="C:\Program Files\..\" CURRENTDIRECTORY="C:\.." CLIENTUILEVEL="0" CLIENTPROCESSID="6684" USERNAME="User" COMPANYNAME=".."
 SOURCEDIR=".." ACTION="INSTALL" EXECUTEACTION="INSTALL" SECONDSEQUENCE="1" ROOTDRIVE="C:\" INSTALLLEVEL="1" ADDLOCAL=Feature4,Feature5,Feature6

Levels of Feature1,Feature2,Feature3 are more than 3. Can't figure out why it's passing INSTALLLEVEL="1".
UPD:
I made next changes, the result is same. The installer is modifying values of INSTALLLEVEL,ADDLOCAL properties on client-side. On server-side: INSTALLLEVEL=11,ADDLOCAL consists of features with "Level" attribute<=11.
<Control Id="ServerButton" Type="PushButton" X="40" Y="120" Width="80" Height="17" ToolTip="!(loc.SetupTypeDlgServerButtonTooltip)" Text="!(loc.SetupTypeDlgServerButton)">
   <Publish Property="WixUI_InstallMode" Value="InstallServer">1</Publish>
   <Publish Event="SetInstallLevel" Value="11">1</Publish>
   <Publish Property="SERVICE" Value="[SERVSTR]">1</Publish>
   <Publish Property="ADDLOCAL" Value="Feature1,Feature2,Feature3">1</Publish>
</Control>

A: I read this article many times and finally found: i have to publish Event='AddLocal' not a Property. Thank's, Yan, for your time very much. Here is working code:
<Control Id="ServerButton" Type="PushButton" X="40" Y="120" Width="80" Height="17" ToolTip="!(loc.SetupTypeDlgServerButtonTooltip)" Text="!(loc.SetupTypeDlgServerButton)">
   <Publish Property="WixUI_InstallMode" Value="InstallServer">1</Publish>
   <Publish Property="SERVICE" Value="[SERVSTR]">1</Publish>
   <Publish Event="AddLocal" Value="ALL">1</Publish>
   <Publish Event="Remove" Value="Feature4">1</Publish>
   <Publish Event="Remove" Value="Feature5">1</Publish>
   <Publish Event="Remove" Value="Feature6">1</Publish>
</Control>

And I added an event to the "Back" button of the next dialog:
<Control Id="Back" Type="PushButton" X="192" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)">
   <Publish Event="SetInstallLevel" Value="3">WixUI_InstallMode="InstallServer"</Publish>
</Control>

A: According to the MSDN documentation, the installation level specified by the INSTALLLEVEL property can be overridden by a number of properties, including ADDLOCAL. Hence, as far as I understand it, even if INSTALLLEVEL is set to 1, it gets overriden by the ADDLOCAL property and is not taken into consideration by the Windows Installer.
If you experience any error or wrong behavior related to this, add more details about it to your question.


text:
Q: Wrong combination of transparency group soft mask and PNG image mask I have a TransparencyGroup-based soft mask as described in 7.5.4 of the PDF specification. It works all right when the image I apply the mask to is a JPG but fails when it has its own mask like a PNG.
doc = new Document(new Rectangle(ToPdf(210), ToPdf(297)));
pdf = PdfWriter.GetInstance(doc, new FileStream("test.pdf", FileMode.Create));
pdf.PdfVersion = PdfWriter.VERSION_1_4;
pdf.CompressionLevel = PdfStream.NO_COMPRESSION;

doc.Open();
var dc = pdf.DirectContent;

dc.Rectangle(0, 0, ToPdf(210), ToPdf(297));
dc.SetColorFill(BaseColor.BLUE);
dc.Fill();

dc.SaveState();
var mask = Image.GetInstance("mask.jpg");
mask.ScaleAbsoluteHeight(ToPdf(100));
mask.ScaleAbsoluteWidth(ToPdf(100));
mask.SetAbsolutePosition(0, 0);

var transparency = dc.CreateTemplate(ToPdf(100), ToPdf(100));
transparency.Group = new PdfTransparencyGroupEx { ColorSpace = PdfName.DEVICEGRAY };
transparency.AddImage(mask);

var softmask = new PdfSoftMask(PdfName.MASK) {
  Subtype = new PdfName("Luminosity"),
  Group = transparency.IndirectReference,
};
dc.SetGState(new PdfGStateEx {
  SoftMask = softmask,
  AlphaIsShape = false,
});

var picture = Image.GetInstance("test.png"); // or test.jpg
//picture.Smask = false;
picture.ScaleAbsoluteHeight(ToPdf(100));
picture.ScaleAbsoluteWidth(ToPdf(100));
picture.SetAbsolutePosition(0, 0);
dc.AddImage(picture);
dc.RestoreState();

doc.Close();

The mask is simply a grayscale image with a fountain fill:

With the PNG, the image will appear with an erroneous background:

Helpers:
public static float ToPdf(double mm) => (float)(mm / 25.4 * 72.0);

public class PdfGStateEx : PdfGState {
  public PdfObject SoftMask {
    set => Put(PdfName.SMASK, value);
  }
}

public class PdfTransparencyGroupEx : PdfTransparencyGroup {
  public PdfName ColorSpace {
    set => Put(PdfName.CS, value);
  }
}

public class PdfSoftMask : PdfDictionary {
  public PdfSoftMask(PdfName type)
    : base(type) {
  }

  public PdfName Subtype {
    set => Put(PdfName.S, value);
  }

  public PdfIndirectReference Group {
    set => Put(new PdfName("G"), value);
  }

  public PdfArray BackdropColor {
    set => Put(PdfName.BC, value);
  }
}

Test files

*

*PDF with a JPG

*PDF with a PNG, SMask

*PDF with a PNG, Mask
Some analysis
in all cases, the image is embedded correctly:
/GS1 gs
q 283.46 0 0 283.46 0 0 cm /img1 Do Q

where the soft mask dictionary is:
<<
  /AIS false
  /SMask
  <<
    /G 1 0 R
    /S /Luminosity
    /Type /Mask
  >>
>>

referencing the transparency group XObject:
<<
  /BBox [0 0 283.46 283.46]
  /FormType 1
  /Group
  <<
    /CS /DeviceGray
    /S /Transparency
  >>
  /Length 38
  /Matrix [1 0 0 1 0 0]
  /Resources
  <<
    /XObject
    <<
      /img0 2 0 R
    >>
  >>
  /Subtype /Form
  /Type /XObject
>>

No difference so far. One of the PNG versions actually clear the SMask entry, then the inherent mask of the PNG disappears, this is to be expected.
So, this will be likely the case because the soft mask of the image will override the soft mask in the graphics state. Now the question boils down to: is there any support in iText to blend the two masks (one from the PNG, one from my own) or do I need to do this separately prior to feeding it to iText?

A:
So, this will be likely the case because the soft mask of the image will override the soft mask in the graphics state.

Indeed, soft masks set via the graphics state and soft masks set with an image essentially operate the same way, and at the same time there can be only one active soft mask.

Now the question boils down to: is there any support in iText to blend the two masks (one from the PNG, one from my own) or do I need to do this separately prior to feeding it to iText?

No, there is no support in iText to blend the two masks; iText only reads images from external sources and embeds them into a PDF or (during extraction) reads them from the PDF for export to some external target, it does not do further processing.
But still you don't have to do this separately prior to feeding it to iText, you can leave this blending to the PDF viewer! While at the same time there can be only one active soft mask, you can make use of nested transparency groups to combine different transparency effects.
In your code simply replace
dc.AddImage(picture);

by
var group = dc.CreateTemplate(ToPdf(100), ToPdf(100));
group.Group = new PdfTransparencyGroupEx();
group.AddImage(picture);
dc.AddTemplate(group, 0, 0);

(i.e. instead of adding the image with its soft mask to the content directly, add it to a separate transparency group and add that transparency group to the content).
The result will change like this:

-->

By the way, you can improve the quality of the transparency mask (in particular at higher resolutions or zoom levels) by using an actual continuous gradient instead of a bitmap with a gradient. Simply replace
transparency.AddImage(mask);

by
PdfShading shading = PdfShading.SimpleAxial(pdf, 0, 0, ToPdf(100), 0, BaseColor.BLACK, BaseColor.WHITE);
transparency.PaintShading(shading);


text:
Q: Entering (input/scanner) two same numbers consecutively to break a loop "while" Java I am a new-bee in java, I have a problem that i cant figure out to compare previous entered number(int) with next one continuously and I need to write a program that repeatedly reads numbers from the user's keyboard. The program stops looping when the user types the same number twice in a row.
Thanks in advance for your kind guidance.
Here's a sample run of the program:
5
13
21
5
4
5
5
Done!
Following was my unsuccessful effort :)

Scanner input = new Scanner(System.in);
          System.out.println("Enter Numbers");

    int x = 0;
    int y = 0;
    x = input.nextInt();
    y = input.nextInt();
    while (x != y) {

        x = input.nextInt();
        y = input.nextInt();

    }

    System.out.println("Done!!!!!!!");
    input.close();

A: You can use loop to read number from console and stop if previous nubmer equals to current one. As marker of first number you can use e.g. null value of Integer prv (as alternative, you can use boolean isFirstLine flag for first line or res.isEmpty()).
public static List<Integer> receiveNumbers() {
    List<Integer> res = new LinkedList<>();
    Integer prv = null;

    try (Scanner scan = new Scanner(System.in)) {
        while (true) {
            int num = scan.nextInt();

            if (prv != null && prv == num)
                break;

            res.add(num);
            prv = num;
        }
    }

    return res;
}

A:
import java.util.Scanner;

public class OngoingPractice {
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int previous, current;

    previous = keyboard.nextInt();
    current = keyboard.nextInt();

    while (current != previous) {
        previous = current;
        current = keyboard.nextInt();
    }

    System.out.println("Done!");

A: Remember the last entered data in one variable and check  it with the current data. If both matches, break the loop.
        Scanner scanner = new Scanner(System.in);
        String previousNumber="";
        while (scan.hasNextInt()) {
          int number = scan.nextInt();
          if(!previousNumber.equals("") && number==Integer.parseInt(previousNumber)) {
            break;
          }else {
            System.out.println(number);
          }
          previousNumber=number+"";
        }

A: Just use an infinite while loop and break if the new int is equal to previous one. As a suggestion you should show how you tried.
Scanner sc = new Scanner(System.in);
    int i;
    Integer j = null;
    boolean flag = false;
    while(true) {
        i = sc.nextInt();
        if(j==null) {j=i; flag = true;}
        if(j==i&&!flag) {
            System.out.println("Done");
            break;}
        j=i;
        flag = false;
    }

Edited : if first one is -1, it won't work as in the comment. so I modified some.


text:
Q: Trapping SIGINT in mono program in docker I created a test image with a simple C# program to test issues with trapping SIGINT signal sent by docker kill -s SIGINT $cont_id command.
dockerfile:
FROM arm32v7/mono
COPY . /usr/local/bin/sigint/
CMD ["/usr/bin/mono" , "/usr/local/bin/sigint/SigIntCatcher.exe"]

Program.cs:
static void Main(string[] args)
{
    Console.CancelKeyPress += Console_CancelKeyPress;
    do Thread.Sleep(2000); while (true);
}

private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine($"Got signal {(e.SpecialKey == ConsoleSpecialKey.ControlC ? "Ctrl+C" : "Ctrl+Break")}");
    Environment.Exit(0);
}

If I start container like docker run -it $image_id, and in another terminal execute docker kill -s SIGINT $cont_id then the program inside the container catches the signal and outputs "Got signal Ctrl+C".
But if I start the container in the detached mode with docker run -d $image_id and try to send SIGINT with docker kill - nothing happens. I also connected to the running container with docker exec -it $cont_id bash and checked that mono process has PID = 1.
Am I doing something wrong or is it a bug in mono/docker?
Despite this example uses the base image for arm system (Raspberry Pi), I have the same problem running similar code in Ubuntu and Windows.


text:
Q: Error with JEST tests on TRAVIS-CI Error
Error: /home/travis/build/ElectronicaGitHub/pictureAvenue/node_modules/jest-
cli/node_modules/jsdom/node_modules/contextify/build/
Release/contextify.node: invalid ELF header

That's happening when i'm trying to start JEST tests, it's just example test from JEST tutorial and looks like
jest.dontMock('../sum');

describe('sum', function() {
 it('adds 1 + 2 to equal 3', function() {
   var sum = require('../sum');
   expect(sum(1, 2)).toBe(3);
 });
});

Locally test with JEST runs fine.
Tried to start mocha tests on travis-ci and it's ok!
But my project on ReactJS and i they advise to use JEST for tests.
How to fix that problem?

A: Found your project on GH: https://github.com/ElectronicaGitHub/pictureAvenue
Almost guaranteed that this is because you checked in the node_modules folder.  This should be downloaded by each consumer of the project, using npm install.  Add a .gitignore file to the root of your project with the following content:

node_modules

Before you do this, you'll need to do:
rm -fr node_modules && \
    git commit -a -m 'remove node_modules from source control' && \
    git push origin master
Then add your .gitignore file and do another commit.
While you're at it, it looks like you're also checking in your sass-cache (.sass-cache\*).  You'll want to do the same thing.
Final thoughts:
Typically source control is great for any artifact or code, it is not great for things that are often OS dependent (like node_modules) or host dependent (.sass-cache).
Hope that helps.


text:
Q: Form submission canceled because the form is not connected-react, express, node js the chrome console returned this error "Form submission canceled because the form is not connected" on hitting the submit button, though nothing was returned in the IDE terminal. The react form is connected to a node js backend using express, nodemailer,cors, google api, dotenv and google-auth-library

const CLIENT_ID = process.env.CLIENT_ID
const CLIENT_SECRET = process.env.CLIENT_SECRET
const REDIRECT_URI = process.env.REDIRECT_URI
const REFRESH_TOKEN = process.env.REFRESH_TOKEN

const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
oAuth2Client.setCredentials({refresh_token:REFRESH_TOKEN})

app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())

app.post("/send_mail", cors(), async (req, res) => {

    const output = `

You have a new contact request

Contact Details

Name: ${req.body.name}

Email: ${req.body.email}

Message

${req.body.message}

  `;

  try{
    const accessToken = await OAuth2Client.getAccessToken()

    const transport = nodemailer.createTransport({
        host: 'example.com',
        port: 465,
        secure: true,
        service: 'gmail',
        auth: {
            type: 'OAuth2',
            user: process.env.USERNAME,
            clientId: CLIENT_ID,
            clientSecret: CLIENT_SECRET,
            refreshToken: REFRESH_TOKEN,
            accessToken: accessToken

        }
    })

    await transport.sendMail({
        from: '"example Contact" <contact@example.com>',
        to: 'hey@gmail.com',
        subject: "test email",
        html: output

    })
} catch (error) {
    return error
}

})

app.listen(7000, () => console.log('Server started...'));

export default function ContactForm() {
  const [ sent, setSent ] = useState(false);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');

  const handleSend = async (e) => {
        setSent(true)
        try {
            await axios.post("http://localhost:7000/send_mail", {
                name, email, message
            })
        } catch (error) {
            console.error(error)
        }
    }

  return (
    <>
        {!sent ? (
      <FormStyle onSubmit={handleSend}>

            Your Name
            <input
              type="text"
              id="name"
              name="name"
              value={name}
              onChange={(e) => setName(e.target.value)}

            />

            Your Email
            <input
              type="email"
              id="email"
              name="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />

            Your message
            <textarea
              type="text"
              id="message"
              name="message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            />

        <button type="submit" >Send</button>
      </FormStyle>
        ) : (

<MailSentAnimation />

          )}
    </>
  );
}


text:
Q: Как реализовать скрипт анализа данных excel(openpyxl) таблицы в pyTelegramBot Всем привет.
У меня имеется скрипт на python, который анализирует таблицу xlsx через openpyxl. В данном скрипте ввожу месяц(месяцы разбиты по страницам), дату и после этого он показывает кто работает в указанную дату.   Возможно ли данный скрипт реализовать в бота pyTelegramBot ?
Может имеются примеры или статьи
import openpyxl
import subprocess
wb = openpyxl.load_workbook(filename = '/home/python/tabl/duty_ck/График дежурств.xlsx')
page = str(input("Введите месяц: "))
sheet = wb[page]
print (sheet)
while True:
#столбец
    print()
    column = int(input("Введите Число месяца: "))
    if column == 1:
        cell = 'D'
    if column == 2:
        cell = 'E'
    if column == 3:
        cell = 'F'
    if column == 4:
        cell = 'G'
    if column == 5:
        cell = 'H'
    if column == 6:
        cell = 'I'
    if column == 7:
        cell = 'J'
    if column == 8:
        cell = 'K'
    if column == 9:
        cell = 'L'
    if column == 10:
        cell = 'M'
    if column == 11:
        cell = 'N'
    if column == 12:
        cell = 'O'
    if column == 13:
        cell = 'P'
    if column == 14:
        cell = 'Q'
    if column == 15:
        cell = 'R'
    if column == 16:
        cell = 'S'
    if column == 17:
        cell = 'T'
    if column == 18:
        cell = 'U'
    if column == 19:
        cell = 'V'
    if column == 20:
        cell = 'W'
    if column == 21:
        cell = 'X'
    if column == 22:
        cell = 'Y'
    if column == 23:
        cell = 'Z'
    if column == 24:
        cell = 'AA'
    if column == 25:
        cell = 'AB'
    if column == 26:
        cell = 'AC'
    if column == 27:
        cell = 'AD'
    if column == 28:
        cell = 'AE'
    if column == 29:
        cell = 'AF'
    if column == 30:
        cell = 'AG'
    if column == 31:
        cell = 'AH'
    print ("\n")

    znach = column
    if znach in range (1, 32):
        print(znach, page, "Дежурит: ")
        print ()

        for i in range(2, 8):
            line = cell + str(i)
            user = "C" + str(i)
            val = sheet[user].value
            if sheet[line].value is not None:
                print (val, sheet[line].value,"ч.")
            i = i + 1
        print ("-----------------------------------")

        for i in range(8, 16):
            line = cell + str(i)
            user = "C" + str(i)
            val = sheet[user].value
            if sheet[line].value is not None:
                print (val, sheet[line].value,"ч.", "Из офиса")
            i = i + 1

    else: print("Такой даты не существует")

print ()

A: Получилось решить проблему.
Делал по примеру https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py
Спасибо @Violet
Брал данные из чаты и делал из них аргументы
    def day_step(message):
    chat_id = message.chat.id
    day = message.text

    if not day.isdigit():
        msg = bot.reply_to(message, 'Введите дату цифрами')
        bot.register_next_step_handler(msg, day_step)
        return
    user = user_dict[chat_id]
    user.day = day
    bot.send_message(message.chat.id, 'Выбрано: ' + user.month + ' ' + user.day)

    wb = openpyxl.load_workbook('График дежурств.xlsx')
    page = str(user.month)
    sheet = wb[page]
    column = int(user.day)


text:
Q: Failed to execute 'getStartPositionOfChar' on 'SVGTextContentElement' What is the reason of the following exception?
DOMException: Failed to execute 'getStartPositionOfChar' on 'SVGTextContentElement': The charnum provided (0) is greater than or equal to the maximum bound (0).

Actually, I'm trying to integrate https://github.com/nlplab/brat with my own created backend. It uses svg with jquery.svg.min.js and jquery.svgdom.min.js. But I am stuck at this exception. The exeption is raised on text element of svg while making the call as
text.getStartPositionOfChar(firstChar).x;

where text is as
<text x="0" y="0">Some Text</text>

and firstChar=0.

A: I believe that bug is fixed in the master branch, but not on the packaged version 1.3. Try to replace your brat with one directly cloned from GitHub (git clone https://github.com/nlplab/brat.git).

A: Using the latest git branch didn't work for me (although it might fix other things)!
I think it is a timing issue as sometimes the re-render worked, other times failed with the above error.
I added a small timeout value to the function (on line 3141) and it seems to have fixed it, at the cost of a small delay in render.


text:
Q: The space of framed functions Framed functions arose in the work of K. Igusa defining cohomology invariants for smooth manifold bundles (Igusa-Klein torsion). In the late 80's, he proved a strong connectivity result about the "space of framed functions" using Morse theory and conjectured that this space was, in fact, contractible. Jacob Lurie recently verified this conjecture using the language of higher category theory in the course of his proof of the Cobordism Hypothesis.
(1) Is there any progress on a more geometric proof of this? The relevant work of Igusa is very geometric and Lurie himself points out that a more direct proof should be found. Perhaps more realistically: is there a geometric heuristic for Lurie's result?
(2) Does anyone know of applications of framed functions beyond defining Igusa-Klein torsion and proving the Cobordism Hypothesis? Pointers into the literature on this topic would be much appreciated.
EDIT: A framed function on $M$ is a pair $(f,\xi)$ of a smooth function $f$ on $M$ having at most $A2$ singularities in the interior of $M$ and no singular points on the boundary, and an orthonormal framing $\xi$ of the negative eigenspace of the Hessian of $f$ at each critical point.

A: It is possible to prove the contractibility directly (and thereby bypass the obstruction theory arguments sketched at the end of section 3 of my paper). The statement itself is an example of an h-principle: namely, one can show fairly easily that the framed function space of ${\mathbb R}^{n}$ is contractible, so the general result hinges on knowing that the framed function spaces also satisfy some sort of "local to global" principle for arbitrary manifolds. (If I remember correctly, Igusa told me that he and Eliashberg sketched out a proof along these lines, but never had the motivation to write it up.)

A: Eliashberg once told me that the framed function theorem should be a consequence of his work on wrinkled maps.
Igusa and I gave a fairly direct proof that the space of framed functions on the circle is contractible. The idea is that the assignment function $f \mapsto \Sigma(f)$ (= its singular set, suitably interpreted as a point of a configuration space) is is quasifibration with contractible fibers when $f$ varies through framed functions on $S^1$. The proof in this case appears in:
Igusa, Kiyoshi; Klein, John The Borel regulator map on pictures. II. An example from Morse theory. K-Theory 7 (1993), no. 3, 225–267.


text:
Q: How to control custom hardware using SIMULINK I have a piece of hardware and a DLL that can be used to control it. This is essentially a motor controller that I have used from C/C++ and MATLAB. I havetried to create a SIMULINK model using the DLL and I can't seem to get it to spin the motor.
The Simulation Target is set to include the header file and DLL. The Model Properties-> callbacks include MATLAB functions to initialize the DLL and hardware. The model includes a C Caller block that should call the DLL function to set the motor speed.
When I run the simulation, I can see the initialization code being executed, the motor never starts spinning. At the end of the simulation, the cleanup function is executed.
I have two thoughts about this. First, the C Caller block doesn't support sending commands over the serial link. Second, the initialization and cleanup code are MATLAB scripts. Is it possible that the MATLAB initialization is not recognized by SDIMULINK? That is, do I have to call the DLLs init function from the model directly (I'm not sure how to do this, but a WAG would be to embed other C Callers, with the required functions).


text:
Q: Dynamic UILabel with proportional width and text-driven height I'm trying to programmatically create a container view with two UILabel subviews which behave as follows:

*

*The container width is pinned to its superview; its height is constrained to fit the labels

*The labels are laid out horizontally, with standard spacing between them (8pts)

*The left label width is 25% of the width of the container

*The right label width fills the available space, minus standard horizontal spacing

*Long text should be broken at word boundaries are flow across multiple lines; both labels must grow vertically to accommodate long text

I have defined the labels with numberOfLines = 0 and lineBreakMode = NSLineBreakByWordWrapping.
Note that the size of the container is completely dynamic; its width is determined by its superview, while its height is determined by its subviews (the labels). The size of the labels is also dynamic; their widths are proportional to the container width, and their heights depend on the length of the text.
I've been able to achieve everything above, except for the last item, with the following constraints (pseudo-code). A is the left label, B is the right.

*

*A.top == container.top

*B.top == container.top

*A.leading = container.leading

*A.trailing == B.leading - 8

*B.trailing == container.trailing

*A == .25 * container.width

*container.height >= A.height

*container.height >= B.height

The last 2 constraints are intended to stretch the container to fit the taller of the labels, but the layout engine seems to ignore the fact that the labels may be multiline. That is, I always get a single line displayed, no matter the length of the text.
So what constraints do I need to add/modify/delete in order to achieve the full set of behaviors described above?

A: To make your labels automatically resize height you need to do following:

*

*Set layout constrains for label (That what you actually have done)

*Set height constraint with low priority. It should be lover than ContentCompressionResistancePriority

*Set numberOfLines = 0

*Set ContentHuggingPriority higher than label's hight priority

*Set preferredMaxLayoutWidth for label. That value is used by label to calculate its height

For example:
self.descriptionLabel = [[[UILabel alloc] init] autorelease];
self.descriptionLabel.numberOfLines = 0;
self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.descriptionLabel.preferredMaxLayoutWidth = 200;

[self.descriptionLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:self.descriptionLabel];

NSArray* constrs = [NSLayoutConstraint constraintsWithVisualFormat:@"|-8-[descriptionLabel_]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)];
[self addConstraints:constrs];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[descriptionLabel_]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
[self.descriptionLabel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[descriptionLabel_(220@300)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];

A: Set the priority of Height Constraints for the labels to low value and try setting the constraints in code.

A: Make sure you set

*

*horizontal and vertical content compression resistance priority. If you do not want label to truncate its content then set it to 1000.i.e. required.

*Content hugging priority. Look at this answer to understand how it works.


text:
Q: Conditionally hidden slides in beamer When creating a presentation, I sometimes create extra slides that contain additional information, a more thorough explanation, or an extra plot pertaining to certain parts of my talk.  These extra slides are usually in a separate PDF and the document is usually only opened if an audience member asks a question or requests information and one of my extra slides supplements my response nicely.
I am wondering if it's possible to insert these slides into my presentation with the two following options:

*

*The extra slides are skipped when progressing through the presentation unless...

*I click on a hyperlink placed somewhere on the slide.  If clicked, we traverse to the extra slide.  From this slide, continuing to the 'next' slide would send us back to the slide that got us here originally.

The above can be accomplished with two (or more) PDFs (one with the presentation, one -- or more -- with the supplemental slides) via hyperref but ideally I would like to only have one document.
I am not familiar enough with ifthen to know if it can be done with that package.
Any help would be much appreciated.

A: See Beamer manual sections 10.7 and 11. Basically, you can use an appendix to make a set of slides after your main presentation (they don't show up in the main ToC). And you can use \hyperlink commands to jump to particular slides (or overlays of slides, even). Short example:
\documentclass{beamer}
\usetheme{Warsaw}
\title{The Title}
\author{The Author}
\date{\today}
\begin{document}
\section{One}
\begin{frame}[label=main]
I suspect someone might ask about supplemental material
\hyperlink{supplemental}{\beamerbutton{here}}.
\end{frame}
\appendix
\section{More}
\begin{frame}[label=supplemental]
Supplemental content.
Back to \hyperlink{main}{\beamerbutton{main}}.
\end{frame}
\end{document}

If you need to exclude the appendix slides from the slide counter, see this question.

A: When your extra information is not too long, you could try to use layers.
If somebody asks, you switch between layers in your document. After this, you can switch back to your presentation layer and continue.
This will not help if your additional material contains many slides (you could define multiple layers, but I think it will become complicated).
And you are restricted in the usage of or pdf-viewer.
Example:
\documentclass{beamer}

\usepackage{tikz}
\usepackage{ocg-p}
\usepackage{blindtext}
\usepackage{hyperref}
\usepackage{pgfplots, pgfplotstable}

%----------------------------------------------------------------%
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}
\frametitle{Title}
  % Insert links to toggle layer visibility
      \toggleocgs[]{pic remark}{Explanation}%Toggle layer

      \begin{tikzpicture}
        \begin{ocg}{Graphic}{pic}{1}
            \begin{axis}[
              ybar stacked, bar width=10mm,
              width=0.9\textwidth, height=0.7\textheight,
              symbolic x coords={AA,BB,CC,DD},
              xtick=data,
              nodes near coords, nodes near coords align={vertical},
            ]
            \addplot [fill=red] coordinates { ({AA},712) ({BB},267) ({CC},240) ({DD},244)};
            \addplot [fill=blue] coordinates { ({AA},433) ({BB},151) ({CC},1413) ({DD},50)};
            \legend{Active,Inactive}
            \end{axis}
        \end{ocg}
       %%
        \begin{ocg}{Remarks}{remark}{0}
            \node [overlay,anchor=south west] at (0,0)
                {\parbox[b]{0.8\textwidth}{\blindtext}};
        \end{ocg}
      \end{tikzpicture}
\end{frame}

\end{document}

Result is a one page document:

If you click on Explanation you get (if your pdf viewer support layers):

A: An alternative solution is to have a button that skips the extra material. This has the disadvantage that you have to remember to press the "don't show the extra material" button when you get to that slide, but it has two advantages. Firstly, the extra slide is right there next to the main material rather than hidden off in an appendix, which might make it easier to organise your material. But secondly, and more importantly, it means that the "extra material" slide can just be a <2> version of the main slide.
\documentclass{beamer}

\begin{document}

\begin{frame}
\frametitle{Slide 1}
\begin{itemize}
\item Say this.
\hyperlink{skip_extra_material}{\beamerbutton{No questions}}
\item<2>Further explanation.
\end{itemize}
\end{frame}

\begin{frame}[label=skip_extra_material]
\frametitle{Slide 2}
\begin{itemize}
\item Continue with the talk.
\end{itemize}
\end{frame}

\end{document}


text:
Q: In optical Multimode fiber MMF, what is the best pulse shaping filter that can be used to mitigate the ISI? In telecommunications there are three pulse shaping filters:
Gaussian filter
raised-Cosine
Sinc filter
In fiber optics what is the most suitable pulse shaping filter that can be used to design the desired pulse shape to mitigate the Inter-symbol Interference (ISI)

A: To eliminate ISI, what's required is a Nyquist filter. The raised-cosine and sinc filters are two examples of Nyquist filters, so either one will, in theory, eliminate ISI.
The Gaussian filter is not a Nyquist filter. You know this because its impulse response is never zero, while a Nyquist filter must have its impulse response go to zero at all times $t = n T_0$. A Gaussian filter might be used in an MMF system because the MMF channel itself has a Gaussian response, so that a Gaussian filter is a channel-matching filter, optimizing received SNR, in these systems.

In fiber optics what is the most suitable pulse shaping filter that can be used to design the desired pulse shape to mitigate the Inter-symbol Interference (ISI)

Any Nyquist filter may be used to minimize ISI.
Practically, building such filters for fiber optic modulation frequencies is difficult, and we simply use a bandwidth-limited receiver that more-or-less matches the desired system bandwidth. Increasing the receiver bandwidth generally improves ISI but degrades received noise, so the receiver is designed to optimize the net effect on bit error rate.


text:
Q: How to include a file only on dashboard widgets page? I want to add some styles to the widgets input fields. Therefore I want to include a style.css file only on the wp-admin/widgets.php page.
How can I detect the above page and include file there?

A: You can use the following code. Asuming that the css file style.css is inside the css folder of your theme:
function wpse_126614_enque( $hook ) {
    if ( 'widgets.php' != $hook ) {
        return;
    }
    $template_url = get_template_directory_uri();
    wp_enqueue_style( 'admin-style-widget', $template_url . '/css/style.css' );
}
add_action( 'admin_enqueue_scripts', 'wpse_126614_enque' );


text:
Q: Create an insert using Alphabet expression I have alphabet column like using this CTE:
;with
cte_tally as
(
select row_number() over (order by (select 1)) as n
from sys.all_columns
)
select
  char(n) as alpha
from
  cte_tally
where
  (n > 64 and n < 91) ;
go

my question is how can I get range inside of this alphabet, I mean, if I create stored procedure who receive two parameters
@FirstLetter CHAR(1)
,@FinalLetter CHAR(2)

FirstLetter value is "C"
FinalLetter value is "F"
First I want to know how many spaces are between C and F
And finally I want to create something like WHILE function using that spaces and all letters between C and F (including C and F)
DECLARE @NumberOfSpaces INT
        ,@FinalFlag INT = 1 ;
SET @NumberOfSpaces = spacesavailable

WHILE(@FinalFlag < NumberOfSpaces)
BEGIN
INSERT INTO .... VALUES (CONCAT(TEST - @FirstLetter))
END

and do that while with all letters between C and F (including C and F)

A: To create a range of letters you can use rangeAB (for this and a bunch of other stuff.) Observe:
DECLARE
  @firstLetter CHAR(1) = 'C',
  @lastLetter  CHAR(1) = 'F';

SELECT letter = CHAR(r.N1)
FROM   core.rangeAB(ASCII(@firstLetter),ASCII(@lastLetter),1,1) AS r;

Returns:
letter
------
C
D
E
F

If I understand what you need correctly, you can calculate "spaces" like this:
DECLARE
  @firstLetter CHAR(1) = 'C',
  @lastLetter  CHAR(1) = 'F';

SELECT Spaces = ASCII(@lastLetter)-ASCII(@firstLetter);

This would indicate that there are 3 spaces between C & F. This may be moot.
RangeAB DDL:
CREATE FUNCTION core.rangeAB
(
  @Low  BIGINT, -- (start) Lowest  number in the set
  @High BIGINT, -- (stop)  Highest number in the set
  @Gap  BIGINT, -- (step)  Difference between each number in the set
  @Row1 BIT     -- Base: 0 or 1; should RN begin with 0 or 1?
)
/****************************************************************************************
[Purpose]:
 Creates a lazy, in-memory, forward-ordered sequence of up to 531,441,000,000 integers
 starting with @Low and ending with @High (inclusive). RangeAB is a pure, 100% set-based
 alternative to solving SQL problems using iterative methods such as loops, cursors and
 recursive CTEs. RangeAB is based on Itzik Ben-Gan's getnums function for producing a
 sequence of integers and uses logic from Jeff Moden's fnTally function which includes a
 parameter for determining if the "row-number" (RN) should begin with 0 or 1.

 I wanted to use the name "Range" because it functions and performs almost identically to
 the Range function built into Python and Clojure. RANGE is a reserved SQL keyword so I
 went with "RangeAB". Functions/Algorithms developed using rangeAB can be easilty ported
 over to Python, Clojure or any other programming language that leverages a lazy sequence.
 The two major differences between RangeAB and the Python/Clojure versions are:
   1. RangeAB is *Inclusive* where the other two are *Exclusive". range(0,3) in Python and
      Clojure return [0 1 2], core.rangeAB(0,3) returns [0 1 2 3].
   2. RangeAB has a fourth Parameter (@Row1) to determine if RN should begin with 0 or 1.

[Author]:
 Alan Burstein

[Compatibility]:
 SQL Server 2008+

[Syntax]:
 SELECT r.RN, r.OP, r.N1, r.N2
 FROM   core.rangeAB(@Low,@High,@Gap,@Row1) AS r;

[Parameters]:
 @Low  = BIGINT; represents the lowest  value for N1.
 @High = BIGINT; represents the highest value for N1.
 @Gap  = BIGINT; represents how much N1 and N2 will increase each row. @Gap is also the
                 difference between N1 and N2.
 @Row1 = BIT;    represents the base (first) value of RN. When @Row1 = 0, RN begins with 0,
                 when @row = 1 then RN begins with 1.

[Returns]:
 Inline Table Valued Function returns:
 RN = BIGINT; a row number that works just like T-SQL ROW_NUMBER() except that it can
      start at 0 or 1 which is dictated by @Row1. If you need the numbers:
      (0 or 1) through @High, then use RN as your "N" value, ((@Row1=0 for 0, @Row1=1),
      otherwise use N1.
 OP = BIGINT; returns the "finite opposite" of RN. When RN begins with 0 the first number
      in the set will be 0 for RN, the last number in will be 0 for OP. When returning the
      numbers 1 to 10, 1 to 10 is retrurned in ascending order for RN and in descending
      order for OP.
      Given the Numbers 1 to 3, 3 is the opposite of 1, 2 the opposite of 2, and 1 is the
      opposite of 3. Given the numbers -1 to 2, the opposite of -1 is 2, the opposite of 0
      is 1, and the opposite of 1 is 0.
      The best practie is to only use OP when @Gap > 1; use core.O instead. Doing so will
      improve performance by 1-2% (not huge but every little bit counts)
 N1 = BIGINT; This is the "N" in your tally table/numbers function. this is your *Lazy*
      sequence of numbers starting at @Low and incrementing by @Gap until the next number
      in the sequence is greater than @High.
 N2 = BIGINT; a lazy sequence of numbers starting @Low+@Gap and incrementing by @Gap. N2
      will always be greater than N1 by @Gap. N2 can also be thought of as:
      LEAD(N1,1,N1+@Gap) OVER (ORDER BY RN)

[Dependencies]:
 N/A

[Developer Notes]:
 1.  core.rangeAB returns one billion rows in exactly 90 seconds on my laptop:
     4X 2.7GHz CPU's, 32 GB - multiple versions of SQL Server (2005-2019)
 2.  The lowest and highest possible numbers returned are whatever is allowable by a
     bigint. The function, however, returns no more than 531,441,000,000 rows (8100^3).
 3.  @Gap does not affect RN, RN will begin at @Row1 and increase by 1 until the last row
     unless its used in a subquery where a filter is applied to RN.
 4.  @Gap must be greater than 0 or the function will not return any rows.
 5.  Keep in mind that when @Row1 is 0 then the highest RN value (ROWNUMBER) will be the
     number of rows returned minus 1
 6.  If you only need is a sequential set beginning at 0 or 1 then, for best performance
     use the RN column. Use N1 and/or N2 when you need to begin your sequence at any
     number other than 0 or 1 or if you need a gap between your sequence of numbers.
 7.  Although @Gap is a bigint it must be a positive integer or the function will
     not return any rows.
 8.  The function will not return any rows when one of the following conditions are true:
       * any of the input parameters are NULL
       * @High is less than @Low
       * @Gap is not greater than 0
     To force the function to return all NULLs instead of not returning anything you can
     add the following code to the end of the query:

       UNION ALL
       SELECT NULL, NULL, NULL, NULL
       WHERE NOT (@High&@Low&@Gap&@Row1 IS NOT NULL AND @High >= @Low AND @Gap > 0)

     This code was excluded as it adds a ~5% performance penalty.
 9.  There is no performance penalty for sorting by RN ASC; there is a large performance
     penalty, however for sorting in descending order. If you need a descending sort the
     use OP in place of RN then sort by rn ASC.
 10. When setting the @Row1 to 0 and sorting by RN you will see that the 0 is added via
     MERGE JOIN concatination. Under the hood the function is essentially concatinating
     but, because it's using a MERGE JOIN operator instead of concatination the cost
     estimations are needlessly high. You can circumvent this problem by changing:
     ORDER BY core.rangeAB.RN to: ORDER BY ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

*** Best Practices ***
--===== 1. Using RN (rownumber)
 -- (1.1) The best way to get the numbers 1,2,3...@High (e.g. 1 to 5):
 SELECT r.RN
 FROM   core.rangeAB(1,5,1,1) AS r;

 -- (1.2) The best way to get the numbers 0,1,2...@High (e.g. 0 to 5):
 SELECT r.RN
 FROM   core.rangeAB(0,5,1,0) AS r;

--===== 2. Using OP for descending sorts without a performance penalty
 -- (2.1) Best Practice for getting the numbers 5,4,3,2,1 (5 to 1):
 SELECT   r.OP
 FROM     core.rangeAB(1,5,1,1) AS r
 ORDER BY R.RN;

 -- (2.2) Best Practice for getting the numbers 5,4,3,2,1,0 (5 to 0):
 SELECT   r.OP
 FROM     core.rangeAB(0,5,1,0) AS r
 ORDER BY r.RN ASC;

 -- (2.3) (ADVANCED) - Ex 2.2. (above) but with better query plan estimations (compare both)
 SELECT   r.OP
 FROM     core.rangeAB(0,5,1,0) AS r
 ORDER BY ROW_NUMBER() OVER (ORDER BY (SELECT NULL));
 -- This will leverage concatination operator instead of a merge join union;
 -- This will not improve performance but the exection plan will include better estimations
;
 -- (2.4) (ADVANCED) The BEST way (leveraging core.O)
 SELECT      o.OP
 FROM        core.rangeAB(0,5,1,0) AS r
 CROSS APPLY core.O(0,5,r.RN)      AS o
 ORDER BY    ROW_NUMBER() OVER (ORDER BY (SELECT NULL));
 -- Note that core.rangeAB.Op is best when there are gaps (@Gap > 1)

--===== 3. Using N1
 -- (3.1) To begin with numbers other than 0 or 1 use N1 (e.g. -3 to 3):
 SELECT r.N1
 FROM   core.rangeAB(-3,3,1,1) AS r;

 -- (3.2) ROW_NUMBER() is built in. If you want a ROW_NUMBER() include RN:
 SELECT r.RN, r.N1
 FROM   core.rangeAB(-3,3,1,1) AS r;

 -- (3.3) If you wanted a ROW_NUMBER() that started at 0 you would do this:
 SELECT r.RN, r.N1
 FROM   core.rangeAB(-3,3,1,0) AS r;

 -- (3.4) Ex 3.3. Guaranteed ORDER BY without a sort in the execution plan
 SELECT   r.RN, r.N1
 FROM     core.rangeAB(-3,3,1,0) AS r
 ORDER BY r.RN;

 -- (3.5) Ex 3.4. But with better cost estimations (similar to ex 2.4)
 SELECT   r.RN, r.N1
 FROM     core.rangeAB(-3,3,1,0) AS r
 ORDER BY    ROW_NUMBER() OVER (ORDER BY (SELECT NULL));

--===== 4. Using N2 and @Gap
 -- (4.1) To get 0,10,20,30...100, set @Low to 0, @High to 100 and @Gap to 10:
 SELECT r.N1
 FROM   core.rangeAB(0,100,10,1) AS r;

 -- (4.2) Adding N2
   -- Note that N2=N1+@Gap; this allows you to create a sequence of ranges.
   -- For example, to get (0,10),(10,20),(20,30).... (90,100):
 SELECT r.N1, r.N2
 FROM  core.rangeAB(0,90,10,1) AS r;

 -- (4.3) Remember that a rownumber is included and it can begin at 0 or 1:
 SELECT r.RN, r.N1, r.N2
 FROM   core.rangeAB(0,90,10,1) AS r;

[Examples]:
--===== 1. Generating Sample data (using rangeAB to create "dummy rows")
 -- The query below will generate 10,000 ids and random numbers between 50,000 and 500,000
 SELECT
   someId    = r.RN,
   someNumer = ABS(CHECKSUM(NEWID())%450000)+50001
 FROM core.rangeAB(1,10000,1,1) AS r;

--===== 2. Create a series of dates; rn is 0 to include the first date in the series
 DECLARE @StartDate DATE = '20180101', @enddate DATE = '20180131';

 SELECT r.RN, calDate = DATEADD(dd, r.RN, @StartDate)
 FROM   core.rangeAB(1, DATEDIFF(dd,@StartDate,@enddate),1,0) AS r;
 GO

--===== 3. Splitting (tokenizing) a string with fixed sized items
 -- given a delimited string of identifiers that are always 7 characters long
 DECLARE @String VARCHAR(1000) = 'A601225,B435223,G008081,R678567';

 SELECT
   itemNumber = r.RN, -- item's ordinal position
   itemIndex  = r.N1, -- item's position in the string (it's CHARINDEX value)
   item       = SUBSTRING(@String, r.N1, 7) -- item (token)
 FROM core.rangeAB(1, LEN(@String), 8,1) AS r;
 GO

--===== 4. Splitting (tokenizing) a string with random delimiters
 DECLARE @String VARCHAR(1000) = 'ABC123,999F,XX,9994443335';

 SELECT
   itemNumber = ROW_NUMBER() OVER (ORDER BY r.RN), -- item's ordinal position
   itemIndex  = r.N1+1, -- item's position in the string (it's CHARINDEX value)
   item       = SUBSTRING
               (
                 @String,
                 r.N1+1,
                 ISNULL(NULLIF(CHARINDEX(',',@String,r.N1+1),0)-r.N1-1,8000)
               ) -- item (token)
 FROM  core.rangeAB(0,DATALENGTH(@String),1,1) AS r
 WHERE SUBSTRING(@String,r.N1,1) = ',' OR r.N1 = 0;
 -- logic borrowed from: http://www.sqlservercentral.com/articles/Tally+Table/72993/

--===== 5. Grouping by a weekly intervals
 -- 5.1. how to create a series of start/end dates between @StartDate & @endDate
 DECLARE @StartDate DATE = '1/1/2015', @endDate DATE = '2/1/2015';
 SELECT
   WeekNbr   = r.RN,
   WeekStart = DATEADD(DAY,r.N1,@StartDate),
   WeekEnd   = DATEADD(DAY,r.N2-1,@StartDate)
 FROM core.rangeAB(0,datediff(DAY,@StartDate,@EndDate),7,1) AS r;
 GO

 -- 5.2. LEFT JOIN to the weekly interval table

 DECLARE @StartDate DATETIME = '1/1/2015', @endDate DATETIME = '2/1/2015';
 BEGIN
   -- sample data
   DECLARE @loans TABLE (loID INT, lockDate DATE);
   INSERT  @loans
   SELECT r.RN, DATEADD(DD, ABS(CHECKSUM(NEWID())%32), @StartDate)
   FROM   core.rangeAB(1,50,1,1) AS r;

   -- solution
   SELECT
     WeekNbr   = r.RN,
     WeekStart = dt.WeekStart,
     WeekEnd   = dt.WeekEnd,
     total     = COUNT(l.lockDate)
   FROM core.rangeAB(0,datediff(DAY,@StartDate,@EndDate),7,1) AS r
   CROSS APPLY (VALUES (
     CAST(DATEADD(DAY,r.N1,@StartDate) AS DATE),
     CAST(DATEADD(DAY,r.N2-1,@StartDate) AS DATE))) dt(WeekStart,WeekEnd)
   LEFT JOIN @loans l ON l.LockDate BETWEEN  dt.WeekStart AND dt.WeekEnd
   GROUP BY  r.RN, dt.WeekStart, dt.WeekEnd ;
 END;

--===== 6. Identify the first vowel and last vowel in a along with their positions
 DECLARE @String VARCHAR(200) = 'This string has vowels';

 BEGIN
   SELECT TOP(1) Position = r.RN, Letter = SUBSTRING(@String,r.RN,1)
   FROM     core.rangeAB(1,LEN(@String),1,1) AS r
   WHERE    SUBSTRING(@String,r.RN,1) LIKE '%[aeiou]%'
   ORDER BY r.RN;

   -- To avoid a sort in the execution plan we'll use OP instead of RN
   SELECT TOP(1) position = r.OP, letter = SUBSTRING(@String,r.OP,1)
   FROM     core.rangeAB(1,LEN(@String),1,1) AS r
   WHERE    SUBSTRING(@String,r.RN,1) LIKE '%[aeiou]%'
   ORDER BY r.RN;
 END;

-----------------------------------------------------------------------------------------
[Revision History]:
 Rev 00 - 20140518 - Initial Development - AJB
 Rev 01 - 20151029 - Added 65 rows. Now L1=465; 465^3=100.5M. Updated comments - AJB
 Rev 02 - 20180613 - Complete re-design including opposite number column (op)
 Rev 03 - 20180920 - Added additional CROSS JOIN to L2 for 530B rows max - AJB
 Rev 04 - 20190306 - Added inline aliasing function(f):
                     f.R=(@High-@Low)/@Gap, f.N=@Gap+@Low - AJB
 Rev 05 - 20191122 - Developed this "core" version for open source distribution;
                     updated notes and did some final code clean-up
*****************************************************************************************/
RETURNS TABLE WITH SCHEMABINDING AS RETURN
WITH
L1(N) AS
(
  SELECT 1
  FROM (VALUES
   ($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),
   ($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),
   ($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),
   ($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),($),
   ($),($)) T(N) -- 90 values
),
L2(N)      AS (SELECT 1 FROM L1 a CROSS JOIN L1 b CROSS JOIN L1 c),
iTally(RN) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM L2 a CROSS JOIN L2 b)
SELECT r.RN, r.OP, r.N1, r.N2
FROM
(
  SELECT
    RN = 0,
    OP = (@High-@Low)/@Gap,
    N1 = @Low,
    N2 = @Gap+@Low
  WHERE @Row1 = 0
  UNION ALL   -- (@High-@Low)/@Gap+1:
  SELECT TOP (ABS((ISNULL(@High,0)-ISNULL(@Low,0))/ISNULL(@Gap,0)+ISNULL(@Row1,1)))
    RN = i.RN,
    OP = (@High-@Low)/@Gap+(2*@Row1)-i.RN,
    N1 = (i.rn-@Row1)*@Gap+@Low,
    N2 = (i.rn-(@Row1-1))*@Gap+@Low
  FROM       iTally AS i
  ORDER BY   i.RN
) AS r
WHERE @High&@Low&@Gap&@Row1 IS NOT NULL AND @High >= @Low
AND   @Gap > 0;


text:
Q: Using bash to concatenate find/replace command with echo I have a CSV file with multiple before/after values which I am using to find and replace values in another large data file (~200MB).
I initially used a loop reading in each before/after value and sed to implement the find and replace.
The issue is that it's understandably a bit slow, so I wanted to try running all of the find/replace in a single line separated by semi-colons to see if it might be faster by only having to traverse the target data file one time.
So I have two values:
find="ABC"
replace="DEF"

Then I initialized the variable:
cmd=""

and within the loop, I tried to use this command:
cmd="${cmd}s/${find}/${replace}/g;"

The idea is to have everything concatenate into one long string like so:
"s/FIND1/REP1/g;s/FIND2/REP2/g;s/FIND3/REP3/g; ..." And so on

Then I could run the command:
perl -i -p -e ${cmd} TARGET_FILE

The issue is that my output for the cmd is looking really strange:
echo ${cmd}
/DEF/g;ABC

The order is totally messed up, I even tried to set ${cmd} to a string like "test" to see what was going on, and the output doesn't change. Somehow the variable order is getting reversed, and the leading "s" is not showing up.
I tried to use printf instead and got the same results. I tried removing the semicolon, changing the forward-slash, escaping the characters, and various other things but nothing seems to be working. Could someone tell me what is going on with this command and why the strange behavior?

A: Doing this in a single string is not scalable. Multiple replacements are also not efficient.
This Perl one-liner reads the csv file with patterns and replacements ("before" and "after" values) into the hash %to. It then constructs the regex $pat by concatenating all the "before" values. Then it reads the file where it replaces "before" with "after" values and prints the result into the output file.
cat > pats.csv <<EOF
FIND1,REP1
FIND2,REP2
FIND3,REP3
EOF

cat > in.txt <<EOF
foo FIND1,FIND2,FIND1
bar FIND2 bar
FIND3
EOF

perl -lpe '
BEGIN {
    %to = map { chomp; split m{,}, $_ }
        do { local @ARGV = q{pats.csv}; <> };
    $pat = join q{|}, keys %to;
    $pat = qr{($pat)};
}
s{$pat}{$to{$1}}gxms;
' in.txt > out.txt

cat out.txt
# Prints this:
foo REP1,REP2,REP1
bar REP2 bar
REP3


text:
Q: Using templates to iterate across struct fields at compile time I work as a TA in a class that teaches DirectX 11 and the current problem is the D3D11_INPUT_ELEMENT_DESC array that generates the input layout. The instructor considers it ugly and "close to hardware." In the instructor's opinion there should be a clean and pretty function we can simply provide our vertex structure to and get an appropriate input layout back. I am attempting to write this function.
I've done some research and the general consensus is that, because C++ does not have reflection, it's not directly possible, but there is an ugly (by a certain measure) workaround using macros and boost phoenix. Unfortunately, I don't have access to Boost. My technology limitation is C++, Visual Studios Community 2017, the Windows 10 SDK, and the June 2010 DirectX 11 SDK. I realize DirectX is already included with the Windows SDK, but there are some utilities we want from the June 2010 version.
It is apparent that I can't write a runtime function to perform this task, but what about a compile time function with templates. All sources I've found thus far have talked about runtime and I have yet to discover a source talking about iterating across struct fields at compile time. I have some experience with templates, but not enough to know whether this is possible or not, let alone how to start. I was hoping someone here might have an idea.
This is my ideal solution:
struct Vertex
{
    XMFLOAT3 pos;
    XMFLOAT3 col;
    XMFLOAT3 norm;
    .
    .
    .
};

const char*[] bindings = {
    "POSITION",
    "COLOR",
    "NORMAL",
    .
    .
    .
};

//Takes a struct as template and a list of semantic bindings to create
//an array of D3D11_INPUT_ELEMENT_DESCs for runtime processing.
template <typename T>
constexpr D3D11_INPUT_ELEMENT_DESC* processStruct(const char** semantics)
{
    //what do I put here?
}

D3D11_INPUT_ELEMENT_DESC* layoutDescriptor = processStruct<Vertex>(bindings);

A: It is not clear for me how you will build the D3D11_INPUT_ELEMENT_DESC using the Vertex-Structor and binding strings. Nevertheless the following try may help you achieving your goal:
#include <thread>
#include <iostream>

const char* bin[] = {
    "pos",
    "col",
    "normal",
    "other"
};

class desc {
    public:
    constexpr desc() : desText(0){}
    constexpr desc(const char * str): desText(str) {}
    constexpr desc operator+(const desc) { return *this; }
    void printName() { std::cout << desText << std::endl;}
    const char* desText;
};

const int ARRAY_SIZE = 4;

template <int N, int I=N-1>
class Table : public Table<N, I-1>
{
public:
    static const desc dummy;
};

template <int N>
class Table<N, 0>
{
public:
    static const desc dummy;
    static desc array[N];
};

template <int N, int I>
const desc Table<N, I>::dummy = Table<N, 0>::array[I] = desc(bin[I]) + Table<N, I-1>::dummy;

template <int N>
const desc Table<N, 0>::dummy = Table<N, 0>::array[0] = desc(bin[0]);

template <int N>
desc Table<N, 0>::array[N];

template class Table<ARRAY_SIZE>;

int main(int, char**)
{
    for (int i=0; i < ARRAY_SIZE; ++i)
        Table<ARRAY_SIZE>::array[i].printName();
}

It converts the a binding list to an array of desc classes.
live example


text:
Q: No overload matches this call. angular2 to angular12

I am upgrading my Angular-2 project to Angular-12 project and when I changed :
Before
import { Http, Response, Headers } from '@angular/http';
After
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
I am facing issue to use HttpHeaders in place of Headers
You can see the images below. I am stuck here. Need some help.

A: The problem is that you set body in a GET request which has no body!
You can use this code below, but you will have to change your backend to use queryParams:
 this.http.get('myurl', { params: dataObject })


text:
Q: Why there's no output generated? What wrong with my code? uniqid() is for generating a unique code and it will be stored to the name attribute then a condition is stated if it is clicked it will generate it's working.. Could some help me please with this one? Thanks in advance..
 <html>
    <form method="POST">

    <?php

    $attname = uniqid();

    echo "<input type='submit' name='$attname' class='btn btn-success' value='Post to Peónline'/>";
    echo $attname;
    if(isset($_POST[$attname])){
    echo 'its working';
    }
    ?>
    </form>

    <html>

A: This isn't going to work.
When you refresh the page the $attname value will change. This will happen when you submit the form. So the actual name you're checking on will change and not be the same as the new $attname.
Put the following after your echo $attname; line:
print_r($_POST);

Also for this to work properly you'll need to nest the <input> tag in a <form> tag e.g.:
<form method="POST">
<input>...</input>
</form>

A: The $attname will change after page refresh.
You need to store that name somewhere.
Add another hidden element.
...
echo "<input type='hidden' name='elemname' value='<?php echo $attname;?>'/>";
...

And after submit,
if (isset($_POST['elemname'])) {
  $elemname = $_POST['elemname'];
  $val = isset($_POST[$elemname]) ? $_POST[$elemname] : '';
  echo $val;
}


text:
Q: Is LatLng inside a polygon I have a typical polygon set on a google map with some latLng's:
var bermudaTriangle = new google.maps.Polygon({
  paths: [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737),
  ]
});
bermudaTriangle.setMap(map);

these are the Bermuda Triangle coords from google's documentation. I also have some random coords, saaay:
var coord1 = new new google.maps.LatLng(26.194876675795218,-69.8291015625)
var coord2 = new new google.maps.LatLng(33.194876675795218,-63.8291015625)

the first one happens to be inside the triangle, and the second one outside. These are just examples though, what I need is a way to find out, if a provided coordinate (not just one of these 2, any coordinte) is inside or outside the polygon (also, not always the Bermuda Triangle, not even a triangle - the polygons can have any number of latLng's). I've looked through the Google Maps API documentation, but I couldn't find any function that provides
an answer to this question.

A: Use the containsLocation(point:LatLng, polygon:Polygon) method.

containsLocation(point:LatLng, polygon:Polygon)   boolean     Computes whether the given point lies inside the specified polygon.

proof of concept fiddle
code snippet:

function checkInPolygon(marker, polygon) {
  var infowindow = new google.maps.InfoWindow();
  var html = "";
  if (google.maps.geometry.poly.containsLocation(marker.getPosition(), polygon)) {
    html = "inside polygon";
  } else {
    html = "outside polygon";
  }
  infowindow.setContent(html);
  infowindow.open(map, marker);
}

var map;
var coord1 = new google.maps.LatLng(26.194876675795218, -69.8291015625);
var coord2 = new google.maps.LatLng(33.194876675795218, -63.8291015625);

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  bermudaTriangle.setMap(map);
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < bermudaTriangle.getPath().getLength(); i++) {
    bounds.extend(bermudaTriangle.getPath().getAt(i));
  }
  bounds.extend(coord1);
  bounds.extend(coord2);
  var marker1 = new google.maps.Marker({
    map: map,
    position: coord1
  });
  var marker2 = new google.maps.Marker({
    map: map,
    position: coord2,
  });
  map.setCenter(bounds.getCenter());
  map.setZoom(3);
  checkInPolygon(marker1, bermudaTriangle);
  checkInPolygon(marker2, bermudaTriangle);
}
google.maps.event.addDomListener(window, "load", initialize);

var bermudaTriangle = new google.maps.Polygon({
  paths: [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737),
  ]
});
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

A: If the Google Maps API doesn't have any methods specifically for this, then you'll need to find or write your own.  It's a common problem in computer graphics, and if you Google "polygon hit testing" you'll find a wealth of information.  This SO answer looks reasonably comprehensive.

A: In V3 API there is google.maps.geometry.poly.containsLocation static method.
See https://developers.google.com/maps/documentation/javascript/reference#poly
So you just have to pass the polygon and the point you want to check if it is or not inside the polygon.

A: Take a look at wikipedia Point in polygon page. There are couple of ways to determine if the point is inside the polygon. One of them is ray casting algorithm. This page has some examples on how to implement that in google maps.


text:
Q: Line limit in TextEditor (SwiftUI) not working I've seen a lot of answers that simply say to use the limit limit view modifier but it doesn't seem to work:
mport SwiftUI

struct TextEditorTest: View {

    @State var text: String = "Type in here"

    var body: some View {

        VStack {

                Text("Sample Text A")

                TextEditor(text: $text)
                    .lineLimit(3)

                Spacer()
        }
    }
}

struct TextEditorTest_Previews: PreviewProvider {
    static var previews: some View {
        TextEditorTest()
    }
}


text:
Q: Best practices to add background image in all ViewControllers swift ios 11 Previously on ios 10 I hade the following code which works perfect for me.
I just added UIView with UIImage + UIView with specific colour. After testing it on ios 11 I found out that some of the screens have this ImageView on top of the rest UI elements, so whats wrong with that
 override func viewDidLoad() {
    super.viewDidLoad()

    configureView()
}

func configureView() {
    view.backgroundColor = UIColor.clear
    let backgroundImage = getBackgroundImage()
    view.addSubview(backgroundImage)
    view.sendSubview(toBack: backgroundImage)
}

func getBackgroundImage() -> UIView {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "lemons")
    backgroundImage.contentMode =  UIViewContentMode.scaleAspectFill

    let backgroundView = UIView(frame: UIScreen.main.bounds)
    backgroundView.backgroundColor = black
    backgroundImage.addSubview(backgroundView)

    return backgroundImage
}

A: If you're creating your view controller programmatically (meaning no storyboard or nib), you can add a background image very simply like this:
class SomeViewController: UIViewController {

    override func loadView() {
        view = UIView()
        view.frame = UIScreen.main.bounds
        setBackground()
    }

    func setBackground() {

        // set image
        let bg = UIImageView()
        bg.image = // some UIImage
        bg.frame = view.bounds
        bg.contentMode = .scaleAspectFill
        bg.clipsToBounds = true
        view.insertSubview(bg, at: 0)

        // set tint
        let tint = UIView()
        tint = view.bounds
        tint = UIColor.red
        tint = 0.5
        view.insertSubview(tint, at: 1)

    }

}

Remember, when you create a view controller programmatically, you must create the view controller's actual view, i.e. view = UIView(). Furthermore, "core" tasks, like setting a background image, should be done in loadView and "finishing-touch" tasks, or tasks that you want to be executed after the view controller has loaded itself entirely into memory, should be executed in viewDidLoad. And, of course, configuring the view controller's view property should definitely not be left for last.

A: Move configureView() call from viewDidLoad into viewWillLayoutSubviews. The latter is inconvenient in that it is called many times in the course of the view controller's life, so use a Bool property to check, so that you only call configureView() once, the very first time.

A: Swift 4:
Better to keep it in helper class:
static func setBlurBackGround(_ vc:UIViewController){
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "BackGround")
        imageView.frame = dBounds
        vc.view.addSubview(imageView)
    }


text:
Q: Double recursion I am trying to figure out this double recursion problem but I cannot. To visualize, I used the function stack.
  if(n==1) {
    return 1;
  }
  else {
    return r((n+1)/2) + r(n/2);
  }
}

Using the stack can someone help me understand how to get the answer if int x = r(10)?


text:
Q: Transparent Tor Proxy with pfSense I'm trying to set up a transparent Tor proxy in Virtualbox using pfSense.
In the end I want all traffic to be passed through Tor, whenever I connect a VM to the same internal network as the proxy.
I set up a new VM for the pfSense router with 1 WAN and 1 LAN connection. (LAN IP in pfSense: 192.168.1.1/24)
I installed Tor and configured the torrc file like this:
DNSPort 53
DNSListenAddress 192.168.1.1
VirtualAddrNetworkIPv4 10.192.0.0/11
AutomapHostsOnResolve 1
RunAsDaemon 1
TransPort 9040
Log info file /var/log/tor/log

I connected to pfSense with a Windows 10 VM, kept the standard configuration, and disabled the DNS Resolver.
In pfSense I set up NAT port forwarding for the destination-ports 80/HTTP, 443/HTTPS and 22/SSH. They are redirected to 127.0.0.1:9040.
Now I connected a Win 10 VM to the internal network and tried to access some websites, with not a single one working. Except for some sites where I'm able to load them via their IP e.g. mmix.cs.hm.edu (129.187.208.9).
I found this article which describes very well what I am trying to do.
I'm pretty sure the Tor configuration is correct, so the problem should be with the pfSense firewall.


text:
Q: Pointing to an element of a struct I want to use the following code to copy the user input into a struct on the heap. I know it is incomplete but that's unimportant for my question.
#include "7.1.h"
#include <stdio.h>
#include <stdlib.h>

int main ()

{
    struct Employee emp;
    struct Employees* emps[3];

    for ( int i = 1; i < 2; i ++)
    {
        printf("Please type in the emplooyes data./n Firstname:");
            scanf("%s", emp.first);

        printf("Please type in the emplooyes data./n Lastname:");
            scanf("%s", emp.last);

        printf("Please type in the emplooyes data./n Title:");
            scanf("%s", emp.title);

        printf("Please type in the emplooyes data./n Salary:");
            scanf("%d", emp.salary);

        emps[i] = createEmployee(char*, char*, char*, int);
    }

}

My question concerns the codepiece emps[i] = createEmployee(char*, char*, char*, int);. I don't know how to give the function createEmployee() the values of the struct Employee emp; as pointers. I know that's not necessary but i want to do it that way. I would be thankful for any advise.

A: This should do it:
emps[i] = createEmployee(emp.first, emp.last, emp.title, emp.salary);

...but if you changed your function a little, it would be a lot better to use:
emps[i] = createEmployee(emp);

Your Employee structure could be defined like so:
struct Employee {
  char first[256];
  //...
};

...in which case 'first' is an array. Or, it could be defined as
struct Employee {
  char *first;
  // ...
};

An array of chars and a pointer to a char are very similar beasts. But in the first case, you will automatically allocate 256 chars for the first name each time you create an Employee. In the second case, you have to allocate the memory manually, and duplicate it appropriately when copying, and remember to delete it as well.
Say your createEmployee method looks like:
Employee *createEmployee(char * first, char * last, char * title, int salary);

If you take the first form of the Employee struct above, you might do:
struct Employee *createEmployee(char * first, char * last, char * title, int salary) {
  struct Employee *retVal = (struct Employee *)malloc(sizeof(struct Employee));
  strcpy(retVal->first, first);
  strcpy(retVal->last, last);
  // etc
  return retVal;
}

In the second case, you might do:
struct Employee *createEmployee(char * first, char * last, char * title, int salary) {
  struct Employee *retVal = (struct Employee *)malloc(sizeof(struct Employee));
  retVal->first = strdup(first);
  retVal->last = strdup(last);
  // etc
  return retVal;
}

Note that the second case makes deleting (and copying) quite tricky.
void deleteEmployee(struct Employee *emp) {
  free(emp->first);
  free(emp->last);
  // etc
  free(emp);
}

...but for the first form, you just have to free(emp).

A: This should work:
emps[i] = createEmployee(emp.first, emp.last, emp.title, emp.salary);

You must consider that the emp data structure is local to your function (for this case main). This might lead to very weird errors if you're using emp anywhere else, because the data allocated for emp will be gone once the function returns - so using any data from emp, such as emp.first and emp.last, might cause some issues.
One way to solve this would be to also allocate emp dynamically, and pass a reference of it anywhere you want - this is usually how it's done.
Another quick hacky way would be to dynamically allocate the stuff that will be lost, such as your pointers:
emps[i] = createEmployee(strdup(emp.first), strdup(emp.last), strdup(emp.title), emp.salary);

strdup() will duplicate the string you give it, and it will store it using malloc() (heap) so it won't be gone when the function returns.

A: First there is probably a typo in
  struct Employees // the s

You could simply pass the emp record as a pointer
  emps[i] = createEmployee( &emp );

And you have to allocate a new structure, that is returned to the caller
  struct Employee *createEmployee(struct Employee *p)
  {
     struct Employee *newe = malloc(sizeof(struct Employee));
     memcpy(newe, p, sizeof(struct Employee));
     return newe;
  }

Assuming the structure contains char [x] and not char *.
Not tested.


text:
Q: How to use setrequired() in google apps script I am pretty new to google apps script, since the google form cannot do the conditional required function, i will need to modify the form myself. I found this code in the google apps script website and i tried to play around with it to kind of test out if i will be able to achieve what i want.
What do i want to achieve:

*

*For 'Do you prefer cats or dogs?' question, if the user chose Cats, the 'Rate your interests' question will be automatically set to required.

What did i get from the codes i have:

*

*The if statement did not work as expected. 'Rate your interests' question is set to required regardless of the if statement conditions.

Below are the codes:
function myfunction(){
var form = FormApp.create('New Form');
var item = form.addCheckboxItem();
item.setTitle('What condiments would you like on your hot dog?');
item.setChoices([
    item.createChoice('Ketchup'),
    item.createChoice('Mustard'),
    item.createChoice('Relish')
]);
var a= form.addMultipleChoiceItem()
.setTitle('Do you prefer cats or dogs?')
.setChoiceValues(['Cats','Dogs'])
.showOtherOption(true);
form.addPageBreakItem()
.setTitle('Getting to know you');
form.addDateItem()
.setTitle('When were you born?');
var b= form.addGridItem()
.setTitle('Rate your interests')
.setRows(['Cars', 'Computers', 'Celebrities'])
.setColumns(['Boring', 'So-so', 'Interesting']);
if (a != null){
b= b.setRequired(true);
}

Logger.log('Published URL: ' + form.getPublishedUrl());
Logger.log('Editor URL: ' + form.getEditUrl());
}

A: With regards to your if statement: Variable "a" will not be null as you have just set a value to variable A.
You have to remember you are creating a form, think of this as a once off process. This script will not be running when the user is submitting their response to you form.
I can see what you are trying to achieve here, sadly it is not possible with the code above.
I could possible recommend setting Do you prefer cats or dogs as a required question, and then going to a different section based on the answer.
E.G I like cats, go to section 2 of the form. I like dogs, go to section 3 of the form. (See pic for example.)


text:
Q: Writing the total request time in seconds to an nginx access log, possibly using a calculated variable I'm trying to modify my nginx access log format to include the request duration, in seconds.
I see two possible variables I could use:
1) $request_time
2) $upstream_response_time
However both of these variables are expressed in microseconds, and I need this value to be rendered in seconds. Is there any way to specify the output as an expression (i.e. $request_time * 1000) or accomplish this in some other way?
Thanks

A: The webserver is not a calculator or statistical program. It's logging function is to provide the raw data you can do your analysis with. If you analysis program is incapable of converting microseconds to seconds you should shop around for other software. In any case, it us unrealistic to expect a program's logging function to perform unit conversions for you. The goal of logging is not to format, yet to record what it has done without impacting the performance of it's core functionality.

A: If you use a reporter like LogStash (ELK stack) you can do some calculation when parsing the log. Here is my example to convert second into millisecond in my Logstash filter for Nginx:
grok {
      match => {
        "message" => "%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] \"%{WORD:verb} %{URIPATHPARAM:logMessage} HTTP/%{NUMBER:httpversion}\" %{NUMBER:response} (?:%{NUMBER:bytes}|-) (?:\"(?:%{URI:referrer}|-)\"|%{QS:referrer}) %{QS:agent} rt=%{NUMBER:duration_sec} cid=%{GREEDYDATA:correlationId}"
      }
}
mutate { convert => [ "duration_sec", "float" ] }
ruby { code => "event['duration_ms'] = event['duration_sec'].to_f * 1000" }

Hope this helps.

A: As noted in the comments $request_time is already in seconds, however it is possible to convert to another unit purely in nginx config as follows.
I realise this is an old question but it seems to get a lot of traffic so perhaps the below will help someone else who, like me, might want to convert to a different unit, in my case nanoseconds (though if you want milliseconds then simply omit the 6 trailing zeros).
This is useful for sending to the Elastic event.duration field - to avoid the faff of an ingest pipeline or similar on the Elastic end (to multiply by 1000000) you can instead do some hideous regex as below.
The fact that $request_time is always zero-padded to 3 decimal places helps, so in the common cases you can append 6 zeros - but you also have to handle leading zeros (before & after the decimal point) to make sure the result doesn't end up with any leading zeros:
map $request_time $request_time_nanos {
    # Simple case for 0.000
    ~^0\.000$ 0;
    # If 0 before decimal place, must remove leading zeros after it, before adding 6 zeros
    ~^0\.(?:0*)([^0].*)$ $1000000;
    # Otherwise just concatenate the full pre- & post-decimal parts, before adding 6 zeros
    ~^([^0][^.]*)\.(.*)$ $1$2000000;
}

Example transformations (commas inserted for readability only):
[sec]    [nanoseconds]
0.000 =>             0
0.110 =>   110,000,000
0.010 =>    10,000,000
1.010 => 1,010,000,000


text:
Q: apply css in combobox value line in function value field In a combobox I'm getting my values with : @Unique(@DbColumn(@DbName(),"Products",4));
When the value of 1 appears in column 5 of this view "Products" I would like to apply the css active (for that line) else I would like to apply the css nonactive (for that line)

A: All the items added to combo box belong to class javax.faces.model.SelectItem. I don't think style attribute is supported on <option> tag (link). But you can set disabled attribute. For that you can add a formula item in your combo box with below code:
var items = new Array();
var values = @Unique(@DbColumn(@DbName(),"Products",4)); // Your list of values
for (var i=0 ; i<values.length ; i++) {
    items[i] = new javax.faces.model.SelectItem(values[i], values[i]);
    if (values[i] == "1") { // If value is one then disable it
        items[i].setDisabled(true);
    }
}

return items;

This would render a disabled option in the combo box on web page which cannot be selected but would be visible.
Update:
If you want the options to be selected then you can add, say asterisk, at beginning of text to indicate that. So your code would be something like:
var items = new Array();
var values = @Unique(@DbColumn(@DbName(),"Products",4)); // Your list of values
for (var i=0 ; i<values.length ; i++) {
    items[i] = new javax.faces.model.SelectItem(values[i], (values[i] == "1" ? "* " : "") + values[i]);
}

return items;


text:
Q: AddJwtBearer OnAuthenticationFailed return custom error I am using Openidict.
I am trying to return custom message with custom status code, but I am unable to do it. My configuration in startup.cs:
services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.Authority = this.Configuration["Authentication:OpenIddict:Authority"];
                o.Audience = "MyApp";           //Also in Auhorization.cs controller.
                o.RequireHttpsMetadata = !this.Environment.IsDevelopment();
                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.StatusCode = HttpStatusCodes.AuthenticationFailed;
                        context.Response.ContentType = "application/json";
                        var err = this.Environment.IsDevelopment() ? context.Exception.ToString() : "An error occurred processing your authentication.";
                        var result = JsonConvert.SerializeObject(new {err});
                        return context.Response.WriteAsync(result);
                    }
                };
            });

But the problem is no content is returned. Chrome developer tools report

(failed)

for Status and

Failed to load response data

for response.
I also tried:
context.Response.WriteAsync(result).Wait();
return Task.CompletedTask;

but the result is the same.
Desired behaviour:
I would like to return custom status code with message what went wrong.

A: This is what worked for me after finding issues related to this exception that seemed to appear after updating packages.
System.InvalidOperationException: StatusCode cannot be set because the response has already started.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.set_StatusCode(Int32 value)
   at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_StatusCode(Int32 value)

The implementation is below,
                OnAuthenticationFailed = context =>
                {
                    context.NoResult();
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    context.Response.ContentType = "application/json";

                    string response =
                        JsonConvert.SerializeObject("The access token provided is not valid.");
                    if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                    {
                        context.Response.Headers.Add("Token-Expired", "true");
                        response =
                            JsonConvert.SerializeObject("The access token provided has expired.");
                    }

                    context.Response.WriteAsync(response);
                    return Task.CompletedTask;
                },
                OnChallenge = context =>
                {
                    context.HandleResponse();
                    return Task.CompletedTask;
                }

A: It's important to note that both the aspnet-contrib OAuth2 validation and the MSFT JWT handler automatically return a WWW-Authenticate response header containing an error code/description when a 401 response is returned:

If you think the standard behavior is not convenient enough, you can use the events model to manually handle the challenge. E.g:
services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = "http://localhost:54540/";
        options.Audience = "resource_server";
        options.RequireHttpsMetadata = false;
        options.Events = new JwtBearerEvents();
        options.Events.OnChallenge = context =>
        {
            // Skip the default logic.
            context.HandleResponse();

            var payload = new JObject
            {
                ["error"] = context.Error,
                ["error_description"] = context.ErrorDescription,
                ["error_uri"] = context.ErrorUri
            };

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = 401;

            return context.Response.WriteAsync(payload.ToString());
        };
    });

A: Was facing same issue, tried the solution provided by Pinpoint but it didnt work for me on ASP.NET core 2.0. But based on Pinpoint's solution and some trial and error, the following code works for me.
var builder = services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(o =>
        {
            o.Authority = "http://192.168.0.110/auth/realms/demo";
            o.Audience = "demo-app";
            o.RequireHttpsMetadata = false;

            o.Events = new JwtBearerEvents()
            {
                OnAuthenticationFailed = c =>
                {
                    c.NoResult();
                    c.Response.StatusCode = 500;
                    c.Response.ContentType = "text/plain";
                    c.Response.WriteAsync(c.Exception.ToString()).Wait();
                    return Task.CompletedTask;
                },
                OnChallenge = c =>
                {
                    c.HandleResponse();
                    return Task.CompletedTask;
                }
            };
        });

A: please check with the bellow code for .net core 2.1
OnAuthenticationFailed =context =>
                {
                    context.Response.OnStarting(async () =>
                    {
                        context.NoResult();
                        context.Response.Headers.Add("Token-Expired", "true");
                        context.Response.ContentType = "text/plain";
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        await context.Response.WriteAsync("Un-Authorized");
                    });

                    return Task.CompletedTask;
                },

A: Below code work with .Net 6(minimal API
var app = builder.Build();
app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized) // 401
    {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(JsonConvert.SerializeObject(new Error()
        {
            Message = "Token is not valid"
        }));
    }
});