text:
Q: access local HTML files without allowing user to modify them I have a client application that currently accesses static HTML files from a server via HTTPS.
Since these files never change, I would like my application to access them from the local file system. However, I do not want the user to be able to modify the HTML, so I would like to somehow embed the files in my assembly, so nobody can tinker with them. Is this possible?

A: Assuming the local file system has some sort of "date last modified" for each file, just store the files in the file system. Also calculate a hash of the contents for each file and keep a private (hidden) record of what you know the hashes should be. Then when your app fetches a file, have it also fetch the date last changed and recalculate the contents hash too. If either the date last changed or the hash is different from what you know it should be, have your app fetch a fresh copy via https: and use that instead.
(If a user [hacker?] is really determined to thwart your scheme and has physical access to the computer, they'll find a way no matter what you do. If physical access is possible, you can't be perfect [although you can prevent "most" modifications by making it so time-consuming the user decides it's not worth it].)


text:
Q: Mock @Input value for Angular component with Jest In our Angular porject, We are migrating jasmine tests to jest.
We are getting some issues when we try to mock @Input values of components in the tests.
For example, in jamsine we use to write something like this :
@Component({
  selector: 'app-message[message]',
  templateUrl: './message.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MessageComponent implements OnInit {
  @Input() message!: Message;
}

describe('MessageComponent', () => {
  let component: MessageComponent ;
  let fixture: ComponentFixture<MessageComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [// some imports],
      declarations: [MessageComponent]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MessageComponent);
    component = fixture.componentInstance;
  });

  it('test1 with input message') {
     component.message = new Message('xxx');
     fixture.detectChanges();
     // some expectations
  }

  it('test2 with another input message') {
     component.message = new Message('yyy');
     fixture.detectChanges();
     // some expectations
  }
});

With jasmine, these tests were always passing and the instance of Message was always set like this in the tests. But with jest, everytime fixture.detectChanges() is called, the component is reset and all the @Input values are set to undefined and I do not know how to deal with it.
I then try another way for doing it insprired by (Angular Unit-Test) How to mock input property in Jasmin? and I now use a HostComponent to call my template like
let testMessage: Message = generateMessage();
@Component({
  selector: 'app-testhost',
  template: `<app-message [message]="message"></app-message>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FakeHostComponent {
  message = testMessage;
}

It works fine if I have only 1 test but I do not know how I can change the value of "message" dynamically in each tests. I feel like I'm missing something or doing something wrong. Should I create a FakeHostComponent for each of my tests ?
So I need help to make these tests a bit prettier and more dynamics. Also I would like to understand why fixture.detectChanges() reset my component input values
As a workaround, I put the value of message in a global variable "testMessage" and create this method that I call in every test, but I am sure there is a way to do it more properly
const createComponent = (message: Message) => {
    testMessage = message;
    fixture = TestBed.createComponent(FakeHostComponent);
    component = fixture.debugElement.children[0].componentInstance;
  };

A: I too was struggling with Input, as it would always be undefined. I tried mocking it in the beforeEach section, but whatever I do, the input value stays undefined and I'm unable to get into the component.
Removing fixture.detectChanges() finally removed console error and tests pass. Not really sure why, but this topic helped!

A: That is strange that @Input values reset with fixture.detectChanges().
With FakeHostComponent, to get a handle on the message value, you can do something like this:
import { By } from '@angular/platform-browser';
....
let component: FakeHostComponent;
let messageComponent: MessageComponent;

beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [// some imports],
      declarations: [MessageComponent, FakeHostComponent]
    }).compileComponents();
  });

beforeEach(() => {
    fixture = TestBed.createComponent(FakeHostComponent);
    component = fixture.componentInstance;
    messageComponent = fixture.debugElement.query(By.directive(MessageComponent)).componentInstance;
    // now you have a handle on FakeHostComponent and MessageComponent
    component.message = 'Hello'; // will change from FakeHostComponent
    fixture.detectChanges();
    console.log(messageComponent.message); // should output the message
  });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deserialize an XML file - an error in xml document (1,2) I'm trying to deserialize an XML file which I receive from a vendor with XmlSerializer, however im getting this exception: There is an error in XML document (1, 2).InnerException Message "<delayedquotes xmlns=''> was not expected.. I've searched the stackoverflow forum, google and implemented the advice, however I'm still getting the same error. Please find the enclosed some content of the xml file:
<delayedquotes id="TestData">
  <headings>
    <title/>
    <bid>bid</bid>
    <offer>offer</offer>
    <trade>trade</trade>
    <close>close</close>
    <b_time>b_time</b_time>
    <o_time>o_time</o_time>
    <time>time</time>
    <hi.lo>hi.lo</hi.lo>
    <perc>perc</perc>
    <spot>spot</spot>
  </headings>
  <instrument id="Test1">
    <title id="Test1">Test1</title>
    <bid>0</bid>
    <offer>0</offer>
    <trade>0</trade>
    <close>0</close>
    <b_time>11:59:00</b_time>
    <o_time>11:59:00</o_time>
    <time>11:59:00</time>
    <perc>0%</perc>
    <spot>0</spot>
  </instrument>
</delayedquotes>

and the code
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class delayedquotes
{
    [XmlElement("instrument")]
    public string instrument { get; set; }
    [XmlElement("title")]
    public string title { get; set; }
    [XmlElement("bid")]
    public double bid { get; set; }
    [XmlElement("spot")]
    public double spot { get; set; }
    [XmlElement("close")]
    public double close { get; set; }
    [XmlElement("b_time")]
    public DateTime b_time { get; set; }
    [XmlElement("o_time")]
    public DateTime o_time { get; set; }
    [XmlElement("time")]
    public DateTime time { get; set; }
    [XmlElement("hi")]
    public string hi { get; set; }
    [XmlElement("lo")]
    public string lo { get; set; }
    [XmlElement("offer")]
    public double offer { get; set; }
    [XmlElement("trade")]
    public double trade { get; set; }

    public delayedquotes()
    {

    }
}

A: Maybe you can try this code:
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class DelayedQuotes
{
    public DelayedQuotes()
    {
        instrument = new List<Instrument>();
    }

    [XmlElement("instrument")]
    public List<Instrument> instrument { get; set; }
}

[XmlType("instrument")]
public class Instrument
{
    [XmlElement("title")]
    public string title { get; set; }
    [XmlElement("bid")]
    public double bid { get; set; }
    [XmlElement("spot")]
    public double spot { get; set; }
    [XmlElement("close")]
    public double close { get; set; }
    [XmlElement("b_time")]
    public DateTime b_time { get; set; }
    [XmlElement("o_time")]
    public DateTime o_time { get; set; }
    [XmlElement("time")]
    public DateTime time { get; set; }
    [XmlElement("hi")]
    public string hi { get; set; }
    [XmlElement("lo")]
    public string lo { get; set; }
    [XmlElement("offer")]
    public double offer { get; set; }
    [XmlElement("trade")]
    public double trade { get; set; }
}

Also, here is a sample code to test the classes above:
static void Main(string[] args)
{
    Console.WriteLine("Initiating test!");

    XmlSerializer serializer = new XmlSerializer(typeof(DelayedQuotes));
    FileStream xmlFile = new FileStream("testXml.xml", FileMode.Open);

    DelayedQuotes quotes = (DelayedQuotes) serializer.Deserialize(xmlFile);

    Console.WriteLine("Finalizing test!");
}

A: Try this code.
var xml = System.IO.File.ReadAllText("test.xml");
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
    XmlSerializer serializer = new XmlSerializer(typeof(delayedquotes));
    delayedquotes data = (delayedquotes) serializer.Deserialize(stream);
}

A: I am not sure how you're deserializing the XML text into your object, but the following worked fine for me:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace XMLSerializationTest
{

    [Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
    public class delayedquotes
    {
        [XmlElement("instrument")]
        public string instrument { get; set; }
        [XmlElement("title")]
        public string title { get; set; }
        [XmlElement("bid")]
        public double bid { get; set; }
        [XmlElement("spot")]
        public double spot { get; set; }
        [XmlElement("close")]
        public double close { get; set; }
        [XmlElement("b_time")]
        public DateTime b_time { get; set; }
        [XmlElement("o_time")]
        public DateTime o_time { get; set; }
        [XmlElement("time")]
        public DateTime time { get; set; }
        [XmlElement("hi")]
        public string hi { get; set; }
        [XmlElement("lo")]
        public string lo { get; set; }
        [XmlElement("offer")]
        public double offer { get; set; }
        [XmlElement("trade")]
        public double trade { get; set; }

        public delayedquotes()
        {

        }
    }

    static class Program
    {
        static void Main(string[] args)
        {
            string source = @"<delayedquotes id=""TestData"">
  <headings>
    <title/>
    <bid>bid</bid>
    <offer>offer</offer>
    <trade>trade</trade>
    <close>close</close>
    <b_time>b_time</b_time>
    <o_time>o_time</o_time>
    <time>time</time>
    <hi.lo>hi.lo</hi.lo>
    <perc>perc</perc>
    <spot>spot</spot>
  </headings>
  <instrument id=""Test1"">
    <title id=""Test1"">Test1</title>
    <bid>0</bid>
    <offer>0</offer>
    <trade>0</trade>
    <close>0</close>
    <b_time>11:59:00</b_time>
    <o_time>11:59:00</o_time>
    <time>11:59:00</time>
    <perc>0%</perc>
    <spot>0</spot>
  </instrument>
</delayedquotes>
";
            var buff = Encoding.ASCII.GetBytes(source);
            var ms = new MemoryStream(buff);
            var xs = new XmlSerializer(typeof(delayedquotes));
            var o = (delayedquotes)xs.Deserialize(ms);

            Console.WriteLine("Title = {0}", o.instrument);
        }
    }
}


text:
Q: Custom word boundaries in regular expression I am trying to match words using a regular expression, but sadly the word boundary character (\b) does not include enough characters for my taste, so I want to add more. (in that precise case, the "+" character)
Here is what I used to have (it is C# but not very relevant) :
string expression = Regex.Escape(word);
Regex regExp = new Regex(@"\b" + expression + @"\b", RegexOptions.IgnoreCase);

This particular regex did not match "C++" and I thought it was a real bummer. So I tried using the \w character in a character class that way, along with the + character :
string expression = Regex.Escape(word);
Regex regExp = new Regex(@"(?![\w\+])" + expression + @"(?![\w\+])", RegexOptions.IgnoreCase);

But now, nothing gets matched... is there something I am missing?

A: (no need to escape the + in a character class)
The problem is that you use a negative lookahead first whereas you should use a negative lookbehind. Try:
@"(?<![\w+])" + expression + @"(?![\w+])"


text:
Q: pasar parse json de ajax a jquery Hola tengo el siguiente código en ajax y lo que quiero es pasar las variables datox y datoy fuera del ajax así las tomo por jquery o javascript.
var datos = [];

            var action = "codigo";

            $.ajax({
                url: 'assets/js/mqtt/ajax.php',
                type: 'POST',
                async: false,
                data:{action:action,seleccion:seleccion},
                success:function(response){
                    var resultados = JSON.parse(response);
                    datosx = resultados.datox;
                    datosy = resultados.datoy;

                },
                error:function(error){
                    console.log(error);
                }
            });
  // Aqui quiero mostrar los arreglos dentro de datosx y datos y
console.log(datosx);
console.log(datosy);

A: Las peticiones Ajax por definición son asíncronas, según MDN:

El término asíncrono se refiere al concepto de que más de una cosa
ocurre al mismo tiempo, o múltiples cosas relacionadas ocurren sin
esperar a que la previa se haya completado.

Es importante no perder de vista esto y considerar que muchas cosas ocurren en una petición Ajax (conexión a la red, recogida de datos, envío de datos, recepción de datos en el servidor, procesamiento de datos, respuesta al cliente, posibles errores, etc) y el orden / momento en que esas cosas ocurren no está pre-establecido.
Por otra parte, cuando hay una petición Ajax el código sigue su curso. Esto es así para que el hilo principal no se bloquee mientras la petición Ajax se completa, produciendo una pésima experiencia de usuario. Por eso, aunque puedes cambiar el comportamiento por defecto de Ajax mediante async: false no es recomendable hacerlo en ningún caso.
Para hacer lo que quieres y tener una petición Ajax que no bloquee el hilo principal, puedes hacerlo de dos maneras:
Manejar los datos dentro del bloque success
        $.ajax({
            url: 'assets/js/mqtt/ajax.php',
            type: 'POST',
            data:{action:action,seleccion:seleccion},
            success:function(response){
                var resultados = JSON.parse(response);
                datosx = resultados.datox;
                datosy = resultados.datoy;
                console.log(datosx);
                console.log(datosy);

            },
            error:function(error){
                console.log(error);
            }
        });

Definir una función que haga de callback
Creas una nueva función y la llamas desde dentro de success pasándole en parámetro la respuesta. En este caso es recomendable crear las variables dentro de la función, así pasas un solo parámetro que sería la respuesta:
        $.ajax({
            url: 'assets/js/mqtt/ajax.php',
            type: 'POST',
            data:{action:action,seleccion:seleccion},
            success:function(response){
                handleResponse( JSON.parse(response) );
            },
            error:function(error){
                console.log(error);
            }
        });

function handleResponse(resultados) {
    datosx = resultados.datox;
    datosy = resultados.datoy;
    console.log(datosx);
    console.log(datosy);
}

Aquí, handleResponse() será invocada sin ninguna duda cuando la petición Ajax haya terminado con éxito.

A: Mejor usar done en vez de success. Con done te aseguras que la petición haya terminado y ahí ya puedes obtener los valores correctos. Quedaría así.
var datos = [];

var action = "codigo";

$.ajax({
    url: 'assets/js/mqtt/ajax.php',
    type: 'POST',
    async: false,
    data:{action:action,seleccion:seleccion},
    error:function(error){
        console.log(error);
    }
}).done(function(response){
    var resultados = JSON.parse(response);
    datosx = resultados.datox;
    datosy = resultados.datoy;

    // Aqui quiero mostrar los arreglos dentro de datosx y datos y
    console.log(datosx);
    console.log(datosy);
});


text:
Q: How to update SearchView query after onQueryTextChange Activity has SearchView, which should have valid query.
Firstly I had that issue:
SearchView not calls onQueryTextChange on second dot
But I found that it is bad practice to set query inside onQueryTextChange.
What is proper way to validate (update) query for SearchView after every symbol have typed?
I saw EditText able to set filters, so, maybe, here exists some alternative for SearchView?

A: Here is code on Gist of custom implementation
And it is more detailed answer about that problem on StackOverflow


text:
Q: Importing FITS file from HEALPix I am trying to read FITS file created by HEALPix software. The file contains a spherical map of a scalar field.
There is the online support on how to use the file in IDL, but not for Mathematica.
I understand FITS is partly binary format, but I expect it is still standardised and contains readable description on how the data is stored.
I tried reading Elements from the file in this way
Import["test.fits", #] & /@
  Import["test.fits", "Elements"]

but the output is quite short and mainly empty lists, especially for
Import["test.fits", "Data"]
Import["test.fits", "TableData"]

The size of my file is 12.6 MB.
Here is a link to the file.
Is there another way to read the content of FITS file, besides these general 'Elements'?
Do I need to know something about the structure of my FITS file in order to be able to read it with Mathematica? Could it be the problem is that Mathematica does not read all types of FITS files?

A: Your file seems to be corrupt, there is one extra byte in the header section. Open in a binary clean text editor, search for "uK^2" and delete exactly one space following the 2.
The file can then be read by this: (adapted from link in comment)
 f = OpenRead["test.fits", BinaryFormat -> True];
 parsehead[hh_] := (metadat[#[[1]]] =
    #[[2]]; #) & /@ ({StringReplace[#[[1]], " " -> ""],
    If[Length[#] > 1, StringReplace[#[[2]], " " -> ""], ""],
    If[Length[#] > 2, #[[3 ;;]], ""]} &@
   StringSplit[ # , {"=", "/"}] & /@ hh)
 getheaders[f_] :=
 parsehead[First@Last@
       Reap[ While[ (Sow[
            StringJoin@BinaryRead[f, Table["Character8", {80}]]] !=
                StringJoin["END", Table[" ", {77}]])] ]]
 hh = getheaders[f];
 Print["lines read = ", nh = Length[hh]]
 blkpad = BinaryRead[f, Table["Byte", {2880 - Mod[nh 80, 2880]}]];
 Union[blkpad] == {32} (* verfy we just read blank *)
 Print["gettingheaders"]
 hh = getheaders[f];
 Print["lines read = ", nh = Length[hh]]
 hh // MatrixForm
 BinaryRead[f, Table["Byte", {2880 - Mod[nh 80, 2880]}]];

(data size/type hard coded based on looking at the header data..)
 data = BinaryRead[f, Table["UnsignedInteger8", {3072}, {4096}], ByteOrdering -> 1];
 blkpad = BinaryRead[f, Table["Byte", {2880 - Mod[ (3072 4096 ) , 2880]}],
       ByteOrdering -> 1];
 Union[blkpad] == {32}
 StreamPosition[f] == FileByteCount[First@f] (* verfy entire file read *)
 Close[f]

The resulting image is pretty much snow, but then I don't know what its supposed to be.
 Image[data/2^8]

the headers:


text:
Q: @SpringBootTest can't not find Jpa Repository with @Autowired I was testing JpaRepository with @SpringBootTest. but somehow it can not find jpa repository bean. I'm using basic spring boot initialze setup with spring boot 2.2.5. Do I need extra configuration for this issue?
@SpringBootTest
class BlockRepositoryTest {

    @Autowired
    private BlockRepository blockRepository;
}

public interface BlockRepository extends JpaRepository<Block, Long> {
}


text:
Q: Problem showing file info with Ajax and PHP
I have a list of files made by my PHP code

if ($handle = opendir($director))
{
    $path="images/files/nou/";
    if(Files::is_empty_dir($director))
        {
            echo "
There are no script available.
";
        }
    else
        {
   while (false !== ($file = readdir($handle)))
   {
         if ($file != "." && $file != "..")
            {
        $size=Files::getSize($director."/".$file);
        $exts=Files::getExtension($file);
                $filex = str_replace(".".$exts,"",$file);
            if(strlen($filex)>10)
                {
                    $filex=substr($filex,0,6);
                }
                echo "
".$filex."
";

There are functions defined in my own class Files.
Good. I want that on mouseover to show file information with this code

function getInfo($file)
        {
            $info="

";
            $info.="File : 	".$file."
";
            $info.="
Extension : 	".Files::getExtension($file)."
";
            $info.="
Size : 	".Files::getSize($file)."
";

            return $info;
        }

I want to show info dynamically with JQuery. I wrote this

$(".file").mouseover(function()
    {
        data=$(this).attr("title");
        alert(data);
    });

It alerts always first filename not what I crossed with mouse. But if I disable mouseover JQuery function, the title appears correctly for each file in part. If I use mouseover function, the selected value from title doesn't appear correctly, it shows first filename in alert no matter what file I crossed with mouse.
I called the alert function to see results before implementing $.ajax function to avoid bad responses.
What's the problem in my script ?
Thank you

A: Your jquery code works, so check something else, may be you need to onload() that script ?
http://jsfiddle.net/oceog/hJyRm/


text:
Q: Node cluster not listening, cluster exits and not respond This problem i got on my machine only. I tried my code on other machines it works perfectly, I didn't got any solution because there is no code level problem, may be its OS problem or may be Nodejs version problem, I don't know.

Operating Syatem: Window 7 Professional 64-bit
Nodejs version: 4.4.3

Code
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log("worker %s died", code);
        cluster.fork();
    });
} else {
    var express = require('express');
    var http = require('http');

    // init app
    var app = express();

    app.get('/',function(req,res){
        res.send('home page');
    });

    function createServer(app) {
        return http.createServer(app);
    }

    app.locals.server = createServer(app);

    app.locals.server.listen(8080, function() {
        console.info("server online");
    });
}

logs on command line
server online
server online
server online
server online

When i hit http://localhost:8080, then new logs are
worker 3221225477 died
server online

and no data got on browser, continuously loading on browser.
Please help.

A: First of all you didn't define any route, where your server can get the request.
As per your code you can define one route in your else condition
app.get('/',function(req,res){
        res.send('home page');
    })

And hit the URLhttp://localhost:8080.
Hope it works


text:
Q: .htaccess - passing an URI argument instead of directory listing PHP I need a suggestion using .htaccess (I presume) or any other solution for the following situation:
On the server, for example I have a folder www.mypage.com/accommodation/ which contains index.php script.
What I would like to do is that when the called URL is something like www.mypage.com/accommodation/apartment-mike   (note no / in the end or extension), that the string "apartment-mike" ($_SERVER['request_uri']) is passed to the index.php script in the accommodation folder instead of trying to directory walk apartment-mike directory.
What would be the best way to do this?

A: First you must rewrite the call to index.php. This is a classic and can be found anywhere
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.php [L]

The next step is accessing the URI itself, which you already figured yourself by using $_SERVER['REQUEST_URI'].

A: You can add the file apartment-mike.php,  contains a ridirection to index.php, to the accomodation folder then add the following lines to the .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

to remove the extension from appearing in the uri
don't forget to add
header("location:index.php");

to the apatement-mike.php if you want it to pass users to the index


text:
Q: Create distinct list of params with list of params using nested dictionaries Giving a list of objects with different params, how to group param values into a list and bind it to another one: I'm trying out with dictionary in c# :
Example: class car : (Update : using the good solution, working code to get nested dico)
public class Car{

    public int Id;
    public Color Color;

}

public class Color
{
    public int Id;
    public string ColorName;
}

public static void Main()
{
    var carList = new List<Car> {
        new Car() { Id = 1, Color = new Color {Id = 1, ColorName = "blue" }},
            new Car() { Id = 1, Color = new Color {Id = 1, ColorName = "blue" }},
            new Car() { Id = 1, Color = new Color {Id = 2, ColorName = "red" }},
            new Car() { Id = 1, Color = new Color {Id = 3, ColorName = "green" }},
    };

    var carColorMap = GetCarscolorsMap(carList);

 public static Dictionary<Id, Dictionary<Id, Color>> GetCarscolorsMap(List<Car> carList)
    {
        return carList.GroupBy(x => new { x.Id, x.Color})
        .GroupBy(x => x.Key.Id)
        .ToDictionary(x => x.Key, v => v.Select(x => x.FirstOrDefault())
        .ToDictionary(x => x.Color.Id, val => val.Color));
    }
}

A: Ideally you should just modify your architecture, to make this simpler, e.g create a table in the db which represent which color options you have to offer per car type.
With that being said, here is a sample which does it using your current architecture.  There are a few ways of doing this, I chose what make sense to me the most. First you group by a composite Key, Id And color.  Then group by just the id so you have a group of groups, from there your selecting out the first car with that color.
Here is a Fiddle to show it working
public class Car{

    public int Id;
    public Color Color;

}

public class Color
{
    public int Id;
    public string ColorName;
}

public static void Main()
{
    var carList = new List<Car> {
        new Car() { Id = 1, Color = new Color {Id = 1, ColorName = "blue" }},
            new Car() { Id = 1, Color = new Color {Id = 1, ColorName = "blue" }},
            new Car() { Id = 1, Color = new Color {Id = 2, ColorName = "red" }},
            new Car() { Id = 1, Color = new Color {Id = 3, ColorName = "green" }},
    };

    var carColorMap = carList.GroupBy(x => new {x.Id, ColorId = x.Color.Id}).GroupBy(x => x.Key.Id).ToDictionary(x => x.Key, v => v.Select(x => x.FirstOrDefault()));

    foreach(var car in carColorMap)
    {
        Console.WriteLine(car.Key);
        foreach(var color in car.Value)

        Console.WriteLine(color.Color.ColorName);
    }

}

A: When reading
var listOfCars = new list<Car>();
var firstCar = new Car(firstCarId,fisrtCarColor);
var secondCar = new Car(firstCarId,secondCarColor);
var thirdCar = new Car(firstCarId,thirdCarColor);
listOfCars.Add(firstCar);
listOfCars.Add(secondCar);
listOfCars.Add(thirdCar);

it looks like you only need 1 car containing 3 colors. So either you over-simplified your code and it doesn't reflect the reality or your solution is over-engineered and makes things look complicated. You could then simplify your desing like below to get something easier:
public sealed class Car
{
    private readonly HashSet<Color> _colors;
    public Car(Id id, params Color[] colors)
    {
        Id = id;
        _colors = new HashSet<Color>(colors);
    }
    public Id Id { get; }
    public IReadOnlyCollection<Color> Colors => _colors;
}

Usage:
var car = new Car(carId, color1, color2, color3);

Console.WriteLine(car.Id);
foreach (var color in car.Colors)
{
    Console.WriteLine(color);
}


text:
Q: Keyboard shortcut for small git diff popup as seen when clicked on the gutter marker? I sometimes want to see the diff of what has changed only per line, but I find it uncomfortable to always move your hand to the mouse and click on the gutter marker. Is there a way to assign a shortcut to open that little diff window (as seen in the image)? I couldn't find an IntelliJ action that opens it.

A: That action is called Change Under Caret.
By default, no shortcut is assigned to it. You can find it with Find Action (Ctrl+Shift+A | ⇧⌘A).

You can also assign a shortcut to it right in this popup with Alt+Enter | ⌥⏎.

Other useful shortcuts:

*

*Next Change: Ctrl+Alt+Shift+Down | ⌃⌥⇧↓

*Previous Change: Ctrl+Alt+Shift+Up | ⌃⌥⇧↑

*Rollback Lines: Ctrl+Alt+Z | ⌥⌘Z
Help documentation:

*

*Review changes - Track changes to a file in the editor

*Source code navigation - Navigate between changes

*Undo changes in Git repository - Revert uncommitted changes

A: Use the keyboard shortcuts for Navigate:Navigate in File:Next Change/Previous Change
To make it even easier, modify the shortcut for that command to your liking in Preferences:Keymap.


text:
Q: IIS7 rewrite regular expression does not identifying + sign I am using PHP with IIS7. In web.config file i have made rewrite rule.
Pattern which i am matching is
^product/([0-9a-zA-Z\+\-]+)$

Now the problem is it does not work when there are + sign in url for example it does not work for
http://mywebsite/product/ABC+DEF+GHI

I need it to work for above.
But it does work for
http://mywebsite/product/ABC DEF GHI

So i guess it is identifying  space but not +
Any help would be appreciated.
Thanks

A: I found answer. Just sharing in case anybody needs.
Just put
<system.webServer>
<security>
    <requestFiltering allowDoubleEscaping="true"/>
</security>

in web.config file.
And Done


text:
Q: Blazor - Add element to SVG object I want to manipulate an SVG object with blazor, is it possible to do this via C# client side, or do I need to use javascript.
For example, draw a line programatically based on clicks in the SVG area.
Any pointers would be greatly appreciated. I found a lot on adding SVG component, but nothing on adding elements to the already existing svg component

A: You can use SVG file contents as the markup in a Blazor component, and then do any of the Blazor-y things you'd normally do.
Put a variable in the svg markup, and build it as a string.
Here's a highly-simplified excerpt:
(MySvgComponent.blazor)
<svg blah blah blah>
    <polyline fill="none" stroke="#0074d9"
        stroke-width="2" points="@PointString" />
</svg>
@code {
    public string @PointString {get;set;}
    public void AddPoint (int X, int Y){
         @PointString += " " + X + "," + Y;
}

You'll have to add your own code to figure out where you want to add the points.  You could make a List<Point> parameter to pass in from a parent or something, and then call AddPoint in a foreach loop in OnInitialized().  You could also very easily replace the stroke color or anything else by replacing literals like "0074d9" with variables "@myColorString."
Handling mouse-click locations will require some fancy JS work.  Try using Javascript Interop with something like the following:
How to get the click coordinates relative to SVG element holding the onclick listener?


text:
Q: Assertion Error when Release the MFC Ext DLL @ dllmodul.cpp #230 I programmed a MFC Extension DLL, it was all right when entering it and using the exported Function;
But When I exit the application, during the DLL release the DLL, it threw a Assertion Error,then I following the error, found it stall at this:
extern "C"
BOOL WINAPI RawDllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
     hInstance;
     if (dwReason == DLL_PROCESS_ATTACH)
     {
#ifdef _AFXDLL
// make sure we have enough memory to attempt to start (8kb)
          void* pMinHeap = LocalAlloc(NONZEROLPTR, 0x2000);
          if (pMinHeap == NULL)
               return FALSE; // fail if memory alloc fails
          LocalFree(pMinHeap);

          // set module state before initialization
          _AFX_THREAD_STATE* pState = AfxGetThreadState();
          pState->m_pPrevModuleState = AfxSetModuleState(&afxModuleState);
     }
     else if (dwReason == DLL_PROCESS_DETACH && !__mixedModuleStartup)
     {
          // restore module state after cleanup
          _AFX_THREAD_STATE* pState = AfxGetThreadState();

          // ************************************************
          VERIFY(AfxSetModuleState(pState->m_pPrevModuleState) ==
          &afxModuleState); // Where Error occurred
          // ************************************************

          DEBUG_ONLY(pState->m_pPrevModuleState = NULL);

#endif //_AFXDLL
     }
     return TRUE;
}

A: You have failed to use AFX_MANAGE_STATE correctly on all entry points to your DLL. So your module state is wrong, hence the assert.
Martyn


text: Q: Error: EISDIR: illegal operation on a directory, read. Elastic beanstalk node.js error I have deployed my code to AWS using beanstalk but i am receiving this error so my environment is unhealthy. My code works stand alone in visual studio however whenever i deploy it to AWS i receive this error. What can i do to solve this enter image description here


text:
Q: Deploy x86 and x64 artifacts to AppVeyor on Github Releases I have a Visual Studio 2017 solution that consists of a single C++ project.
I wanted AppVeyor to build for x86 and x64 and deploy the 2 executables on GitHub Releases.
While deploying only for one arch seems to work fine I found out that my appveyor.yml file replaces the executable once a job finishes and another starts.
For the record, this is my first deployment ever so I would need some guidance.
Here is some info on Github Releases https://www.appveyor.com/docs/deployment/github/
Here is my appveyor.yml file
version: '{build}'
image: Visual Studio 2017
configuration: Release
platform:
- x86
- x64
build:
  verbosity: minimal
artifacts:
- path: Release\pathfinding.exe
  name: pathfinding-x86.exe
- path: x64\Release\pathfinding.exe
  name: pathfinding-x64.exe
deploy:
- provider: GitHub
  auth_token:
    secure: the-token-is-hidden-on-purpose
  force_update: true
  on:
    APPVEYOR_REPO_TAG: true

A: I figured it out!
Here is my repository by the way: https://github.com/xorz57/pathfinding
The problem was my visual studio build tree.
If you use the default visual studio project properties the executable files have the exact same filename even though they are on a different directory when you build for x86 and x64 and that's why appveyor never uploaded a second executable to GitHub Releases. So I went to visual studio and opened up my project settings to change the build tree.

Make sure to change Configuration to All Configurations and Platform to All Platforms. Then proceed to change the following three options Output Directory, Intermediate Directory, Target Name. In the picture above I show you how I configured my own project. Of course this is not the only way nor I am suggesting this is the best prossible way to organize your project.
The point is to have different filename for the executable files.
Now I push a new tag and everything works as intended.

And here is my updated appveyor.yml file
version: '{build}'
image: Visual Studio 2017
configuration: Release
platform:
- x86
- x64
build:
  parallel: true
  verbosity: minimal
artifacts:
- path: Build\Release\pathfinding-x86.exe
  name: pathfinding-x86.exe
- path: Build\Release\pathfinding-x64.exe
  name: pathfinding-x64.exe
deploy:
- provider: GitHub
  auth_token:
    secure: the-token-is-hidden-on-purpose
  force_update: true
  on:
    APPVEYOR_REPO_TAG: true


text:
Q: Can not make the settings from the sidebar gadget get applied OK, I am not an expert at Sidebar Gadgets, but I have this project I will have to make for school. Have tried to solve it on my own but I got really stuck.
I will have to use the Cirip API (Cirip.ro being a kind of Twitter), and for the use of the API I have to input the username. I do so by means of the Settings, but when closing the settings there is no effect.
Here is the code, but it's pretty messy. I am not a web programmer so javascript/html is new to me.
http://www.box.net/shared/7yogevhzrr

EDIT: Ok, so I have narrowed it down a little and optimized my code here but it is still not working. I have made it as simple as possible.
In the main html I have this:

In the gadget.js:
var userName;

document.onreadystatechange = function DoInit() {

    document.body.style.width = 251;
    document.body.style.height= 351;
    document.body.style.margin=2;
    userName="danieliuhasz";
    System.Gadget.settingsUI = "settings.html";
    System.Gadget.onSettingsClosing = settingsClosed;

}

function setUserName(userNameSet){

    userName = userNameSet;
}

function getUserName(){

    return userName;
}

function settingsClosed()
{

    var username = System.Gadget.Settings.read("username");
    setUserName(username);
}

In the settings.html:

Username:

<input name="userBox" type="text" maxlength="50" />

In settings.js:
document.onreadystatechange = function DoInit()
{

    if(document.readyState=="complete")
    {
        var user = System.Gadget.Settings.read("userName");

        if(user != "")
        {
            userBox.value = user;
        }
    }
}

System.Gadget.onSettingsClosing = function(event)
{

    if (event.closeAction == event.Action.commit)
    {
        var username = userBox.value;
        if(username != "")
        {
              System.Gadget.Settings.write("username", username);
              System.Gadget.document.parentWindow.settingsClosed();

        }
    }
}

I really can't figure it out. The output of this is "undefined".

A: I don't have a RAR unpacker on this machine so I can't take a look at the file, but I can give you a little bit of advice about saving settings.  If you need further help, try pasting the code into your question (see my comment above).
When working with settings, you need to catch the System.Gadget.onSettingsClosing event in your JavaScript code.  In this event handler, you can either make the settings temporary, by setting properties in the gadget window, or you can make them semi-permanent, by using System.Gadget.Settings.write to store the settings.  Let's say your username/password html looks like this:
Username: <input id="username" type="text">

Password: <input id="password" type="password">

Your JavaScript should look something like this:
System.Gadget.onSettingsClosing = function (event) {
    // First, we need to make sure the user clicked the OK button to save
    if (event.closeAction == event.Action.commit) {
        // If they did, we need to store the settings
        var username = document.getElementById("username").value,
            password = document.getElementById("password").value;

        System.Gadget.Settings.write("username", username);
        System.Gadget.Settings.write("password", password);

        /* Finally, we can call a function defined in the main gadget window's
           JavaScript to let it know that the settings have changed */
        System.Gadget.document.parentWindow.settingsHaveChanged();
    }
}

In your main gadget's JavaScript, settingsHaveChanged might look something like the following function:
function settingsHaveChanged () {
    var username = System.Gadget.Settings.read("username"),
        password = System.Gadget.Settings.read("password");

    sendAPIRequest(username, password);
}


text:
Q: Can I pass an object as the parameter for an onClick function I am currently trying to create an onclick event for a button that calls a separate function and passes uses an object as the parameter for this function.
My code can be seen below:
async function getJourneyAwait(){
  const routes = await getJourney();
  var innerHTML = " ";
  if(!(routes === null)) {
    for (var i = 0; i < routes.length; i++){
        console.log(routes[i])
        console.log(typeof(routes[i]))
        var route = routes[i]
        innerHTML += '
 Route ' + i+1 + ': <button onClick=startJourney(' + route + ')>Start Trip</button>
'
    }
    document.getElementById('tripmessage').innerHTML = innerHTML;
  }
}

function startJourney(route){

    console.log(route);
}

When I try to click the Start Trip button I get an error stating: Uncaught SyntaxError: Unexpected end of input at .(index):1
When I inspect the button element it there seems to be some kind of error with the parameter as the element is as follows:

<button onclick="startJourney([object" object])="">Start Trip</button>

I have tried multiple different ways and in some cases I have been able to get the function to run but when I do all that is logged to the console is undefined. For example, if I remove the plus signs and quotes on either side of 'route' the function runs but undefined is logged to the console.

A: The [object object] that you are seeing is the result of the conversion of your route object to a string format.
I suggest one of two approaches:

*

*Create the button element using createElement, assign the startJourney function to the onclick property using button.onclick = function() { createJourney(route) ]} and append it to the parent element.

*Add an id to the button element and add a click event listener using addEventListener("click", createJourney(route))
Edit: As pointed out by @Teemu, in case you use option #1, you'll have to replace var i = 0 by let i = 0 since in a loop with a let-based index, each iteration through the loop will have a new variable i with loop scope.

A: You should I would recommend you use Data attributes and also bind your buttons this way:

function getJourneyAwait(){
  const routes = getJourney();
  var innerHTML = " ";
  if(routes) {
    for (var i = 0; i < routes.length; i++){
        var route = routes[i]
        innerHTML += '
 Route ' + route + ': <button onclick="startJourney(this)" data-route="' + route + '">Start Trip</button>
'
    }
    document.getElementById('tripmessage').innerHTML = innerHTML;
  }
}

function getJourney(){
  return [1, 2, 4, 6]
}

function startJourney(element){
    console.log(element.dataset.route);
}

<button onclick="getJourneyAwait()">GetJourney</button>


text:
Q: Pandas replace column values with a list I have a dataframe df where some of the columns are strings and some are numeric. I am trying to convert all of them to numeric. So what I would like to do is something like this:
col = df.ix[:,i]
le = preprocessing.LabelEncoder()
le.fit(col)
newCol = le.transform(col)
df.ix[:,i] = newCol

but this does not work. Basically my question is how do I delete a column from a data frame then create a new column with the same name as the column I deleted when I do not know the column name, only the column index?

A: This should do it for you:
# Find the name of the column by index
n = df.columns[1]

# Drop that column
df.drop(n, axis = 1, inplace = True)

# Put whatever series you want in its place
df[n] = newCol

...where [1] can be whatever the index is, axis = 1 should not change.
This answers your question very literally where you asked to drop a column and then add one back in.  But the reality is that there is no need to drop the column if you just replace it with newCol.

A: newcol = [..,..,.....]

df['colname'] = newcol

This will keep the colname intact while replacing its contents with newcol.


text:
Q: UIDatePicker hours are disabled I have a UIDatePicker object and I am setting it up as follows but for some reason my hours field is disabled on the current date but minutes are not. Not exactly sure what I am missing,  any help would be appreciated.
UIDatePicker *picker = [[UIDatePicker alloc] init];
picker.date = [NSDate dateWithTimeIntervalSinceNow:DATE_MIN_SECONDS_OFFSET];
picker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:DATE_MIN_SECONDS_OFFSET];

This is what My datepicker looks like
http://img.skitch.com/20100417-d75gq78pjwjb9d37ku9msmcduc.png

A: It appears to be a known bug.


text:
Q: setTimeOut in Angular to cause a delay in returning data getCustomersFromAPICall(): CustomerModel[] {
    setTimeout(()=> {
        return this.dataFromAPICall = [
            {
                firstName: 'Nintendo',
                lastName: 'Switch',
                caseID: 123,
                employeeNumber: 1234,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Intermittent,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Open,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('12/01/1990'),
                endDate: new Date('12/01/2000'),
                lastUpdated: new Date('1/1/1991')
            },
            {
                firstName: 'Nintendo',
                lastName: 'Switch',
                caseID: 124,
                employeeNumber: 1234,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Continuous,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Closed,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('12/01/1990'),
                endDate: new Date('12/01/2000'),
                lastUpdated: new Date('1/1/1991')
            },
            {
                firstName: 'Nintendo',
                lastName: 'Switch',
                caseID: 125,
                employeeNumber: 1234,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Intermittent,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Closed,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('12/01/1990'),
                endDate: new Date('12/01/2000'),
                lastUpdated: new Date('1/1/1991')
            },
            {
                firstName: 'Storm',
                lastName: 'Kevin',
                caseID: 123,
                employeeNumber: 1239,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Intermittent,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Open,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('12/01/1990'),
                endDate: new Date('12/01/2000'),
                lastUpdated: new Date('1/1/1991')
            },
            {
                firstName: 'Scott',
                lastName: 'Summer',
                caseID: 124,
                employeeNumber: 1235,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Continuous,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Closed,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('12/01/2000'),
                endDate: new Date('12/01/2001'),
                lastUpdated: new Date('1/1/2005')
            },
            {
                firstName: 'Victor',
                lastName: 'Von Doom',
                caseID: 125,
                employeeNumber: 1236,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Intermittent,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Open,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('12/01/2010'),
                endDate: new Date('12/01/2005'),
                lastUpdated: new Date('1/1/2009')
            },
            {
                firstName: 'Bruce',
                lastName: 'Banner',
                caseID: 126,
                employeeNumber: 1237,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Continuous,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Open,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('05/01/1990'),
                endDate: new Date('01/01/1000'),
                lastUpdated: new Date('1/1/2021')
            },
            {
                firstName: 'Peter',
                lastName: 'Parker',
                caseID: 127,
                employeeNumber: 1238,
                photo: 'https://t4.ftcdn.net/jpg/02/90/27/39/360_F_290273933_ukYZjDv8nqgpOBcBUo5CQyFcxAzYlZRW.jpg',
                displayCaseCode: '15',
                reasonName: '1C',
                frequencyType: FrequencyType.Continuous,
                emailAddress: 'NJ',
                networkID: 'ABC',
                caseState: CaseState.Closed,
                requestDate: new Date('12/12/2012'),
                startDate: new Date('08/01/2015'),
                endDate: new Date('01/01/1000'),
                lastUpdated: new Date('10/1/2022')
            }
        ];
    }, 2000);
    return this.dataFromAPICall;
}

With this code, i do not seem to be getting the desired results
 findEmployee() {
    //debugger;
    this.searchEmployeeList = this.getCustomersFromAPICall();

if I remove the setTimeout, it works fine but I wanted to test the UI if the network was slow by adding a setTimeout()

A: Your code is correctly returning an empty value
It would be easier for you if you replaced the lengthy object with a smaller one, and trimmed your variable/function names. You would instantly recognise that this is incorrect:
getCustomers(){

    setTimeout(()={
        return this.data = [{ test: 1 }]
    })
    return this.data
}

Your function sets up a timeout, but immediately returns the current value of this.data. That is why you are getting nothing back - you are getting the value of this.data before you have added the elements to it.
What you probably want is an asynchronous function
Look into promises: how to create them and how to return them.
See if you can design an asynchronous function: this can return a promise, rather than an actual value. The promise can later resolve into the actual value. For example, this could be after a delay controlled by setTimeout.

A: Try using Promises...
 const customerFixture: CustomerModel[] = {
       ...
       employeeNumber: 1234,
       endDate: new Date('12/01/2000'),
       lastUpdated: new Date('1/1/1991'),
       ...
}

getCustomersFromAPICall(): Promise<CustomerModel[]> {
   // Here you return a promise that be resolve in 2 seconds (2000 in milliseconds) with customers
   return new Promise((resolve) =>
      setTimeout(() => resolve(customerFixture), 2000),
    );;
}

async findEmployee() {
    //You should wait the promise to be solved using "await" word before the method call. Also to make this work you have to add "async" word before this method name.
    this.searchEmployeeList = await this.getCustomersFromAPICall();
    // try to log it
    console.log(this.searchEmployeeList)

Another option if you dont want to use async/await would be
findEmployee() {
    //In this case you dont block the thread waiting the two seconds to be solved
    this.getCustomersFromAPICall().then(customers => {
      this.searchEmployeeList = customers;
      console.log(this.searchEmployeeList)
    })
    // try to log it


text:
Q: SQL Server Data Tools business intelligence with express edition If I install in my PC :

*

*SQL Server 2014 Express edition

*SQL Server Data Tools Business Intelligence

Can I build SSIS packages?
I don't care about deploying, I just need a development environment.
Thanks in advance for the help.

A: You can build and compile packages in SQL Server Data Tools with BI. They can only be deployed to SQL Server Standard or higher, which isn't an issues since you mention you just need a development environment.
Here are specific available features:

*

*Features by Edition of SQL Server: http://msdn.microsoft.com/en-us/library/cc645993.aspx

*Requirements for running SSIS in development projects: http://msdn.microsoft.com/en-us/library/ms365338.aspx


text:
Q: Join lists in a list of lists What's the best way to join two consecutive lists in a list of lists ?
For example if I have the list
x = {{1}, {2}, {3}, {4}}

and I want to get in x
{{1}, {2, 3}, {4}}.

I want to join arbitrary positions.
Edit
I want to do this using the least amount of extra memory. Imagine that instead of having numbers I have big lists.

A: l = {{a}, {b}, {c}, {d}};
j[l_, from_, to_] := {Sequence @@ l[[1 ;; from - 1]], Join @@ l[[from ;; to]],
                      Sequence @@ l[[to + 1 ;;]]}

j[l, 2, 4]
(*
->{{a}, {b, c, d}}
*)

A: Belisarius' answer works well if you are willing to work with indexes. If you prefer to work in terms of the list elements rather than their positions, here is a rule-based solution.
innerJoin[data : {{_} ..}, a_, b_] :=
  data /. {x___, y : PatternSequence[{a}, ___, {b}], z___} :> {x, Flatten[{y}], z}

innerJoin[{{1}, {2}, {3}, {4}}, 2, 3]

{{1}, {2, 3}, {4}}

innerJoin[{{a}, {b}, {c}, {d}}, a, c]

{{a, b, c}, {d}}

Edit -- new and improved algorithm featuring the under appreciated PatternSequence :-)

A: list = {{1}, {2}, {3}, {4}}

I asked some questions in my comments but in the absence of clarification about what you want, i.e. will this always be applied to 4 element lists, why not just this:
list[[2]] = Flatten[list[[{2, 3}]]];
list[[3]] = Sequence[];
list

(* {{1}, {2, 3}, {4}} *)

or if you want to make it a function -- probably unnecessary because it is a straightforward two step process:
newList[list_List] := Module[{tmp = list}, tmp[[2]] = Flatten[tmp[[{2, 3}]]];
tmp[[3]] = Sequence[]; tmp]

Edit
Since you've said in your edit 4 hours ago that your actual example is big lists in place of the 4 numbers so you probably won't want to display output
list[[2]] = Flatten[list[[{2, 3}]]];
list[[3]] = Sequence[];
list;

or
list[[2]] = Flatten[list[[{2, 3}]]];
list = Delete[list, 3];

newList2[list_List] := Module[{tmp = list}, tmp[[2]] = Flatten[tmp[[{2, 3}]]];
Delete[tmp, 3]]

A: A bit more general version with Drop and ReplacePart:
list = List /@ Range@8
{from, to} = {3, 6}; (* specify first and last positions to be joined *)
ReplacePart[Drop[list, {from + 1, to}], from -> Join @@ Take[list, {from, to}]]

{{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}}

{{1}, {2}, {3, 4, 5, 6}, {7}, {8}}

With ReplaceAll and Repeated:
list /. {x : Repeated[_, {from-1}], y : Repeated[_, {to-from+1}], z___} :> {x, Join@y, z}

{{1}, {2}, {3, 4, 5, 6}, {7}, {8}}


text:
Q: RSS Viewer does not work on publishing the page I used RSS viewer Web part for RSS feeds. This works well in edit mode and showing all the feeds. But as I published the page, this web part does not able to retrieve feeds from the respective site and keeps on searching for the feeds.
So, Please help me..

A: Take a look at http://jaredmatfess.wordpress.com/2013/04/23/sharepoint-february-2013-cu-cod-breaks-the-rss-viewer-webpart/
Apparently the Feb 2013 critical update has a bug which breaks the RSS Viewer Webpart on non-anonymous sites. May fix the prob you are having!


text:
Q: SQL Load Data Special Characters I'm trying to import data into SQL from a CSV in PHP My Admin so it may be a PHP My Admin problem. The problem i'm having is that some of the columns use special characters for instance:
"Adán, Antonio"
Ends up as just "Ad".
The column structure is as follows:

CREATE TABLE IF NOT EXISTS `players` (
  `player_name` varchar(255) COLLATE utf8 NOT NULL,
  `player_nation` varchar(255) CHARACTER SET utf8 NOT NULL,
  `player_club` varchar(255) CHARACTER SET utf8 NOT NULL,
  `player_position` varchar(255) CHARACTER SET utf8 NOT NULL,
  `player_age` tinyint(2) NOT NULL,
  `player_dob` varchar(32) CHARACTER SET utf8 NOT NULL,
  `player_based` varchar(255) CHARACTER SET utf8 NOT NULL,
  `player_id` int(10) unsigned NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8;

I'm guessing it's something to do with the character set but mysql.com just suggests to alter the table to characters set utf8 which it already is.
Any ideas how else I can prevent this?

UPDATE
Inserting into the database is fine, so i'm guessing it's not to do with my table structure. It seems to be specifically to do with importing from a CSV.
This is the query for load data, as generated by PHP My Admin

LOAD DATA LOCAL INFILE 'C:\\Windows\\Temp\\php21E4.tmp' INTO TABLE `players` FIELDS TERMINATED BY ';' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\r\n'.

SOLUTION
I discovered the problem. My CSV was encoded with a Western Europe charset. After faffing around for a bit to convert it to UTF8 it imported just fine. Not an SQL problem at all.

A: Can you track where the truncation is happening, its quite possible that the issue isn't with your DB at all.
Try a simple insert into your DB table from the command line with the special chars and see if it succeeds.
Then try logging the various steps in the import to track where the issue occurs...


text:
Q: Given a start and end point, and a distance, calculate a point along a line Looking for the quickest way to calculate a point that lies on a line
a given distance away from the end point of the line:
void calculate_line_point(int x1, int y1, int x2, int y2, int distance, int *px, int *py)
{
    //calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2
    *px = ???
    *py = ???
}

Thanks for the responses, no this is not homework, just some hacking out of
my normal area of expertise.
This is the function suggested below. It's not close to working. If I
calculate points every 5 degrees on the upper right 90 degree portion of
a circle as starting points and call the function below with the center of the circle as x2,y2 with a distance of 4 the end points are totally wrong. They lie below and to the right of the center and the length is as long as the center point. Anyone have any suggestions?
void calculate_line_point(int x1, int y1, int x2, int y2, int distance)
{

//calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2

  double vx = x2 - x1; // x vector
  double vy = y2 - y1; // y vector

  double mag = sqrt(vx*vx + vy*vy); // length

  vx /= mag;
  vy /= mag;

// calculate the new vector, which is x2y2 + vxvy * (mag + distance).

  px = (int) ( (double) x2 + vx * (mag + (double)distance) );
  py = (int) ( (double) y2 + vy * (mag + (double)distance) );

}
I've found this solution on stackoverflow but don't understand it completely, can anyone clarify?

A: I think this belongs on MathOverflow, but I'll answer since this is your first post.
First you calculate the vector from x1y1 to x2y2:
float vx = x2 - x1;
float vy = y2 - y1;

Then calculate the length:
float mag = sqrt(vx*vx + vy*vy);

Normalize the vector to unit length:
vx /= mag;
vy /= mag;

Finally calculate the new vector, which is x2y2 + vxvy * (mag + distance).
*px = (int)((float)x1 + vx * (mag + distance));
*py = (int)((float)y1 + vy * (mag + distance));

You can omit some of the calculations multiplying with distance / mag instead.

A: These equations are wrong:
px = (int) ( (double) x2 + vx * (mag + (double)distance) );

py = (int) ( (double) y2 + vy * (mag + (double)distance) );

The correct equations are:
px = (int) ( (double) x2 + vx * (double)distance );

py = (int) ( (double) y2 + vy * (double)distance );

Tom


text:
Q: How using 'extended' option for Surf algorithm I want to concatenate SIFT and SURF descriptors to see if it gives better accuracy so I need that SIFT and SURF have the same number of columns. So I want to code on 128 bits SURF descriptors and so I need to use "extended" option. I do this like it :
SurfFeatureDetector detector2(minHessian);
detector2.extended=1;

and then:
extractor2.compute(img, keypoints_4, descriptors2);
But I do this :
cout<<"descriptors2   "<<descriptors2.rows<<" +  "<<descriptors2.cols<<endl;

it gives that

descriptors2   168 +  64

So my question is to take into account the extended parameter ? What am I doing wrong ? Should I need to give a similar parameter to the extractor?
Thanks in advance

A: The answer was quite simple. I needed to add
extractor2.extended=1;


text:
Q: How do I catch a particular exception that I am expecting? I have been trying to make a simple zip file password cracker (just for fun, not malicious purposes) however my try and except statement will not work. No matter the input it always leads to the except statement, and the else is never executed (even though the zip file does extract)
import zipfile

k = 0
file = zipfile.ZipFile('john.zip')
def check(i):
    p = bytes(i, 'ascii')
    try:
        file.extractall(pwd=p)
    except:
        return False
    else:
        return True

def crack():
        x = open('john(1).txt', 'r')
        for i in x.readlines():
            i.strip('\n')
            k = check(i)
            if k == True:
                print('Password is: ' + k)
                break;
            x.close()
        x.close()`

A: 1) Log the error in the except block. Helps a lot.
2) You are closing the file in the 'for' loop. Bad idea as the loop reads lines from the file.
3) The last line has a reverse quote character at the end (may be a typo in the question): `

A: I got it working with a couple of changes in crack() as shown in comments below.  Here is what worked for me:
…
def crack():
    x = open('john(1).txt', 'r')
    for i in x.readlines():
        i = i.strip() # not just the statement i.strip('\n')
        k = check(i)
        if k == True:
            print('Password is: ' + i) # not print('Password is: ' + k)
…


text:
Q: Where is GetAllUsers in membership provider? I looked at membership provider documentation and there should be two GetAllUsers method in membership provider (http://msdn.microsoft.com/en-us/library/system.web.security.membership.getallusers ).
But when I look at methods exposed by System.Web.Security (in
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.ApplicationServices.dll )

It only has one method (the one that has paging capability).
Where can I find a method to return all users from database? It seems there is no way to get list of all users or  find how many user is in the database.
--Update
looking at System.Web.Security, i found that SqlMembershipProvider is defined as follow:
public class SqlMembershipProvider : System.Web.Security.MembershipProvider

but this class doesn't have any public GetAllUsers() method.
How can I access its base GetAllUsers method?

A: I think you should be looking in the System.Web.dll not System.Web.ApplicationServices.dll

A: The way it works is that you have to have your membership provider, like a SqlMembershipProvider, configured in your web.config. The Membership.GetAllUsers method will then take the default configured MembershipProvider and call its method GetAllUsers and pass in 0 for the current page index and int.MaxValue for the total records per page (as well as an out int to get the total records in the store).
If you are having issues calling this method check the following:

*

*You have the correct .net assemblies referenced

*

*System.Web

*System.Web.ApplicationServices

*System.Configuration

*You have the correct namespace referenced System.Web.Security either

*

*In your using statements at the top of the file

*Directly on the type where referenced

*Your web.config has a registered default MembershipProvider
Notes

*

*SqlMembershipProvider, which derives from MembershipProvider, is not the same type or type hierarchy as type Membership. So not all the methods you see on Membership can be found on types deriving from MembershipProvider.

*The type Membership is static and so all its members including Membership.GetAllUsers are static as well.

*The type Membership is there as a convenience, most of its members call through to the registered default MembershipProvider.

Code sample:
using System.Web.Security;
namespace MyNameSpace
{
    public class MembershipTests
    {
        public void Test()
        {
            var users = Membership.GetAllUsers();
            // same as
            var totalRecords = 0;
            users = Membership.GetAllUsers(0, int.MaxValue, out totalRecords);
            // same as (Membership.Provider gets the default registered MembershipProvider)
            users = Membership.Provider.GetAllUsers(0, int.MaxValue, out totalRecords);
        }
    }
}

From the documentation

Remarks
GetAllUsers returns the information for all membership users for an application as a collection of MembershipUser objects. Be careful when using the GetAllUsers method with very large user databases, as the resulting MembershipUserCollection in your ASP.NET page may degrade the performance of your application.

A: The question is "Where is GetAllUsers in membership provider?"
The answer is that it is not in MembershipProvider.  It is in System.Web.Security.Membership
The MSDN link you provided in your question says the same thing.
The method GetAllUsers static and overloaded.
int userCount = 0;
MembershipUserCollection muc1 =  System.Web.Security.Membership.GetAllUsers();
MembershipUserCollection muc2 = System.Web.Security.Membership.GetAllUsers(0, int.MaxValue, out userCount);

If you are having namespace issues, they shuffled some things around between .net 3.5 and .net 4.0
This bit me several years ago.
.Net 4.0 System.Web.Security.MembershipProvider ambiguous reference?


text:
Q: WPF: How to always have a new row available in a datagrid? I am currently using a WPF/Xaml datagrid with a ViewModel and I am having an issue keeping a new empty row at the bottom. I can tab or enter my way and the datagrid creates a new row, but the users are wanting to always have the new row to click into. Is there an easy way to do this? I have tried a few ways and have come up short.
I have CanUserAddRows = true and AutoGenerateColums = false if that helps any.

A: Insert a new Item in your ObservableCollection.

A: You could set the CanUserAddRows property of the DataGrid to false and handle the addition of the "new" blank row yourself. Whenever you want a new row, you should add a "blank" object without any properties set on it to your ObservableCollection<T> source collection.
The hard part to figure out is probably when to add the row. You could for example do it when the user sets a property of the last item in your source collection.
If the type T implements the INotifyPropertyChanged interface, you could subscribe to the PropertyChanged event of each item that gets added to the source collection and check whether to add a new item in the event handler, e.g.:
private void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var dirtyItem = sender as T;
    if (dirtyItem != null && sourceCollection.LastOrDefault() == dirtyItem)
    {
        T newRow = new T();
        newRow.PropertyChanged += OnItemPropertyChanged;
        sourceCollection.Add(t);
    }
}


text:
Q: Exception: You do not have permission to call insertRowsAfter (line 5) I'm making a custom function that inserts a row after a certain point. When I created a working version of what I intend for my function to do, my function shows an exception "Exception: You do not have permission to call insertRowsAfter (line 5)." despite the function working when I run it.
function CREATEROW() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();

sheet.insertRowsAfter(10, 1);
}

So why is it screaming at me?

A: A custom function cannot affect cells other than those it returns a value to. In other words, a custom function cannot edit arbitrary cells, only the cells it is called from and their adjacent cells. To edit arbitrary cells, use a custom menu to run a function instead.
Reference: Custom functions


text:
Q: How do I check when the user has stopped scrolling? I am using https://facebook.github.io/react-native/docs/scrollview.html, which has a handy onScroll prop, but how do I get when the user has stopped scrolling?
Basically, I'd like to hide a button when the user is scrolling, show it when they aren't.

A: In your component state, store the last time at which you've received a scroll event. In your render method, check when the last scroll event happened and decide whether your button should become visible again or not.
Rough example:
// Observe the scroll events.
<ScrollView onScroll={(e) => {
    this.setState({lastScroll: new Date()})
}} />

// Check if the last scroll happened later than 300ms ago.
if (this.state.lastScroll.getTime() < (new Date()).getTime() - 300) {
    // Render the button.
}


text:
Q: Error: postcss-svgo: Error in parsing SVG: Unquoted attribute value with AngularJS and Laravel > @ production /mnt/d/PHP/project/myApp
> cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

Error: postcss-svgo: Error in parsing SVG: Unquoted attribute value
Line: 0
Column: 12
Char: \

npm run watch, npm run development working fine but npm run production not working. Please help
I am using angularJS and Laravel 6.


text:
Q: Cannot use object of type as array on array_push I am running into an issue trying to push an object into an Array in PHP. My Object looks like the below sample and has 2 empty array's. When i try to use the push_array function i get the error

PHP Fatal error:  Uncaught Error: Cannot use object of type
  ResidentialListing as array in /var/www/html/PHRETS/retsphp.php:95

Not sure why as Changes is a Array.
Here is how i call it where $r is an Object but i get same error if i try to push string.
array_push($Listing['Changes'], $r);

Below is $Listing Object
object(ResidentialListing)#86 (5) {
  ["_id"]=>
  string(36) "b77130b6-aea8-4325-9f04-fb77d2cc307f"
  ["_type"]=>
  string(11) "Residential"
  ["Record"]=>
  object(Residential_obj)#110 (18) {
    ["ListingId"]=>
    string(9) "S09100062"
    ["ListingKeyNumeric"]=>
    string(7) "4461874"
    ["StandardStatus"]=>
    string(6) "Closed"
    ["PreviousStandardStatus"]=>
    string(0) ""
    ["ParcelNumber"]=>
    string(10) "6051018010"
    ["UniversalPropertyID"]=>
    string(0) ""
    ["MLSAreaMajor"]=>
    string(17) "699 - Not Defined"
    ["MajorChangeType"]=>
    string(0) ""
  }
  ["Images"]=>
  array(0) {
  }
  ["Changes"]=>
  array(0) {
  }
}

A: You're incorrectly referencing $Listing->Changes as $Listing['Changes'].
It is looking for an array key on an object when you really want the value of the property.
Change
array_push($Listing['Changes'], $r);

to
array_push($Listing->Changes, $r);


text:
Q: jQuery 1.8.1 data() error retrieving HTML5 data-attribute I'm trying to extract the FIRST data attribute from the following mark-up:
<button class="buttonMiddle" data-vid="1">
    who helped them
</button>

<button class="buttonMiddle" data-vid="2">
    who helped them
</button>

the JS I've conjured is:
var button1 = $('.buttonMiddle').get(0).data('vid');

console.log(button1);

Chrome's console gives me this:

Uncaught TypeError: Object # has no method 'data'

I've covered the basic troubleshooting --> jQuery is loaded before this js file, they are both loaded just before the closing body tag (so no need for $(function() {// find data-attribute});.

A: Try to use eq() instead of get() here:
var button1 = $('.buttonMiddle').eq(0).data('vid');


text:
Q: Loop through a Array of Doubles in a class and set the values When I create a class and use the Sub New() option, I want to loop through 16 1d and 2d array of doubles and set all elements to 999999999. I have the following code below, but the compiler doesn't like it. Can anybody help me?
For Each p As PropertyInfo In Me.GetType().GetProperties()
    If p.CanRead AndAlso p.PropertyType.Name.IndexOf("Double[]") > -1 Then
        For x As Integer = 0 To DirectCast(p.GetValue(Me, Nothing), Double()).GetLength - 1
            'code to set array element = 999999999
        Next
    End If
Next

A: You need to specify the dimension when using GetLength on an array that may have multiple dimensions.
Change:
For x As Integer = 0 To DirectCast(p.GetValue(Me, Nothing), Double()).GetLength - 1

to
For x As Integer = 0 To DirectCast(p.GetValue(Me, Nothing), Double()).GetLength(0) - 1

It will not compile, otherwise.


text:
Q: Python - how to multiply daily values in dataframe with hourly percentages in a dictionary to get dataframe with hourly values I have a dataframe of daily transit ridership data for each station of a city and I also have a dictionary with the hourly ridership distribution in percentages.
I would like to create a dataframe of hourly transit ridership for each station by multiplying the daily ridership values in the dataframe with the hourly predictions in the dictionary.
For instance, the data frame looks as follows:
    Austin-Forest Park  Harlem-Lake
date
2018-11-01  2248.0  4021.0
2018-11-02  1983.0  3850.0
2018-11-03  837.0   2308.0
2018-11-04  604.0   1443.0

And the hourly percentage ridership distribution looks like this
with each key/value combination being a certain hour and % of daily ridership.
hourly_distribution = {0:0.017, 1:0.017, 2:0.008, 3:0.008, 4:0.004,
                          5:0.004, 6:0.008, 7:0.021, 8:0.051, 9:0.042,
                          10:0.042, 11:0.038, 12:0.034, 13:0.038, 14:0.051,
                          15:0.068, 16:0.084, 17:0.11, 18:0.101, 19:0.084,
                          20:0.059, 21:0.051, 22:0.034, 23:0.025}

hourly_distribution_weekend_days = {0:0.015, 1:0.015, 2:0.008, 3:0.008,4:0.008, 5:0.008,
                         6:0.015, 7:0.023, 8:0.038, 9:0.046, 10:0.054,
                         11:0.077, 12:0.092, 13:0.092, 14:0.092, 15:0.092,
                         16:0.062, 17:0.054, 18:0.054, 19:0.054, 20:0.031,
                         21:0.031, 22:0.015, 23:0.015}

My expected outcome would then be this for Austin-Forest Park on 2018-11-01:
    Austin-Forest Park
Date
2018-11-01 00:00:00 38.2
2018-11-01 01:00:00 38.2
2018-11-01 02:00:00 18.0
2018-11-01 03:00:00 18.0
2018-11-01 04:00:00 9.0
2018-11-01 05:00:00 9.0
2018-11-01 06:00:00 18.0
2018-11-01 07:00:00 47.2
2018-11-01 08:00:00 114.6
2018-11-01 09:00:00 94.4
2018-11-01 10:00:00 94.4
2018-11-01 11:00:00 85.4
2018-11-01 12:00:00 76.4
2018-11-01 13:00:00 85.4
2018-11-01 14:00:00 114.6
2018-11-01 15:00:00 152.9
2018-11-01 16:00:00 188.8
2018-11-01 17:00:00 247.3
2018-11-01 18:00:00 227.0
2018-11-01 19:00:00 188.8
2018-11-01 20:00:00 132.6
2018-11-01 21:00:00 114.6
2018-11-01 22:00:00 76.4
2018-11-01 23:00:00 56.2

From this small sample, the expected shape of the new dataframe would then be (96,2) with 2 columns and 4 days x 24 hours of hourly ridership values.
Would anyone have any idea how to write this in Python?
Thank you!

A: You can use numpy.outer for the product and list comprehension with pandas.to_datetime to build the new datetime index as follow:
import pandas as pd
import numpy as np
import datetime

idx = pd.to_datetime(['2018-11-01', '2018-11-02', '2018-11-03', '2018-11-04'])
df_daily = pd.DataFrame({'Austin-Forest Park': [2248.0, 1983.0, 837.0, 604.0],
                         'Harlem-Lake': [4021.0, 3850.0, 2308.0, 1443.0]},
                         index=idx)
df_daily.index.name = 'date'

hourly_distribution = {0:0.017, 1:0.017, 2:0.008, 3:0.008, 4:0.004,
                          5:0.004, 6:0.008, 7:0.021, 8:0.051, 9:0.042,
                          10:0.042, 11:0.038, 12:0.034, 13:0.038, 14:0.051,
                          15:0.068, 16:0.084, 17:0.11, 18:0.101, 19:0.084,
                          20:0.59, 21:0.051, 22:0.034, 23:0.025}

distrib = [hourly_distribution[key] for key in hourly_distribution]

datetime_idx = pd.to_datetime([datetime.datetime(i.year, i.month, i.day, key) for i in idx for key in hourly_distribution])
data = np.outer(df_daily['Austin-Forest Park'], distrib).ravel()

df = pd.DataFrame({'Austin-Forest Park': data}, index=datetime_idx)
df.index.name = 'date'

which outputs
                     Austin-Forest Park
date
2018-11-01 00:00:00              38.216
2018-11-01 01:00:00              38.216
2018-11-01 02:00:00              17.984
2018-11-01 03:00:00              17.984
2018-11-01 04:00:00               8.992
...                                 ...
2018-11-04 19:00:00              50.736
2018-11-04 20:00:00             356.360
2018-11-04 21:00:00              30.804
2018-11-04 22:00:00              20.536
2018-11-04 23:00:00              15.100

[96 rows x 1 columns]

A: Imagining you have following dataframe definition:
import pandas as pd

df_daily = pd.Series([2248, 1983, 837, 604], index=pd.date_range(start='2018-11-01', end='2018-11-04'))

You can do:
df_daily = (
    df_daily
        .resample('H', closed='right').ffill()
        .to_frame(name='park')
        .assign(hour=lambda df: df.index.hour)
        .apply(lambda x: hourly_distribution[x['hour']]*x['park'], axis=1)
)

df_daily

Explanation:

*

*First, you upsample your data to an hourly basis using resample. .fffill will use the day value for all hours.

*Then you create a column named hour.

*You use hour column to find equivalent percentage on hourly_distribution dictionary and multiply it by total day visitors that I just called park.


text:
Q: Powershell Script Truncated Result I have the following script,
$filteracl = {$_.IdentityReference -match "User" -and ($_.FileSystemRights -band 131241 -or $_.FileSystemRights -band 278)}
$objects = Get-ChildItem "C:\" -Recurse -Force
foreach ($i in $objects)
{
$i.GetAccessControl().Access | Where $filteracl  | Select `
                                @{n="Path";e={$i.fullname}},
                                @{n="User";e={$_.IdentityReference}},
                                @{n="Permission";e={$_.FileSystemRights}}
}

However, the output from the path is being truncated. I have no idea how to solve this.

A: Try Format-Table -Wrap like:
$filteracl = {$_.IdentityReference -match "User" -and ($_.FileSystemRights -band 131241 -or $_.FileSystemRights -band 278)}
$objects = Get-ChildItem "C:\" -Recurse -Force
foreach ($i in $objects)
{
$i.GetAccessControl().Access | Where $filteracl  | Select `
                                @{n="Path";e={$i.fullname}},
                                @{n="User";e={$_.IdentityReference}},
                                @{n="Permission";e={$_.FileSystemRights}} |
                                Format-Table -Wrap
}

Since the whole statement is in a loop and Format-Table displays headers, so you'll see multiple headers. To get rid of that you can edit your script to store the output in an Array and then finally display when the loop is complete. Something like:
$filteracl = {$_.IdentityReference -match "User" -and ($_.FileSystemRights -band 131241 -or $_.FileSystemRights -band 278)}
$objects = Get-ChildItem "C:\" -Recurse -Force
$OutputView = @()
foreach ($i in $objects)
{
    $s = $i.GetAccessControl().Access | Where $filteracl
    $output = New-Object PSObject
    $output | Add-Member -MemberType NoteProperty -Name "Path" -Value $i.fullname
    $output | Add-Member -MemberType NoteProperty -Name "User" -Value $s.IdentityReference
    $output | Add-Member -MemberType NoteProperty -Name "Permission" -Value $s.FileSystemRights
    $OutputView += $output
}

$global:outputView |
Select-Object Path,User,Permission


text:
Q: (Learning Bash) How to run multiple postgresql command from bash file This is what I am doing manually.
user@host: sudo -u postgres psql
postgres=# create database myproj;
postgres=# create user myuser with password 'mypass';
postgres=# alter role myuser set client_encoding to 'utf8';
postgres=# alter role myuser set default_transaction_isolation to 'read committed';
postgres=# alter role myuser set timezone to 'UTC';
postgres=# grant all privileges on database myproj to myuser;
postgres=# \q

The question is if I want to save it to .sh file and run, what should be the content. something like this?
sudo -u postgres psql -c "create database myproj;"
sudo -u postgres psql -c "create user myuser with password 'mypass';"
sudo -u postgres psql -c "alter role myuser set client_encoding to 'utf8';"
sudo -u postgres psql -c "alter role myuser set default_transaction_isolation to 'read committed';"
sudo -u postgres psql -c "alter role myuser set timezone to 'UTC';"
sudo -u postgres psql -c "grant all privileges on database myproj to myuser;"

A: You may use a Here document
$cat yourscript.sh
sudo -u postgres psql <<'INP'
create database myproj;
create user myuser with password 'mypass';
..
..
INP

If you wish to isolate the SQL commands from shell, put it in a separate .sql file and call using -f option or psql \i option.
$cat dbscript.sql
     create database myproj;
     create user myuser with password 'mypass';
..

Run it as
sudo -u postgres psql -U <yourusername> -d <yourdbname> -f dbscript.sql

Or
sudo -u postgres psql <<INP
\i /path/dbscript.sql


text:
Q: Writing shell in C - redirect/advanced redirectiion implementation For redirect (>) and advanced (>+), I'm unsure how to begin. I'm trying to traversing my space linked lst (which was tokenized by ; and \n whitespace) and seeing if it's ">" and save the prev node for progAndArgs of my redirection struct and the next node as the outFile.
I think I'm doing it correctly but it could very well be wrong.
parse* p = tokenize_line_semicolons(pinput);

        myPrint("HERE\n");
        // setup redirection struct
        parse *temp2_p = p;
        space *spc2;
        while (temp2_p != NULL) {
            spc2 = tokenize_space(temp2_p->cmd);
            space* temp_s = spc2;
            char* prev = temp_s->spc;
            if (strcmp(prev,"\n")==0)
                error();
            temp_s = temp_s->next;
            while (temp_s != NULL) {
                if (strcmp(temp_s->spc, ">") == 0) {
                    redirection r;
                    r.progAndArgs = prev;
                    if (temp_s->next->spc != NULL)
                        r.outFile = temp_s->next->spc;
                    else
                        error();
                }
                temp_s = temp_s->next;
            }
            temp2_p = temp2_p->next;
        }

But once I get a redirection struct correctly, I'm unsure how to use dup/dup2/creat/write/open/read to do > and >+ (I read the man pages). Please help!
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

void myPrint(char *msg)
{
    write(STDOUT_FILENO, msg, strlen(msg));
}

void error()
{
    char error_message[30] = "An error has occurred\n";
    write(STDOUT_FILENO, error_message, strlen(error_message));
}

typedef struct parse
{
    char* cmd;
    struct parse* next;
} parse;

typedef struct space
{
    char* spc;
    struct space* next;
} space;
typedef struct dble
{
    space* s;
    struct dble* next;
} dble;

typedef struct redirection
{
    char* progAndArgs;
    char* outFile;
} redirection;

char** p_to_char(space *s)
{
    char** args = (char**)malloc(sizeof(char*)*514);
    space *temp = s;
    int i = 0;

    while (temp != NULL) {
        args[i] = strdup(temp->spc);
        // myPrint(args[i]);
        // myPrint("\n");
        temp = temp->next;
        i++;
    }
    return args;
}

parse* setparse(char* s)
{
    parse* p = (parse*)malloc(sizeof(parse));
    p->cmd = strdup(s);
    p->next = NULL;

    return p;
}

space* setspace(char* s)
{
    space* sp = (space*)malloc(sizeof(space));
    sp->spc = strdup(s);
    sp->next = NULL;

    return sp;
}

dble* setdble(space* spc)
{
    dble* d = (dble*)malloc(sizeof(dble));

    space* temp = spc;
    while (temp != NULL) {
        d->s = temp;
        d->next = (dble*)malloc(sizeof(dble));
        d = d->next;
        temp = temp->next;
    }
    return d;
}

void show_parse(parse* p)
{
    //myPrint("Show parse\n");
    parse* temp = p;
    while(temp != NULL) {
        // myPrint(temp->cmd);
        // myPrint("->");
        temp = temp->next;
    }
    //myPrint("\n");
}

void show_space(space* sp)
{
   // myPrint("Show space\n");
    space* temp = sp;
    while(temp != NULL) {
        // myPrint(temp->spc);
        // myPrint("->");
        temp = temp->next;
    }
    //myPrint("\n");
}

// TODO - SEE IF DBLE PRINTING RIGHT OR SET UP WRONG
void show_dble(dble* d)
{
    dble* temp = d;
    //myPrint("Show dble\n");
    while(temp != NULL) {
        show_space(temp->s);
        temp = temp->next;
    }
    //myPrint("\n");
}

/* tokenized by spaces's - SEPARATE COMMANDS AND PARAMETERS */
space* tokenize_space(char* cmd)
{
    char* token_ptr = strdup(cmd);

    char *token, *token2;
    token =  strtok_r(token_ptr, " ", &token2);
    space* s = setspace(token);
    space* fst = s;

    while (token != NULL) {
        token = strtok_r(NULL," ", &token2);
        if (token==NULL){
            return fst;
        }
        s->next = setspace(token);
        s = s->next;
    }
    return fst;
}

/* tokenized by newline and ;'s - SEPARATE COMMANDS WITH PARAMTERS*/
parse* tokenize_line_semicolons(char* input)
{
    //myPrint("Starting Tokens!\n");

    if (strcmp(input,"\n")) {
        error();
        return NULL;
    }
    else {
        myPrint("HERE\n");
    char* token_ptr = input;

    char *token;
    token =  strtok_r(token_ptr, ";\n", &token_ptr);
    parse* p = setparse(token);
    parse* fst = p;

    while (token != NULL) {
        token = strtok_r(NULL,";\n", &token_ptr);
        if (token==NULL){
            return fst;
        }
        p->next = setparse(token);
        //tokenize_redirect(p);
        p = p->next;
    }
    return fst;
    }
}

void do_cd(char* param)
{
    int v;
    // myPrint(param);
    // myPrint("\n");

    if (strcmp(param, "") == 0 || strcmp(param, "~") == 0) {
        char *directory = getenv("HOME");
        v = chdir(directory);
    } else if (param[0] == '/') {
        //myPrint("~ /\n");
        char* directory = param;
        v = chdir(directory);
        //exit(v);
    } else {
        char buf[100];
        char *directory = getcwd(buf,100);
        strcat(buf,"/");
        strcat(buf,param);
        //myPrint(directory);
        v = chdir(directory);
    }
    if (v == -1)  // chdir error returning
        error();
}

int run_cmds(char* cmd, char** args, space* s)
{

// myPrint("START run_cmds!!! s->spc: ");
// myPrint(s->spc);
// myPrint(", cmd: ");
// myPrint(cmd);
// myPrint("\n");

    // all cmds return 0 if pass (from exho $?)
    if (strcmp(s->spc, "exit") == 0) {
        // myPrint("DOING exit\n");
        exit(0);
    }
    else if (strcmp(s->spc, "pwd") == 0) {
        // myPrint("DOING pwd\n");
        char* buff = (char*)malloc(sizeof(char)*100);
        myPrint(getcwd(buff,100));
        myPrint("\n");
    } else if (strcmp(s->spc, "cd") == 0) {
        //myPrint("DOING cd\n");
        do_cd(s->next->spc);
    }
    else {
        // myPrint("FORK");
        // myPrint("\n");
        pid_t pid = fork();

        if (pid == 0) {
            // myPrint("CHILD");
            // myPrint("\n");
            // myPrint(args[0]);
            // myPrint("\n");
            if (execvp(args[0], args) < 0)
                error();
            exit(0);
        } else {
            // myPrint("PARENT");
            // myPrint("\n");
            int status;
            pid_t ppid = waitpid(pid,&status,WUNTRACED);
            // myPrint("PARENT 2");
            // myPrint("\n");
            return ppid;
        }
    }
    return 0;
}

//Redirect throws an error if the file already exists or no file specified

int main(int argc, char *argv[])
{
    char cmd_buff[100];
    char *pinput;

    // implementing batch mode
        if (argc > 1) {
            int len = strlen(argv[1]);
            if (argv[1][0] == '[' && argv[1][len-1] == ']') {
                argv[1]++;
                argv[1][len-2] = '\0';
            }

            FILE *fp = fopen(argv[1],"r");
            if (fp == NULL) {
                error();
                exit(1);
            }
            char buff[514];
            //myPrint("we are about to fgets\n");
            while (fgets(buff,514,fp) != NULL) {
                // myPrint("We are fgetsing\n");
                // myPrint(buff);
                tokenize_line_semicolons(buff);
            }
            fclose(fp);
        } else if (argc >= 3) {
            error();
            exit(1);
        }

    while (1) {
       myPrint("myshell> ");
        pinput = fgets(cmd_buff, 100, stdin);

        if (!pinput) {
            myPrint("pinput\n");
            exit(0);
        }

        // if 513th char is neither \n or null terminator, its invalid input
        if (strlen(pinput) > 512) {
            // myPrint(pinput);
            // myPrint("\n");
            error();
            exit(1);
        }

        parse* p = tokenize_line_semicolons(pinput);

        myPrint("HERE\n");
        // setup redirection struct
        parse *temp2_p = p;
        space *spc2;
        while (temp2_p != NULL) {
            spc2 = tokenize_space(temp2_p->cmd);
            space* temp_s = spc2;
            char* prev = temp_s->spc;
            if (strcmp(prev,"\n"))
                error();
            temp_s = temp_s->next;
            while (temp_s != NULL) {
                if (strcmp(temp_s->spc, ">") == 0) {
                    redirection r;
                    r.progAndArgs = prev;
                    if (temp_s->next->spc != NULL)
                        r.outFile = temp_s->next->spc;
                    else
                        error();
                }
                temp_s = temp_s->next;
            }
            temp2_p = temp2_p->next;
        }

        parse* temp_p = p;
        space *spc;
        dble *d = (dble*)malloc(sizeof(dble));
        dble* tmp_d = d;

        while (temp_p != NULL) {
            spc = tokenize_space(temp_p->cmd);
            d->s = spc;
            d->next = (dble*)malloc(sizeof(dble));
            d = d->next;
            temp_p = temp_p->next;
        }

        show_parse(p);
        show_dble(tmp_d);

        char** args = p_to_char(spc);
        //myPrint("HERE");
        while (p != NULL) {
            run_cmds(p->cmd, args, tmp_d->s);
            p = p->next;
            tmp_d = tmp_d->next;
        }
    }
}

A: You call setparse(token) which uses its argument without ever checking whether it is null.


text:
Q: Does a semicolon remove the effect of 'do not' in the prior sentence? I wrote the sentence below at the beginning of my composition to express 'Do not hold the keys on the piano which belongs to the chord you are playing between the time when it finishes and a different chord follows'

Don't hold the notes; release your hands when a chord finishes and
a different one follows.

Does that convey my intended meaning or does it mean 'Do not hold the notes and do not release your hands' (which would be illogical and vague to the performer)?

A: It does.
In most cases, a semicolon can be replaced by a period to create two sentences. Your sentence would then translate to:

*

*Don't hold the note.

*Release your hands when a chord finishes and a different one follows.

When in doubt, clarify. You can clarify by using instead.

Don't hold the notes. Instead, release your hands when a chord finishes and a different one follows.


text:
Q: How do Hide/Mask id from url in react How do Hide/Mask id from url in react..
here is my code:
<Link to={`/renderform/${item._id}`} >
<td>{item.formName}</td>
</Link>

<Route path="/renderform/:formId" element={<FormRenderComp />} />

this code is working fine, now i want to hide the id

A: Your design is based on the fact that the URL contains the id. It is a nice and standard way to handle a state for your app, and have URLs that describe what they do. If you really want to obfuscate ids, you need to deeply modify this design.
You could use another unique identifiers for your forms, like CMS do to generate URL for articles (based on article title in general). Eg /render/1234 would become /renderform/my-form-title-slugified for example. But you would need to set up a mechanism to generate those unique slugs which is not trivial.
You could also try to store the clicked form id in another state management tool, like Redux, Recoil, MobX, or a parent component state. You would need to, when an item is clicked, store the item id in your state, then in the detail page (/renderform) you could read that id, fetch the item and display it.


text:
Q: Heroku app with Django and postgres crashing unexpectdly I am new to Django development, but I am in a situation where I need to deploy a large project on Heroku.
I ran my app in local system, it worked fine.
I pushed the same to Heroku and it also worked fine. But after few hours I open my app URL in browser , then app is saying Some thing has broken,intimated to admin.
The app worked fine before few hours, but what happened after few hours.
I just pushed my old DB backup to Heroku DB, Thats it app running fine now.
But I confused what happened to my app, I am facing this problem again and again,
how can I avoid this problem in future.
My app configuration:
psycopg2==2.4.5
Django==1.4

A: This could be a number of causes. It sounds more like a database issue. I would run the following command
heroku pg # TAKE NOTE OF THE HEROKU_POSTGRESQL_[COLOR]_URL

heroku pg:reset HEROKU_POSTGRESQL_[COLOR]_URL --confirm [appname]

This will reset your postgres database that is the active one, remove all tables etc.
Then I would run the regular command to get your database backup and running.
manage.py syncdb

You can also do the following
manage.py validate

This will go through your modules and tell you if any errors are present.
If that fails - enable debug in your settings.py file.
Also you can run "heroku logs" this will tell you the last few errors and statuses that have been hit with your app.
Let me know if this works, if not I will help debug further.


text:
Q: FInd value in array of objects using javascript Given the following:
var myArray = [
  {
    id: "3283267",
    innerArray: ["434","6565","343","3665"]
  },
  {
    id: "9747439",
    innerArray: ["3434","38493","4308403840","34343"]
  },
  {
    id: "0849374",
    innerArray: ["343434","57575","389843","38493"]
  }
];

How would I search the objects inside myArray to determine if the string "38493" is present in the innerArray and then return a new array with the id of the object....like such:
var arrayWithIds = ["9747439", "0849374"];

A: You can filter your array and then map ids (using ES6 syntax):
const arrayWithIds = myArray
  .filter(a => a.innerArray.includes('38493'))
  .map(a => a.id)

Here is ES5 alternative:
var arrayWithIds = myArray
  .filter(function(a) {
    return ~a.innerArray.indexOf('38493');
  })
  .map(function(a) {
    return a.id;
  })

A: Simple solution using Array.forEach and Array.indexOf functions:
var search =  "38493",
    result = [];

myArray.forEach(function(o) {
     if (o.innerArray.indexOf(search) !== -1) this.push(o.id);
}, result);

console.log(result);  // ["9747439", "0849374"]

A: ES5 way, you may also do as follows.

var myArray = [
  {
    id: "3283267",
    innerArray: ["434","6565","343","3665"]
  },
  {
    id: "9747439",
    innerArray: ["3434","38493","4308403840","34343"]
  },
  {
    id: "0849374",
    innerArray: ["343434","57575","389843","38493"]
  }
],
 searchData = "38493",
     result = myArray.reduce(function(p,c){
                             return ~c.innerArray.indexOf(searchData) ? (p.push(c.id),p) : p;
                             },[]);
console.log(result);


text:
Q: Local Docker run fails (An assembly specified in the manifest was not found) I am trying to test my local Docker build before I deploy to AWS. My app has dependencies to AWSSDK.Core via NuGet and I am using the following Docker file:
FROM microsoft/dotnet:2.2.0-aspnetcore-runtime AS runtime
WORKDIR /My.App
COPY bin/Release/netcoreapp2.2 .
ENV ASPNETCORE_URLS http://+:5000
EXPOSE 5000
ENTRYPOINT ["dotnet", "My.App.dll"]

To build my file
docker build -t myapp .

However, when I try to run it with
docker run -it --rm --name my_app myapp

I get the error
Error:
  An assembly specified in the application dependencies manifest (My.App.deps.json) was not found:
    package: 'AWSSDK.Core', version: '3.3.106.17'
    path: 'lib/netstandard2.0/AWSSDK.Core.dll'

As far as I can tell, I should be adding a RUN command to install the AWSSDK in my Docker image but I cannot find it. So, my question would be: Am I doing something wrong? If not, is there some kind of reference as to the locations of packages to use in Docker?

A: After digging around some, I found a few possible answers. First I found this blog post which exemplifies how to use docker with .NET with a very simple project. The solution to my problem was to use the dotnet package command, which gathers all the dependencies and puts them in a single directory.
However, after digging some more, I found Microsoft's Container Tools in Visual Studio which, by pressing the right mouse button on the project, offers to add Docker Support which is more elaborate than the first solution.


text:
Q: Setting .gitconfig Location My .gitconfig file was located in a drive that was recently deleted. Now doing any git commits and pushes, I'm noticing my git user name has changed. When trying to add a new global username, I'm presented with the following error:
error: could not lock config file H://.gitconfig: Permission denied

Would the best course of action would be to recreate a .gitconfig file, place that in the C drive, and tell git to look there for user credentials?