Why dictonary object to json to fill dropdown does not preserve order list

Question: I'm trying to populate drowdown list in jquery from my controller method which return ordered dictionary object for key value pair. but when my drop down list filled, it does not preserve the order why is is like so
Here is my controller action method code ..
    public JsonResult GetRolesByGroupId(string groupCode)
    {
        var getRoleList = BusinessLayer.GetRoles()
            .Where(x => x.GroupCode == groupCode)
            .Select(i => new {i.RoleId, i.RoleDesc})
            .OrderBy(i => i.RoleDesc)
            .ToList();

        //var groupCodeList = getRoleList.Where(x => x.GroupCode == groupCode).OrderBy(o => o.RoleDesc)
         //   .ToDictionary(g => g.RoleId.ToString(), g => g.RoleDesc);

         Dictionary<string, string> objlist = new Dictionary<string, string>();
         getRoleList.ForEach(e=>objlist.Add(e.RoleId.ToString(),e.RoleDesc));

        return Json(objlist, JsonRequestBehavior.AllowGet);
    }

and here is my jquery code..
     $('#groupCodeList').on("change",
            function () {
                if ($('#groupCodeList option:selected').text() === "All") {
                    $('#RoleId').empty();
                    $('#RoleId').append('<option value=""></option>');
                    $('#RoleId').append('<option value="">All</option>');
                } else {
                    if ($('#groupCodeList option:selected').text()) {
                        $.getJSON(getRolesUrl,
                            { groupCode: $('#groupCodeList').val() },
                            function (data) {
                                $('#RoleId').empty();
                                $('#RoleId').append('<option value="">--Select--</option>');
                                $.each(data,
                                    function (key, val) {
                                        $('#RoleId').append('<option value="' + key + '">' + val + '</option>');
                                    });
                            });
                    } else {

                        $('#RoleId').empty();
                        $('#RoleId').append('<option value=""></option>');
                        //selectedCategory = "";
                    }

                }

What is the issue here, can someone help me, how to bind dropdown with sorted dictionary/list object with json in jquery.? help appreciated.
Answer: If you want to  fill dropdown and preserve order list, there are two ways, you can refer to them, hope them can help :
One way:
you can remove Dictionary<string, string> objlist , just return ordered getRoleList .
like:
 return Json(getRoleList, JsonRequestBehavior.AllowGet);

Then  change below:
$.each(data,
      function (key, val) {
      $('#RoleId').append('<option value="' + key + '">' + val + '</option>');
                                    });

with:
$.each(data, function (i, item) {
        $("#RoleId").append(`<option value="${item.roleId}">${item.roleDesc}</option>`);
                    });

Second way:
Exchange the  Dictionary<string, string> objlist key and value like:
 getRoleList.ForEach(e => objlist.Add(e.RoleDesc,e.RoleId.ToString()));

Then change the code like:
$.each(data,
  function (key, val) {
     $('#RoleId').append('<option value="' + val + '">' + key + '</option>');
                        });

Comment: Great, thank you https://stackoverflow.com/users/17124525/qing-guo. both the options are working fine. I'll go with first since don't want to use dictionary here. it's my bad I have done it some time back but unfortunately didn't click back to my mind. anyway thanks a lot to remind me.


I am replacing a ceiling fan in a bedroom and the wiring in the receptacle is confusing me

Question:

I am replacing an old ceiling fan and combination switch in a bedroom in my house. I am trying to connect a new switch that controls both functions (fan and light) separately, as well as a dimming function for both. The previous fan (while unsightly), worked perfectly fine with the old combo switch. The top controlled the light, the bottom controlled the fan. Problem is, when I took the old fan off, and installed the new fan, there were only 3 wires coming out of the ceiling: load (black), neutral (white), and ground (bare). The new switch demanded two load wires (one for each function). I did not take a picture of the way it was wired beforehand (although i wish I had for the life of me). The point is, the ceiling fans were both wired the same way from the wires protruding from the ceiling itself.
In the electrical box, there are 3 sets of wires. From testing I have figured out that the two sets protruding from the bottom are both hot, and the single set of wires coming from the top are the load wires for the fan. The 3 neutral (white) wires were not all connected together originally, but the instructions for the new switch told me to do that. I cannot rewire the old switch to control both functions, a single switch just controls both. if i touch either of the two bottom hot wires to the load wire for the fan, both the light and fan come on and are steady.
I spoke with an electrician about it and he said I either needed a fourth wire or it had something to do with the break-away tab on the old combo switch. I am not trying to use the new switch anymore, I just want to understand how the thing was wired originally. THERE IS NO FOURTH WIRE. I have not added or removed any wires from the previous configuration with the exception that there may have been two wires spliced into one (from the remains of disconnecting the old switch there is about a 3-4 inch black wire by itself no longer connected or spliced to anything else), but like I said, I didn't take a picture of what it looked like beforehand. I am perplexed, please help.
Comment: To control light and fan separately you need 3 wires. If you're positive there's only a black, white and bare copper then it sounds like they used the black, the white and  the copper ground wire for the 3rd wire. That's not an acceptable way to wire the fan.
Comment: Has this recently become unacceptable? I believe the fan to be original to the house ~1973. Is it not up to code, hazardous, or just to protect electricians when working? To be safe and to code, will I need to have someone run another line? Thanks for your help.
Comment: One of the electrical experts should comment soon and they can answer your question better. If the fan is original someone may have added the switch at some later point and did the creative wiring. Another option  is to get a remote control which will work with your existing wiring, the remote can control the light and fan separately.
Comment: Thanks, I was going to ask about a digital option, I'm sure that is much more straightforward. Thanks again.
Comment: Bootlegging ground was always unacceptable.  Safety ground is for safety, and it's not insulated because it's never supposed to be hotter than ground.  Bootlegging neutral from ground risks electrifying all the grounds in your house.  But normally when someone installs a ceiling fan rated box, they also install the proper /3+gnd cable.  **This suggests another danger: that the ceiling box is not actually fan-rated**.
Answer: Take your fan controller back and get a Lutron MA-LFQM instead
Most fan controllers on the market today are incompatible with your wiring configuration, where there is only one hot going up to the fan from the switch.  However, there is one that's suitable, and that's the Lutron MA-LFQM.  This uses a module in the fan canopy to decode a digital signal from the wall controller into separate fan and light outputs, and isn't too hard to find.  (It also can use matching Lutron accessory controls for 3-way or 4-way work.)
Once you get the correct control in, you'll want to pick one of the bottom hot/neutral pairs and stick with it, capping the other incoming hot and neutral off individually.  Once you do that, the control is wired according to the single-pole instructions, with the load neutral nutted to the remaining neutral, the line hot connected to the black screw on the control, and the load hot connected to a brass screw on the control.
At the ceiling fan, the canopy module is wired with its white neutral to the remaining neutrals (fan-neutral and incoming-neutral), its black to the incoming black (switched-hot), its red to the light kit wire off the fan (typically blue), and its yellow to the fan wire on the fan (typically black).  Connect all the bare/green grounds (fan ground, box ground, incoming ground) together, button up both boxes, turn the breaker on, follow the control activation procedure in the instructions, and enjoy your fan!
Answer: I think Platinum Goose has correctly guessed how this was originally wired: the white and the black wires were used as switched line/hot going to the fan and and light loads, and the bare wire was (mis-)used as the neutral. I've seen shenanigans like this once or twice when an electrician came up short by one conductor. It's true that this practice violates code requirements, and has for some time.
So, what to do from here? If the lights and fan must be controlled separately, there are two options:

install more cable between the switch and the light/fan so that conventional wired control (or plain switches) can be used
use a remote control solution. For example, Lutron (and other vendors) offers a nice ceiling fan controller which offers adjustable fan speed and light dimming from the control on the wall.

One other note: you wrote that "if i touch either of the two bottom hot wires to the load wire for the fan, both the light and fan come on and are steady." That does make it sound as if you have two separate hot sources coming into this box. That isn't inherently bad, but it is at least unexpected, and would be important to learn why this is the case.


Can't connect to MySQL on Windows 7 using JDBC, but works via phpmyadmin and other admin tools?

Question: TL;DR:
Every time I try to use JDBC to connect to a local MySQL server (that works on tons of other sql clients), it doesn't connect at all and I get an exception:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
.... stack trace ....
Caused by: java.net.SocketException: Invalid argument: connect

More detailed info:
I've got a local MySQL server running that I can connect to with using the following info:

address: localhost or 127.0.0.1 (both work)
port: 3306
and my username/password/db name

Using the applications: HeidiSQL, phpmyadmin, MySQL Workbench and mysqladmin
Running mysqladmin version confirms that the server is up, working, and has tcp/ip enabled.
Doing mysqladmin variables shows that "skip_networking" is off (see below for full config).
The MySQL log shows nothing out of the ordinary (also below).
I'm using JDBC connector v5.1.15, mysql-connector-java-5.1.15-bin.jar. It's in my project class path with Eclipse.
All windows 7 (Ultimate, 64bit if it matters) firewalls are off.
Yet I still get the stack trace error as shown below. I can't for the life of me figure out what's wrong when everything else is able to connect just fine...
I've tried to include all relevant information below. I'm hoping it's just something simple and stupid that I've overlooked and can't find because I'm looking too hard...but eh who knows :/ heh.
I've tried everything I've been able to find in other similar questions online but nothing seems to work (incl. https://stackoverflow.com/a/2985169/211750 , https://stackoverflow.com/a/2103092/211750 , https://serverfault.com/questions/89955/unable-to-connect-to-mysql-through-jdbc-connector-through-tomcat-or-externally and others)
My test code:
package sqltest;

import com.mysql.jdbc.Driver;
import java.sql.DriverManager;
import java.util.Properties;

public class main {

    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/dbname?user=user&password=****&";

        Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();

        DriverManager.getConnection(url);
    }

}

Stack trace: http://pastebin.com/qv332y86
MySQL variables dump: http://pastebin.com/merSEDdD
My.ini: http://pastebin.com/EWZX2enz
MySQL mysqladmin version:
Server version          5.5.20-log
Protocol version        10
Connection              localhost via TCP/IP
TCP port                3306
Uptime:                 1 min 37 sec

Threads: 1  Questions: 17  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.175

MySQL log:
120314 21:37:20 [Note] Plugin 'FEDERATED' is disabled.
120314 21:37:20 InnoDB: The InnoDB memory heap is disabled
120314 21:37:20 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120314 21:37:20 InnoDB: Compressed tables use zlib 1.2.3
120314 21:37:20 InnoDB: Initializing buffer pool, size = 128.0M
120314 21:37:20 InnoDB: Completed initialization of buffer pool
120314 21:37:20 InnoDB: highest supported file format is Barracuda.
120314 21:37:20  InnoDB: Waiting for the background threads to start
120314 21:37:21 InnoDB: 1.1.8 started; log sequence number 1619921
120314 21:37:21 [Note] Event Scheduler: Loaded 0 events
120314 21:37:21 [Note] wampmysqld: ready for connections.
Version: '5.5.20-log'  socket: ''  port: 3306  MySQL Community Server (GPL)
120314 21:38:02 [Note] wampmysqld: Normal shutdown

120314 21:38:02 [Note] Event Scheduler: Purging the queue. 0 events
120314 21:38:02  InnoDB: Starting shutdown...
120314 21:38:02  InnoDB: Shutdown completed; log sequence number 1619921
120314 21:38:02 [Note] wampmysqld: Shutdown complete

Comment: http://stackoverflow.com/questions/8216713/java-net-socketexception-invalid-argument-connect seems to suggest a problem with IPV6.  Is that what you're using?
Comment: +1: Well written question. Also: have you tried to change your connection string to 127.0.0.1 as [this comment](http://stackoverflow.com/questions/8216713/java-net-socketexception-invalid-argument-connect#comment10343027_8347425) suggests?
Comment: Maybe your firewall blocks connections for java.exe?
Comment: @JimGarrison I tried with it both enabled and disabled already, yes. Didn't seem to change anything though. I also disabled all extra network adapters in case. And last night, after posting this, I also tried it by closing every single extra process and service I could that was not required for the project or windows to run.
Comment: @Deco thanks :) I've tried with both localhost and 127.0.0.1 doesn't seem to matter. Note however, I can connect with either localhost or 127.0.0.1 from any of the other SQL admin tools.
Comment: @a_horse_with_no_name I've disabled windows firewall entirely and have no other firewall installed. I also tried disabling A/V in case.
Comment: Actually upon further investigation, it was indeed the IPV4/IPV6 issue from @JimGarrison ...but since I was doing this in tomcat I had to go through a round-about way of setting the system property.
Answer: Turned out it was Java preferring IPv6 messing things up so I had to add -Djava.net.preferIPv4Stack=true, but since I was running things under tomcat I had to go through a round-about way of setting the property. I'm not sure what the standard way of doing it is (if any) but I got it working by editing Catalina.bat and adding -Djava.net.preferIPv4Stack=true to the end of the file. See:
rem Execute Java with the applicable properties
if not "%JPDA%" == "" goto doJpda
if not "%SECURITY_POLICY_FILE%" == "" goto doSecurity
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% -Djava.net.preferIPv4Stack=true -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:doSecurity
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% -Djava.net.preferIPv4Stack=true -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Djava.security.manager -Djava.security.policy=="%SECURITY_POLICY_FILE%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:doJpda
if not "%SECURITY_POLICY_FILE%" == "" goto doSecurityJpda
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %JPDA_OPTS% %DEBUG_OPTS% -Djava.net.preferIPv4Stack=true -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:doSecurityJpda
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %JPDA_OPTS% %DEBUG_OPTS% -Djava.net.preferIPv4Stack=true -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Djava.security.manager -Djava.security.policy=="%SECURITY_POLICY_FILE%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end

:end

Comment: The standard way to provide this is by setting / adding it to the JAVA_OPTS environment variable
Answer: or for tomcat, CATALINA_OPTS can be set in environment variable


Image won't stop rotating in pygame

Question: I have this section of code (similar to the previous piece of code). It's supposed to just sweep 50 degrees left, then stop and sweep 100 degrees right, then stop and sweep 100 degrees to the left, and so forth. Only problem is it stops at the left, goes right, then continues to go right, even though I have a stop there to prevent that from happening.
                try:
                    screen.blit(Turrets[1], (TurretCoords[1]))
                    if Rotation == 1:
                        print(TurretRotation[1])
                        print(Rotation)
                        TurretRotation[1] = TurretRotation[1] - 1
                        Turrets[1] = pygame.transform.rotozoom(Turret, TurretRotation[1], 1)
                        if TurretRotation[1] == -50:
                            Rotation = -1
                    else:
                        print(TurretRotation[1])
                        print(Rotation)
                        TurretRotation[1] = TurretRotation[1] + 1
                        Turrets[1] = pygame.transform.rotozoom(Turret, TurretRotation[1], 1)
                        if TurretRotation[1] == 50:
                            Rotation = 1

Yes, I know, I was supposed to change the variables capital letters, and I haven't gotten around to it yet.
This is the output I get from the console.
-1 = Rotate
1 = TurretRotation[1]
-1
2
-1
3
-1
4
-1
5
-1
6
-1
7
-1
8
-1
9
-1
10
-1
11
-1
12
-1
13
-1
14
-1
15
-1
16
-1
17
-1
18
-1
19
-1
20
-1
21
-1
22
-1
23
-1
24
-1
25
-1
26
-1
27
-1
28
-1
29
-1
30
-1
31
-1
32
-1
33
-1
34
-1
35
-1
36
-1
37
-1
38
-1
39
-1
40
-1
41
1
40
1
39
1
38
1
37
1
36
1
35
1
34
1
33
1
32
1
31
1
30
1
29
1
28
1
27
1
26
1
25
1
24
1
23
1
22
1
21
1
20
1
19
1
18
1
17
1
16
1
15
1
14
1
13
1
12
1
11
1
10
1
9
1
8
1
7
1
6
1
5
1
4
1
3
1
2
1
1
1
0
1
-1
1
-2
1
-3
1
-4
1
-5
1
-6
1
-7
1
-8
1
-9
1
-10
1
-11
1
-12
1
-13
1
-14
1
-15
1
-16
1
-17
1
-18
1
-19
1
-20
1
-21
1
-22
1
-23
1
-24
1
-25
1
-26
1
-27
1
-28
1
-29
1
-30
1
-31
1
-32
1
-33
1
-34
1
-35
1
-36
1
-37
1
-38
1
-39
1
-40
1
-41
1
-42
1
-43
1
-44
1
-45
1
-46
1
-47
1
-48
1
-49
1
-50
1
-51
1
-52
1
-53
1
-54
1
-55
1
-56
1
-57
1
-58
1
-59
1
-60
1
-61
1
-62
1
-63
1
-64
1
-65
1
-66
1
-67
1
-68
1
-69
1
-70
1
-71
1
-72
1
-73
1
-74
1
-75
1
-76
1
-77
1
-78
1
-79
1
-80
1
-81
1
-82
1
-83
1
-84
1

Comment: Better `print(TurretRotation[1], Rotation)` to get both variables in one line. Or even `print('%4d %4d % (TurretRotation[1], Rotation) )` to get result better formatted.
Comment: `TurretRotation` changes 1...41 then 41...-84 . Maybe there was some problem before `if TurretRotation[1] ...` was executed so it didn't change direction but `try` catched that problem and you got no error.
Answer: I can't run it so I can only advice - I see you have print - so see what's going on with variables. Maybe one of them is changed in different place.
But you can do one this - use <= and >= - it should help.
if TurretRotation[1] >= 50:

if TurretRotation[1] <= -50:

Comment: Thanks. I could give you the full code for you to run it if you want.
Comment: First try your skills to find problem :)
Comment: I can't get it to work. I added the output from the IDLE window (or CMD or Terminal). The rotation number eventually gets so big that the game crashes entirely.
Comment: So better checks with `>=` and `<=` then with `==`. If you get `-70` then `-70 <= -50` and it should change direction but `-70 == -50` will not change it.
Comment: I tried it with the <= 50 but it still goes on and on.
Comment: Sorry, not `<= 50` but `>= 50` and `<= -50`.

Image won't stop rotating in pygame


Failing to Create XML in powershell with LF & UTF-8

Question: I've been trying the past few days to create a Powershell script that will create a XML file with 2 fields saying the time. Problem is the XML created is CR LF with UTF-8 BOM and what I need is LF with UTF-8.
Edit - Following 'LotPings' advise, adding the code at did change the XML to Unix(FL) but it still on UTF8-BOM while it causing me problems.
how can i change it from UTF8-BOM to UTF8 ?
I have never handled Powershell and I have no idea how I can achieve that.
# Set The Formatting
$xmlsettings = New-Object System.Xml.XmlWriterSettings
$xmlsettings.Indent = $true
$xmlsettings.IndentChars = "    "
$hour = (Get-Date).hour
$day = (Get-Date).dayofweek

# Checking If Its Too Late
If ($day -eq "Saturday" -and $hour -lt "8")
{
    $hour = "00"
}
else
{
    if ($day -ne "Saturday" -and $hour -lt "7")
    {
        $hour = "00"
    }
}

# Set the File Name Create The Document

$XmlWriter = [System.XML.XmlWriter]::Create("S:\NowPlaying\Ch0-News13.xml", $xmlsettings)

# Start the Root Element
$xmlWriter.WriteStartElement("track")

    $xmlWriter.WriteElementString("name",$hour.ToString()+":00" + "News Flash of")
    $xmlWriter.WriteElementString("artist","News Channel")

$xmlWriter.WriteEndElement() # <-- End <Track>

# End, Finalize and close the XML Document
$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()

Comment: Possible duplicate of [How can I generate XML with CR, instead of CRLF in XmlTextWriter](https://stackoverflow.com/questions/3415294/how-can-i-generate-xml-with-cr-instead-of-crlf-in-xmltextwriter)
Answer: Expand your $xmlsettings with:
$xmlsettings.NewLineChars = "`n"

Sample output (hex) 0A marked with [0A]:
> Format-Hex .\Ch0-News13.xml

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   EF BB BF 3C 3F 78 6D 6C 20 76 65 72 73 69 6F 6E  <?xml version
00000010   3D 22 31 2E 30 22 20 65 6E 63 6F 64 69 6E 67 3D  ="1.0" encoding=
00000020   22 75 74 66 2D 38 22 3F 3E[0A]3C 74 72 61 63 6B  "utf-8"?>.<track
00000030   3E[0A]20 20 20 20 3C 6E 61 6D 65 3E 31 36 3A 30  >.    <name>16:0
00000040   30 4E 65 77 73 20 46 6C 61 73 68 20 6F 66 3C 2F  0News Flash of</
00000050   6E 61 6D 65 3E[0A]20 20 20 20 3C 61 72 74 69 73  name>.    <artis
00000060   74 3E 4E 65 77 73 20 43 68 61 6E 6E 65 6C 3C 2F  t>News Channel</
00000070   61 72 74 69 73 74 3E[0A]3C 2F 74 72 61 63 6B 3E  artist>.</track>

## Q:\Test\2019\02\21\SO_54809424.ps1
# Set The Formatting
$File = "S:\NowPlaying\Ch0-News13.xml"
$xmlsettings = New-Object System.Xml.XmlWriterSettings
$xmlsettings.Indent = $true
$xmlsettings.IndentChars = "    "
$xmlsettings.NewLineChars = "`n"
$hour = (Get-Date).hour
$day = (Get-Date).dayofweek

# Checking If Its Too Late
If ($day -eq "Saturday" -and $hour -lt "8"){
    $hour = "00"
} else {
    if ($day -ne "Saturday" -and $hour -lt "7"){
        $hour = "00"
    }
}

# Set the File Name Create The Document
$XmlWriter = [System.XML.XmlWriter]::Create($File, $xmlsettings)

# Start the Root Element
$xmlWriter.WriteStartElement("track")

$xmlWriter.WriteElementString("name",$hour.ToString()+":00" + "News Flash of")
$xmlWriter.WriteElementString("artist","News Channel")

$xmlWriter.WriteEndElement() # <-- End <Track>

# End, Finalize and close the XML Document
$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()

Comment: So i've added that line into my .ps1 file but i still have the same issue. the XML i've been created is still (Windows CR LF) and UTF-8 BOM.
Comment: I just checked again, my changed script (appended above) produces exactly the shown output.


How to create variable filename and store variable on sd card with Arduino

Question: The example "SD_Test" in the Arduino IDE works perfectly. Now i want to expand it.
First: I want to use a variable file name. I found some example in the internet and also in stackoverlow for this, but nothing works (still searching for a minimal example)
writeFile(SD, "/hello.txt", "Hello ");

i want
writeFile(SD, filename, "Hello ");

where filename is a variable which handles something like "file.txt"
Second: I want to do the same for the content, which i want to save in this file. So instead of
writeFile(SD, "/hello.txt", "Hello ");

i want
writeFile(SD, "/hello.txt", datas);

As an example: I can print out this
        printf("%04x", datas);

Now i want to save this variable 'datas' with 4 hex in the file, exactly how it looks in the serial monitor.
Answer: You can use the following code for writing on the SD card.
You need to download two library files for this names are mentioned in the code.
Remember to format you SD card first into FAT32
Hope this will help you.
/*  Author: Ashish Kumar
    Org: INVOOTECH                            */
#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;

File myFile;
 char *b="hellow.txt";
 char p;
const int chipSelect = 4;

void setup() {
Serial.begin(9600);
 if (!card.init(SPI_HALF_SPEED, chipSelect))   //error statement
  {
    Serial.println("initialization failed. Things to check:");
    return;
  }
  if (!volume.init(card))           //error statement
  {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }
    if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }

}

void loop() {
  myFile = SD.open(b);
if (myFile) {
      p=myFile.read();
      Serial.write(p);
    }
    // close the file:
    myFile.close();

}

Comment: error: Sd2Card card does not name a type / SdVolume volume does not name a type
Comment: Can you share the connection of sd card module with the arduino uno so that i can assist you better.
Answer: Okay. So what I have done is create a file in loop.
#include <SPI.h>
#include <SD.h>

File myFile;

int chipSelectNumber = 10;
String prefix = "test";
String extension = ".txt";
String filename;
int fileNumber=0;
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  initSDCard();
}
void loop() {
  createFileAndEnterData();

}

//This Function will create file and Enter modbus data in the file
void createFileAndEnterData(){

 String temp;
 temp = prefix;
 temp.concat(fileNumber);
 temp.concat(extension);
 filename = temp;
 Serial.println(filename);
 fileNumber++;
 boolean statusFileCreate = createFile(filename);
 if(statusFileCreate){
  Serial.println("File Creation Successful");
 }
 else{
  Serial.println("File Creation Unsuccessful");
 }
 delay(1000);
}

boolean createFile(String fileName){
  myFile = SD.open(fileName, FILE_WRITE);
  if(myFile){
    Serial.print("Creating file : ");
    Serial.print(fileName);
    Serial.print(" ");
    myFile.println("");
    myFile.close();
    return true;
  }
  else{
    return false;
  }
}

void initSDCard(){

  Serial.print("Initializing SD card...");

  if (!SD.begin(chipSelectNumber)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
}

void openFile(String fileName){
  myFile = SD.open(fileName, FILE_WRITE);
  if (myFile) {
    Serial.println("Opened File");
  } else {
    Serial.println("error opening test.txt");
  }
}
void deleteFile(String filename){

}
void writeFile(String fileName){
    // re-open the file for reading:
  myFile = SD.open(fileName);
  if (myFile) {
    Serial.println(fileName);

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());

    }
    myFile.close();

  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

}

There are some unnecessary functions, just avoid that.
The following function will create file:-
void createFileAndEnterData(){

 String temp;
 temp = prefix;
 temp.concat(fileNumber);
 temp.concat(extension);
 filename = temp;
 Serial.println(filename);
 fileNumber++;
 boolean statusFileCreate = createFile(filename);
 if(statusFileCreate){
  Serial.println("File Creation Successful");
 }
 else{
  Serial.println("File Creation Unsuccessful");
 }
 delay(1000);
}

Hope this solves your problem.
Thank You.


Does putting the graphics into 2D save battery

Question: FS is a very power intensive game. I have often felt my phone get hot when I play it for more than 10 minutes. I have assumed it is because of the number of 3D elements being rendered during gameplay.
When I zoom out of the game enough the graphics turn 2D:

Does this affect the power consumption of the game? Will the amount of charge in my battery last longer while I have the game like this?
Comment: My guess is that the best way to test this is to leave the game running for say, an hour and check the battery, then switch the zoom and check again. Most likely recharging in between. That *might* give you some idea.
Answer: The battery will last a small amount longer because it's not constantly re-rendering 3D modelling but it's not a considerable amount. This is because the processes that remain active to keep the game running still use up a fair bit of power.
Comment: Processes such as keeping track of where Ds are, training timers, resource timers, etc. Makes sense. Thanks :)
Comment: Happy to help :)
Comment: My phone certainly gets considerably hotter in 3D mode than 2D.
Answer: I also faced battery problems while playing the game on my iPhone.  I tried following in the directions in this article: Download Fallout Shelter PC; and started playing on my computer. I hope this works to you as well.


Is there a way to configure Alamofire to not dispatch results to the main queue?

Question: I am building with an iOS application framework that is already opinionated about how the output of effects (such as network calls) should be dispatched back to the main queue.
Ergo, using my application framework and Alamofire in stock configuration, I believe Alamofire is dispatching my result to the main queue, and then my application framework is re-dispatching the result to the main queue. This is not a show-stopping problem, but it is a small performance penalty that I do not need to pay, if I could configure Alamofire to not perform that final dispatch back to the main queue.
Basically, I would like to configure Alamofire to behave like vanilla URLSession, where it is the caller's responsibility to dispatch back to the main queue.
I have read the Alamofire docs describing the handful of queues you can pass in to an Alamofire Session to configure where different parts of the Alamofire pipeline happen, but I can't quite figure out if there a configuration I can set up to effectively opt out of that last dispatch for the response handler.
Thanks for any thoughts.
Answer: All of Alamofire's features that dispatch to the main queue can take a specific queue instead, but you can't set a default for all of them at once. For instance, if you want your response handlers to be called on a specific queue, pass that queue to the response handler: responseDecodable(queue: someQueue). Otherwise all of Alamofire's internal events happen on a specific set of queues, such as the Session's rootQueue, which you can also use for the other features.
Comment: That would be up to Dispatch itself. It may be able to optimize that case since there's no need to queue hop and it would simply enqueue the work onto the queue. Enqueuing work onto a queue is lightweight anyway so there's no need to worry about it.
Comment: Hey Jon, thanks for answering. To follow up a bit, because I _have_ to re-dispatch later because of my application framework, what I'm looking for from Alamofire is `.responseDecodable(queue: someAliasForCurrentQueueOfTaskSoNoDispatchHappensAtAll)`. It sounds like I could make a single custom queue and hand it to every part of Alamofire's pipeline, but within Alamofire the dispatch calls _are_ going to happen, even if all the calls are "dispatch from customQueue1 to customQueue1", ie the cost of the dispatch call itself is unavoidable. Is that correct?


constexpr for values passed in by reference

Question: I had this piece of code which compiles
#include <bitset>

struct A{
    std::bitset<50> b; };

void test(A a){
    static_assert(sizeof(int)*8 < a.b.size(), "can't accomodate int in bitset");
    int x = 5;
    a.b = x; }

int main(){
    A a;
    test(a); }

But this doesn't
#include <bitset>

struct A{
    std::bitset<50> b;
};

void test(A& a){
    static_assert(sizeof(int)*8 < a.b.size(), "can't accomodate int in bitset");
    int x = 5;
    a.b = x;
}

int main(){
    A a;
    test(a);
}

Fails with this error
const.cpp: In function 'void test(A&)': const.cpp:8:5: error: non-constant condition for static assertion
     static_assert(sizeof(int)*8 < a.b.size(), "can't accomodate int in bitset");
const.cpp:8:5: error: 'a' is not a constant expression

Why is a.b.size() not treated as a constexpr in the second case? Isn't the constexpr for std::bitset::size() the one that should be treated as const as per the reference? Or does the non-const reference passed in the second case trigger the compiler to generate the error?
Compiler version:
g++ 4.8.4 on Ubuntu 14.0.4, compiled with g++ const.cpp -std=c++1y
Answer:

Deprecation Notice

This answer is now obsolete due to the changes in P2280: Using unknown pointers and references in constant expressions (proposal accepted into C++23 and applied as a defect report to C++11).GCC 14 and more recent compilers accept the original code as valid. See https://godbolt.org/z/KE5G969ca.

A& a is not usable in constant expressions, making your program ill-formed.
The rule forbidding a.b.size() to be a constant expression with a being a A& is the following:

[expr.const]/3
A variable is usable in constant expressions after its initializing declaration is encountered if it is a constexpr variable, or it is of reference type or of const-qualified integral or enumeration type, and its initializer is a constant initializer.

In your case, the variable a is:

not declared constexpr (as a function argument, it wouldn't make sense),
and is not an integral or enumeration type,
and is not a reference whose initialization is a constant initializer:

[expr.const]/2
A constant initializer for a variable or temporary object o is an initializer for which interpreting its full-expression as a constant-expression results in a constant expression, except that if o is an object, such an initializer may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types.

Take the following reduced example:
struct s { constexpr static bool true_value() { return true; } };
void assert_on(s const& ref)
{
    static_assert(ref.true_value());
}

int main()
{
    assert_on(s{});
}

gcc-9 wrongly accepts it1, but clang-8 produce the right diagnostic:

error: static_assert expression is not an integral constant expression

Full demo: https://godbolt.org/z/t_-Ubj

1) This is GCC bug #66477, active from version 5.1 and yet to be resolved.
Comment: So, then is there a way to achieve what I intended to do i.e statically check whether the bitset member of the passed in variable(by ref) is enough to accommodate the integer?
Comment: This is half the answer, the other half is http://eel.is/c++draft/expr.const#4.12
Answer: With pointers from others1, it appears to be a compiler bug in both gcc and clang. It's fixed in gcc 5.1 but is, as of 2019-07-25, still a bug in clang 8.0
This is a bug of gcc, introduced in version 5.1. See other answer.

1)

Seems to be a (now fixed) compiler bug as it complies with the latest gcc version: https://godbolt.org/z/ZaDXED
Comment: Is it possible that it's a gcc's bug, clang is correct?
Comment: @songyuanyao Clang isn't the only one complaining. See e.g. [this](https://godbolt.org/z/7ORbU3).
Comment: @songyuanyao after reading it more carefully, I'm convinced. See other answer.


How do I externally backup my Switch game saves?

Question: When selling a Nintendo Switch, how can I backup game save content so I can access it in the future? I know Nintendo Online has game save backup for the duration of the subscription but I'm looking for something lasting longer, since it doesn't make sense to pay for a subscription without having the device.
Answer: According to Nintendo Support Q&A, this unfortunately cannot be done.

Save data (saved game progress and related achievements, etc.) is without exception stored in the system memory. It cannot be moved or saved onto a microSD card.

So, it would seem the only way to backup Switch saves is to use Nintendo's online services for their cloud backups.
Comment: You can also transfer saves to a second nearby Switch (System Settings > Data Management > Transfer Your Save Data > Send Save Data to Another Console), but that deletes the save from the original console, so is no good as a backup.


Allowing numbers from 1 to 100 with EditorFor

Question: I've tried to use the following RegEx annotation, but it didn't work:
[RegularExpression(@"([0-9]|[0-9]\d|100)$"]

(this answer suggest that it's a bad approach)
I also tried with maskedInput 1.2.2 (jQuery), but it won't accept any single digit value
jQuery(function ($) {
    $("#MyControl").mask("99"); //also tried "9?9"
});

Is it ever possible to have a mask accepting value from 1 to 100 only?
Comment: Are you talking about data validation or are you talking about input typing restriction to not allow people to type in i.e. "abc" in an input field? Because these two are different and none of the server-side data annotations will help you with the latter.
Comment: @RobertKoritnik The sooner the validation, the better for me. So if it's possible to prevent the user from entering anything other then a number from 1 to 100, that'd be nice!
Answer: Have a look at the RangeAttribute.
Comment: @AndréPena: You're wrongly concerned. `RangeAttribute` does set entity property constraints that are being validated. Could be that you've used it on a wrong data type... Similar to what Mathieu likely did. He likely put regular expression on an `int` property which of course didn't do the trick.
Comment: RangeAttribute is not generating validation as far as I'm concerned
Answer: The short answer is "no", since there is an infinite representation of the integers 1-100 (1, 01 , 001, 0001, etc., are all valid representations of the number 1.
You could restrict data entry to the canonical representation (1-9, 11-99, 100) like this:
(100|([1-9][0-9])|[1-9]

That should do the trick.
Comment: Amongst the answers, this will validate first. The form doesn't need to be sumbitted for the user to see that his input is wrong


Minecraft went small

Question: something happened to my Minecraft . I changed language and when I returned back to English everything came up smaller. I cannot get back to my old normal settings. Please help.
Answer: I doubt that this was caused by you changing the language.
I think you accidently changed the GUI Scale setting. Try changing it back to normal.
Comment: thank you so much we turned the GUI Scale on auto and it worked. thanks again for the help!!!!

Minecraft went small


__repr__ decorator fails on subclasses

Question: Background
I wrote a decorator function to modify the __repr__ of a given class, such that when an class instance is called all its attributes are printed to the user. When used in the on the Container class in the example below the decorator __repr__dec behaves as intended.
Input
def __repr__wrapper(self):
    """Show all attributes."""
    return "Attributes: "+", ".join(list(self.__dict__.keys()))

def __repr__dec(func):
    """Replaces the __repr__ function of a class with __repr__wrapper"""
    def call(*args, **kwargs):
        func.__repr__ = __repr__wrapper
        result = func(*args, **kwargs)
        return result
    return call

@__repr__dec
class Container(object):
    def __init__(self, *args, **kwargs):
        self.metadata = args[0]
        for k,v in kwargs.items():
            self.__dict__[k] = v

occ = Container(42, how="now")
occ

Output
Attributes: metadata, how

However when trying to subclass Container I receive a TypeError message:
Input
class Handle(Container):
    def __init__(self, *args, **kwargs):
        Container.__init__(self, *args, **kwargs)

han = Handle(42)

Output
TypeError                                 Traceback (most recent call last)
<ipython-input-17-b4c252411c1f> in <module>()
----> 1 class Handle(Container):
      2     def __init__(self, *args, **kwargs):
      3         Container.__init__(self, *args, **kwargs)
      4
      5 han = Handle(42)

TypeError: function() argument 1 must be code, not str

Question
Why does sub-classing Conatainer fail when using the __repr__dec function? Is it possible to fix this?
Comment: @IgnacioVergaraKausel Metaclasses are overkill here. And "not inherited" is not an accurate description of what's happening. The decorated class object is _replaced_ with the `call` function defined in `__repr__dec`. In other words, `Container` is actually a function, not a class. _That's_ why trying to inherit from it throws an exception.
Comment: Why can't you just define `__repr__` in `Container`?
Comment: I didn't know that decorators don't get inherited. Now this is starting to make sense.
Comment: Your decorator is nothing but a function. You can't subclass functions.
Comment: Is it possible to make a decorator that returns a class instead of a function?
Answer: The problem is that your decorator made Container a function and no longer a class. You can control it very simply:
>>> type(Container)
<class 'function'>

This is because your use of the decorator ends in the following:

declare a undecorated class
class Container:
    ...

use the decorator on it:
Container = __repr__dec(Container)

As __repr__dec returns a function you have indeed change Container into a function able to return objects having the expected __repr__ member, but it is no longer a class.
Your decorator must return a class if you want to be able to later subclass it:
def repr_dec(cls):
    cls.__repr__ = __repr__wrapper
    return cls

Then everything is fine:
>>> Container
<class '__main__.Container'>
>>> occ=Container(42, how="now")
>>> occ
Attributes: metadata, how

And you can successfully subclass it:
>>> class Handle(Container):
    def __init__(self, *args, **kwargs):
        Container.__init__(self, *args, **kwargs)

>>> han = Handle(42, foo="now")
>>> han
Attributes: metadata, foo

Handle class has inherited the __repr__ method from its parent.
Answer: def replace_str(cls):
    class Wrapper:
        def __init__(self, *args, **kargs):
            self.wrapped = cls(*args, **kargs)
        def __getattr__(self, attrname):
            return getattr(self.wrapped, attrname)
        def __str__(self):
            return "Attributes: " + ", ".join(list(self.wrapped.__dict__.keys()))
    return Wrapper

@replace_str
class Container(object):
    def __init__(self, *args, **kwargs):
        self.metadata = args[0]
        for k,v in kwargs.items():
            self.__dict__[k] = v

Using a proxy class could easily achieve this.
also, metaclass could do this:
class PrintKey(type):
    def __new__(meta, classname, bases, namespace):
        namespace['__str__'] = lambda self: "Attributes: " + ", ".join(list(self.__dict__.keys()))
        return type.__new__(meta, classname, bases, namespace)

class Container(object, metaclass=PrintKey):
    def __init__(self, *args, **kwargs):
        self.metadata = args[0]
        for k,v in kwargs.items():
            self.__dict__[k] = v

__repr__ decorator fails on subclasses


My program sometimes writes an extra ] or } at the end of data in json file?

Question: I have written a note taking tool for myself as my first program. Its actually working really well for the most part however sometimes the program will write an extra ]or } at the end of the list or dict stored inside of said json file.
It doesn't happen often and I think it is only happening when I am writing new lines of code or changing existing lines that read/write to said files. I am not 100% sure but that is what it looks like.
For example I have a single list stored in a file and I use the indent="" flag to make sure as it writes the files its a little more readable for me if I ever have to edit said files. Sometimes when running my program after changing up some code or adding code I get an error stating a file has "extra data" in it.
The error looks something like this:
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 2 (char 5791)

and the cause of the error would be something like this:
[
"Help",
"DataTypes",
"test",
"Variables",
]] # the error would be cause by this extra ] at the end of the list

What I don't understand is why does the program sometimes add and extra ] or } at the end of the data in my json files?
Is there something I am doing wrong when I open the file or dump to the file?
Here are some sections of code I have that are used to open files and dump to files:
path = "./NotesKeys/"
notebook = dict()
currentWorkingLib = ""
currentWorkingKeys = ""
#~~~~~~~~~~~~~~~~~~~< USE TO open all files in Directory >~~~~~~~~~~~~~~~~~~~
with open("%s%s"%(path,"list_of_all_filenames"), "r") as listall:
    list_of_all_filenames = json.load(listall)

def openAllFiles(event=None):
    global path
    for filename in os.listdir(path):
        with open(path+filename, "r+") as f:
            notebook[filename] = json.load(f)
openAllFiles()

And here is how I am updating the data in the file. Just ignore the e1Current, e1allcase, e2Current they are used to keep the format of the users input for filenames (dict key) lower case in the dictionaries where the notes are stored and maintain the case the user imputed for a display list. This should not be related to the file read write issue.:
Edit: removed unrelated code per commenters request.
#~~~~~~~~~~~~~~~~~~~< UPDATE selected_notes! >~~~~~~~~~~~~~~~~~~~

            dict_to_be_updated = notebook[currentWorkingLib]
            dict_to_be_updated[e1Current] = e2Current
            with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:
                json.dump(dict_to_be_updated, working_temp_var, indent = "")

I am aware of how to open a file and use the data and how to dump data to said file and update the content loaded in the variables of the program based off the newly dumped data.
Am I missing something important during this process? Should I be doing something to ensure data integrity in the json files?
Comment: @TankorSmash Basically, a [MCVE](http://stackoverflow.com/help/mcve).
Comment: @TankorSmash removed the unrelated stuff
Answer: You are opening files in read-write mode, r+:
with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:

This means you'll be writing to a file that already has data in it, and sometimes the existing data is longer than what you are now writing to the file. That means you'll end up with some trailing data at the end.
You can see this by writing a shorter demo string to a file, then using r+ to write less data to the same file, then reading again:
>>> with open('/tmp/demo', 'w') as init:
...     init.write('The quick brown fox jumps over the lazy dog\n')
...
44
>>> with open('/tmp/demo', 'r+') as readwrite:
...     readwrite.write("Monty Python's flying circus\n")
...
29
>>> with open('/tmp/demo', 'r') as result:
...     print(result.read())
...
Monty Python's flying circus
r the lazy dog

Don't do this. Use w write mode so the file is truncated first:
with open("%s%s"%(path,currentWorkingLib), "w") as working_temp_var:

This ensures your file is cut back to size 0 before you write a new JSON document.
Comment: AHH that makes sense. I will try that. I am not really able to test it because I am not sure what is triggering the problem because it feels a little random however It does look like the correct solution. Thank you for your input. This should do the trick. :D
Comment: @SierrMountainTech: what triggers is that you first write one JSON object, then later on write a JSON object with less data in it. By one character by the looks of it. Should be easy to trigger if you know how much data you are putting into the object; put a lot in, then put less in.
Comment: That makes sense. Some of the files may get a space removed from time to time when I am looking through my notes. However some of the data that is being written is a refresh of existing data (mainly the list of flie_names) and that only gets longer. It never gets shorter. I have not created the function to remove files yet in my program. And sometimes that list runs into the same problem.


How to check for something every tick, but only run a command one time when the condition is met?

Question: I'm making a Minecraft 1.16 datapack and I need to check if a player is in a certain location. I want to check for that condition every tick and then run a function when it is met.
I'm currently using this command: execute as @a[x = 10, y = 56, z = 42, dx = 8, dy = 10, dz = 0] run say Passed
The problem is that when the condition is met, the run say Passed part also executes every tick, which is not what I want.
When the condition is met, I want that command to only run once, and not every tick, while still checking the condition every tick.
But, I also want the command to be able to run again after a second or so.
Could I do this by checking the condition every tick, then running a function that has a timer that only executes a command if it was previously executed 1 or more seconds ago?
Comment: if im understanding correctly you want it to check every tick but not run every tick the condition is met?
Comment: So you want to continually check if the condition is met until the condition is met and then resume the check when the condition is no longer met?
Comment: If you were making an adventure map or something of that nature, I would advise you to hook a command block to a monostable redstone circuit. But I don't think you can do that in a data pack. I suspect the answer you are looking for involves scoreboards in some fashion, but I don't know enough about how they work to provide a more specific answer.
Comment: @Topcode Yes, that's what I'm looking for
Comment: @randomuser922 Pretty much yeah
Answer: you could make a scoreboard that stores a timer, that counts down to 0 and once that 0 is hit, the command can be run again
setup:
/scoreboard objectives add Timers dummy

so you'll run these functions each tick:
execute if score FunctionX Timers matches 1.. run scoreboard players remove FunctionX Timers 1
execute if score FunctionX Timers matches 0 run execute as @a[x = 10, y = 56, z = 42, dx = 8, dy = 10, dz = 0] run function <namespace>:passed

and in passed.mcfunction
scoreboard players add FunctionX Timers 20
say passed

this will make the command run only every 20 gameticks


Can I energize a circuit before it's inspected?

Question: I live in Washington state, and state law requires electrical permits and inspections for locations without a municipal inspector to go through the state Labor and Industries (LNI) department. Homeowners are permitted to do their own electrical work, provided they apply for the appropriate permits and get their work inspected.
LNI's website states:

You must request inspection:

Before you bury or conceal anything
Within 3 days of completing the installation or one day of energizing - whichever occurs first.

It's not explicitly stated, but the second item in this list seems to imply that circuits can be energized before inspection. Is my understanding correct?
Comment: I'm not aware of anything that says you can't. IMO it *does* explicitly state "or [within] one day of energizing". How else would *you* check your work?
Comment: I think the spirit of the law is "you fixed it, great - Now shut it down and call us to check it".
Comment: I just built a house in Washington.  I had electricians doing the work, but everything was energized before inspection.
Comment: Are we talking rough or final? Rough wouldn't be energized. Final will.
Comment: "Within ... one day of energizing" seems clear and explicit enough. It will be on for up to 24 hours before testing...
Comment: I think the point of this is to allow you to energize things and begin testing and using them as long as the inspection is scheduled, without leaving a loophole that would allow you to do evade inspections by leaving things permanently in that "unfinished" state.
Comment: Since you're building anyway, install a generator interlock and an inlet on the side of the building.  You can flip to "generator" and power the house via the inlet, long before you get inspected and approved for utility power.   No, I don't mean an *actual* generator, I was more thinking off your EV's convenience outlet, neighbor, battery pack and the like.
Answer: What you have quoted pretty clearly states that you "must request inspection within one day of energizing," which means they evidently don't expect it to be dead until inspected.
Particularly since I would guess that "requesting inspection" and "inspection happening" are generally separated by some time.


C# inheritance - arrays invalid, lists valid?

Question: This is a newbie question. Why can't I inherit from an array, similar to how I inherit from a list?
For example:

public class Foo
{}

public class FoosArray : Foo[] // invalid "unexpected token" error message
{}

public class FoosList : List<Foo> // valid
{}
Comment: `List` is a class. `Foo[]` is not a class.
Comment: @JohnSaunders That depends on how you define "class". It is a reference type which is not an interface. But I think I know what you mean.
Answer: Arrays are special types. The implementation of arrays is provided by CLR at runtime. Array is the base class for all array types, but there is no class such as Foo[] so you can't inherit from it since there is no implementation.
Comment: Also, `Foo[]`, while being a special type, can be considered a `sealed` type. If I remember correctly, `typeof(Foo[]).IsSealed` returns `true`.
Comment: I noticed both: it is sealed and also not a class in the sense that it can't be inherited from. This answers my question.


Nemo 2.0 does not render desktop correctly with Compiz

Question: I am using Ubuntu without Unity but with Compizan Nemo as file manager. Since the update to Nemo 2.0 it does not render the desktop correctly anymore.
Instead of the background picture I see a black background and every window movement leaves a strange effect on the desktop:

Is this is a bug? Where to post Nemo bugs. Does someone know a workaround?
EDIT: I have created a bug report here.
The problem is, that in Nemo 2.0 it's capability to render the desktop was removed. See here
Answer: Cinnamon is causing problems when running Nemo desktop under Unity. You have to completely remove both packages, add the Nemo only PPA from NoobsLab, the Backports and Cinnamon repositories install Cinnamon packages along with Nemo, finally reinstall and configure Nemo.
Here are the steps that I followed to get Nemo installed independently:

Completely remove Nemo and Cinnamon
sudo apt-get --purge remove nemo cinnamon
Make sure all packages are removed by using Synaptic Package Manager
(there is probably a way to use regex with the apt-get remove command
but I am not comfortable enough to try that) Note: I did this
because some packages were not automatically removed using apt-get, I
searched for both Cinnamon and Nemo to manually select any packages
installed for either package then used the completely remove
option.
Purge all entries for Cinnamon and Nemo from the compiz settings
database
dconf reset -f /org/cinnamon/
dconf reset -f /org/nemo/
Add the NoobsLab PPA and install Nemo Version 5.0~raring~NoobsLab.com
sudo add-apt-repository ppa:noobslab/nemo
sudo apt-get update
sudo apt-get install nemo nemo-fileroller
Add Nemo to the mime defaults
xdg-mime default nemo.desktop inode/directory application/x-gnome-saved-search
Nemo by default is set to handle the desktop but Nautilus overrides that so just disable Nautilus
gsettings set org.gnome.desktop.background show-desktop-icons false

Voilà! Nemo is happily taking care of your desktop again!

Update:
If your desktop is black when you first login:

Open Startup Applications (dash->Startup Applications)
Click "Add"

Name: Nemo
Command: nemo -n
Comment: Start the Nemo Desktop Manager

Reboot and Nemo will start
Comment: The command:

"sudo add-apt-repository ppa:noobslab/nemo"

yields:

"Cannot access PPA (https://launchpad.net/api/1.0/~noobslab/+archive/nemo) to get PPA information, please check your internet connection."

Do you mean:

"sudo add-apt-repository ppa:noobslab/mint"
Comment: Following your directions, after a restart, the desktop is not black, but blank (no desktop icons) (also, I've added the start-up entry, still the same). When I run nemo, a new window opens, and also the rendering problem of the desktop re-occurs. Should we install an older version of nemo (1.x)?
Comment: NoobsLabs simply copies the packages from the WebUpd8 Nemo PPA and re-brands them. So why not use the original? http://www.webupd8.org/2013/10/install-nemo-with-unity-patches-and.html I tend to fix a lot of Nemo stuff for that PPA and usually those fixes arrive weeks and sometimes months later in that other PPA. For instance, at the time I'm posting this comment, the WebUpd8 Nemo PPA has Nemo 2.2.1 (with quite a few extra fixes compared to upstream; I uploaded it to the PPA about 2-3 weeks ago) while the NoobLabs PPA has Nemo 2.2.0 - screenshot: http://i.imgur.com/6KdyRKH.png
Answer: Since I had originally installed nemo following the instructions listed here:
http://www.webupd8.org/2012/12/how-to-install-nemo-file-manager-in.html
I reversed it using ppa-purge instead of manually hunting down all the packages:
sudo ppa-purge ppa:gwendal-lebihan-dev/cinnamon-stable

After that I followed Andy Braham's instructions to used the NoobsLabs PPA for Nemo.
Answer: I had what I think was a closely related problem.  I am running Gnome Shell in Quantal 12.10 and loaded Nemo to replace Nautilus.  Unfortunately, I don't recall how I installed it.
After a while, my desktop failed to render properly.  It looked strange; as-if the theme had been lost.  The Look-and-Feel of Gnome Shell was gone.  The colors made editing filenames on icons impossible.  There were a number of other major annoyances.
I followed Andy Braham's advice (from the accepted answer) to remove the software.  But then I followed the Noob Labs's blog posting http://www.noobslab.com/2013/10/nemo-file-manager-with-extensions-for.html to reinstall Nemo.
After a reboot, the problem was resolved.  I hope it stays resolved.  But I'm not sure, since I saw the problem come and go (mostly come and stay) prior to the fix.
[It really seems that Ubuntu is fragmenting into either a) an unacceptably de-featured desktop OS; or b) a difficult to configure desktop OS.  Hopefully that will improve eventually.]
Answer: I had the same problem, but got it working now with nemo 2.2.1.
What I did was

purge cinnamon-daily completely as mentioned by user114408
sudo ppa-purge ppa:gwendal-lebihan-dev/cinnamon-daily

follow all steps as mentioned by Andy Braham including the update, except I used http://ppa.launchpad.net/webupd8team/nemo/ubuntu instead of noobslab.

I don't have the glitch anymore. I will try install cinnamon again (stable version this time) and if the problem comes back I'll post it here. But since you aren't using cinnamon, the above should work. Worked for me in Ubuntu 14.04 anyway.


AngularJS changing model value in one controller triggers model update in others

Question: EDIT:
Ok I update the example to avoid the loop problem, so back to the original question it sill recalculate B model objects.
In this example:
http://jsfiddle.net/qn2Wa/

<input ng-model="m">
        {{a()}}

<input ng-model="m">
        {{b()}}

JS
function A($scope) {
    $scope.m='a';
    var counter = 0;
    $scope.a = function(){
        console.log("A " + counter++);
        return $scope.m;
    }
}
function B($scope) {
    $scope.m='b';
    var counter = 0;
    $scope.b = function(){
        console.log("B " + counter++);
        return $scope.m;
    }
}

as soon as I change the input value in controller A, it will call b() which is in a totally separate controller.
Why would it recalculate the model objects in the other controllers? Is there a way to avoid this?
If you see the console log you can see that B is printed every time you type something in A input field which is in a totally separate controller and scope.

JUST FOR REFERENCE I keep the original code for the question here.
It has error since it is updating the model in the function call as pointed out by some of the comments, this is fixed in the above code. The error could be moved to a separate question.
http://jsfiddle.net/m8xtA/

<input ng-model="m">
        {{a()}} - {{counter}}

<input ng-model="m">
        {{b()}} - {{counter}}

JS
function A($scope) {
    $scope.m='a';
    $scope.counter = 0;
    $scope.a = function(){
        $scope.counter++;
        return $scope.m;
    }
}
function B($scope) {
    $scope.m='b';
    $scope.counter = 0;
    $scope.b = function(){
        $scope.counter++;
        return $scope.m;
    }
}

Comment: you have this error in the console: `10 $digest() iterations reached. Aborting!`
Comment: @DavinTryon : binding a function (i.e. `{{a()}}`) is a mistake due to angular's internal mechanism and its `$digest` loop which will call `a()` in an endless loop
Comment: @DavinTryon http://www.thinkster.io/pick/PQ1TiYfWQf/digest
Comment: @Cherniv can you explain why this code would produce that error?
Comment: @Utopik do you know of a doc or blog that explains this, just curious. Thanks.
Comment: Question is edited with the example to avoid the digest error.
Comment: @Utopik: binding to a function is very normal thing to do, let's say a() calculate the class name for an element on the page  instead of {{a()}}
Comment: In your case, it is not a "very normal thing". Your new example "works" because you break two-way data binding ( counter is not part of the scope anymore, so angular can't play with it ).
You can bind function if your function does not make any change in the scope (as `sza` pointed it out ).
Why it calls b() function? After each modification of the scope, angular check for changes. How can angular know if the result of b() is new or not, without calling it ? So angular calls b() every time.
It is not obvious, but believe me, using `$watch` is a good practice, and the easiest correct way ;)
Comment: And in your example ( `` ), a() will be executed every time a change is made. ( see http://jsfiddle.net/qn2Wa/5/, check your console )
Comment: It does make sense that a() is called since it is in the same scope as A controller. But b() is in totally different controller and they don't share the scope. So angular should know that changing model object in one scope won't change values in a totally different scope.
Comment: And in the updated example calling function b() does not change any scope variable, so I believe it is a normal thing now.
Comment: @danial I recommend you post it on github and the creator could have a better interpretation. It seems a normal behavior to be but I am not sure.
Comment: @danial : from the above link, you can see $digest is applied to $rootScope, not the current scope. That's why b() is called even if it is from a different scope.
Comment: @Utopik yes I found that in the angular code too, and tried to patch it locally so it would just apply it to ancestors and children but it won't be ideal solution since I don't want to keep patching the new versions. I posted it on [angularjs github](https://github.com/angular/angular.js/issues/3960) and the response was that it is the intended behaviour of angularjs.
Answer: here is a working solution :
http://jsfiddle.net/m8xtA/1/
Using $watch is a good way to accomplish that.
function A($scope) {
    $scope.m='a';
    $scope.counter = 0;
    //executed each time `m' is changed
    $scope.$watch('m',function(){
        $scope.counter++;
    })
}
function B($scope) {
    $scope.m='b';
    $scope.counter = 0;
    //executed each time `m' is changed
    $scope.$watch('m',function(){
        $scope.counter++;
    })
}

Hope this help, cheers
Comment: I updated the original question. I don't want to accomplish what you are suggesting here. I just want to avoid updating one controller model object to recalculate the other controller's.
Answer: During the template rendering, if you change the model or object used for binding the template, it will trigger a new rendering cycle which will end up with a endless loop. It will cause this error 'Error: 10 $digest() iterations reached. Aborting!'.
In your code, when {{a()}} is being rendered, it modifies the object counter by the statement $scope.counter++;, which will trigger the endless loop since in the template {{counter}} needs to be rendered.
(What you see is caused by the broken evaluation, so you will see some funky behavior.)
Comment: Just curious, why then if you declare a different `counter` do you still get the same issue:  http://jsfiddle.net/Cnw7R/
Comment: @DavinTryon Not the case you demonstrated. Since `a()` update the `counter`, and you have `{{counter}}` in the template of controller `A` as well, then it causes the problem. Try to comment `$scope.counter++;` and you will not see the error any more. Does it make sense?
Comment: Thanks, I edited the question to avoid this digest issue. Still the original question remains.


Codeigniter show search results in same view?

Question: On Search view, I have this form :
<form class="form-horizontal col-centered" method="POST"action="Search/search">

            <input type="text" class="form-control" id="inputPassword3" placeholder="Type something" name="title">

                <input class="btn btn-default" type="submit" value="Search"name="submit2">

</form>

Form action is set to : action="Search/search"
Search-controler and seach function in that controler. All work fine, after submit form I get result,but result show in :
 http://localhost/ci/index.php/Search/search

My idea is to show result of function search in same view where is form,so after submit form,to get result on Search view.
Tnx
Comment: its better to use ajax for search purposes since it passes its response to the same html page and you can update your html with the returned response
Comment: I will try now that,tnx
Comment: I would use jqery ajax instead of pure ajax. Keep it simple.
Comment: one advise:do not use function name and class name same.if so that function will treat as constructor(`__construct`) function.
Answer: Try using AJAX to get result in same view.
Ref Ex:
1. Learning how to use AJAX with CodeIgniter

AJAX Codeigniter Example
Comment: I will try,tnx for link!
Comment: Please do not provide only links in your answer.Write some details from the link and refer the links as for more details.
Answer: in your form(action="Search/search") you set controller Search and calling function search. In this case when your function execute it will return data from your search function.
So your URL looks like  http://localhost/ci/index.php/Search/search
If you want remove second search word from URL, you can pass data to index of Search Controller. So this will solved. then it looks like http://localhost/ci/index.php/Search.


Ignore IE's Temprorary Internet Files

Question: I have an ASP.NET 2.0 application that it's static contents (*.js, *.css etc.) are located in the same server but I want to try to use CDN hosting for them.
Last week I've just changed the links of this static contents (<link>,

Ignore IE's Temprorary Internet Files


How to prevent a YAML Deployment Pipeline from running when the Build Pipeline doesn't produce an artifact

Question: We have a build pipeline that gets triggered for a CI build that only publishes artifacts when the build succeeds and is not a PR build nor a Scheduled build.
We only want the release pipeline defined below to run when the build pipeline publishes an artifact. If it doesn't publish an artifact the triggered release pipeline fails.
My understanding that I believe is from reading learn.microsoft.com was that if the resource doesn't produce an artifact it won't trigger a resource trigger (I currently can't find support for that claim). We just added a scheduled nightly build for running some long running tests to the build pipeline.  As configured the conditions on the publish tasks prevented an artifact from being created but the release pipeline is still being triggered and results in a failure.
trigger: none
pr: none
resources:
  pipelines:
  - pipeline: API-Deployment
    source: API-Build
    trigger:
      branches:
        include:
        - refs/heads/main

How do we prevent the release pipeline from running when the build pipeline is triggered by a scheduled or a PR build?  Or how can we inspect to find out whether or not the triggering build produced an artifact so that we can prevent stages/jobs/tasks from running and failing when an artifact doesn't exist?
Answer: The way we ended up addressing this thanks to the help of @Leo Liu-MSFT was by adding a PrepStage that all first tier stages depends upon that uses Azure DevOps REST APIs to call the artifacts endpoint for the triggering pipeline.  Then set the hasArtifacts variable that is used in the condition of subsequent stages that depend on PrepStage.
Below is the YAML of the prep stage and an example of a stage that depends on it.
stages:
  - stage: PrepStage
    displayName: Prep Stage
    jobs:
      - job: JA
        displayName: Deployment Prep Job
        cancelTimeoutInMinutes: 1
        steps:
          - checkout: none
          - task: PowerShell@2
            name: setHasArtifacts
            inputs:
              targetType: 'inline'
              script: |
                $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds/$(triggerPipeRunID)/artifacts?api-version=4.1"
                Write-Host "URL: $url"
                $artifacts = Invoke-RestMethod -Uri $url -Headers @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
                $artifactCount = $artifacts.count
                Write-Host "Artifact Count: $artifactCount"

                if ($artifactCount -gt 0) {
                    Write-Host "Set Variable hasArtifacts to True"
                    Write-Host "##vso[task.setvariable variable=hasArtifacts;isOutput=true]True"
                }
                else {
                    Write-Host "Set Variable hasArtifacts to False"
                    Write-Host "##vso[task.setvariable variable=hasArtifacts;isOutput=true]False"
                }
            env:
               SYSTEM_ACCESSTOKEN: $(System.AccessToken)
          - script: echo "hasArtifacts - $(setHasArtifacts.hasArtifacts)"
            name: echovar

  - stage: SB
    dependsOn: PrepStage
    condition: and(succeeded(), eq(dependencies.PrepStage.outputs['JA.setHasArtifacts.hasArtifacts'], 'True'))
    jobs:
      - job: JB
        condition: and(succeeded(), eq(stageDependencies.PrepStage.JA.outputs['setHasArtifacts.hasArtifacts'], True))
        variables:
          varFromStageA: $[ stageDependencies.PrepStage.JA.outputs['JA.setHasArtifacts.hasArtifacts'] ]
          varFromStageA2: $[ stageDependencies.PrepStage.JA.outputs['setHasArtifacts.hasArtifacts'] ]
        steps:
        - checkout: none
        - script: |
            echo "varFromStageA: $(varFromStageA)"
            echo "varFromStageA2: $(varFromStageA2)"

A couple of things worthy of note that were hard to find.  First notice the two different syntaxes for referencing the variable hasArtifacts in the conditions on stage SB and job JB.  We are only using the condition at the stage level, but I put both here because of how hard it was to find out how to reference a variable set in one stage as a condition of a stage that depends upon it. Both of these conditions work.
The second thing to take note of is variable $(triggerPipeRunID) which is used in the url of the rest api request. It is defined above the stages
trigger: none
pr: none
resources:
  pipelines:
  - pipeline: API-Deployment #Azure DevOps has lots of names for this. Most common seems to be "PipelineIdentifier" see variable below.  Another is less descriptive name is "Alias".
    source: API-Build  #this is the name of the build pipeline as specified in Azure DevOps Pipelines UI
    trigger:
      branches:
        include:
        - refs/heads/main

variables:
- name: triggerPipeRunID
  value: $(resources.pipeline.API-Deployment.runID)

This is working for us now.  While it still triggers the Release pipeline even when the API-Build doesn't produce an artifact, the deployment stages are skipped and the pipeline run doesn't get recorded as a failure.
Answer: Thanks for posting in Developer Community.
I'm afraid there is no such out-of-the-box way to prevent the release pipeline from running when the build pipeline doesn't produce an artifact when you use the resource pipeline trigger.
That's because artifact resource triggers are not currently supported. You could check the document Define resources in YAML:
Current support resource trigger type:
resources:
  pipelines: [ pipeline ]
  builds: [ build ]
  repositories: [ repository ]
  containers: [ container ]
  packages: [ package ]
  webhooks: [ webhook ]

On the other hand, when we use pipeline resource triggers, there is no artifact filter for us to restrict whether an artifact is included in the resouorce:
Evaluation of artifact version.
As workaround, we could use the Classic pipeline instead of the YAML for the release pipeline, so that we could select the artifact source:

If you still want use the YAML, you could remove the pipeline resource triggers, then add the one powershell task to invoke REST API to trigger the release pipeline with the condition:
and(succeeded(), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI'))


Comprehensive guide to setup android sdk with eclipse on Ubuntu 14.04 LTS 64 bit

Question: I have shifted to Ubuntu only few weeks ago and after setting up Ubuntu my first step was to setup Eclipse for android development. I do not have any knowledge of Linux. I have searched on google and on this website for a comprehensive guide. Most of the guides are for older versions of Ubuntu and most of the instructions are not working for me. As I am not very well-versed in linux so often I had to start over with clean copy of Ubuntu.
I have found this guide that have ultimately made the android development worked for me.
Hopefully it will help other users too.
Comment: Thank you very much for sharing this, it is better to split it into 2 parts: a question and an answer. See [About] To understand the AskUbuntu model. Also https://askubuntu.com/help/self-answer
Comment: To install the Android SDK with eclipse, first make sure you [install openjdk-?-sdk and openjdk-?-jre](http://openjdk.java.net/install/) (preferably the latest available) and you can download the package (32 or 64 bit) from: http://developer.android.com/sdk/index.html#download and this link shall guide you further with getting the bundle installed: http://developer.android.com/sdk/installing/index.html?pkg=adt. Also, check this askubuntu answer: http://askubuntu.com/a/466245/212123
Answer: The following are the steps in setting up android SDK on ubuntu 14.04:
<code># ++++++++++++++++++++++++++++++
# apt-get update and upgrade
# ++++++++++++++++++++++++++++++
sudo apt-get update
sudo apt-get upgrade

# ++++++++++++++++++++++++++++++
# For development
# ++++++++++++++++++++++++++++++
sudo apt-get install build-essential

# ++++++++++++++++++++++++++++++
# Git
# ++++++++++++++++++++++++++++++
sudo apt-get install git
git --version
#git version 1.9.1

# ++++++++++++++++++++++++++++++
#  (required for adb)
# ++++++++++++++++++++++++++++++
#bash: /usr/local/android-sdk-linux/platform-tools/adb: No such file or directory
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0
#adb: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory
sudo apt-get install g++-multilib

# ++++++++++++++++++++++++++++++
# Android SDK
# ++++++++++++++++++++++++++++++
# http://developer.android.com/sdk/index.html
# DOWNLOAD FOR OTHER PLATFORMS - SDK Tools Only - Linux 32 & 64-bit
# android-sdk_r22.6.2-linux.tgz
tar zxvf android-sdk_r22.6.2-linux.tgz
mv android-sdk-linux android-sdk_r22.6.2-linux
sudo mv android-sdk_r22.6.2-linux /usr/local/
sudo ln -s /usr/local/android-sdk_r22.6.2-linux /usr/local/android-sdk-linux
echo '' >> ~/.profile
echo '# Android SDK' >> ~/.profile
echo 'export ANDROID_SDK_HOME="/usr/local/android-sdk-linux"' >> ~/.profile
echo 'export PATH="$PATH:$ANDROID_SDK_HOME/tools"' >> ~/.profile
echo 'export PATH="$PATH:$ANDROID_SDK_HOME/platform-tools"' >> ~/.profile
source ~/.profile

# ++++++++++++++++++++++++++++++
# Android NDK
# ++++++++++++++++++++++++++++++
# https://developer.android.com/tools/sdk/ndk/index.html
# Linux 64-bit (x86)
# android-ndk-r9d-linux-x86_64.tar.bz2
tar xjvf android-ndk-r9d-linux-x86_64.tar.bz2
mv android-ndk-r9d android-ndk-r9d-linux-x86_64
sudo mv android-ndk-r9d-linux-x86_64 /usr/local/
sudo ln -s /usr/local/android-ndk-r9d-linux-x86_64 /usr/local/android-ndk-linux
echo '' >> ~/.profile
echo '# Android NDK' >> ~/.profile
echo 'export ANDROID_NDK_HOME="/usr/local/android-ndk-linux"' >> ~/.profile
echo 'export PATH="$PATH:$ANDROID_NDK_HOME"' >> ~/.profile
source ~/.profile

# ++++++++++++++++++++++++++++++
# Android w/Eclipse
# ++++++++++++++++++++++++++++++

# Run android command
# android

# Android SDK Manager
#   Installed
#     Tools - Android SDK Tools 22.6.2
#   default checked
#     Tools - Android SDK Platform-tools 19.0.1
#     Tools - Android SDK Build-tools 19.0.3
#     Android 4.4.2 (API 19) All
#     Extras - Android Support Library 19.1
#   install 13 packages

# Eclipse - Help - Install New Software...
#   Name: ADT Plugin
#   Location: https://dl-ssl.google.com/android/eclipse/

#   Developer Tools, NDK Plugins

#   Eclipse restart
#   -> Android SDK "Location of the Android SDK has not been setup in the preferences" -> Close
#   -> Welcome to Android Development -> Use exsting SDKs
#   Existing Location: /usr/local/android-sdk-linux
#   -> Next -> Finish

# Confirm : Eclipse - Window - Preferences - Android
</code>
Comment: It would be great if you included the Java installation.


Coding style in javascript

Question: I am interested in your opinion regarding the following code:
            this.skipAdmCharge = function (tot) {
                if (FR.rynTag.hasOwnProperty('prodfix')) {
                    var prodfix = FR.rynTag.prodfix;
                    for (var prop in prodfix) {
                        if (prodfix.hasOwnProperty(prop)) {
                            if (prodfix[prop].key === 'ADM') {
                                tot.amt -= prodfix[prop].price * prodfix[prop].quantity
                            }
                        }
                    }
                }
            }

and this one below:
            this.skipAdmCharge = function (tot) {
                var prodfix = FR.rynTag.prodfix;
                if (prodfix) {
                    for (var prop in prodfix)
                        if (prop && (prop.key === 'ADM'))
                           tot.amt -= prop.price * prop.quantity
                }
            }

Which one do you consider to be better? And if so, why?
Thank you!
Comment: This isn't a matter of "style"; it's a matter of correctness for a given problem in a given context. Without knowing the context it's not possible to give an answer.
Comment: I'm voting to close this question as off-topic because commentary about working programs is appropriate for codereview.stackexchange.com.
Comment: As they don't do the same, the example is a little misleading
Comment: @Pointy I think OP refers to the lack of braces (not sure)
Comment: @dystroy maybe, but the most prominent difference (to me) is the lack of `.hasOwnProperty()` tests in the second code sample.
Comment: @Point I agree it is the `hasOwnProperty()` that is the difference.  While the two codes are not the same, I think the 2nd style is more clear, and probably what the OP intends to accomplish.
Comment: Always use braces. Not using them is prone error
Comment: I thought this question was "primarly opinion based" but it turns out it's mainly "unclear"
Comment: I think this question is OK, the OP just want to know which one is better
Comment: Always use braces to delimit blocks. The additional typing is negligeable compared to the time spent tracking errors upon a single incidence of  adding a code line to the for loop / else branch without thinking of the missing block delimiters.
Answer: Both have few unwanted checks..
Example in case of first one if (prodfix.hasOwnProperty(prop)) is not necessary
In case of second one,  if (prop && not necessary.
 this.skipAdmCharge = function (tot) {
    try {
        var prodfix = FR.rynTag.prodfix;
        if (prodfix) {
            for (var prop in prodfix)
                if (prop.key === 'ADM'))
                    tot.amt -= prop.price * prop.quantity
        }
    } catch (e) {
        console.log("failed to calculate total amount in skipAdmCharge" + e.message);
    }
}

PS:I am also new to JavaScript!

Coding style in javascript


I use plastic 2 x 4 electrical j boxes and the 2 t retainer tabs keep breaking off months after install what am I doing wrong or is there a better?

Question: Screw tight retainer Tabs on plastic 2x4 electrical boxes keep breaking off in wall months after install.
Comment: There's honestly no good reason to use plastic boxes. They don't even cost less than metal, and they are inferior in every way.
Comment: Buy an old work steel box and use the clamps built into it...
Comment: @Ecnerwal, If the metal box is being installed without attachment to a stud, what device do you recommed to clamp it to the back side (inside) of drywall?
Answer: The best solution is to use metal old work boxes instead of the plastic ones. The template that comes with the plastic boxes is usually too big, you have to carefully trace and cut the smallest hole for the box. The plastic ones are OK for switches but often fail when used for outlets because of the pushing and pulling of the plugs. There are plastic boxes that attach to studs if you're dead set on using them. You might have to do a little drywall patching but the tab issue will be solved.
Answer: You are over tightening the screws to the tabs. Do not use a drill. Use an old fashioned screwdriver.
When you feel a bit of resistance  STOP.  Tightening further stresses the plastic around the screws, softening and degrading it. After a few periods of stress the plastic breaks.
Comment: I think you're also implying to use a hand screwdriver, not a drill. A lot of people don't realize hand screwdrivers are a thing lol.
Comment: OH heck yes!   I totally forgot that people use a drill.  I need to state that. Thanks
Comment: It can also help to pre-screw the tabs before you install the box, when you're able to hold the tabs as you screw them in.  Basically run the screw all the way into the tab and back it out again.  This loosens up the threads in the tabs so it's easier to do when the box is in place.


Use standard error of mean or population distribution?

Question: Question:

Marks obtained by certain number of students are assumed to be
  normally distributed with mean 65 and variance 25. If three students
  are taken at random, what is the probability that exactly two of them
  will have marks over 70?

The textbook way to solve it is:
Finding the probability (p) that a student gets more than 70 marks. Then find $3(C)2 * p^2 *  q$
To find the probability(p) the solution first calculates z=$(70-65)/5$
My confusion is that why did it use the standard deviation of the population(5) instead of using mean of the sampling distribution of sample mean which would have been $5/sqrt(3)$?
In general how do I know when to use what because a lot of questions related to normal distribution first calculate the standard error of mean to calculate the z score.
Comment: What does this have to do with the sample mean?  The condition is that exactly two have marks over $70$.  That says nothing about the sample mean.  If the question was about the sum of those students' marks, you might look at the distribution of the sample mean.
Comment: http://stattrek.com/sampling/sampling-distribution.aspx
Consider the question given in the above link in Example 1: It requires to calculate weight of average student but it uses standard error of mean to calculate the z score rather than the population s.d like in this similar question.
Why?
Answer: Since you were given information about all the students taking the test, you know the true population mean and standard deviation. In other words, the problem is trying to get you to relate a score of 70 to the area under the curve. The area under the curve to the left of 70 represents the percentage $p$ of students who got a 70 or worse. In other words, if I randomly pick a student from the class, the chance that they did worse than 70 is $p$. A similar case can be made for the right side of 70. Maybe in terms of a diagram,
$$\text{test score} \Longleftrightarrow z\text{-score} \Longleftrightarrow \text{area under cruve } p.$$
Finally, since each student is independent of each other, you have $n=3$ independent trials with probability $p$ of success. This is a binomial distribution. Hence, the answer the book provided.
Comment: Thanks for answering. I have posted my doubt as a comment to my question.
Answer: In the stattrek example, you are not told the true distribution of the population of students. You only know the average weight and the sd. I take a sample of 50 students and then take the average of these 50 students. I call that $\bar X$. I need to know what is the probability that the average weight $\bar X$ of a sampled student will be less than 75 pounds. Well, when you take the average of 50 students, you are adding up 50 different draws from the population. The CLT implies that $\bar X$ will (approximately) follow a normal distribution. In order to use the normal approximation, you need the average of $\bar X$ and the standard distribution of $\bar X$.
It turns out that the average of $\bar X$ is the true population average
$$\text{avg of }\bar X = \mu_{\bar X} = 80 \text{ lbs.}$$
Using higher statistics, you can show that the standard deviation of
$\bar X$ is
$$\sigma_{\bar X} = \frac{20}{\sqrt{50}}.$$
I ignored the correction factor. I believe this is called the square root law. It is just a fact you have to take for granted in lower stats. Now, you have the average of $\bar X$ and the sd of $\bar X$. Next, it is just a matter of using the usual techniques to use the normal approximation.
Comment: No problem. Up votes and check marks would be greatly appreciated. :)
Comment: Right now I don't have the reputation to upvote but as soon as I have it, I will come back to upvote it :)


How to execute another powershell script with dynamic path, optional parameter and array parameter?

Question: From a main PowerShell script I want to call another PowerShell script with an optional parameter and another non optional string array parameter. Something like this (with the dysfunctional call included for explanatory reasons):
$theOptionalParam = "maybe"
$theArrayParam = "A", "B"
$theDirectory = "SomeRelativePath"

#This is the part not working:
.\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam

The SubScript.ps1 starts off like this:
[CmdletBinding()]
Param(
   [Parameter(Mandatory=$false)][string]$OptionalParam,
   [Parameter(Mandatory=$true)][string[]]$ArrayParam
)

But no matter what I try, I get an error or simply the first value of the array ("A") and the rest is discarded.
How do I execute the subscript correct with both the dynamic path, optional parameter and array parameter?
Comment: `& .\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam`
Comment: @mhbuur Please post the exact error message in the question
Comment: It is working for me that way. If you have different behavior, then you should include command, that you actually trying, along with error message, you got.
Comment: @PetSerAl - Thanks alot - it was my ISE session that went sour. I restarted and now it works. Put that into an answer and I'll accept :-)
Answer: To interpret .\$theDirectory\SubScript.ps1 as expandable string and expand value of $theDirectory variable, you should use invoke operator &.
& .\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam

You can see that by looking at parsed AST:
{& .\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam}.
Ast.EndBlock.Statements[0].PipelineElements[0].CommandElements[0].GetType().Name
# ExpandableStringExpressionAst
{.\$theDirectory\SubScript.ps1 -OptionalParam $theOptionalParam -ArrayParam $theArrayParam}.
Ast.EndBlock.Statements[0].PipelineElements[0].CommandElements[0].GetType().Name
# StringConstantExpressionAst

As you can see, if you does not use & invoke operator, then .\$theDirectory\SubScript.ps1 interpreted as constant string, not as expandable string.


If a ring has no zero-divisors and it contains a nonzero element $b$ such that $b^2 = b$, then show that $b$ is the unity for that ring

Question:
Suppose that $\mathbb{R}$ is a ring with no zero-divisors and that $\mathbb{R}$ contains a nonzero element $b$ such that $b^2 = b$. Show that $b$ is the unity for $\mathbb{R}$.

I attempted to show that $ab=a$ as $b$ is the unity for that ring. Now, with that assumption, $$(ab)^2=a^2$$
$$\implies abab=a^2$$
Multiplying both sides by $b$ and using $b^2=b$ we get:
$$abab=a^2b=a(ab)$$
Not only can we not take inverse on both sides (as it is not mentioned), but this kinda seems like a circular proof. I proved what I assumed so it is definitely incorrect.
I am unable to come up with any other method. What is the correct proof here?
Answer: Let $a\in R$ an arbitrary, nonzero element. Then $ba = b^2a \implies (b^2-b)a =0 \implies b^2-b=0\implies b(b-1)=0 \implies b=0 \text{ or } b=1$, but since we have assumed $b\neq 0$ we have $b=1$ (unity in the ring)
Edit:
There actually isn't really any need for the arbitrary element $a$ -- we could just have easily have said $b^2=b \implies b^2-b=0$ and worked from there. Sorry for the  extraneous detail.
Comment: Correct! But, in your problem statement you assume that the ring has no zero divisors. So since we have $(b^2-b)a =0$ and we assume $a\neq0$, we must have that $b^2-b=0$
Comment: I was taught in a ring if $ab=0$ we cannot assume $a=0$ or $b=0$
Comment: @GaurangTandon when someone teaches something you should make sure they teach you *why*
Answer: One has to show that $ab=a$ for all $a$. Consider the product $x:=(ab-a)b$. By distributivity $x=ab^2-ab=ab-ab=0$. Since $b\not=0$ we get $ab-a=0$ as desired.
Note that it is not necessary to assume that the ring has a multiplicative unit. This follows from the assumptions.
Answer: Let $e$ be the unit element of $R$. Then $e^2=e$ and $ae=a=ea$ for all $a\in R$. Thus $b(e-b) = be-b^2= b-b=0$ and so $e-b = 0$ since $R$ has no zero divisors and $b\ne 0$ by hypothesis. Hence, $b=e$.


How is PHP fsockopen different from WebSockets in HTML5?

Question: Is it only the server side vs. client side?
Can you have an instant message sent via PHP's fsockopen or am I limited due to polling with Javascript on the other side, the client?
Comment: websockets are a html5 facility. fsockopen is to open a regular tcp socket. you might have problems with fsockopen with firewalls and negotiation.
Comment: Can you tell me what "html5 facility" means?
Comment: maybe part of html5 spec is a better way to describe it.
Answer: fsockopen creates the "normal" system sockets and thus can be used to connect to mail servers etc. WebSockets look similar at first but they are bidirectional data transfer encapsulated inside a HTTP(S) connection. This means, that you cannot use them to directly connect to mail servers etc. Instead you would need to have a WebSocket peer which forwards the data to plain sockets.


Function of exponential order whose derivative is not

Question: I am looking for a function of exponential order(i.e. bounded in absolute value by $Me^{ct}$ for some $M, c$) whose derivative is not of exponential order.
My thought was to look for functions which oscillate wildly between + and - in continually decreasing "periods," but I'm having trouble finding specific functions. Any help is appreciated.
Answer: How about this: $\sin(e^{t^2})$


Windows Defender Firewall has blocked some features of Android Studio

Question: Should I allow the application to access? Which choice should I choose if I allow it to access, private networks or public networks or both? Thanks!
Comment: You can trust Android Studio if you download it from the right source. So don't worry about that just allow it.
Comment: Thanks for you reply! Yes, I downloaded it from the main site. So, I should check both choices?
Comment: Of course, it won't harm your PC
Answer: You should allow both,   as it needs to download 3rd party libraries  from time to time.