text:
Q: Error on size of class I have a problem with converting a byte array into a class or struct.
The class is like this:
[Serializable()]
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public class General {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = Defines.CENTR_NAME_LENGTH + 1)] byte[] centralName;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = Defines.PROJECT_NAME_LENGTH + 1)] byte[] projectName;
    byte misc;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] byte[] accessCode2;
    byte transmActive;
    byte transmHour;
    byte transmMin;
    [MarshalAs(UnmanagedType.U1)] public int Cp;
    [MarshalAs(UnmanagedType.U1)] public int Rp;
    [MarshalAs(UnmanagedType.U1)] public int Lcd;
    [MarshalAs(UnmanagedType.U1)] public int Relais;
    [MarshalAs(UnmanagedType.U1)] public int Pr;
    [MarshalAs(UnmanagedType.U1)] public int Sc;
    byte rd;
    byte reserve1;
    [MarshalAs(UnmanagedType.U1)] public int LocalCentrId;
    [MarshalAs(UnmanagedType.U1)] public int PrinterSel;
    [MarshalAs(UnmanagedType.U1)] public int Slave1;
    [MarshalAs(UnmanagedType.U1)] public int Slave2;
    [MarshalAs(UnmanagedType.U1)] public int Slave3;
    [MarshalAs(UnmanagedType.U1)] public int Master;
    [MarshalAs(UnmanagedType.U1)] public int AlarmRepeat;
    [MarshalAs(UnmanagedType.U1)] public int FaultRepeat;
    [MarshalAs(UnmanagedType.U1)] public int ResetSil1;
    [MarshalAs(UnmanagedType.U1)] public int ResetSil2;
    [MarshalAs(UnmanagedType.U1)] public int EvacDelayed1;
    [MarshalAs(UnmanagedType.U1)] public int EvacDelayed2;
    [MarshalAs(UnmanagedType.U1)] public int Led1;
    [MarshalAs(UnmanagedType.U1)] public int Led2;
    [MarshalAs(UnmanagedType.U1)] public int GenControl;
    [MarshalAs(UnmanagedType.U1)] public int ExtraGenControl;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = Defines.MAX_NMB_SIL_CONTROL)] byte[] silenceControls ;
    byte autoResetFault;
    byte autoResetSC;
    [MarshalAs(UnmanagedType.U1)] public int InitEvacDelay;
    [MarshalAs(UnmanagedType.U1)] public int SilenceEvacOff;
    byte summerTime;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] byte[] accessCode1;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] byte[] btPinCode;

    public string CentralName { get { return Encoding.ASCII.GetString(centralName); } set { centralName = Encoding.ASCII.GetBytes(value); } }
    public string ProjectName { get { return Encoding.ASCII.GetString(projectName); } set { projectName = Encoding.ASCII.GetBytes(value); } }
    public bool BackBeep {
        get {
            return (misc & 0x01) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x01;
            } else {
                misc ^= 0x01;
            }
        }
    }
    public bool StartStopEvac {
        get {
            return (misc & 0x02) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x02;
            } else {
                misc ^= 0x02;
            }
        }
    }
    public bool GenBehEvacKey {
        get {
            return (misc & 0x04) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x04;
            } else {
                misc ^= 0x04;
            }
        }
    }
    public bool GenBehEvacDet {
        get {
            return (misc & 0x08) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x08;
            } else {
                misc ^= 0x08;
            }
        }
    }
    public bool EvacDelayed {
        get {
            return (misc & 0x10) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x10;
            } else {
                misc ^= 0x10;
            }
        }
    }
    public bool SirService {
        get {
            return (misc & 0x20) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x20;
            } else {
                misc ^= 0x20;
            }
        }
    }
    public bool ResetSilService {
        get {
            return (misc & 0x40) != 0x00;
        }
        set {
            if (value) {
                misc |= 0x40;
            } else {
                misc ^= 0x40;
            }
        }
    }
    public string AccessCode1 { get { return Encoding.ASCII.GetString(accessCode1); } set { accessCode1 = Encoding.ASCII.GetBytes(value); } }
    public string AccessCode2 { get { return Encoding.ASCII.GetString(accessCode2); } set { accessCode2 = Encoding.ASCII.GetBytes(value); } }
    public bool EvacDirect { get { return transmActive == 0x01; } set { transmActive = (Byte)(value ? 0x01 : 0x00); } }
    public TimeSpan EvacDirectTime { get { return new TimeSpan(transmHour, transmMin, 0); } set { transmHour = (Byte)value.Hours; transmMin = (Byte)value.Minutes; } }
    public bool Rd { get { return rd == 0x01; } set { rd = (value ? (Byte)0x01 : (Byte)0x00); } }
    public List<int> SilenceControl {
        get {
            List<int> retVal = new List<int>();
            if (silenceControls != null) {
                foreach (byte b in silenceControls) {
                    retVal.Add(b);
                }
            }
            return retVal;
        }
        set {
            silenceControls = new byte[Defines.MAX_NMB_SIL_CONTROL];
            for (int t = 0; t < Defines.MAX_NMB_SIL_CONTROL && t < value.Count; ++t) {
                silenceControls[t] = (Byte)value[t];
            }
        }
    }
    public bool AutoResetFault { get { return autoResetFault == 0x01; } set { autoResetFault = (Byte)(value ? 0x01 : 0x00); } }
    public bool AutoResetPower { get { return autoResetSC == 0x01; } set { autoResetSC = (Byte)(value ? 0x01 : 0x00); } }
    public bool SummerTime { get { return summerTime == 0x01; } set { summerTime = (Byte)(value ? 0x01 : 0x00); } }
    public string BtPinCode { get { return Encoding.ASCII.GetString(btPinCode); } set { btPinCode = Encoding.ASCII.GetBytes(value); } }

    public General() {
        Console.WriteLine("Create General");
        SetDefault();
    }

    public void SetDefault() {
        CentralName = "MD2400";
        ProjectName = "Limotec";
        Cp = 1;
        Rp = 0;
        Lcd = 0;
        Relais = 1;
        Pr = 0;
        Sc = 1;
        Rd = true;
        BackBeep = false;
        AccessCode1 = "654321";
        AccessCode2 = "123456";
        EvacDirect = false;
        EvacDirectTime = new TimeSpan( 0, 0, 0 );
        BtPinCode = "1111111111111111";
        SummerTime = true;
        GenControl = 1;
        ExtraGenControl = 0;
        SilenceControl.Add( 3 );
        InitEvacDelay = 2;
        EvacDelayed = false;
        StartStopEvac = false;
        SirService = false;
        ResetSilService = false;
        GenBehEvacKey = true;
        GenBehEvacDet = true;
        Master = 32;
        Slave1 = 0;
        Slave2 = 0;
        Slave3 = 0;
        AlarmRepeat = 0;
        FaultRepeat = 0;
        ResetSil1 = 0;
        ResetSil2 = 0;
        Led1 = 0;
        Led2 = 0;
        EvacDelayed1 = 0;
        EvacDelayed2 = 0;
        LocalCentrId = 0;
        AutoResetFault = true;
        AutoResetPower = true;
    }

    [OnDeserialized()]
    internal void OnDeserialized(StreamingContext contect) {
        Config.Singleton.Log.Info( string.Format( "General loaded: {0} {1}", CentralName, ProjectName ) );
    }
}

When I do Marshall.SizeOf(typeof(General)) I get an ArgumentException. The size or offset cannot be calculated.
Is there a problem if I use private variables and public properties in the same class? The properties are only for converting the variable in something more usefull. (Byte array into string)
How can I solve it so that I can put a byte array into the class using Marshal.PtrToStructure ?

A: For me it just works: I get 43, which agrees with 2 * 21 + 1. I've checked .NET 2.0, 3.5 and 4.5 (and for 4.5 I checked both x86 and x64) - it just seems fine.
No, properties don't matter: the marshal code is only looking at fields.

Edit: what does happen, though, is that the data doesn't match:

Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout.

You need to ensure the arrays are of the right length - the following is ugly, but works, sort-of (don't set an over-length string!):
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 21)]
byte[] centralName = new byte[21];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 21)]
byte[] projectName = new byte[21];
byte misc;

public string CentralName {
    get {
        int i = Array.IndexOf(centralName, (byte)0);
        if (i < 0) i = centralName.Length;
        return Encoding.ASCII.GetString(centralName, 0, i);
    }
    set {
        Array.Clear(centralName, 0, centralName.Length);
        Encoding.ASCII.GetBytes(value, 0, value.Length, centralName, 0);
    } }
public string ProjectName {
    get {
        int i = Array.IndexOf(projectName, (byte)0);
        if (i < 0) i = projectName.Length;
        return Encoding.ASCII.GetString(projectName, 0, i);
    }
    set {
        Array.Clear(projectName, 0, projectName.Length);
        Encoding.ASCII.GetBytes(value, 0, value.Length, projectName, 0);
    } }

with example:
unsafe static void Main()
{
    int i = Marshal.SizeOf(typeof(General));
    General obj = new General { CentralName = "abc", ProjectName = "def" },
            clone;
    byte[] b = new byte[i];
    fixed(byte* a = b)
    {
        IntPtr ptr= new IntPtr(a);
        Marshal.StructureToPtr(obj, ptr, false);
        clone = (General) Marshal.PtrToStructure(ptr, typeof(General));
    }
    Console.WriteLine(clone.CentralName); // abc
    Console.WriteLine(clone.ProjectName); // def
}

or:
unsafe static void Main()
{
    int i = Marshal.SizeOf(typeof(General));
    General obj = new General { CentralName = "abc", ProjectName = "def" },
            clone;
    byte* a = stackalloc byte[i];

    IntPtr ptr= new IntPtr(a);
    Marshal.StructureToPtr(obj, ptr, false);
    clone = (General) Marshal.PtrToStructure(ptr, typeof(General));

    Console.WriteLine(clone.CentralName); // abc
    Console.WriteLine(clone.ProjectName); // def
}


text:
Q: Class arguments inside method java I can't find info about that.
Is it possible and if yes then how to use class arguments inside the method?
public static class allDragons {
    String name;
    Integer resource;
}

public void MethodName() {
    dragonImage.setImageResource(rareDragon.resource); // here I would like to refer to the argument, but it doesn't work.
}

ImageView dragon;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dragon);

    dragonImage = findViewById(R.id.dragonimg);

    allDragons rareDragon = new allDragons();

    rareDragon.number = 1;
    rareDragon.resource = (R.drawable.dragon);

    ...

I found that I should use something like: setImageResource(allDragons().rareDragon.resource), but it still not work. I tried many combinations and modifiers but still failed. How? Possible? Other way?

A: Maybe I'm completely wrong - it's not really clear to me what you're trying to achieve, but maybe this helps you to find an answer.
AllDragons is a static class definition. You can create instances of it (like you did in method onCreate()) and assign it to a member instead of a local variable:
public class OuterClass {

    public static class AllDragons {
        String name;
        Integer resource;
    }

    ImageView dragon;

    // In order to access "rareDragon" in any method of this class,
    // you need to create a member
    AllDragons rareDragon;

    public void methodName() {
        dragonImage.setImageResource(rareDragon.resource);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dragon);

        dragonImage = findViewById(R.id.dragonimg);

        rareDragon = new allDragons();

        rareDragon.number = 1;
        rareDragon.resource = (R.drawable.dragon);
    }
}

PS:
I adapted your class/field/method names. In Java there a some Coding Conventions existing:

*

*Class names should start with a capital letter

*Method names and fields should start with a lower-case letter

*Constants should be written completely in upper-case letters

redpajama_set_name: RedPajamaStackExchange


text:
Q: adb -s emu geo fix not works without using telnet My app works on Google Apis 17. I want to set the gps location after an emulator is being launched.
I try to this follow how-to-emulate-gps-location-in-the-android-emulator.
1st. get the serials number of the emulator.
>adb devices
emulator-5554

2nd run
adb -s emulator-5554 emu geo fix 121.4961236714487 31.24010934431376

There are no warnings and errors. I am programming on windows7.
It not work. However when I send gps info manually in eclipse(ADT22.6), it works. My app can locate the location correctly. What did eclipse do? How to make the adb command work? Thanks

A: Have you try sending it via telnet? First you have to connect to the emulator:
telnet localhost 5554

Then you can use the geo command to send latitude and logitude:
geo fix 121.4961236714487 31.24010934431376

A: The command requires input of longitude latitude.
adb emu geo fix 41.4961236714487 271.24010934431376
KO: invalid latitude value. Should be in [-90,+90] range
Here's the string which works for me:
adb emu geo fix -71.2230 41.9067
Prior to reversing the input I was in Antarctica.


text:
Q: WCF: The request for security token could not be satisfied because authentication failed I'm working on an WCF service that is secured by Oauth via DotnetOpenAuth.
Somewhere I've got a configuration error that's causing the error "The request for security token could not be satisfied because authentication failed." in my code and I can't see to find a setup that works.
Works fine localhost to localhost but once I put it on my server (not on the domain) it fails from that server to itself or from localhost to the server.
I'm a little worried about some of the other solutions on this site as they seem to disable security. Mostly it's that they don't seem to work for me.
Provider:
   <system.serviceModel>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DataApiBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
                <serviceAuthorization serviceAuthorizationManagerType="OAuthServiceProvider.Code.OAuthAuthorizationManager, OAuthServiceProvider" principalPermissionMode="Custom" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <services>
        <service behaviorConfiguration="DataApiBehavior" name="OAuthServiceProvider.DataApi">
            <endpoint address="" binding="wsHttpBinding" contract="OAuthServiceProvider.Code.IDataApi">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        </service>
    </services>
    <serviceHostingEnvironment>
        <baseAddressPrefixFilters>
            <add prefix="http://devel.nanaimo.ca/" />
        </baseAddressPrefixFilters>
    </serviceHostingEnvironment>
</system.serviceModel>

Consumer:
<system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IDataApi" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Message">
                    <transport clientCredentialType="Windows" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://devel.nanaimo.ca/NanaimoProfile/DataApi.svc"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDataApi"
            contract="CodeServiceOauthProvider.IDataApi" name="WSHttpBinding_IDataApi">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>

Update: Looks like OAuthServiceProvider.Code.OAuthAuthorizationManager Is not being called on live. It's instantiated but CheckAccessCore is never called. I have no idea why yet.

A: This is just blind shot but AuthorizationManager is used to authorize users and it is called after authentication but you have your service configured with default WsHttpBinding - it uses message security with Windows authentication. Windows authentication doesn't work between computers which are not part of the same domain.
I would start with basicHttpBinding which defaults to no security (no authentication). If it works then you can think about what security do you expect.

A: I eventually just created a windows username and password with very little rights and hard coded the username into my library. Certificated could have been another answer but I never got them to work.


text:
Q: Sails Waterline ORM query inside array.map() Code snippet below is using sails waterline ORM to make DB queries and sending response. However, the execution flow is weird, The code outside of map function is running before the map function has finished executing. 'I am outside of map' is being printed in the console before 'I am inside of map'. I think it can be solved this using Promise or async / await. I have tried using Promise.all() below, but it doesn't work, the response is always an empty array. I would be grateful if you could give an example on how to solve this kind of issues.
allMembers: (req, res) => {
  const projectId = req.params.id;

    ProjectMembers.find({projectId: projectId}).exec( (err, members) => {
        if(err) res.serverError("bad request!");

        if(members.length === 0) res.notFound({message: "No members are found for this project!"});

        let membersInfo = [];
        let promise = Promise.all(members.map(m => {
            User.findOne({id: m.userId}).exec( (err, user) => {
                if(err) membersInfo.push({name: null, userId: null, email:null,rate:null, error: 'Internal error!'})
                else if(!user) membersInfo.push({name: null, userId: null, email:null,rate:null, error: 'No user found'})
                else membersInfo.push({name: user.name, userId: user.id, rate: m.rate, error: null})
                console.log("i am inside of map");
            })
        }));

    console.log("I am outsie of map")
    promise.then( (resolve) => {return res.ok({members: membersInfo})});
}

A: I was about to tell you "don't use queries in .map", but on looking, I think your code is quite close to working. The argument of Promise.all has to be an array of promises. Each User.findOne is indeed a promise - the stumbling block is that once you use .exec it no longer returns a promise.
I think the answer is to do your processing inside the .then instead of right inside the .map:
ProjectMembers.find({projectId: projectId}).exec( (err, members) => {
    if(err) return res.serverError("bad request!");

    if(members.length === 0) return res.notFound({message: "No members are found for this project!"});

    let promise = Promise.all(members.map(m => User.findOne({id: m.userId})));

    promise.then( (values) => {
        // values is the array of user objects returned from the array of queries
        let membersInfo = values.map((user) => {
            if (!user) {
                return {name: null, userId: null, email:null,rate:null, error: 'No user found'};
            } else {
                return {name: user.name, userId: user.id, rate: m.rate, error: null};
            }
        });
        return res.ok({members: membersInfo});
    }, (err) => {
        return res.serverError("Error finding users");
    });

The promise only has a single fail callback, so you lose the ability to individually catch and handle querying errors (though you can still individually handle not-found results).


text:
Q: Can someone in Europe redeem a Minecraft gift card purchased in America? My friend's Microsoft account recently got hacked and he now needs to repurchase Minecraft Java Edition. I was looking to gift him a Minecraft Java gift card but he is in Europe and I am in the United States, will it affect the purchase at all?

A: There's no region-locking on Minecraft gift cards. All he needs is a Microsoft account, and he'll be able to redeem the code anywhere in the world at https://www.minecraft.net/en-us/redeem. (and no, the /en-us/ on this is not important)


text:
Q: Analyze touching particles with holes in a microscopic image I am looking for an easy method to count individual particles in a microscopic image. It is quite difficult for Mathematica to detect them, because they are touching each other.
I am quite a beginner in Mathematica and can't figure out how I can remove the white centers of the particles. I know there are some similar questions around, but non where the particles have bright centers AND are touching each other.
This is the image:

Thanks a lot in advance.

A: Preprocess like this:
ClusteringComponents[
  Erosion[Binarize[mySpheres, {.5, .98}], DiskMatrix[1]]] // Colorize

A: The simplest thing that can work is to search white blobs instead of black blobs, and ignore the ones that have low circularity (calculated from the area/perimeter^2 ratio):
img = Import["http://i.stack.imgur.com/LaMAg.jpg"]
img = ColorConvert[img, "Grayscale"];
components =
  ComponentMeasurements[
   MorphologicalBinarize[Closing[img, DiskMatrix[5]]], {"Centroid",
    "Circularity", "EquivalentDiskRadius"}, #2 > 0.75 &];

Show[img,
 Graphics[{Red, Thick, Circle @@@ components[[All, 2, {1, 3}]]}]]


text:
Q: Type mismatch expecting bool list but get int list I am going filter an int list based on the 2 boundaries. To do it i used the List.filter in this way:
let CountFilesInRange ele lowerRang upperRange=
   match ele with
   | ele when lowerRang< ele< upperRange -> true
   | _                                   ->false

List.filter (CountFilesInRange  0 5000) listOfSizes

In the last line I have this error with listOfSizes:
Type mismatch expecting bool list but get int list

How can i fix it?

A: *

*As say @ildjarn  - not valid syntax

*You have wrong order of parameters.
Probably, you wanted to do this:

Example:
let listOfSizes = [1;2;3;4]

let betweenExclusive lowerBound upperBound value =
   match value with
   | value when lowerBound < value && value < upperBound -> true
   | _                                                   -> false

List.filter (betweenExclusive 1 4) listOfSizes |> printfn "%A"

Print:
[2; 3]

Link:
https://dotnetfiddle.net/3179jr
Edit:
Thank you @Sehnsucht for the comment. This function can be rewritten as:
let betweenExclusive lowerBound upperBound value =
   lowerBound < value && value < upperBound


text:
Q: Redirecting input and output in a shell Hi I've been programming a shell in c and I got stuck while trying to redirect. While redirecting the stdout in my program works the stdin doesn't.
void redirect(node_t* node){
    // mode 0: >$%d mode 1: < mode 2: > mode 3: >>
    int input = 0;
    if(node->redirect.mode == 2){
        input = 1; // >
    } else{
        input = 0; // <
    }
    int pid = 0;
    int *status = 0;
    char * filename = node->redirect.target; // filename
    int fd;
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
    if((pid = fork()) == 0){
        dup2(fd, input); // STDIN OR STDOUT
        close(fd);
        node_t* node2 = node->redirect.child;
        execvp(node2->command.program, node2->command.argv); // execute program
        printf("failed to execvp\n");
        exit(1);
    } else {
        wait(status);
    }
}

I'm new to the fork() but my question is what am I doing wrong here that redirecting stdout works but stdin it writes nothing to the given file.

A: As mentioned in the comments, you need to use different open options depending on whether you're opening the file for input or output redirection. You can put this into your if.
int flags;
if(node->redirect.mode == 2){
    input = 1; // >
    flags = O_WRONLY | O_CREAT | O_TRUNC;
} else{
    input = 0; // <
    flags = O_RDONLY;
}
int pid = 0;
int *status = 0;
char * filename = node->redirect.target; // filename
int fd;
fd = open(filename, flags, 0666);

Also, you need to specify the permission modes for the case where the output file is created. It's OK to specify this argument all the time, it will be ignored when O_CREAT isn't in the flags.


text:
Q: Portuguese characters - charset in html How make the Portuguese characters look fine on html?
That's what I have used in my html
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

A: I used to have lots of similar problems but now have a policy of always translating to html codes (as listed on (for example) http://www.starr.net/is/type/htmlcodes.html) for rendering. This saves a lot of grief (and testing) in my experience.


text:
Q: Can I view websites on an iPad in an iPhone sized window? I'm trying to test out how my website looks on the iPhone, but all I have is an iPad. Is there a way to force the iPad into iPhone size view window?

A: Nope, you can't do that. But if you have a Mac, you can install Xcode from the Mac App Store for free.
It comes with an app called iOS Simulator which will let you run Mobile Safari on your Mac, including the resolution of older iPhones/iPods (non-retina display), new retina display iPhones, and the iPad's resolution.
It also implements all the touch screen Javascript events (eg: onmouseover is triggered when you tap instead of onclick, then onclick is triggered when you tap again), double tap to zoom into a DOM element, and will properly show you how things like fixed position CSS elements will appear, which is very different on Mobile Safari compared to regular desktop Safari, and it gives you all the iOS form elements (<select multiple> fields are completely different for example).
I'm not aware of any way to properly test your website on Windows or Linux, changing the browser window size is not good enough.

A: Well, you could find a third-party browser app that is only for the iPhone and use that on your iPad.  There are plenty of free ones.  Just search for "browser" in the App Store.

A: More or less any browser which has a special iPhone version (not universal) will work. I recommend the Perfect Browser, or Aquari iPhone browser.

A: You can use Dolphin browser. Just download it for iPad from iPhone apps section. You can also use service like http://testiphone.com

A: If you can use a desktop version of Google Chrome, it can emulate an iPhone.  In the debug mode, click the "emulate devices" icon near of top left of the debug panel, and it can let you emulate iPhones, iPad, Samsung phones, and many other models (the list is about 20 items long).
It not only emulate the width and height, but it will act according to your meta tag for viewport as well.  So if you have this line in your HTML <head> section:
<meta name="viewport" content="width=device-width, initial-scale=1">

Then the emulator for iPhone 6 Plus will show a "yes I am a small screen and I will act accordingly" version of the page.  On the other hand, without the above line, iPhone 6 Plus will pretend itself to be a powerful browser with a wide screen, and show you the page -- but in this case the text will be very small and not very readable.  So what I mean is, Google Chrome will emulate your phone with the HTML code being displayed faithfully, as if it is a real device.
Compare that with Firefox version 44.0, which can only emulate the device size, but it won't care about the meta line above, so you could see one version of the page on Firefox, and see a different version of the page on a real device.
Here is a screenshot of emulating an iPhone 6 Plus:


text:
Q: Convert An Relational Array to Tree Object in Typescript I have structure database in array of objects stored like this;
array = [ {"name": "a", "id": "1",  "parentId": NULL},
 {"name": "b", "id": "2", "parentId": "1"},
 {"name": "c", "id": "3", "parentId": "1"},
 {"name": "d", "id": "4", "parentId": "1"},
 {"name": "e", "id": "5", "parentId": "2"},
 {"name": "f", "id": "6", "parentId": "3"},
 {"name": "g", "id": "7", "parentId": "3"},
 {"name": "h", "id": "8", "parentId": "4"},
 {"name": "j", "id": "9", "parentId": "4"}]

And I want to get like this tree object;
{
    a: {
        b: {
            e: {}
        },
        c: {
            f: {},
            g: {}
        },
        d: {
            h: {},
            j: {}
        }
    }
}

A: you can use recursion:
buildTree(arr, root) {
  return {
    [root.name]: arr
      .filter(x => x.parentId === root.id)
      .map(x => buildTree(x))
      .reduce((a, b) => ({ ...a, ...b }), {}),
  };
}

const tree = buildTree(array, array.find(x => !x.parentId));

A: Possible implementation:
function grow(items) {
    var things = {"": {}};
    for (var i of items) {
        things[i.id] = {};
    }
    for (var i of items) {
        things[i.parentId || ""][i.name] = things[i.id];
    }
    return things[""];
}

The two loops could be merged if there is a guarantee that the parent always precedes its children.

A: You could take a single loop and respect the parents as well.
This approach works with unsorted data as well.

var array = [{ name: "a", id: "1", parentId: null }, { name: "b", id: "2", parentId: "1" }, { name: "c", id: "3", parentId: "1" }, { name: "d", id: "4", parentId: "1" }, { name: "e", id: "5", parentId: "2" }, { name: "f", id: "6", parentId: "3" }, { name: "g", id: "7", parentId: "3" }, { name: "h", id: "8", parentId: "4" }, { name: "j", id: "9", parentId: "4" }],
    tree = function (data, root) {
        var o = {};
        data.forEach(({ name, id, parentId }) => {
            o[id] = o[id] || {};
            o[parentId] = o[parentId] || {};
            o[parentId][name] = o[id];
        });
        return o[root];
    }(array, null);

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


text:
Q: Netty Parallel Handler Processing Following recommendations elsewhere I am attempting to parallelize my final inbound handler in a Netty pipeline as such
public final class EchoServer {
    private EventLoopGroup group = new NioEventLoopGroup();
    private UnorderedThreadPoolEventExecutor workers = new UnorderedThreadPoolEventExecutor(10);

    public void start(int port) throws InterruptedException {
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel channel) throws Exception {
                            channel.pipeline().addLast(workers, new SimpleChannelInboundHandler<DatagramPacket>() {
                                @Override
                                public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
                                    System.err.println(packet);
                                    // Simulated database delay that I have to wait to occur before repsonding
                                    Thread.sleep(1000);
                                    ctx.write(new DatagramPacket(Unpooled.copiedBuffer("goodbye", StandardCharsets.ISO_8859_1), packet.sender()));
                                }

                                @Override
                                public void channelReadComplete(ChannelHandlerContext ctx) {
                                    ctx.flush();
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    cause.printStackTrace();
                                }
                            });
                        }
                    });

            b.bind(port).sync().channel().closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }

    public void stop() {
        group.shutdownGracefully();
    }
}

I have ten clients that connect concurrently, as a test, and I am measuring execution time for handling all the requests. As expected with the 1 second delay and sequential execution it takes just over 10 seconds. I am trying to get execution down to somewhere sub 2 seconds to prove parallel handling.
From what I understand adding the handler to the pipeline with an explicitly assigned executor is supposed to parallelize that handlers work across the thread in the executor.
Instead of seeing a increase in performance, what I am finding is that my client is not receiving the responses when I add the parallel processing. The thread sleep is there to simulate the potential time it will take to write the incoming data to a database. Am I doing something obviously wrong here?

A: I worked around the apparently lack of Netty support for doing final end UDP processing in parallel using standard java concurrency mechanisms.
public final class EchoServer {
    private EventLoopGroup group = new NioEventLoopGroup();
    private ExecutorService executors = Executors.newFixedThreadPool(10);

    public void start(int port) throws InterruptedException {
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                protected void initChannel(NioDatagramChannel channel) throws Exception {
                    channel.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
                        @Override
                        public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
                            CompletableFuture.runAsync(() -> {
                                System.err.println(packet);
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("goodbye", StandardCharsets.ISO_8859_1),
                                        packet.sender()));
                            }, executors);
                        }

                        @Override
                        public void channelReadComplete(ChannelHandlerContext ctx) {
                            ctx.flush();
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                            cause.printStackTrace();
                        }
                    });
                }
            });

            b.bind(port).sync().channel().closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }

    public void stop() {
        group.shutdownGracefully();
    }
}


text:
Q: Where GitLab CE displays commit status? GitLab has an api to set commit status and Jenkins has a plugin that sets this status.
Now I have a stupid question: where my user can see this status is displayed in GitLab interface?
Screenshots are welcomed!

A:
The green checkbox appears near the commit id in the top right of the screen.


text:
Q: mouseenter, mouseleave in Firefox I'm facing a strange issue in Firefox 16.
In a div I'm fading in on a mouseenter (and fade out on mouseleave) event there is a select Tag embedded. When I move the mouse over the options the div fades out and in and so on. But there is no chance to select a option.
This does not happen in Chrome. Has anyone an idea why this is happening and how to fix it?
Fiddle: http://jsfiddle.net/sCmnd/2/

A: Try that: http://jsfiddle.net/sCmnd/3/ . I tested it on Firefox and it worked.
mouseleave:function(evt) {
    if (evt.target.nodeName.toLowerCase() !== "select") {
        $('div.fade').fadeOut();
    }
}

For some reason mouseleave triggers on select element, but this doesn't allow fadeout when mouseleave is triggered by select element.


text:
Q: How add Click function to Dynamic Items that created by Json? I'm trying to add a click event handler for each element that was created from JSON dynamically.
Here is my code :
$.getJSON('slides.json', function (data) {
    for (var i = 0; i < data.length; i++) {
        var s = sym.getSymbol("Base").createChildSymbol("Frame", "Slider");
        s.$("Frame").css({
            "background-image": "url('" + data[i].image + "')"
        });
        s.$("Frame").click("click", function (e) {
            alert(data[i].title)
        });
        s.getSymbolElement().css({
            "position": "absolute",
            "right": i * 81 + 5 + "px"
        });
        sym.getSymbol("Base").$("Slider").css({
            "width": i * 81 + 5 + "px"
        });
    } //for
});

This code would create 5 Frame with their image dynamically from JSON file. I want to be able to click on them and alert the index of the clicked image.
But in the code above, when I click on any image it always alerts 5, i.e. just the last value of i.
I also tried to replace i with data[i].title but nothing happened, there is no access to the JSON file that can read information from that.
How can I solve this?

A: You can use jQuery .on api to attach event for dynamic contents.
this sample code will atach click event for all dynamically created div elements
$("body").on("click", "div", function(event){
  alert($(this).text());
});

A: That's because when the click event fires, the for-loop has already completed and the value of i remains 5. I don't think I fully understand what you're trying to do here, but you might try saving the title in the element and reloading it when the click event fires:
for ( var i=0; i < data.length; i++ ) {
    var s = sym.getSymbol("Base").createChildSymbol("Frame", "Slider");
    s.$("Frame").css({"background-image":"url('"+data[i].image+"')"});
    s.$("Frame").data('title', data[i].title);
    s.$("Frame").click("click", function(e){ alert($(this).data('title'))});
}


text:
Q: How to add withX method live template to IntelliJ IDEA I really like the ability to automatically generate getters and setters but I also like to have a set of associated withX methods for each property of a POJO. Is there a way to create a live template for those and use it to generate a withX method for every selected property like the getter/setting generation happens via the generate menu?
I found an example of a live template on this SO post but I'm not sure how to use it correctly. I can select it from another menu by using the cmd+j shortcut but none of the variables populate...probably because I wasn't prompted to select the properties I want to generate this for.
public $THIS_TYPE$ with$Property$($TYPE$ $property$) {
    set$Property$($property$);
    return this;
}

A: Fluent setter generator plugin is not exactly what you asked, but it provides a simple dialog to select target fields, eventually generating for each of them some code like:
public $THIS_TYPE$ with$Property$($TYPE$ $property$) {
  this.$property$ = $property$;
  return this;
}


text:
Q: Number too small to do math with I am creating a simple app in Angular that calculates loan payments. To calculate the monthly payment I have to deal with a pretty small number.
I tried using the "Big" library to no avail as I didn't really understand how it worked. Typescript only has one "number" type so using a number with more memory is out of the question I assume.
Here is the code:
calcDisFac(i: number, n: number) {
    console.log(i);
    console.log(n);

    const firstTerm = Math.pow((1 + i), n) - 1;
    console.log(firstTerm);
    const secondTerm = Math.pow((i * (1 + i)), n);
    console.log(secondTerm);
    return firstTerm / secondTerm;
}

Use the example case where i = (7.75 / 100) / 12 and n = 360
The expected output is 3300 or somewhere around there and the problem is the number is so small it just becomes 0. Any help is appreciated.

A: Here is the answer you get when you perform your calculation for secondTerm with WolframAlpha, which will use symbolic computation where necessary to achieve greater precision than JavaScript's floating point math:  4.46531771441003×10^-788.  That number is so close to zero that it should be a warning sign to you that something is probably wrong with your calculation.
The result coming out of calcDisFac((7.75 / 100) / 12, 360) would be something like 2.049241445165735×10^788 which, while technically not infinite, is close enough when it comes to something like a monthly payment.  It's certainly significantly larger than 3300 of anything I have in my wallet, including atoms.
Backing up... the math you are doing does not calculate loan payments for any type of loan I've ever seen.  You can derive the formula yourself for a fixed-rate loan with fixed monthly payments and an initial balance, or you can get it from somewhere like Wikipedia's article on mortgage calculators.  I think it would look something like:
function loanPayment(
  initialBalance: number,
  interestRatePerPeriod: number,
  numberOfPayments: number
) {
  const accrual = Math.pow(1 + interestRatePerPeriod, numberOfPayments);
  const paymentRatio = (interestRatePerPeriod * accrual) / (accrual - 1);
  return paymentRatio * initialBalance;
}

JavaScript's floating point math should be more than adequate to handle this calculation for reasonable values of initialBalance, interestRatePerPeriod, and numberOfPayments.  And note that you do need an initial balance for the math to make any sense (the payment will be proportional to the initial balance).
So, working backwards from the desired result of 3300, if the initial balance of the loan is something like 460000 then you get:
console.log(loanPayment(460000, 7.75 / 100 / 12, 360)); /// 3295.496

Does that help?  Good luck!
Link to code


text:
Q: Blackberry OS version If I develop Blackberry application for OS version 6.0, will the application be compatible with OS version 4.5? If not, is there some way to port the application easily?

A: If you develop against a specific SDK (eg 6.0) your application will only be deployable to devices that use the matching OS version (6.0 in this case).
In order to develop applications that specifically target different OS versions, you must build separate deployable binaries for each version.  Alternatively, you can build for the lowest common denominator -- if you want to support OS 4.5, build for 4.5 and your app will run (though not always gracefully) on all later BB OS versions.
Two open source projects that you can use for examples are BBSSH  and LogicMail.
Neither of these uses preprocessor directives, however both take slightly different approaches to managing multiple target OS's; which solution is more appropriate is best determined by your own needs. Both use ant-based builds; and I think both target from OS 4.5 to 6.0.  (Older versions of LogicMail target back to 4.1 I believe)
Build scripts can be found here:

*

*BBSSH SVN (build.xml,build-impl.xml, build.properties)

*LogicMail SVN (build.xml, build.properties)

Both projects can also be looked to for specific  methods of handling things like utilizing features introduced in later OS versions seamlessly to your users -- either providing a custom implementation prior for earlier versions, or disabling the functionality as is appropriate.
Finally a quick note: if you continue to not accept valid answers, you'll soon find that people are less willing to answer you.

A: Try to use "Preprocessor Directives" to support multiple blackberry devices.

A: I m not 100% sure but probably not, because version 6.0 uses newer libraries.But try develope in lower version os and it will run at higher version.
hope it helps
Wblade

A: For an example of a quality open source project that supports many different BB OS versions, check out LogicMail.
The ant build.xml loads platform-specific classes based on the target:
<if><isset property="jde460.home"/><then>
  <fileset id="bb460_fileset" dir="..">
    <include .../>
      ...

As far as I can tell, this project does not rely on the preprocessor.


text:
Q: Algorithm for overlapping sets There is a game consists of N rounds. After each round, the winner (either you or me) will be awarded one point. The player with more points at the end of the game wins.
You wants that after each round in the game you are having at least M times the points than me.
For Example N=3 , M=1
the possible sequence of winners of rounds are:
DDD     // D is you and M is me
DMD
DDM

MDD    // Is not possible as you are having 1 point and i am having zero so condition violted

My approach:
In a particular game the only two possibilities are that you win or I win, so I make a recursive call to calculate the score for both the possibilities.
                                   D
                                M           D          // At M+1 game(M wins or D wins)
                              D or M      D or M       // At M+2 game(M wins or D wins)
                    .
                    .
                    . ans so on
                                 At last round return 1

Code:
public static int score(int rounds, int m, int score1, int current, int score2) {
    int sum=0;

    if (current == rounds && score2 == 0) return 1;
    if (current == rounds && score1 / score2 >= m) return 1;
    if (score2 != 0 && score1 / score2 < m) return 0;
    if (score2 == 0 || score1 / score2 >= m) {
        sum += score(rounds, m, score1, current + 1, score2 + 1);
        sum += score(rounds, m, score1 + 1, current + 1, score2);
    }
    return sum;
}

System.out.println(score(rounds,m,m,m,0));

This solution is taking very long time for larger value of N in the range of 10^6. How can i speed up my approach.

A: Suppose you are going to play N games (in sequence) and at each step you record whether player A wins or player B wins.  You generate a sequence that looks like AABABBAABA, etc.  You want to count the number of such sequences where there are M times as many A's as B's (I assume you mean at least M times as many).  Since N is fixed, you have an upper bound on the number of B's.  I.e. #B's + #A's = N and #A's >= M*#B's, so (M+1)*#B's <= N and so #B's <= N/(M+1).
Let us say, that you can have at most K B's in the string (and there are N characters total).  For each 1 <= k <= K there are N choose k ways to place the B's (assuming you have k of them) and the rest are A's.  In total, then, there are SUM(k=0..K) (N choose k) such possibilities.
So instead of using the code to generate all these, just have your code compute the (N choose k) values and sum them up.


text:
Q: Disassembler Visual Studio C++ I am using debugging in Visual Studio and disassembler window to get the instruction code in hex, but when the main call a function (as Fig.1), the function instructions appear in a sperate section (as Fig. 2)
Is there any way to show the function instructions appears as a part of the main?
main section in dissasembler window

function section in dissasembler window

Thanks,

A: Based on mov eax, 0CCCCCCCCh it seems you're working with a Debug build.
In Debug mode Visual Studio does not inline any function by default.
You can switch to Release mode or enable function inlining in compiler settings (C/C++ - Optimization - Inline Function Expansion) and the call to fun() will probably get inlined.

A: Disassembly is always going to be a separate window, there are options on the context menu for the disassembly window that allows you to control what is shown (source code or not, or instruction addresses or not, for example).


text:
Q: Getting user input with while statement def function(user):
    options = get_options(user)
    print(options)
    user_input = input("please select option: ")
    while user_input not in options:
        user_input = input("please select option: ")
    print(user_input)

If in the above code "options" is equal to a list of numbers, for example [80,90,100] why does the code not break when I input one of those values? The code should first print the list of numbers and then ask the user to select one of the numbers and repeat the same question until a valid response is given but I'm having trouble with the looping while statement that does not end. Also would like to print the valid number that the user gave at the end of the function.


text:
Q: prestashop/nginx multi lang "no input file specified" on index.php request we have prestashop running smoothly on nginx;
when we enabled multi language on the site, the below issue is faced:
usually after payment, without multi lang, you are redirected back to this page:
http://www.domain.com/index.php?controller=order-confirmation&id_cart=21293&id_module=83&key=e1dbc21a0e7a8c04910968
on our apache environemnt, this works well
on nginx,
what happened when multi language was enabled is when you reach the above link, the lang parameter is added to the url (when it should not):
http://www.domain.com/en/index.php?controller=order-confirmation&id_cart=21293&id_module=83&key=e1dbc21a0e7a8c049109689ecf36499b
or
http://www.domain.com/fr/index.php?controller=order-confirmation&id_cart=21293&id_module=83&key=e1dbc21a0e7a8c049109689ecf36499b
which causes the user to fall on a prestashop error "input file not specified"
the above redirection should not happen, once an order is done, the following URL must work without redirection nor adding the 'en' or 'fr' code before index.php:
http://www.domain.com/index.php?controller=order-confirmation&id_cart=21293&id_module=83&key=e1dbc21a0e7a8c049109689ecf36499b
the nginx configuration is as follows:
    location /favicon {
            alias /var/www/vhosts/11footballclub.com/httpdocs/img/facicon.ico;
    }

      location / {
          index index.html index.htm index.php;

    try_files $uri $uri/ /index.php?$args;
      }

      location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
          access_log        off;
          log_not_found     off;
          expires           360d;
      }

      location ~ /\. {
          access_log off;
          log_not_found off;
          deny all;
      }

      location = /favicon.ico {
          log_not_found off;
          access_log off;
      }

      location = /robots.txt {
          allow all;
          log_not_found off;
          access_log off;
      }

      location ~ \.php$ {
          include /etc/nginx/fastcgi_params;
          fastcgi_pass  127.0.0.1:9000;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME /var/www/vhosts/11footballclub.com/httpdocs$fastcgi_script_name;
          fastcgi_param PHP_VALUE max_execution_time=180;
      }

      # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
      location ~ /\. {
          deny all;
          access_log off;
          log_not_found off;
      }

      rewrite ^/api/?(.*)$ /webservice/dispatcher.php?url=$1 last;

      rewrite "^/c/([0-9]+)(\-[_a-zA-Z0-9-]*)/(.*)\.jpg$" /img/c/$1$2.jpg last;
      rewrite "^/c/([_a-zA-Z-]+)/(.*)\.jpg$" /img/c/$1.jpg last;

      rewrite "^/([a-z0-9]+)\-([a-z0-9]+)(\-[_a-zA-Z0-9-]*)/(\P{M}\p{M}*)*\.jpg$" /img/p/$1-$2$3.jpg last;
      rewrite "^/([0-9]+)\-([0-9]+)/(\P{M}\p{M}*)*\.jpg$" /img/p/$1-$2.jpg last;
      rewrite "^/([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$1$2.jpg last;
      rewrite "^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$1$2$3.jpg last;
      rewrite "^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$1$2$3$4.jpg last;
     rewrite "^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$1$2$3$4$5.jpg last;
      rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6.jpg last;
      rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7.jpg last;
      rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8.jpg last;
      rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9.jpg last;

    #rewrite "^/index.php\?controller=http(.*)$" $1 last;

      rewrite "^/([0-9]+)\-(\P{M}\p{M}*)+\.html(.*)$" /index.php?controller=product&id_product=$1$3 last;
      rewrite "^/([0-9]+)\-([a-zA-Z0-9-]*)(.*)$" /index.php?controller=category&id_category=$1$3 last;
      rewrite "^/([a-zA-Z0-9-]*)/([0-9]+)\-([a-zA-Z0-9-]*)\.html(.*)$" /index.php?controller=product&id_product=$2$4 last;
      rewrite "^/([0-9]+)__([a-zA-Z0-9-]*)(.*)$" /index.php?controller=supplier&id_supplier=$1$3 last;
      rewrite "^/([0-9]+)_([a-zA-Z0-9-]*)(.*)$" /index.php?controller=manufacturer&id_manufacturer=$1$3 last;
      rewrite "^/content/([0-9]+)\-([a-zA-Z0-9-]*)(.*)$" /index.php?controller=cms&id_cms=$1$3 last;
      rewrite "^/content/category/([0-9]+)\-([a-zA-Z0-9-]*)(.*)$" /index.php?controller=cms&id_cms_category=$1$3 last;

    rewrite "^/module/([_a-zA-Z0-9-]*)/([_a-zA-Z0-9-]*)$" /index.php?fc=module&module=$1&controller=$2 last;

      rewrite ^/page-not-found$ /index.php?controller=404 last;
      rewrite ^/address$ /index.php?controller=address last;
      rewrite ^/addresses$ /index.php?controller=addresses last;
      rewrite ^/authentication$ /index.php?controller=authentication last;
      rewrite ^/best-sales$ /index.php?controller=best-sales last;
      rewrite ^/cart$ /index.php?controller=cart last;
      rewrite ^/contact-us$ /index.php?controller=contact-form last;
      rewrite ^/discount$ /index.php?controller=discount last;
      rewrite ^/guest-tracking$ /index.php?controller=guest-tracking last;
      rewrite ^/order-history$ /index.php?controller=history last;
      rewrite ^/identity$ /index.php?controller=identity last;
      rewrite ^/manufacturers$ /index.php?controller=manufacturer last;
      rewrite ^/my-account$ /index.php?controller=my-account last;

     rewrite ^/new-products$ /index.php?controller=new-products last;
      rewrite ^/order$ /index.php?controller=order last;
      rewrite ^/order-follow$ /index.php?controller=order-follow last;
      rewrite ^/quick-order$ /index.php?controller=order-opc last;
      rewrite ^/order-slip$ /index.php?controller=order-slip last;
      rewrite ^/password-recovery$ /index.php?controller=password last;
      rewrite ^/prices-drop$ /index.php?controller=prices-drop last;
      rewrite ^/search$ /index.php?controller=search last;
      rewrite ^/sitemap$ /index.php?controller=sitemap last;
      rewrite ^/stores$ /index.php?controller=stores last;
      rewrite ^/supplier$ /index.php?controller=supplier last;

      location ~* \.(gif)$ {
        expires 2592000s;
      }

      location ~* \.(jpeg|jpg)$ {
        expires 2592000s;
      }

      location ~* \.(png)$ {
        expires 2592000s;
      }

      location ~* \.(css)$ {
        expires 604800s;
      }

      location ~* \.(js|jsonp)$ {
        expires 604800s;
      }

A: Add this location block to your config file.
location ~ (/lang1|/lang2)/index\.php$ {
    try_files $uri $uri/ /index.php?$args;
}

Where lang1 and lang2 are languages used in your website (for example 'en', 'ru' and etc.). You can add more languages by appending |/language_name inside brackets.
P.s. don't forget to restart/reload your nginx server after modifications.

A: Here's an example of configuration that works pretty well with Nginx, PrestaShop v1.6.1.x (two languages enabled: EN/FR), PHP-FPM 7.2 and an SSL certificate from Let's Encrypt.
If you copy/paste this example (in your /etc/nginx/sites-enabled folder), please remember to:

*

*Replace 'myshop.com' by your domain name

*Replace 'myadminfolder' by your PrestaShop admin folder name

*Replace '(/fr|/en)' with the language codes you are actually using

*Generate your SSL certificate using Let's Encrypt certbot tool (optional, remove this section if you don't want to use SSL)

*Make sure your PHP-FPM socket file is located in /var/run/php/php7.2-fpm.sock, otherwise modify this path

Thanks @Canarius for the tip!
server {
        listen [::]:80;
        listen 80;
        server_name myshopname.com www.myshop.com
        root /var/www/myshopname.com/;
        index index.php index.html;
        access_log /var/log/nginx/myshopname.com.access_log;
        error_log /var/log/nginx/myshopname.com.error_log;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                auth_basic off;
                allow all;
                log_not_found off;
                access_log off;
        }

        # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
        location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
        }

        gzip on;
        gzip_disable "msie6";
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 1;
        gzip_buffers 16 8k;
        gzip_http_version 1.0;
        gzip_types application/json text/css application/javascript;

        rewrite ^/api/?(.*)$ /webservice/dispatcher.php?url=$1 last;
        rewrite ^/([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$1$2.jpg last;
        rewrite ^/([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$1$2$3.jpg last;
        rewrite ^/([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$1$2$3$4.jpg last;
        rewrite ^/([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5.jpg last;
        rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6.jpg last;
        rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7.jpg last;
        rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8.jpg last;
        rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9.jpg last;
        rewrite ^/c/([0-9]+)(-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg last;
        rewrite ^/c/([a-zA-Z-]+)(-[0-9]+)?/.+\.jpg$ /img/c/$1.jpg last;
        rewrite ^/([0-9]+)(-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg last;

        location ~ (/fr|/en)/index\.php$ {
                try_files $uri $uri/ /index.php?$args;
        }

        try_files $uri $uri/ /index.php?$args;

        location /myadminfolder/ {
                if (!-e $request_filename) {
                        rewrite ^/.*$ /myadminfolder/index.php last;
                }
        }

        location ~ .php$ {
                fastcgi_split_path_info ^(.+.php)(/.*)$;
                fastcgi_keep_conn on;
                include /etc/nginx/fastcgi_params;
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_read_timeout 300;
        }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/www.myshopname.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.myshopname.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}


text:
Q: What is the name of this book? I read it as a child, a sci-fi book. It started with a government program that discovered an alternate universe, and every person save one went crazy, and could not speak about it. She got pregnant, and took her son into it. He was raised being able to swap between worlds.
After a while, he became employed by the government to use the abilities and he discovered there were other people in this dimension. They started transporting goods, but the shipments sometimes ended in the wrong place. It was because they lacked the mathematics to transport correctly.


text:
Q: How to run a Single CircleCi job that requires multiple primary languages? (Using Docker Executor) My development team maintains two separate web applications that interact via REST.
One application is built in Go and the other in Python.
In order confirm that the two apps interact properly prior to Prod releases, we aimed to create an automated CircleCI Integration testing job that does the following:
Integration Test Requirements:

*

*Check out Go and Python App

*Build and start both apps on localhost

*Run live integration tests where the Go App calls the Python app

Problem:
The Pre-Built Docker Images in CircleCi (https://circleci.com/docs/2.0/circleci-images/) only support one primary language.
Solution:
In order to run both a Go and Python server in the same CircleCI job, we created a custom Docker image that combines the public circleCI Golang and Python images.
In order to help other teams who may run into a similiar situation (i.e. a team that wants a Java + Python CircleCi docker container), sharing steps we took to solve this problem.
Steps to create a custom Go + Python docker image and use in CircleCi

*

*Create a public repository in Docker Hub and link it to an existing Github account.

*Here's the Docker Hub repo we used for this example: https://hub.docker.com/r/ejparz/circleci-images/dockerfile

*We created our DockerFile based on the public CircleCi Go and Python docker images available here:

GO: https://github.com/CircleCI-Public/circleci-dockerfiles/blob/master/golang/images/1.11.0/Dockerfile
Python: https://github.com/CircleCI-Public/circleci-dockerfiles/blob/master/python/images/3.7.2-stretch/Dockerfile
Public go docker base image here: https://github.com/docker-library/golang/blob/master/1.11/stretch/Dockerfile
Our custom DockerFile:
    FROM circleci/golang:1.11-stretch
    FROM circleci/python:3.7.2-stretch

    #Create regular go directory
    COPY --from=0 /go /go

    #Copy go binaries
    COPY --from=0 /usr/local/go /usr/local/go

    ENV GOPATH /go
    ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH

    #Use Root to set path permissions
    USER root
    RUN chmod -R 777 "$GOPATH"

    #Add circleci user
    USER circleci

    #Add Shell
    CMD ["/bin/sh"]

*After linking our Github Dockerfile to Docker Hub and auto building, we were able to reference the image in our CircleCi file
run-system-integration-tests:
   docker:
      - image: ejparz/circleci-images:latest

From there, we were able to start our Python app on one port.
  - run:
        name: Start Python Django Server in background
        command: |
          cd ~/app
          pipenv run python manage.py runserver
        background: true
  - run:
        name: Waiting for python server to be ready
        command: |
          for i in `seq 1 10`;
          do
            nc -z localhost 8000 && echo Success && exit 0
            echo -n .
            sleep 1
          done
          echo Failed waiting for server && exit 1

Then call that port from our golang app. (Or curl for basic test purposes)
     - run:
        name: Test Port connectivity
        command: |
          curl http://localhost:8000

That's it.
With some small tweaks to the above DockerFile template, other teams/users should be able to easily compose different CircleCi Primary language containers.

A: Create a custom Docker Image that combines the desired primary languages :
FROM circleci/golang:1.11-stretch
FROM circleci/python:3.7.2-stretch

#Create regular go directory
COPY --from=0 /go /go

#Copy go binaries
COPY --from=0 /usr/local/go /usr/local/go

ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH

#Use Root to set path permissions
USER root
RUN chmod -R 777 "$GOPATH"

#Add circleci user
USER circleci

#Add Shell
CMD ["/bin/sh"]


text:
Q: EF Core Power Tools: Missing setter for collections Is there a way to have the EF Core Power Tools create setters for collections, like so:
class Parent
{
    // ...
    public virtual ICollection<Child> Children { get; } // Setter is missing
}

The setter would be extremely useful with AutoMapper.
Otherwise we have to explicitly specify the mapping like this.


text:
Q: Is Raphael an alternative to Flash based web app I am developing a web app which requires rotating and scaling one Image over the other. Image to be rotated and scaled should have a transparent background.
For this I tried using KinecticJS which uses HTML5 canvas element but because of Canvas element's image rendering techniques, my Image was getting distorted.
Now, I have option of moving either to RaphaelJS or to Flash but I am not getting sure-shot idea which to choose.
Can anyone please suggest the pros and cons when RaphaelJS is compared to Flash.
Thanx in advance.

A: It depends from your app.
If you are using JS in your app then go with Raphael JS. It is very easy to create interactive app with Raphael JS.  Although, Raphael is a little heavy to use in the webapp, but you should also cosider the fact that flash is very heavy too. You should compare the timing on different browsers using flash and Raphael JS.
Depending how big is your flash or how many Raphael elements your using on your webapp, the loading time will differ.

A: If those are your only two requirements for the image manipulation I would completely recommend using Raphael.
The main pros of Raphael for this project are that:

*

*It will be lighter than a FLASH.

*Raphael is supported across platforms and devices, whereas Flash is not (this is one of the major drawback of Flash).

The cons of using Raphael would be that:

*

*It has less support for more complex image manipulation and animation. For example, if you need to group several images together and apply transformation to them, this is harder to accomplish with Raphael. FLASH, on the other hand, makes it very easy to group images together and apply transformations to them.

In your description you mention that you need to manipulate just "one image" so the cons won't be a major setback for your particular project.
I hope this helps.

A: Thanx for your help.
I found my solution using PaperJS. It specifically provides functions to handle Raster Images.


text:
Q: Best way to transfer more values from one server to another via an HTTP call? I've to transfer data from one machine to another machine connected on a network. May be some 10-20 values to be transfered and that depends. All I do is pack up/ marshal the values in a json and transfer it to another server (say which is another machine connected on a network) via a http post call. Say the data flows from ServerA to ServerB in ServerA I have to pack up all the data to construct the json and in the ServerB I have to unmarshal it which eats up most of my code like the following
    String student_id = json.getString("sid");
    String student_role_number = json.getString("rnumber");
    String student_name = json.getString("name");
    String isDayScholar = json.optString("dayscholar", "false");
    String stream = json.optString("stream", "");
    String class_section = json.getString("section");

It's light when the value is 4-5 when there are more number of values like 20-25 I feel quite heavy in doing this get/set operations.Is there any better way to avoid/minimise this?

A: It's light when the value is 4-5 when there are more number of values like 20-25, If you could just hardcode all the required keys in some data structure then that might help. For example in your case all the necessary keys are sid,rnumber,name,dayscholar etc.
Keep a separate hardcoded data struct for your keys
org.json.JSONObject jsonObject = new org.json.JSONObject();
java.util.Map<String , Object> otherMap = new java.util.HashMap<>();

String[] myLovedKeys = {"sid" , "rnumber" , "name" , "dayscholar" , "stream" , "section"};
for( int x = 0; x < myLovedKeys.length; x++ )
{
    if( myLovedKeys[x].equals("dayscholar") || myLovedKeys[x].equals("stream") )
    {
        String value = "";
        if( myLovedKeys[x].equals("dayscholar") )
        {
            value = json.optString( myLovedKeys[x] , "false" );
            jsonObject.put( myLovedKeys[x] , value );
            otherMap.put( myLovedKeys[x] , value );
        }
        else
        {
           value = json.optString( myLovedKeys[x] , "" ); // stream key-value
           jsonObject.put( myLovedKeys[x] , value );
           otherMap.put( myLovedKeys[x] , value );
        }
    }
    else
    {
        String keyValue = json.getString( myLovedKeys[x] );
        jsonObject.put( myLovedKeys[x] , keyValue );
        otherMap.put( myLovedKeys[x] , keyValue );
    }
}

This will allow you to exactly know which key is currently being processed inside the loop and you can handle diverse behaviors depending on which key you are interested in dealing with
Now the reason why I have declared a JSONObject and a java.util.Map is because I simply want to elaborate the fact that if you are missing org.json.* library, then you can easily get away by using a java.util.Map, but if you have the org.json* library, then you can also deal with problem in a more comfortable manner. Now lets say we wanted to access the data then we could easily try things like
for( int x = 0; x < myLovedKeys.length; x++ )
{
    System.out.println( "java.util.Map: [" myLovedKeys[x] + "=" + otherMap.get( myLovedKeys[x] ) );
    System.out.println( "org.json.JSONObject: " + myLovedKeys[x] + "=" + jsobObject.getJSONObject( myLovedKeys[x] ) );
}

In a similar fashion, you can modify and update those values
otherMap.put( myLovedKeys[0] , "SomeValue");
otherMap.put( myLovedKeys[1] , "Other Value" );
otherMap.put( "sid" , "SomeValue" );
otherMap.put( "rnumber" , "toSomeName");
//myLovedKeys[0] = "sid" , myLovedKeys[1] = "rnumber"

Similarly you can have the some changes reflected in the jsonObject variable. What you have to realize is that you have to deal with the pain of hardcoding all the key-names somewhere in your code, and yes that is going to take some typing :), Please let me know if that is still not enough to help your case


text:
Q: Is there a way to alias scope variable for a html node? I Have a directive myDirective which has a template and transcended html (transclude: true)
myDirective template has a repeater ng-repeat="item in transformSourceData"and transcluded template uses item to render page, now my question is how to use item in transcluded html without saying $parent.item
I want something like init-my-scope="item=$parent.item" so that I do not need to use $parent.item in my transcluded html.
The reason to do that is I need my transcluded html to preserve its origin scope since it has bindings to its originated scope and only uses item from parent, and also it interpolate some string from a model which is binded to its scope which evaluate to !item.property
Here is the structure:
myModule.directive('myDirective', function() {
var directive = {
        bindToController: true,
        controller: myDirectiveController,
        controllerAs: 'vm',
        restrict: 'E',
        transclude: true,
        scope: {
            data: '=sourceData',
        },
        template: '

'
    };
    return directive;
});

and in my template:
<my-directive source-data="someData">
    {{$parent.item.property}}

    {{originScope.data}}
</my-directive>

in above example originScope.someCondition will evaluate to !item.property but item.property wont be available and the value can be retrieved using $parent.item.property
so I need to somehow tell my template when ever you encounter item refer to  $parent.item and all the places which is binded to $parent.item.xyz will be rather bind to item.xyz.


text:
Q: Will the creation of several million Hard Links on a Windows File System Create performance problems? I want to implement something similar to Apple TimeMachine on a Windows computer. Windows has a function called CreateHardLink. Microsoft's documentation for hard links  does not imply that using this feature excessively will create performance problems, but Microsoft frequently fails to mention this fact.
Will I get into trouble if I create a zillion hard links on a file system?


text:
Q: Mysql group_concat with a many to many relation I've three tables
+-------------+  +-----------------------------+  +-----------+
| WORKSPACES  |  | USERS_WORKSPACES            |  | USERS     |
+-----+-------+  +----+---------+--------------+  +----+------+
| id  | title |  | id | user_id | workspace_id |  | id | name |
+-----+-------+  +----+---------+--------------+  +----+------+
|  1  |  W1   |  | 1  |   1     |     1        |  |  1 |  U1  |
|  2  |  W2   |  | 2  |   1     |     2        |  |  2 |  U2  |
|  3  |  W3   |  | 3  |   2     |     2        |  |  3 |  U3  |
+-----+-------+  +----+---------+--------------+  +----+------+

I'm trying to query the db to list unique workspaces for a given user_id. For each workspace returned I want a group of unique user ids. Like so:
For user_id = 2
+--------------+-----------------+-------+
| workspace_id | workspace_title | users |
+----------------------------------------+
| 1            | W1              | 1     |
+----------------------------------------+
| 2            | W2              | 1,2   |
+----------------------------------------+

For user_id = 2
+--------------+-----------------+-------+
| workspace_id | workspace_title | users |
+----------------------------------------+
| 2            | W2              | 1,2   |
+----------------------------------------+

With this query I can list unique user ids for all the workspaces. How can I limit the listing to only the workspaces associated with a specified user_id?
SELECT w.id,
       w.title,
       group_concat(b.user_id) as users
FROM   workspaces w,
       users_workspaces b,
       users u
WHERE  w.id = b.workspace_id
  AND  b.user_id = u.id
GROUP BY w.id

A: Your query looked functionally correct.  However, you don't need to join in the users table, because you can get user_id from users_workspaces.  And, you should use proper join syntax:
select w.id, w.title, group_concat(uw.user_id) as users
from workspaces w join
     users_workspaces uw
     on w.id = uw.workspace_id
group by w.id;

If you want to limit this to workspaces associated with a particular user id, then use a having clause:
select w.id, w.title, group_concat(uw.user_id) as users
from workspaces w join
     users_workspaces uw
     on w.id = uw.workspace_id
group by w.id
having sum(uw.user_id = @USERID) > 0;

A: try this -- you can substitute any value or variable for the user_id in the where clause.:
SELECT
w.id,
w.title,
group_concat(b.user_id) as users
FROM
workspaces w
JOIN users_workspaces b ON w.id = b.workspace_id
JOIN users u ON b.user_id = u.id
where
u.user_id = 2
group by w.id


text:
Q: how to import visual basic function into asp.net using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.VisualBasic;

public partial class ReportGeneration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet query = (DataSet)Session["myDataset"];
        GridView1.DataSource = query;

        GridView1.DataBind();

    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DateTime dt;
        long age;
        Datefunctions3.DateClass d1 = new Datefunctions3.DateClass();
        //DateFunctions2.DateClass d1 = new DateFunctions2.DateClass();

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string s1 = e.Row.Cells[8].Text;
            dt = Convert.ToDateTime(e.Row.Cells[8].Text);
            // age = d1.DateDifference(da.Year, dt, DateTime.Now);
            age = d1.DateDifference(DateInterval.year, d1, DateTime.Now);

            e.Row.Cells[8].Text = age.ToString();
        }
    }
}

This is my code it shows error under the dateinterval not able to solve the problem have added a dll file of my visual basic function into the BIN folder as well

A: Here's an extension function that will give you the age w/o needing to use a VB function:
<Extension()> Function Age(dStart As DateTime) As Integer
  Dim dNow As DateTime = DateTime.Now
  Return dNow.Year - dStart.Year - If(dNow.Month > dStart.Month OrElse dNow.Month = dStart.Month AndAlso dNow.Day > dStart.Day,0,1)
End Function

usage:
age = d1.Age

or, if you don't want to use an extension, use it directly:
  Dim dNow As DateTime = DateTime.Now
  age = dNow.Year - d1.Year - If(dNow.Month > d1.Month OrElse dNow.Month = d1.Month AndAlso dNow.Day > d1.Day,0,1)

I just noticed that your code is C#... you'll need to convert my vb to C#


text:
Q: Rails validate number of nested fields submitted I have a form_for that creates a poll. The poll has many poll_options aka choices as nested attributes.
Question -- How can I validate the number of poll_options? It does not makes sense to have a poll with only 1 choice.
Here is my model:
class PollOption < ApplicationRecord
  belongs_to :poll
  has_many :poll_responses
  accepts_nested_attributes_for :poll_options,
    reject_if: proc { |attributes| attributes['value'].blank? },
    allow_destroy: true

  validates :poll_options, length: {
    minimum: 1, too_short: "must be at least 2.",
    maximum: 5, too_long: "can be 5 at most."
  }

Here is my view:
<%= f.fields_for :poll_options do |poll_option| %>
  <%= render 'poll_option_fields', f: poll_option %>
<% end %>

The error that I get is related to my render line in the view:
exception reentered

I also tried this validation, but it neither worked, nor produced errors:
  def validates(value)
    if value.count < 1
      errors.add(:base, "must have at least 2 choices.")
    end
  end

UPDATE: here are my request params:
{"utf8"=>"✓", "authenticity_token"=>"6h+wZ+RUAOIp8iXFX0V9t0MSxTGtFHpe7PZS3fJeF3JejaIbAm2jidLyg0qYII26NYX+F1BH6FHWNCFJ7nzymQ==", "poll"=>{"user_id"=>"2", "active"=>"true", "question"=>"Example - Which of these do you like best?", "poll_options_attributes"=>{"0"=>{"value"=>"a", "_destroy"=>"0"}, "1"=>{"value"=>"b", "_destroy"=>"0"}, "2"=>{"value"=>"c", "_destroy"=>"0"}, "3"=>{"value"=>"", "_destroy"=>"0"}}}, "commit"=>"Save Poll", "controller"=>"polls", "action"=>"create"}

A: You should validate in the poll model, you can add a custom validation in Poll like this:
def validates_amount_of_polls
  if poll_options.size < 2
     errors.add(:base, "must have at least 2 choices")
  end
end


text:
Q: replace amazon associates link builder shotcodes in wordpress While amazon is stopping it's own wordpress plugin by March 2020, I was moving towards another and found a pretty good one. But afaik none supports migration of the old amazon_link and amazon_textlink shortcodes to their own shortcode format. As I used it quite a few hundred times along the past years, it is impossible to replace them by hand.
Thus, I came up with the idea of using regular expressions.
What I have now in wordpress posts is something like:
lorem ipsum blabla

[amazon_link asins='B07ZGG8WB5,B005LD2IWE' template='template' store='somecode-21' marketplace='DE' link_id='acd3b40d-de6f-4e2d-825e-56eabdaf44b5']

lorem ipsum...

where at least one ASIN (e.g. B07ZGG8WB5) must be present and multiple are just separated by a comma.
So what I got up to now is this regex
\[amazon_link asins='([A-Z0-9]{10}(?:,[A-Z0-9]{10})*)' [^]]*\]

which, from what I can see in (online) regex tools, works fine recognizing just the amazon link content and put the ASINs into a capture group.
But here I am stuck. What can I do now to replace everything matched outside the capturing group so in the end, I get
[amazon box="B07ZGG8WB5,B005LD2IWE"/]

in these posts? and is this possible in MYSQL diretly or should it be done in a separate php?


text:
Q: (input) attribute in Angular I can't seem to find out what (input) does in Angular. Here's the code sample:
<input class="form-control" placeholder="person" (input)="filterPersons($event.target.value, 'Hair Colour')">

I have placed a log inside the filterPersons method to see when it is executed but nothing gets outputted at all when I click/unclick the checkbox or submit the form. What functionality does (input) actually provide?
Worth noting that there are no errors and the codebase works fine and in fact there are multiple examples of this throughout the codebase so I know it's not a simple typing error but I cannot see what effect it has.

A: It seems like what you want is this:
https://developer.mozilla.org/de/docs/Web/HTML/Element/Input/checkbox
as the input type and then you can listen for changes via the change event instead of input (There is no input on checkbox):
<input type="checkbox" class="form-control" placeholder="person" (change)="filterPersons($event.target.value, 'Hair Colour')">

As on getting triggered on the form submit, you would have to do that programmatically or store the state when the input changes.

A: I don't know why could not able to find what (input) actually does. In your code
<input class="form-control" placeholder="person" (input)="filterPersons($event.target.value, 'Hair Colour')">

(input) call filterPersons method with 2 parameters.
Please check the stackblitz link and see the console.log value. It changes on every single input.
StackBlitz Demo Link.

A: Try providing type="text" / type="number" and I'm sure you will see your method being executed. The (input) event fires on every key press and can be used if you want immediate validation of an input (The (change) event fires when you leave the control.)


text:
Q: select multiple column into a single row Suppose I've got two tables:
Table A:
Item1Name  Item1Code  Item2Name   Item2Code
ABC         001         DEF          002

Table B:
ItemCode     ItemType
  001        Cookware
  002         Drinks

What should the select statement be to generate following result?
Item1Name  Item1Code  Item2Name   Item2Code   Item1Type    Item2Type
ABC         001         DEF          002       Cookware      Drinks

A: Seems that you have an item detail table (Table B) that holds the item characteristics and another table that relates 2 items (Table A). You should start with Table A and join twice with Table B (once for each item), to get their characteristics.
SELECT
    A.Item1Name,
    A.Item1Code,
    B1.ItemType,
    A.Item2Name,
    A.Item2Code,
    B2.ItemType
FROM
    TableA A
    LEFT JOIN TableB B1 ON A.Item1Code = B1.ItemCode
    LEFT JOIN TableB B2 ON A.Item2Code = B2.ItemCode

You should check if you need an INNER or LEFT join (left will return NULL if no matching record is found).


text:
Q: How to translate get_intermediate_image_sizes? I use the following code to get image sizes:
public function getImageSizes(){
        global $_wp_additional_image_sizes;
        $sizes = array();
        foreach(get_intermediate_image_sizes() as $s){
            $sizes[$s] = array(0, 0);
            if( in_array( $s, array( 'thumbnail', 'medium', 'large' ) ) ){
                $sizes[$s][0] = get_option( $s . '_size_w' );
                $sizes[$s][1] = get_option( $s . '_size_h' );
            } else {
                if ( isset( $_wp_additional_image_sizes ) && isset( $_wp_additional_image_sizes[ $s ] ) )
                    $sizes[$s] = array( $_wp_additional_image_sizes[$s]['width'], $_wp_additional_image_sizes[$s]['height'] );
            }
        }
        return $sizes;
    }

The result is a select with image sizes, something like this:
<option value="thumbnail">Thumbnail</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="tribe_image_widget_custom" selected='selected'>Custom</option>

The question is how to translate sizes (Thumbnail, Medium, Large and Custom)? By default the sizes are in English, I need them to be another language (I use CodeStyling Localization plugin for it).
Thank you!
P.S.: to biuld a select I use this code:
<select class="widefat" id="<?php echo $this->get_field_id('size'); ?>" name="<?php echo $this->get_field_name('size'); ?>">
    <?php foreach ($this->getImageSizes() as $name => $atts): ?>
        <option value="<?php echo $name ?>"<?php echo ($name==$size?' selected':'') ?>><?php echo ucwords($name) . ' ('. implode( 'x', $atts ). ')' ?></option>
    <?php endforeach ?>
</select>

A: You can use __(), _e(), _x() or _ex() and your textdomain to make your theme or plugin translatable.
I stripped your code snippet to the basics, so you will get the idea more easily:
<select class="widefat">
  <?php foreach ( $this->getImageSizes() as $name => $atts ) : ?>
    <option value="<?php echo $name; ?>" ?>>
      <?php echo ucwords( __( $name, 'textdomain' ) ); ?>
    </option>
  <?php endforeach; ?>
</select>

Unfortunately internationalization is not possible with variables like $name so you will have to provide the default image size names to make them accessible:
$sizes = array(
  __( 'thumbnail', 'textdomain' ),
  __( 'medium', 'textdomain' ),
  __( 'large', 'textdomain' )
);

If you're adding the image sizes yourself you can avoid the hack above if adding them like this:
add_image_size( __( 'custom-image-size', 'textdomain' ), $width, $height, $crop );


text:
Q: Keytool plugin eclipse not working I have to connect a java program to a LDAP server over SSL.
I've installed Keytool plugin for Eclipse correctly.
Created the keystore, imported the .cer into the keystore and all these informations appear alongside the console tab, so in the Keytool tab.
I wonder myself why my program still got error over SSL, but works fine without it.
I also tried the console version of keytool and all is correct, all appears in the tab correctly but the program is not working.
So, what can be the problem? Configuration or anything else?
In conclusion, is there a test/code I can do to verify if the problem is connected also with my program, or is a general problem?

A: SOLUTION:
add to C:\Program Files....jre7\lib\security\cacerts YOUR .cer.
This, after creating a fake and useless keystore just to allow Eclipse to add the keytool tab, nearby console tab.


text:
Q: Determine the maximum size of a graph Determine the maximum size of a graph of order $n$ having a maximum matching of $k$ edges
a) if  $n=2k$
b)if $n=2k+2$

A: If $n=2k$ then the answer is clearly obtained by the complete graph.
If $n=2k+2$ the answer is $\binom{2k}{k}-(2k+1)$. Clearly if we remove all the edges from a fixed edge from $K_{2k+2}$ we get a graph whith this size and a maximum matching of size $k$.
To see that every edge with more edges has a complete matching of size $k$ we use induction:
We first prove that a graph of size $2k+2$ with $k\geq 2$ in which every vertex has degree at least $2k$ has a perfect matching. Proving this is easy by induction, the base case $k=2$ is easy, the graph must be a cycle. we now prove the whole thing.
Claim: a graph with $2k+2$ vertices and less than $2k+1$ missing edges has a perfect matching.
Base case: when $k=1$ we have $K_4$ minus at most two edges, the casework shows it is true easily.
Inductive step: we wish to prove the statement is true for a given $k> 1$. Suppose $G$ is a graph with $2k+2$ vertices and less than $2k+1$ missing edges. If a certain vertex has more than $1$ missing edge let $uv$ be one of them and consider $G'=G\setminus\{uv\}$ , notice $G'$ has less than $2k$ edges missing, so $G'$ has a perfect matching, we can extend this to a perfect matching for $G$ using $uv$. If no vertex of $G$ has more than $1$ edge missing the graph also has a perfect matching, we proved it earlier.


text:
Q: passportjs local connectflash not working with ejs I have a project using passportjs fully working, but not showing flash messages.
The passportjs file looks like this:
  passport.use('local-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
  },
  function (req, email, password, done) {
    if (email) {
      email = email.toLowerCase()
    } // Use lower-case e-mails to avoid case-sensitive e-mail matching

    // asynchronous
    process.nextTick(function () {
      User.findOne({ 'local.email': email }, function (err, user) {
        // if there are any errors, return the error
        if (err) {
          console.log(err)
          return done(err)
        }

        // if no user is found, return the message
        if (!user) {
          console.log('No user found')
          return done(null, false, req.flash('message', 'No user found'))
        }

My routes.js file looks like this:
  // Login
  app.get('/login', function (req, res) {
    console.log('login get')
    res.render('pages/login', {message: req.flash('messsage')})
  })

my login.ejs file looks like this:
  <%if (message) {%>
    <%=message%>

  <%}%>

I have no idea why it isn't working?
Here comes my server.js if it is any problem related to includes:
var express = require('express')
var mongoose = require('mongoose')
var passport = require('passport')
var path = require('path')
var ejs = require('ejs') // Not used?
var fs = require('fs') // Not used?

const session = require('express-session')
const MongoStore = require('connect-mongo')(session)

// Reads .env variables for encrypted data
require('dotenv').config()

var port = process.env.PORT || 8080
var db = process.env.MONGO_URI

mongoose.connect(db) // connect to our database

var app = express()

app.set('views', './views')
app.set('view engine', 'ejs')

// GET /public/style.css etc.
app.use(express.static(path.join(__dirname, '/public')))

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded())

app.use(session({
  secret: 'hakunamatata',
  store: new MongoStore({
    mongooseConnection: mongoose.connection,
    saveUninitialized: false,
    resave: false
  })
}))

var flash = require('connect-flash')
app.use(flash())

var initPassport = require('./app/authentication/passport')
initPassport(passport)

app.use(passport.initialize())
app.use(passport.session()) // persistent login sessions

require('./app/routes/routes')(app, passport)

app.listen(port)
console.log('Dev port is: ' + port)

A: I tested with:
req.flash('loginMessage', 'No user found')

instead of:
req.flash('message', 'No user found')

and on the routes.js file:
{message: req.flash('loginMessage')}

instead of:
{message: req.flash('message')}

And now it works... I dont know what made the difference, but I hope this can help someone else in the future..


text:
Q: Installing AjaxTerm with NginX using SSL I am using Ubuntu 11.04 and trying to install AjaxTerm using https. Any guide to use NginX to serve AjaxTerm using https protocal?
Also I would like to put AjaxTerm to be served under https://localhost/ajaxterm/ instead of the default http://localhost:8022.
How to do it?
Thanks.

A: I am assuming that you would like to setup ajaxterm to a remote server & not really localhost.
Setting up at a url like /ajaxterm would be difficult, but you can easily set it up at a subdomain like ajaxterm.yourserver.com with following lines inside the http directive in nginx
server {
    listen 80;
    server_name ajaxterm.yourserver.com;
    location / {
        proxy_pass http://127.0.0.1:8022;
        proxy_redirect default;
    }
}

This should get you http://ajaxterm.yourserver.com running for you. To get it running on https, you can tweak the instructions for apache here


text:
Q: Add a scrollbar to JFrame I'm having some problem finding a way to add a scrollbar in a JFrame. I found a method to redirect System.{in,out,err} to a JTextArea but I was not successful in adding a scrollbar. I hope this question is not redundant.
public class console extends JTextArea {

 public static JTextArea console(final InputStream out, final PrintWriter in) {
    final JTextArea area = new JTextArea();
        new SwingWorker<Void, String>() {
        @Override protected Void doInBackground() throws Exception {
            Scanner s = new Scanner(out);
            while (s.hasNextLine()) publish(s.nextLine() + "\n");
            return null;
        }
        @Override protected void process(List<String> chunks) {
            for (String line : chunks) area.append(line);
        }
    }.execute();
    area.addKeyListener(new KeyAdapter() {
        private StringBuffer line = new StringBuffer();
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (c == KeyEvent.VK_ENTER) {
                in.println(line);
                line.setLength(0);
            } else if (c == KeyEvent.VK_BACK_SPACE) {
                line.setLength(line.length() - 1);
            } else if (!Character.isISOControl(c)) {
                line.append(e.getKeyChar());
            }
        }
    });

    return area;
}
public static void main(String[] args) throws IOException {
    PipedInputStream inPipe = new PipedInputStream();
    PipedInputStream outPipe = new PipedInputStream();
    System.setIn(inPipe);
    System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));

    PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);

    JFrame frame = new JFrame("\"Console\"");

    frame.getContentPane().add(console(outPipe, inWriter));
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

   // my code
  }

A: Create a new JScrollPane object and set the ScrollBarPolicies.
If you do not want to the scollbars to appear always, just delete the policies.
EDIT
Also, don't use KeyListener on text components, use a combination of DocumentListner and key bindings instead. (Thanks to @MadProgrammer)

Solution
JScrollPane jsp = new JScrollPane(console(outPipe, inWriter));
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(jsp);

Output

A: You can try with,
public class Test {

    public static void main(String [] a) {

        final JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane pane = new JScrollPane(
                           JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        frame.setContentPane(pane);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
   }

}


text:
Q: Send emails automatically in aspx c# sql I want to be able to send emails automatically (every week) to a person letting them know to add their hours in the system. I have a button that does the job of sending the emails but I would like to automatically send the emails.

A: SQL Server Agent - You can use sp_send_dbmail to send email, and SQL Server Agent to schedule the job. All can be done within SQL Server. Can refer the below link for more information.
https://learn.microsoft.com/en-us/sql/ssms/agent/sql-server-agent
Or as you said you have a button already, so have a web logic already. You can use Hangfire package and schedule that function from your application. So you would be using the existing logic just few lines new to add job in HangFire.
http://docs.hangfire.io/en/latest/

A: Here is a link about how to create a scheduled task to run a C# console application (as requested in comments above):
http://www.c-sharpcorner.com/UploadFile/manas1/console-application-using-windows-scheduler/
I have implemented this approach for multiple different purposes (including an implementation of an email class) and I would definitely recommend it.  it's very straightforward and easy to deploy from Visual Studio after the initial setup.


text:
Q: Questions with To Be v To Do I know does it taste good is grammatically correct. But is is it good correct?
Both are in reference to food.
I keep hearing people using the second, especially in American TV shows.


text:
Q: Importing AWS downloaded Sentinel-2 data into SNAP software? I have downloaded Sentinel-2 L1C granules from AWS. I saved it as .SAFE format and now have for each tile downloaded as folder structure:

*

*AUX_DATA

*IMG_DATA

*QI_DATA

i would like to run some algorithms (atmospheric correction, biophysical procesor, etc.) with ESA's SNAP sowftware on these files.
As there is no .xml file downloaded from AWS, how can i import this file-structure into the SNAP software?
So far i can only select each band independently and load in SNAP as one product, but i would like all bands together as one product.

A: The Sentinel-2 L1C AWS bucket is populated by Sinergise, who also publish a Python library called sentinelhub-py that allows you to reconstruct the .SAFE format as expected by SNAP including the relevant XML files. The documentation also explains the differences between the original, compact and reconstructed formats.


text:
Q: Having two Android activity in foreground When calling someone with messenger on android the app open an other activity in foreground and we can switch between each other like if they were two different apps.
Could someone give me some information on how this works?
This seems impossible for me based on what I know about android.

A: Drawing over other apps would be a way to implement this.
here you have a simple example of it.