Q: How to Format TextBox While Typing? When the user types in the textbox i want it to format itself with decimals.
For example, if the user types 10000 I want it to show up like 10,000 while he types it.

A: Here you go.  Handing backspace/delete made it especially challenging.  That was fun! :-)
I have added this to my online portfolio of scripts at rack.pub.

function toast(a,b){b||(b=2750);var c={message:a,timeout:b};snackbarContainer.MaterialSnackbar.showSnackbar(c)}var doc=document,textArea=doc.getElementById("area"),numArray=[],backArray=[],num="",numF="",regx="",thisChar="",lastChar="",str="",index=0;window.snackbarContainer=doc.querySelector("#toast"),textArea.addEventListener("keydown",function(){var a=event.keyCode;if(str=this.value,(8==a||46==a)&&(backArray=[],index=str.length-1,lastChar=str.charAt(index),!isNaN(lastChar)||","==lastChar))for(var b=str.length-1;b>=0;b--){if(" "==str.charAt(b))return;if(isNaN(str.charAt(b))&&","!=str.charAt(b))return;backArray.push(str.charAt(b))}if(32==a&&backArray[1]){var c=backArray.reverse().slice(0,-1).join(""),d=c.replace(/\,/g,""),e=Number(d).toLocaleString().toString(),f=str.lastIndexOf(c);f>=0&&f+c.length>=str.length&&(str=str.substring(0,f)+e),this.value=str}}),textArea.addEventListener("keypress",function(){if(thisChar=this.value.slice(-1),isNaN(thisChar)){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);this.value=a}else{if(" "==thisChar){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);return void(this.value=a)}numArray.push(thisChar)}});
        html body {
            font-family: 'Roboto', sans-serif;
            background: #f5f5f5;
        }
        .text-right{
            text-align:right;
        }
        .text-center{
            text-align:center;
        }
        .text-left{
            text-align:left;
        }
        .thin{
            font-weight: 100;
        }
        .heading{
            font-size:3em;
        }
        .subtitle{
            margin-top: -16px;
        }
        #submit{
            margin-top:10px;
        }
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.indigo-pink.min.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">

commas.js demo

                        JavaScript to automatically add commas to numbers in a text area

                        Basically it auto formats numbers as you type in the text area.  Give it a try.

                    <textarea class="mdl-textfield__input" type="text" rows= "3" id="area" ></textarea>
                    Type Here...

A: use replace and a regex then just Queue that up on keyup.
$(selector).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//will replace with commas

A: That problem proved to be more challenging than I expected (I should have known better). Here is what I got, using vanilla Javascript.
You can set event handler for the onkeyup event of the TextBox:
<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />

And here is the Javascript code:

Credits:
CMS's solution to extract digits from string in Regex using javascript to return just numbers.
Alan Moore's regular expression to insert thousand separators in How do I add thousand separators with reg ex?.
Note: Ron Royston's idea of using toLocaleString is also very interesting. It could provide a more universal solution. You could replace this line of processKeyUp:
txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

with the following:
txt.value = Number(extractNumber(value)).toLocaleString();

A: Try an input mask, here is an example:
http://digitalbush.com/projects/masked-input-plugin/

A: You can use jquery masking framework
references:
Jquery Masking
Source at git


Q: How to debug application as root in Geany on Raspbian Jessie Having installed Geany on a Raspberry Pi and added the Debugger plugin, I need the debugger to run the application as root as I am accessing the GPIO libraries and pins on the Raspberry Pi.
I usually run the program using sudo ./programName
I cannot find an option in the debug settings to prefix the debug target with sudo.

A: Try running geany with sudo geany.


Q: MS Teams - TaskModule close the window I display a third party web page(client page) in the task module

*

*using Deeplink
https://teams.microsoft.com/l/task/botid?url=https:test.com/test.html&height=450&width=510&title=Custom+Form&completionBotId=botid

*new AdaptiveOpenUrlAction() { Title = "Enable MS Team access", Url = new Uri(DeeplinkHelper.DeepLink }

Here the web page is opening in Task module, I need to close this task module by clicking the button available on the web page(URL) and send the result to completionBotId.
Any sample pls that need to implement in client-side code.

A: There are two steps to make this work:

*

*you need to reference the Teams Javascript SDK in your web page

*When your user clicks the button, you would call microsoftTeams.tasks.submitTask  in your 'click' event handler. There are a few parameter options for this method, depending on whether you want it to send anything back to your bot. To simply close the window, call microsoftTeams.tasks.submitTask(null);, or if you want to send an object back, call microsoftTeams.tasks.submitTask(whateverObjectYouWantToSendBack);


Q: DialogWhenLarge adjustResize not working The activity theme is Theme.AppCompat.Light.DialogWhenLarge. I can not get the activity to resize when keyboard is up. Configuring android:windowSoftInputMode="adjustResize" or getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
 has no effect, all I'm getting is adjustPan behaviour. However, I can confirm that adjustNothing works. Any ideas how to make an activity with DialogWhenLarge theme to resize with keyboard?
Result with adjustResize:

Result with adjustNothing:

A: I've found a workaround, but would still like to hear if anyone had a similar problem.
Workaround:

*

*Replaced Activity's theme DialogWhenLarge with Theme.AppCompat.Light.Dialog. This allows the adjustResize to behave as expected with ActionBarActivity

*Added toolbar.xml layout as android.support.v7.widget.Toolbar

*Assigned the toolbar as action bar in my Activity

*Set activity's height for 10' tablets layout-sw720dp to 500dp for better presentation

Configure toolbar as action bar:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout...);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
}

More on toolbar at android developer blog and stackoverflow


Q: When drilling down, how to retrieve the parent? In a dimension I have
1st layer > 2nd layer
I display a chart with values from 1st layer and drilling down to 2nd layer when clicked on.
Once clicked, the graph displays value for the children, so 2nd layer only.
How do I retrieve and display the 1st layer that was clicked on ?

A: Charts can generate iccube-events for a couple of js events (I guess here on row click).
Check the image below :

Edit:
For a bar chart, use "On Navigate" event.


Q: How to add an image to be returned by a map in REACT (JS) I'm building a chatbox, on a card I have a messageList that I made with useState:

I'm trying to add images to the initMessageList to be displayed on the card with preview using useRef but it does not show the image (I'm changing the 'messageList' func):

function ConvBoard({ name }) {
const [initMessageList, setMessageList] = useState([])

const messageList = initMessageList.map((now, key) => {
    if (now.Image) {
        return
    }
    return <Message text={now.text} key={key} />
});

let newText = useRef(null);

const addMessage = () => {
    if (newText.current.value != "") {
        setMessageList([...initMessageList, {
            text: newText.current.value,
            key: initMessageList.length
        }])
        newText.current.value = ""
    }
}

const onKeyFunc = function onKeyEnter(e) {
    if (e.key === "Enter" && newText.current.value != "") {
        { addMessage() };
    }
}

const [image, setImage] = useState();
const [preview, setPreview] = useState();

const pressRef = useRef();

useEffect(() => {
    if (image) {
        const reader = new FileReader()
        reader.onloadend = () => {
            setPreview(reader.result)
        };
        reader.readAsDataURL(image)
        setMessageList([...initMessageList, {
            text: preview,
            key: initMessageList.length
        }])
    } else {
        setPreview(null)
    }
}, [image]);

return (
    <Tab.Pane eventKey={name}>
        <Card className='card'>
            <extraWarper className="extra">
                {messageList}
            </extraWarper>
        </Card>
        <InputGroup>
            <FormControl className='inputLine' ref={newText}
                placeholder="your text" onKeyPress={onKeyFunc}
            />
            <Button variant="outline-secondary">record</Button>
            <DropdownButton title="upload" variant="outline-secondary">
                <button onClick={(event) =>
                    pressRef.current.click()
                }>
                    Send image
                </button>
                <input ref={pressRef} id="filePicker" style={{ display: "none" }} type={"file"}
                    onChange={(event) => {
                        const file = event.target.files[0]
                        if (file) {
                            setImage(file)
                        } else {
                            setImage(null)
                        }
                    }
                    } />
            </DropdownButton>
            <Button variant="outline-secondary" onClick={addMessage}>send</Button>
        </InputGroup>

    </Tab.Pane>
);

export default ConvBoard
}
now the site looks like this:

but when i try to add an Image its blank.
Any ideas?
(Sorry for the mess, and thank you!)

A: There is no now.Image in this code.
    if (now.Image) {
        return
    }
    return <Message text={now.text} key={key} />
});

there may be now.Text which represents now.Image and preview in your code
because you set it in this part of code
 setMessageList([...initMessageList, {
            text: preview,
            key: initMessageList.length
        }])


Q: Mysql SELECT query returns false when ran in PHP I'm trying:
$mysqli = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$usernames_results = $mysqli->query("SELECT username FROM users WHERE user_id = $member_id") or trigger_error($mysqli->error);
while($user_row = $username_results->fetch_object()) {
// do stuff with$user_row
}

This always returns FALSE. I'm certain $member_id is not null and that it does exist in the database. I ran the SQL query directly on the database and it returns the correct result. The error I get is

Fatal error: Call to a member function fetch_object() on a non-object`

when calling fetch_object() on $usernames_results.
$mysqli is also defined correctly because this works:
$conversations_results = $mysqli->query("SELECT UserID, ConversationID FROM Conversation_Members WHERE UserID = $user_id");

I have tried looking at $mysqli->error but it's empty.
What am I doing wrong in the first query?
This question has been wrongly marked duplicate before. Please do not mark this as a duplicate unless you're certain the suggested duplicate answers my problem.


Q: Tkinter quit button I just started learning python and I have a problem that I canno't get a button to close my program. The code:
from tkinter import *
import ScoreboardController as SC

class guiController(Frame):

    def open_scoreboard(self):
        scoreBoard = SC.ScoreboardController("scores.txt")
        for x in range(len(scoreBoard)):
            print("Name: {} \nScore: {}". format(scoreBoard[x].name, scoreBoard[x].score))

    def start_game(self):
        pass

    def hide_main_window(self):
        self.score_button.pack_forget()
        self.start_button.pack_forget()

    def create_widgets(self):

        self.frame = Frame(master=None, width=800, height=600)
        self.frame.pack()

        self.start_button = Button(self.frame)
        self.start_button["text"] = "Játék indítása"
        self.start_button["bg"] = "#5E99FF"
        self.start_button["fg"] = "#ffffff"
        self.start_button["command"] = self.start_game
        self.start_button.pack()
        self.start_button.place(x=300, y=455, bordermode=OUTSIDE, height=50, width=200)

        self.score_button = Button(self.frame)
        self.score_button["text"] = "Eredmények"
        self.score_button["bg"] = "#5E99FF"
        self.score_button["fg"] = "#ffffff"
        self.score_button["command"] = self.open_scoreboard
        self.score_button.pack()
        self.score_button.place(x=300, y=400, bordermode=OUTSIDE, height=50, width=200)

        self.quit_button = Button(self.frame)
        self.quit_button["text"] = "Kilépés"
        self.quit_button["bg"] = "#5E99FF"
        self.quit_button["fg"] = "#FFFFFF"
        self.quit_button["command"] = self.destroy()
        self.quit_button.pack()
        self.quit_button.place(x=300, y=510, bordermode=OUTSIDE, height=50, width=200)

    def __init__(self, master=None):

        Frame.__init__(self, master)
        self.place()
        self.create_widgets()

When I click the button it doesn't do anything (self.quit_button).
The other buttons work.
Thank you in advance

A: I could not fully test your code however here is what you would do when needed to destroy master. Your code was a bit hard to test please in the future do not include stuff that cannot be tested like your ScoreboardController. Also I rewrote your buttons to something simpler.
import tkinter as tk

class Example(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.create_widgets()

    def start_game(self):
        pass

    def hide_main_window(self):
        self.score_button.pack_forget()
        self.start_button.pack_forget()

    def create_widgets(self):
        self.start_button = tk.Button(self, text="Játék indítása", bg="#5E99FF", fg="#ffffff")
        self.start_button.pack()

        self.score_button = tk.Button(self, text="Eredmények", bg="#5E99FF", fg="#ffffff", command=self.start_game)
        self.score_button.pack()

        self.quit_button = tk.Button(self, text="Kilépés", bg="#5E99FF", fg="#ffffff", command=self.master.destroy) # without ()
        self.quit_button.pack()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack() # root passing to master in the Frame class
    root.mainloop()


Q: is_dir folder permission Unix I have a simple PHP script (who.php):
<?php
echo `whoami`;
echo is_dir('/home/pdfs/')?'Yes':'No';

/home/pdfs is user1:www and has 770 permissions.
PHP is wwwrun in the group www.
1) if I do sudo -u wwwrun php who.php I get
wwwrun
No

2) If I do sudo -u user1 php who.php I get
user1
Yes

Why is is_dir returning FALSE in the first case?

A: wwwrun doesn't have permissions to read /home and hence can't directly verify that /home/pdfs in fact even exists, much less that it is a directory.


Q: Parsing Adafruit Ultimate GPS in Arduino Im new in Arduino programming and i have quite a problem which is save longitude and latitude values of my new Adafruit Ultimate GPS Breakout. im using the tutorial giving in the website then i tried to apply parsing code in the library
Open up the File→Examples→Adafruit_GPS→parsing sketch and upload it to the Arduino. Then open up the serial monitor.
i got the results in my serial monitor as shown in the attached file (i highlighted my question in the snap below)
Im trying to save the values of my location in the degree which is appear in the serial monitor as
Location (in degrees, works with Google Maps): 32.5011, 44.4499
A part of the standard code for display result is:
Serial.print("\nTime: ");
    Serial.print(GPS.hour, DEC); Serial.print(':');
    Serial.print(GPS.minute, DEC); Serial.print(':');
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    Serial.println(GPS.milliseconds);
    Serial.print("Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", ");
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      Serial.print("Location (in degrees, works with Google Maps): ");
      Serial.print(GPS.latitudeDegrees, 4);
      Serial.print(", ");
      Serial.println(GPS.longitudeDegrees, 4);
      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      Serial.print("Angle: "); Serial.println(GPS.angle);
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);

the results is shown below

next i tried to define 2 variable in order to copy the longitude and latitude value by adding simple code after the Serial.println(GPS.longitudeDegrees, 4); as shown below
Serial.print("Location (in degrees, works with Google Maps): ");
      Serial.print(GPS.latitudeDegrees, 4);
      Serial.print(", ");
      Serial.println(GPS.longitudeDegrees, 4);
      lat1= (GPS.latitudeDegrees, 4);
      lon1=(GPS.longitudeDegrees, 4);
      Serial.println (lat1);
      Serial.println (lon1);
      delay (500);

then i got only number four in my lat1 and lon1 value in serial monitor

then i edit the code by removing number 4 from it as shown below
Serial.print("Location (in degrees, works with Google Maps): ");
  Serial.print(GPS.latitudeDegrees, 4);
  Serial.print(", ");
  Serial.println(GPS.longitudeDegrees, 4);
  lat1= GPS.latitudeDegrees;
  lon1=GPS.longitudeDegrees;
  Serial.println (lat1);
  Serial.println (lon1);
  delay (500);

then i got only 2 number after the dot
32.5011 → 32.50
44.4499 → 44.45
as shown in the attached below

so im asking how can i save the full number in my lon1 and lat1 because i need these number for further analysis
BTW i tried to defie lon1, lat1 as float, double and still same issue just 2 number after digit i got
thank you all

A: Floating point numbers have an infinite number of decimal places.  When you print them it will only print 2 unless you specify with the second parameter how many to print.
For example:
float x = 67.1234

Serial.print(x); // will print 67.12
Serial.print(x,3); // will print 67.123
Serial.print(x, 4); // will print 67.1234
Serial.print(x,6);  // will print 67.123400

So what you are seeing is just how many places  you told it to print.  But the variable always has the whole number with an infinite number of decimal places.
Now with floats on an Arduino only the first 6 or 7 decimal places will be accurate.  But the number itself has an infinite number of digits after the decimal if you want to print them.
Also note that the second parameter is only doing something in the print statement.  Lots of people will try to do this:
float x = 67.1234 , 2;

thinking that this will somehow save a number with only 2 digits of precision, but this isn't the case.  In this case it would just save the number 2.  As you saw in your experiment.  This is how the comma operator works.  It's only in the print function that you get to specify.  Again, the actual number itself has an infinite number of decimal places you can print.


Q: User Initiated Kernel dump in Windows XP I remember watching a webcast from Mark Russinovich showing the sequence of keyboard keys for a user initiated kernel dump. Can somebody refresh my memory on the exact order of the keys.
Please note this is for XP.

A: http://psacake.com/web/jr.asp contains full instructions, and here's an excerpt:

While it may seem odd to think about purposefully causing a Blue Screen Of Death (BSOD), Microsoft includes such a provision in Windows XP. This might come in handy for testing and troubleshooting your Startup And Recovery settings, Event logging, and for demonstration purposes.

Here's how to create a BSOD:

Launch the Registry Editor (Regedit.exe).
Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters.
Go to Edit, select New | DWORD Value and name the new value CrashOnCtrlScroll.
Double-click the CrashOnCtrlScroll DWORD Value, type 1 in the Value Data textbox, and click OK.
Close the Registry Editor and restart Windows XP.
When you want to cause a BSOD, press and hold down the [Ctrl] key on the right side of your keyboard, and then tap the [ScrollLock] key twice. Now you should see the BSOD.

If your system reboots instead of displaying the BSOD, you'll have to disable the Automatically
Restart setting in the System Properties dialog box. To do so, follow these steps:

Press [Windows]-Break.
Select the Advanced tab.
Click the Settings button in the Startup And Recovery panel.
Clear the Automatically Restart check box in the System Failure panel.
Click OK twice.

Here's how you remove the BSOD configuration:

Launch the Registry Editor (Regedit.exe).
Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters.
Select the CrashOnCtrlScroll value, pull down the Edit menu, and select the Delete command.
Close the Registry Editor and restart Windows XP.
Note: Editing the registry is risky, so make sure you have a verified backup before making any changes.

And I may be wrong in assuming you want BSOD, so this is a Microsoft Page showing how to capture kernel dumps:
https://web.archive.org/web/20151014034039/https://support.microsoft.com/fr-ma/kb/316450

A: As far as I know, the "Create Dump" command was only added to Task Manager in Vista. The only process I know of to do this is using the adplus VBScript that comes with Debugging Tools. Short of hooking into dbghelp and programmatically doing it yourself.

A: You can setup the user dump tool from Microsoft with hot keys to dump a process.  However, this is a user process dump, not a kernel dump...

A: I don't know of any keyboard short cuts, but are you looking for like in task manager, when you right click on a process and select "Create Dump"?


Q: Is it Compulsory for FlatList that json response should start with [] always? I was using flatlist to display data and in response I am getting some data.
But, the json response string is starting with the {}braces and not with the []brackets.
So, was Getting below error :
Invariant Violation: Tried to get frame for out of range index Nan.
After doing log what am I getting in my dataSource of FlatList is [Object Object]
I have checked json response in postman and its like : {{[]}}, in short its not starting with []brackets.
So, am little confused here that Is it compulsory for FlatList to have dataSource or json response starting with []brackets.
If not then What might be the issue there for the error ? and If is it, the How can I convert it in required format ?
Thanks.
EDIT
Doing like this :
 .then((response) => response.json())
      .then((responseJson) => {

        this.setState({ isLoading: false,dataSource: responseJson.screen_details})

      })
      .catch((error) => {
        console.error(error);
      });

But, Still Issue exists with Objects are not valid as a React child.

A: For FlatList the data property requires an array, as highlighted in the docs. Since FlatList works by taking a list of items and rendering a seperate row for each, the data property needs to be an array.
Once you receive your JSON data, I would recommend only passing the required array to the FlatList, e.g.:
<FlatList
    data={myResponse.listOfItems}
    ...
    />

Where myResponse is your JSON object and listOfItems is your array of items.
Also, according to the docs, there is no dataSource property, the correct property is simply data.


Q: Why can't C compilers rearrange struct members to eliminate alignment padding?
Possible Duplicate:
Why doesn't GCC optimize structs?
Why doesn't C++ make the structure tighter?

Consider the following example on a 32 bit x86 machine:
Due to alignment constraints, the following struct
struct s1 {
    char a;
    int b;
    char c;
    char d;
    char e;
}

could be represented more memory-efficiently (12 vs. 8 bytes) if the members were reordered as in
struct s2 {
    int b;
    char a;
    char c;
    char d;
    char e;
}

I know that C/C++ compilers are not allowed to do this. My question is why the language was designed this way. After all, we may end up wasting vast amounts of memory, and references such as struct_ref->b would not care about the difference.
EDIT: Thank you all for your extremely useful answers. You explain very well why rearranging doesn't work because of the way the language was designed. However, it makes me think: Would these arguments would still hold if rearrangement was part of the language? Let's say that there was some specified rearrangement rule, from which we required at least that

*

*we should only reorganize the struct if actually necessary (don't do anything if the struct is already "tight")

*the rule only looks at the definition of the struct, not inside inner structs. This ensures that a struct type has the same layout whether or not it is internal in another structure

*the compiled memory layout of a given struct is predictable given its definition (that is, the rule is fixed)

Adressing your arguments one by one I reason:

*

*Low-level data mapping, "element of least surprise": Just write your structs in a tight style yourself (like in @Perry's answer) and nothing has changed (requirement 1). If, for some weird reason, you want internal padding to be there, you could insert it manually using dummy variables, and/or there could be keywords/directives.

*Compiler differences: Requirement 3 eliminates this concern. Actually, from @David Heffernan's comments, it seems that we have this problem today because different compilers pad differently?

*Optimization: The whole point of reordering is (memory) optimization. I see lots of potential here. We may not be able to remove padding all together, but I don't see how reordering could limit optimization in any way.

*Type casting: It seems to me that this is the biggest problem. Still, there should be ways around this. Since the rules are fixed in the language, the compiler is able to figure out how the members were reordered, and react accordingly. As mentioned above, it will always be possible to prevent reordering in the cases where you want complete control. Also, requirement 2 ensures that type-safe code will never break.
The reason I think such a rule could make sense is because I find it more natural to group struct members by their contents than by their types. Also it is easier for the compiler to choose the best ordering than it is for me when I have a lot of inner structs. The optimal layout may even be one that I cannot express in a type-safe way. On the other hand, it would appear to make the language more complicated, which is of course a drawback.
Note that I am not talking about changing the language - only if it could(/should) have been designed differently.
I know my question is hypothetical, but I think the discussion provides deeper insight in the lower levels of the machine and language design.
I'm quite new here, so I don't know if I should spawn a new question for this. Please tell me if this is the case.

A: There are multiple reasons why the C compiler cannot automatically reorder the fields:

*

*The C compiler doesn't know whether the struct represents the memory structure of objects beyond the current compilation unit (for example: a foreign library, a file on disc, network data, CPU page tables, ...). In such a case the binary structure of data is also defined in a place inaccessible to the compiler, so reordering the struct fields would create a data type that is inconsistent with the other definitions. For example, the header of a file in a ZIP file contains multiple misaligned 32-bit fields. Reordering the fields would make it impossible for C code to directly read or write the header (assuming the ZIP implementation would like to access the data directly):
struct __attribute__((__packed__)) LocalFileHeader {
    uint32_t signature;
    uint16_t minVersion, flag, method, modTime, modDate;
    uint32_t crc32, compressedSize, uncompressedSize;
    uint16_t nameLength, extraLength;
};

The packed attribute prevents the compiler from aligning the fields according to their natural alignment, and it has no relation to the problem of field ordering. It would be possible to reorder the fields of LocalFileHeader so that the structure has both minimal size and has all fields aligned to their natural alignment. However, the compiler cannot choose to reorder the fields because it does not know that the struct is actually defined by the ZIP file specification.

*C is an unsafe language. The C compiler doesn't know whether the data will be accessed via a different type than the one seen by the compiler, for example:
struct S {
    char a;
    int b;
    char c;
};

struct S_head {
    char a;
};

struct S_ext {
    char a;
    int b;
    char c;
    int d;
    char e;
};

struct S s;
struct S_head *head = (struct S_head*)&s;
fn1(head);

struct S_ext ext;
struct S *sp = (struct S*)&ext;
fn2(sp);

This is a widely used low-level programming pattern, especially if the header contains the type ID of data located just beyond the header.

*If a struct type is embedded in another struct type, it is impossible to inline the inner struct:
struct S {
    char a;
    int b;
    char c, d, e;
};

struct T {
    char a;
    struct S s; // Cannot inline S into T, 's' has to be compact in memory
    char b;
};

This also means that moving some fields from S to a separate struct disables some optimizations:
// Cannot fully optimize S
struct BC { int b; char c; };
struct S {
    char a;
    struct BC bc;
    char d, e;
};

*Because most C compilers are optimizing compilers, reordering struct fields would require new optimizations to be implemented. It is questionable whether those optimizations would be able to do better than what programmers are able to write. Designing data structures by hand is much less time consuming than other compiler tasks such as register allocation, function inlining, constant folding, transformation of a switch statement into binary search, etc. Thus the benefits to be gained by allowing the compiler to optimize data structures appear to be less tangible than traditional compiler optimizations.

A: It would change the semantics of pointer operations to reorder the structure members. If you care about compact memory representation, it's your responsibility as a programmer to know your target architecture, and organize your structures accordingly.

A: If you were reading/writing binary data to/from C structures, reordering of the struct members would be a disaster.  There would be no practical way to actually populate the structure from a buffer, for example.

A: Keep in mind that a variable declaration, such as a struct, is designed to be a "public" representation of the variable.  It's used not only by your compiler, but is also available to other compilers as representing that data type.  It will probably end up in a .h file.  Therefore, if a compiler is going to take liberties with the way the members within a struct are organized, then ALL compilers have to be able to follow the same rules.  Otherwise, as has been mentioned, the pointer arithmetic will get confused between different compilers.

A: Structs are used to represent physical hardware at the very lowest levels.  As such the compiler cannot move things a round to suit at that level.
However it would not be unreasonable to have a #pragma that let the compiler re-arrange purely memory based structs that are only used internally to the program.  However I don't know of such a beast (but that doesn't meant squat - I'm out of touch with C/C++)

A: C is designed and intended to make it possible to write non-portable hardware and format dependent code in a high level language. Rearrangement of structure contents behind the back of the programmer would destroy that ability.
Observe this actual code from NetBSD's ip.h:

/*
 * Structure of an internet header, naked of options.
 */
struct ip {
#if BYTE_ORDER == LITTLE_ENDIAN
    unsigned int ip_hl:4,       /* header length */
             ip_v:4;        /* version */
#endif
#if BYTE_ORDER == BIG_ENDIAN
    unsigned int ip_v:4,        /* version */
             ip_hl:4;       /* header length */
#endif
    u_int8_t  ip_tos;       /* type of service */
    u_int16_t ip_len;       /* total length */
    u_int16_t ip_id;        /* identification */
    u_int16_t ip_off;       /* fragment offset field */
    u_int8_t  ip_ttl;       /* time to live */
    u_int8_t  ip_p;         /* protocol */
    u_int16_t ip_sum;       /* checksum */
    struct    in_addr ip_src, ip_dst; /* source and dest address */
} __packed;

That structure is identical in layout to the header of an IP datagram. It is used to directly interpret blobs of memory blatted in by an ethernet controller as IP datagram headers. Imagine if the compiler arbitrarily re-arranged the contents out from under the author -- it would be a disaster.
And yes, it isn't precisely portable (and there's even a non-portable gcc directive given there via the __packed macro) but that's not the point. C is specifically designed to make it possible to write non-portable high level code for driving hardware. That's its function in life.

A: Your case is very specific as it would require the first element of a struct to be put re-ordered. This is not possible, since the element that is defined first in a struct must always be at offset 0. A lot of (bogus) code would break if this would be allowed.
More generally pointers of subobjects that live inside the same bigger object must always allow for pointer comparison. I can imagine that some code that uses this feature would break if you'd invert the order. And for that comparison the knowledge of the compiler at the point of definition wouldn't help: a pointer to a subobject doesn't have a "mark" do which larger object it belongs. When passed to another function just as such, all information of a possible context is lost.

A: C [and C++] are regarded as systems programming languages so they provide low level access to the hardware, e.g., memory by means of pointers. Programmer can access a data chunk and cast it to a structure and  access various members [easily].
Another example is a struct like the one below, which stores variable sized data.
struct {
  uint32_t data_size;
  uint8_t  data[1]; // this has to be the last member
} _vv_a;

A: Not being a member of WG14, I can't say anything definitive, but I have my own ideas:

*

*It would violate the principle of least surprise - there may be a damned good reason why I want to lay my elements out in a specific order, regardless of whether or not it's the most space-efficient, and I would not want the compiler to rearrange those elements;

*It has the potential to break a non-trivial amount of existing code - there's a lot of legacy code out there that relies on things like the address of the struct being the same as the address of the first member (saw a lot of classic MacOS code that made that assumption);
The C99 Rationale directly addresses the second point ("Existing code is important, existing implementations are not") and indirectly addresses the first ("Trust the programmer").

A: Here's a reason I didn't see so far - without standard rearrangement rules, it would break compatibility between source files.
Suppose a struct is defined in a header file, and used in two files.
Both files are compiled separately, and later linked. Compilation may be at different times (maybe you touched just one, so it had to be recompiled), possibly on different computers (if the files are on a network drive) or even different compiler versions.
If at one time, the compiler would decide to reorder, and at another it won't, the two files won't agree on where the fields are.
As an example, think of the stat system call and struct stat.
When you install Linux (for example), you get libC, which includes stat, which was compiled by someone sometime.
You then compile an application with your compiler, with your optimization flags, and expect both to agree on the struct's layout.

A: suppose you have a header a.h with
struct s1 {
    char a;
    int b;
    char c;
    char d;
    char e;
}

and this is part of a separate library (of which you only have the compiled binaries compiled by a unknown compiler) and you wish to use this struct to communicate with this library,
if the compiler is allowed to reorder the members in whichever way it pleases this will be impossible as the client compiler doesn't know whether to use the struct as-is or optimized (and then does b go in front or in the back) or even fully padded with every member aligned on 4 byte intervals
to solve this you can define a deterministic algorithm for compacting but that requires all compilers to implement it and that the algorithm is a good one (in terms of efficiency). it is easier to just agree on padding rules than it is on reordering
it is easy to add a #pragma that prohibits the optimization for when you need the layout of to a specific struct be exactly what you need so that is no issue


Q: Why toggling a setInterval() which changes a image source is only decreasing the interval time after each toggle? I tried to toggle the setInterval() function by clicking on an image.
On first click it will start to change the image with a time interval that we set. But after the second click the setInterval() function is not being stopped (which I wanted), instead the interval reduces. And the interval keep on reducing after each click. Which means it is not toggling properly. Here is the code:
<!DOCTYPE html>

<title>Learning JavaScript</title>

Click on image to set timer on or off

A: Here's a working example for your problem

var settimernow="off";
var stop;

function change_timer(){
   if(settimernow==="on"){
      clearInterval(stop);
      settimernow="off";
   }
   else{
      stop=setInterval('change()',2000);
      settimernow="on";
       }
}

function change(){
      var img=document.getElementById('browser');
      if(img.src==="https://www.w3schools.com/css/trolltunga.jpg")         {
        img.src="http://hdwallpaperfun.com/wp-content/uploads/2015/07/Big-Waves-Fantasy-Image-HD.jpg";
      }
      else
      {
          img.src="https://www.w3schools.com/css/trolltunga.jpg";
      }
}

Click on image to set timer on or off

A: This line
var stop=setInterval('change()',2000);

... creates a new, locally scoped variable stop instead of assigning to the one you created in the outer scope, so when you later run clearInterval(stop) (in a new 'instance' of the function with a new scope) you're not clearing the interval you created previously.
The same goes for the settimer variable.
Simply remove the var keyword from those lines in the change_timer() function and it will work as intended.


Q: How to start TinyMCE 4 in full screen mode? Is there a way to start TinyMCE 4 in full screen mode? I just upgraded from TinyMCE 3.x, but the way it was done in 3.x does not seem to work in 4.x:
<head>
<script type="text/javascript" src="TinyMCE/tinymce.min.js"></script>
<script type="text/javascript">
  tinyMCE.init({
    oninit : function() {
      tinyMCE.get('editor').execCommand('mceFullScreen');
    }
  });
</script>
</head>

<body>
  <textarea id="editor"></textarea>
</body>

Any suggestions?

A: Found out how to do it:
<head>
<script type="text/javascript" src="TinyMCE/tinymce.min.js"></script>
<script type="text/javascript">
  tinyMCE.init({
    plugins: [ 'fullscreen' ],
    setup: function(editor) {
      editor.on('init', function(e) {
        editor.execCommand('mceFullScreen');
      });
    }
  });
</script>
</head>

<body>
  <textarea id="editor"></textarea>
</body>

A: It is described in the official documentation too.
tinymce.activeEditor.execCommand('mceFullScreen');

be sure you have included it in the plugins like this
tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  plugins: 'fullscreen',
  menubar: 'view',
  toolbar: 'fullscreen'
});

here is a link to the official documentation.
Official docs for tinymce editor fullscreen


Q: Is there a way to create aws eventbridge rule to apply for only one resource? for example I have a iam eventbridge rule that is triggered for any changes to the roles as below:
{
  "source": ["aws.iam"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": ["iam.amazonaws.com"],
    "eventName": ["AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy", "DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy", "PutGroupPolicy", "PutRolePolicy", "PutUserPolicy"]
  }
}

Is there any way to update this rule and trigger only if this happens for say role testone
?

A: I am not sure about the EventBridge filter for the purpose but found a very easy technique from the link below:
https://aws.amazon.com/premiumsupport/knowledge-center/eventbridge-create-custom-event-pattern/
So basically you have to let the event you are targeting to be in your cloudtrail or get teh email notifications and then copy and paste the only wanted part. So for my problem I did this and it is workng exactly as I wanted.
{
  "source": ["aws.iam"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": ["iam.amazonaws.com"],
    "eventName": ["AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy", "DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy", "PutGroupPolicy", "PutRolePolicy", "PutUserPolicy"],
    "requestParameters": {
      "roleName": ["testone"]
    }
  }
}

A: You would use an EventBridge filter for you rule so that it only matches the specific role.


Q: Why kernel code/thread executing in interrupt context cannot sleep? I am reading following article by Robert Love
http://www.linuxjournal.com/article/6916
that says
"...Let's discuss the fact that work queues run in process context. This is in contrast to the other bottom-half mechanisms, which all run in interrupt context. Code running in interrupt context is unable to sleep, or block, because interrupt context does not have a backing process with which to reschedule. Therefore, because interrupt handlers are not associated with a process, there is nothing for the scheduler to put to sleep and, more importantly, nothing for the scheduler to wake up..."
I don't get it. AFAIK, scheduler in the kernel is O(1), that is implemented through the bitmap. So what stops the scehduler from putting interrupt context to sleep and taking next schedulable process and passing it the control?

A: Because the thread switching infrastructure is unusable at that point.  When servicing an interrupt, only stuff of higher priority can execute - See the Intel Software Developer's Manual on interrupt, task and processor priority.  If you did allow another thread to execute (which you imply in your question that it would be easy to do), you wouldn't be able to let it do anything - if it caused a page fault, you'd have to use services in the kernel that are unusable while the interrupt is being serviced (see below for why).
Typically, your only goal in an interrupt routine is to get the device to stop interrupting and queue something at a lower interrupt level (in unix this is typically a non-interrupt level, but for Windows, it's dispatch, apc or passive level) to do the heavy lifting where you have access to more features of the kernel/os.  See - Implementing a handler.
It's a property of how O/S's have to work, not something inherent in Linux.  An interrupt routine can execute at any point so the state of what you interrupted is inconsistent.  If you interrupted the thread scheduling code, its state is inconsistent so you can't be sure you can "sleep" and switch threads.  Even if you protect the thread switching code from being interrupted, thread switching is a very high level feature of the O/S and if you protected everything it relies on, an interrupt becomes more of a suggestion than the imperative implied by its name.

A:
So what stops the scehduler from putting interrupt context to sleep and taking next schedulable process and passing it the control?

The problem is that the interrupt context is not a process, and therefore cannot be put to sleep.
When an interrupt occurs, the processor saves the registers onto the stack and jumps to the start of the interrupt service routine.  This means that when the interrupt handler is running, it is running in the context of the process that was executing when the interrupt occurred.  The interrupt is executing on that process's stack, and when the interrupt handler completes, that process will resume executing.
If you tried to sleep or block inside an interrupt handler, you would wind up not only stopping the interrupt handler, but also the process it interrupted.  This could be dangerous, as the interrupt handler has no way of knowing what the interrupted process was doing, or even if it is safe for that process to be suspended.
A simple scenario where things could go wrong would be a deadlock between the interrupt handler and the process it interrupts.

*

*Process1 enters kernel mode.

*Process1 acquires LockA.

*Interrupt occurs.

*ISR starts executing using Process1's stack.

*ISR tries to acquire LockA.

*ISR calls sleep to wait for LockA to be released.

At this point, you have a deadlock.  Process1 can't resume execution until the ISR is done with its stack.  But the ISR is blocked waiting for Process1 to release LockA.

A: I think it's a design idea.
Sure, you can design a system that you can sleep in interrupt, but except to make to the system hard to comprehend and complicated(many many situation you have to take into account), that's does not help anything. So from a design view, declare interrupt handler as can not sleep is very clear and easy to implement.

From Robert Love (a kernel hacker):
http://permalink.gmane.org/gmane.linux.kernel.kernelnewbies/1791
You cannot sleep in an interrupt handler because interrupts do not have
a backing process context, and thus there is nothing to reschedule back
into. In other words, interrupt handlers are not associated with a task,
so there is nothing to "put to sleep" and (more importantly) "nothing to
wake up". They must run atomically.
This is not unlike other operating systems. In most operating systems,
interrupts are not threaded. Bottom halves often are, however.
The reason the page fault handler can sleep is that it is invoked only
by code that is running in process context. Because the kernel's own
memory is not pagable, only user-space memory accesses can result in a
page fault. Thus, only a few certain places (such as calls to
copy_{to,from}_user()) can cause a page fault within the kernel. Those
places must all be made by code that can sleep (i.e., process context,
no locks, et cetera).

A:
So what stops the scehduler from putting interrupt context to sleep and taking next schedulable process and passing it the control?

Scheduling happens on timer interrupts. The basic rule is that only one interrupt can be open at a time, so if you go to sleep in the "got data from device X" interrupt, the timer interrupt cannot run to schedule it out.
Interrupts also happen many times and overlap. If you put the "got data" interrupt to sleep, and then get more data, what happens? It's confusing (and fragile) enough that the catch-all rule is: no sleeping in interrupts. You will do it wrong.

A: Disallowing an interrupt handler to block is a design choice. When some data is on the device, the interrupt handler intercepts the current process, prepares the transfer of the data and enables the interrupt; before the handler enables the current interrupt, the device has to hang. We want keep our I/O busy and our system responsive, then we had better not block the interrupt handler.
I don't think the "unstable states" are an essential reason. Processes, no matter they are in user-mode or kernel-mode, should be aware that they may be interrupted by interrupts. If some kernel-mode data structure will be accessed by both interrupt handler and the current process, and race condition exists, then the current process should disable local interrupts, and moreover for multi-processor architectures, spinlocks should be used to during the critical sections.
I also don't think if the interrupt handler were blocked, it cannot be waken up. When we say "block", basically it means that the blocked process is waiting for some event/resource, so it links itself into some wait-queue for that event/resource. Whenever the resource is released, the releasing process is responsible for waking up the waiting process(es).
However, the really annoying thing is that the blocked process can do nothing during the blocking time; it did nothing wrong for this punishment, which is unfair. And nobody could surely predict the blocking time, so the innocent process has to wait for unclear reason and for unlimited time.

A: Even if you could put an ISR to sleep, you wouldn't want to do it. You want your ISRs to be as fast as possible to reduce the risk of missing subsequent interrupts.

A: The linux kernel has two ways to allocate interrupt stack. One is on the kernel stack of the interrupted process, the other is a dedicated interrupt stack per CPU. If the interrupt context is saved on the dedicated interrupt stack per CPU, then indeed the interrupt context is completely not associated with any process. The "current" macro will produce an invalid pointer to current running process, since the "current" macro with some architecture are computed with the stack pointer. The stack pointer in the interrupt context may point to the dedicated interrupt stack, not the kernel stack of some process.

A: By nature, the question is whether in interrupt handler you can get a valid "current" (address to the current process task_structure), if yes, it's possible to modify the content there accordingly to make it into "sleep" state, which can be back by scheduler later if the state get changed somehow. The answer may be hardware-dependent.
But in ARM, it's impossible since 'current' is irrelevant to process under interrupt mode. See the code below:
#linux/arch/arm/include/asm/thread_info.h
94 static inline struct thread_info *current_thread_info(void)
95 {
96  register unsigned long sp asm ("sp");
97  return (struct thread_info *)(sp & ~(THREAD_SIZE - 1));
98 }

sp in USER mode and SVC mode are the "same" ("same" here not mean they're equal, instead, user mode's sp point to user space stack, while svc mode's sp r13_svc point to the kernel stack, where the user process's task_structure was updated at previous task switch, When a system call occurs, the process enter kernel space again, when the sp (sp_svc) is still not changed, these 2 sp are associated with each other, in this sense, they're 'same'), So under SVC mode, kernel code can get the valid 'current'. But under other privileged modes, say interrupt mode, sp is 'different', point to dedicated address defined in cpu_init(). The 'current' calculated under these mode will be irrelevant to the interrupted process, accessing it will result in unexpected behaviors. That's why it's always said that system call can sleep but interrupt handler can't, system call works on process context but interrupt not.

A: High-level interrupt handlers mask the operations of all lower-priority interrupts, including those of the system timer interrupt. Consequently, the interrupt handler must avoid involving itself in an activity that might cause it to sleep. If the handler sleeps, then the system may hang because the timer is masked and incapable of scheduling the sleeping thread.
Does this make sense?

A: If a higher-level interrupt routine gets to the point where the next thing it must do has to happen after a period of time, then it needs to put a request into the timer queue, asking that another interrupt routine be run (at lower priority level) some time later.
When that interrupt routine runs, it would then raise priority level back to the level of the original interrupt routine, and continue execution. This has the same effect as a sleep.

A: It is just a design/implementation choices in Linux OS. The advantage of this design is simple, but it may not be good for real time OS requirements.
Other OSes have other designs/implementations.
For example, in Solaris, the interrupts could have different priorities, that allows most of devices interrupts are invoked in interrupt threads. The interrupt threads allows sleep because each of interrupt threads has separate stack in the context of the thread.
The interrupt threads design is good for real time threads which should have higher priorities than interrupts.


Q: nested if else statment not working via target cell Hi I have a private sub (worksheet by change) which will run one of 26 macro's based on a cells value.  All these do is hide or unhide specific row's based on the value from a cell which has a formula in it.
Now when I manually change the value of the cell the worksheet change event and macro's all work as they are meant to, BUT they don't work when the cell value is change via the formula, or rather bits of them do.
I have set the worksheet, and range variables in each macro, and likewise the target cell within the worksheet change event properly (dim r as range, etc.)
The code for the worksheet change event is below - wondered if anyone can spot or help as to why this doesn't seem to work when running without the manual cell value change
If I can avoid it I don't want to programmatically change the value in the cell (if "a condition" then r.value="A value" 26 times!)
here is the worksheet code
Dim r As Range, r1 As Range, r2 As Range, r3 As Range, r4 As Range, r5 As Range, r6 As Range, r7 As Range, r8 As Range
Dim r9 As Range, r10 As Range, r11 As Range, r12 As Range, r13 As Range, r14 As Range, r15 As Range, r16 As Range

Private Sub Worksheet_Change(ByVal Target As Range)

'Set range for selecting the region
Set r = Range("O19")

'Set facility ranges

Set r1 = Rows("22:24"): Set r2 = Rows("25:27"): Set r3 = Rows("28:30"): Set r4 = Rows("31:33")

'set product line ranges
Set r5 = Rows("37"): Set r6 = Rows("38"): Set r7 = Rows("39"): Set r8 = Rows("40"): Set r9 = Rows("41"): Set r10 = Rows("42"): Set r11 = Rows("43:45")
Set r12 = Rows("46:48"): Set r13 = Rows("49"): Set r14 = Rows("51:52"): Set r15 = Rows("36"): Set r16 = Rows("50")

'Hiding facility Rows based on product line

If r.Value = 1 Then ' Select Facility & all cells hidden
    Application.Run ("Select_Facility")
    ElseIf r.Value = 2 Then ' This is for North America & no Facility
    Application.Run ("NA_NoFacility")
    ElseIf r.Value = 3 Then ' This is for Breen Only
    Application.Run ("Breen")
    ElseIf r.Value = 4 Then ' This is for Conroe Only
    Application.Run ("Conroe")
    ElseIf r.Value = 5 Then ' This is for Lafayette Only
    Application.Run ("Lafayette")
    ElseIf r.Value = 6 Then ' This is for Breen & Conroe Only
    Application.Run ("Breen_Conroe")
    ElseIf r.Value = 7 Then ' This is for Breen & Lafayette Only
    Application.Run ("Breen_Lafayette")
    ElseIf r.Value = 8 Then ' This is for Conroe & Lafayette
    Application.Run ("Conroe_Lafayette")
    ElseIf r.Value = 9 Then ' This is for All North America
    Application.Run ("All_NA")
    ElseIf r.Value = 10 Then ' This is for Europe and no facility
    Application.Run ("Europe_NoFacility")
    ElseIf r.Value = 11 Then 'This is for Gateshead only
    Application.Run ("Gateshead")
    ElseIf r.Value = 12 Then 'This is for Kintore only
    Application.Run ("Kintore ")
    ElseIf r.Value = 13 Then 'This is for Kintore & Gateshead only
    Application.Run ("All_Europe")
    ElseIf r.Value = 14 Then ' This is for Middle East and no facility
    Application.Run ("Europe_NoFacility")
    ElseIf r.Value = 15 Then 'This is for Dubai only
    Application.Run ("Dubai")
    ElseIf r.Value = 16 Then 'This is for Saudi only
    Application.Run ("Saudi")
    ElseIf r.Value = 17 Then 'This is for Dubai and Saudi only
    Application.Run ("Dubai_Saudi")
    ElseIf r.Value = 18 Then ' This is for Far East & no Facility
    Application.Run ("FE_NoFacility")
    ElseIf r.Value = 19 Then ' This is for Loyang Only
    Application.Run ("Loyang")
    ElseIf r.Value = 20 Then ' This is for Tuas Only
    Application.Run ("Tuas")
    ElseIf r.Value = 21 Then ' This is for Perth Only
    Application.Run ("Perth")
    ElseIf r.Value = 22 Then ' This is for Loyang & Tuas Only
    Application.Run ("Loyang_Tuas")
    ElseIf r.Value = 23 Then ' This is for Loyang & Perth Only
    Application.Run ("Loyang_Perth")
    ElseIf r.Value = 24 Then ' This is for Tuas and Perth Only
    Application.Run ("Tuas_Perth")
    ElseIf r.Value = 25 Then ' This is for All far East facilities
    Application.Run ("All_FE")
    ElseIf r.Value = 26 Then ' This is for Global
    Application.Run ("All_Global")
End If

The user could select a number of combinations of facilities which give me 26 variants - hence the 26 options above - originally the hide row's instructions were inside each ElseIF option but its wouldn't work there either.
The way the form works is the user selects the region, and then will select the relevant facilities - this will change the target cell twice, and also amend the hidden and visible rows. from which the user will select yes or no.

A: First, you need to work with Worksheet_Calculate() event, as already mentioned by Sam. But there's something more: why are you using a 26-conditions if-clause?
Create a next worksheet (Application_Sheet), with two columns, something like this:
R_Value      Application
      1   Select_Facility
      2       No_Facility
    ...               ...

Instead of the complicated if-clause, do something like this (not tested):
Application.Run(Range(Application_Sheet!B1).Offset(r.Value).Value)

A: I have implemented some of the changes recommended above, and while the code does seem neater, I cannot get this to work at all, here is my code for the worksheet_calculate() and the referenced macro.  I keep getting a code execution interrupted error which then points back to the Worksheet_Calculate() name when I hit the debug option.
Private Sub Worksheet_Calculate()

'Define the worksheets & Ranges for use in this routine
Dim r As Range: Set r = Range("N19")

'Hiding facility Rows based on product line
Application.Run (Range("AB1").Offset(r.Value).Value)

End Sub

and one of the macro's is
Sub Select_Facility()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Supplier Details")

ws.Activate
Rows("22:24").EntireRow.Hidden = True
Rows("25:27").EntireRow.Hidden = True
Rows("28:30").EntireRow.Hidden = True
Rows("31:33").EntireRow.Hidden = True
Rows("37").EntireRow.Hidden = True
Rows("38").EntireRow.Hidden = True
Rows("39").EntireRow.Hidden = True
Rows("40").EntireRow.Hidden = True
Rows("41").EntireRow.Hidden = True
Rows("42").EntireRow.Hidden = True
Rows("43:45").EntireRow.Hidden = True
Rows("46:48").EntireRow.Hidden = True
Rows("49").EntireRow.Hidden = True
Rows("51:52").EntireRow.Hidden = True
Rows("36").EntireRow.Hidden = True
ws.Rows("50").EntireRow.Hidden = True

End Sub

Perhaps its something simple I am doing wrong, but....  Oh and all the rows in the above list are set to hidden as standard before I start.


Q: I want to customize some indicators in backtrader When I am using my own method, I met some problems, my program responds: Invalid parameter value for nbdev (expected float, got int)
I am really confused
after several tries, I suppose that the problem is caused because of my indicators.
I hope to learn how to customize my own indicators, and here is my code.
# indicator
class AJ(bt.Indicator):
    params = dict(ema1=21, atr=17, ema2=5, ema3=2)
    lines = ("AJ", "VAR2", "VAR3", "VAR4", "VAR5", "VAR6", "AK", "AD1")
    plotinfo = dict(subplot = True)
    plotlines = dict(
        AJ = dict(ls="--"),
        VAR2 = dict(_samecolor=True),
        VAR3 = dict(_samecolor=True),
        VAR4 = dict(_samecolor=True),
        VAR5 = dict(_samecolor=True),
        VAR6 = dict(_samecolor=True),
        AK = dict(_samecolor=True),
        AD1 =  dict(_samecolor=True)
    )

    def __init__(self):
        # self.l.expo的l代表从dataframe里面抽取一列的数据
        self.l.VAR2 = (self.datas[0].close * 2 + self.datas[0].high + self.datas[0].low) / 4
        self.l.VAR3 = bt.talib.EMA(self.l.VAR2, timeperiod=self.params.ema1)
        self.l.VAR4 = np.sqrt(bt.talib.VAR(self.l.VAR2, timeperiod=self.params.ema1))
        self.l.VAR5 = ((self.l.VAR2 - self.l.VAR3) / self.l.VAR4 * 100 + 200) / 4
        self.l.VAR6 = (bt.talib.EMA(self.l.VAR5, timeperiod=self.params.ema2) - 25) * 1.56
        self.l.AK = bt.talib.EMA(self.l.VAR6, timeperiod=self.params.ema3)* 1.22
        self.l.AD1 = bt.talib.EMA(self.l.AK, timeperiod=self.params.ema3)
        self.l.AJ = 3 * self.l.AK - 2 * self.l.AD1

# execute
class Strategy(bt.Strategy):

    # 用于记录的模板（以后可直接copy）
    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print("%s, %s" % (dt.isoformat(), txt))

    def __init__(self):
        self.AJ = AJ()
        self.close = self.data.close

    # 比较格式化的东西，每次可以直接抄
    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            # 记录一下买入的信息
            if order.isbuy():
                self.log(
                    "BUY EXECUTED, Price: {:.2f}, Cost: {:.2f}, Commission: {:.2f}".format(
                        order.executed.price,
                        order.executed.value,
                        order.executed.comm
                    )
                )

                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm

            # 记录一下卖出的信息
            else:
                self.log(
                    "SELL EXECUTED, Price: {:.2f}, Cost: {:.2f}, Commission: {:.2f}".format(
                        order.executed.price,
                        order.executed.value,
                        order.executed.comm
                    )
                )

            # 记录一下过去了几个蜡烛条，也就是几个交易周期
            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log("Order Cancel/Margin/Rejected")

        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return

        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))

    # 执行交易的东西！！！
    def next(self):
        if not self.position:
            if self.AJ[-1] < -40 and self.AJ[0] > -40:
                self.order = self.order_target_percent(target=0.95)
        else:
            if self.AJ[-1] > 140 and self.AJ[0] < 140:
                self.order = self.sell()

# main
if __name__ == "__main__":
    cerebro = bt.Cerebro()

    # 提取数据再喂数据
    data = bt.feeds.PandasData(dataname=yf.download("510050.SS", "2017-01-01", "2022-01-01", auto_adjust=True))

    cerebro.adddata(data)

    # 添加策略
    cerebro.addstrategy(Strategy)

    # 设定开始价格
    cerebro.broker.setcash(1000000)
    cerebro.broker.setcommission(commission = 0.0001)

    # 告诉你每次买多少的股票
    cerebro.addsizer(bt.sizers.PercentSizer, percents = 98)

    # 加入分析
    cerebro.addanalyzer(bta.SharpeRatio, _name='sharpe')
    cerebro.addanalyzer(bta.DrawDown, _name='drawdown')
    cerebro.addanalyzer(bta.Returns, _name='returns')

    # 执行交易
    print("Start Portfolio Value {}".format(cerebro.broker.getvalue()))
    back = cerebro.run()
    print("End Portfolio Value {}".format(cerebro.broker.getvalue()))

    # 把分析的结果搞出来
    par_list = [[x.analyzers.returns.get_analysis()['rtot'],
                 x.analyzers.returns.get_analysis()['rnorm100'],
                 x.analyzers.drawdown.get_analysis()['max']['drawdown'],
                 x.analyzers.sharpe.get_analysis()['sharperatio']
                 ] for x in back]
    par_df = pd.DataFrame(par_list, columns=['Total Return', 'APR', 'Drawdown', 'SharpRatio'])
    print(par_df)

    # 画图
    cerebro.plot(style = "candle")

A: self.l.VAR2 = (self.datas[0].close * 2 + self.datas[0].high + self.datas[0].low) / 4
        self.l.VAR3 = bt.talib.EMA(self.l.VAR2, timeperiod=self.params.ema1)
        self.l.VAR4 = bt.talib.STDDEV(self.l.VAR2, timeperiod=self.params.ema1, nbdev = 1.0)
        self.l.VAR5 = ((self.l.VAR2 - self.l.VAR3) / self.l.VAR4 * 100 + 200) / 4
        self.l.VAR6 = (bt.talib.EMA(self.l.VAR5, timeperiod=self.params.ema2) - 25) * 1.56
        self.l.AK = bt.talib.EMA(self.l.VAR6, timeperiod=self.params.ema3)* 1.22
        self.l.AD1 = bt.talib.EMA(self.l.AK, timeperiod=self.params.ema3)
        self.l.AJ = 3 * self.l.AK - 2 * self.l.AD1


Q: java script function inside razor block I am calling a EditDetails javascript function on click only if user has Admin permissions else disabling the button.
I see the error
"Cannot implicitly convert type bool to string " at the javascript function name.
What may be the issue?
 <img src='../../Images/Edit.png' alt='Click to Edit'
 onclick="@(Model.AdminPermissions ? "javascript:EditDetails('#@rowId');" ? "")" disabled="@(Model.AdminPermissions ? "" : "disabled")"

A: The error you were seeing is because you had accidentally included an extra ? inside of your @() block, and it should have been a :

Overall, it was close you just need to make sure that you break out of the string concatenation and get back to the razor (server) scope for the rowId.


Q: Azure API Management does not validate required properties in payload We are using Azure API Management in a project, and we want APIM to be our shield against invalid requests. Since we've already specified what a valid request looks like in our OpenAPI specification and uploaded that to APIM, it seems like a reasonable assumption.
I have specified a component in our OpenAPI (version 3.0.1) specification like this:
TemperatureRange:
  description: Defines a desired temperature range
  required:
    - min
    - max
  properties:
    min:
      type: number
    max:
      type: number

When uploaded to APIM the schema looks fine:
{
    "required": [
        "min",
        "max"
    ],
    "properties": {
        "min": {
            "type": "number"
        },
        "max": {
            "type": "number"
        }
    },
    "description": "Defines a desired temperature range"
}

However, when I call an API that uses this definition, I can leave out properties even though they are marked as required.
The payload I sent looks like this, leaving out the required max property:
[{
    "someProperty": "someValue",
    "temperatureRange": {
        "min": -18,
    }
}]

I can't find any documentation on this and it isn't mentioned in any restrictions. What is the intended behavior?

A: Looks like this is functionality that has been requested but has not been implemented: https://feedback.azure.com/forums/248703-api-management/suggestions/17369008-schema-validation-in-apim


Q: Does Lua support Decorators? I come from a Python background and really like the power of Python Decorators.
Does Lua support Decorators?
I've read the following link but it's unclear to me:  http://lua-users.org/wiki/DecoratorsAndDocstrings
UPDATE
Would you also mind given an example how how to implement it in Lua if it's possible.

A: The "decorators" documented at the page you quote (and used for example in this one to add type-checking) have little to do with Python's oddly-named "decorator syntax" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in Lua's wiki are a Lua idiom to support an application of the Decorator Design Pattern to Lua functions (by holding "extra attributes" -- such as docstrings, typechecking functions, etc -- in separate global tables).
Lua does support HOFs (I'm not sure if you can re-bind a function name to the result of applying a HOF to the function, but you can easily, as the wiki pages show, use an anonymous "original function" and only bind a name to the HOF's result with that anon function as the arg).
Python's "decorator syntax" syntax sugar is nice (and, to my surprise, seems to have increased the use of HOFs by most Pythonistas by an order of magnitude!-), but there's nothing intrinsic or essential about them that you can't do in Lua (and Lua's anonymous functions run circle around Python's goofy, limited lambda anyway -- just like in Javascript, they have essentially the same power, and pretty much the same syntax, as a "normal" named function!-).


Q: Saving a reference to a int Here is a much simplified version of what I am trying to do
static void Main(string[] args)
{
    int test = 0;
    int test2 = 0;
    Test A = new Test(ref test);
    Test B = new Test(ref test);
    Test C = new Test(ref test2);
    A.write(); //Writes 1 should write 1
    B.write(); //Writes 1 should write 2
    C.write(); //Writes 1 should write 1
    Console.ReadLine();
}
class Test
{
    int _a;
    public Test(ref int a)
    {
        _a = a; //I loose the reference here
    }
    public void write()
    {
        var b = System.Threading.Interlocked.Increment(ref _a);
        Console.WriteLine(b);
    }
}

In my real code I have a int that will be incremented by many threads however where the threads a called it will not be easy to pass it the parameter that points it at the int(In the real code this is happening inside a IEnumerator). So a requirement is the reference must be made in the constructor. Also not all threads will be pointing at the same single base int so I can not use a global static int either. I know I can just box the int inside a class and pass the class around but I wanted to know if that is the correct way of doing something like this?
What I think could be the correct way:
static void Main(string[] args)
{
    Holder holder = new Holder(0);
    Holder holder2 = new Holder(0);
    Test A = new Test(holder);
    Test B = new Test(holder);
    Test C = new Test(holder2);
    A.write(); //Writes 1 should write 1
    B.write(); //Writes 2 should write 2
    C.write(); //Writes 1 should write 1
    Console.ReadLine();
}
class Holder
{
    public Holder(int i)
    {
        num = i;
    }
    public int num;
}
class Test
{
    Holder _holder;
    public Test(Holder holder)
    {
        _holder = holder;
    }
    public void write()
    {
        var b = System.Threading.Interlocked.Increment(ref _holder.num);
        Console.WriteLine(b);
    }
}

Is there a better way than this?

A: Basically, the answer is Yes, you need a class.
There is no concept of 'reference to int' that you can store as a field. In C# it is limited to parameters.
And while there is an unsafe way (pointer to int, int*) the complexities of dealing with the GC in that scenario make it impractical and inefficient.
So your second example looks OK.

A: You cannot store a reference to a variable, for precisely the reason that someone could do what you are doing: take a reference to a local variable, and then use that reference after the local variable's storage is reclaimed.
Your approach of making the variable into a field of a class is fine. An alternative way of doing the same thing is to make getter and setter delegates to the variable. If the delegates are closed over an outer local variable, that outer local will be hoisted to a field so that its lifetime is longer than that of the delegates.

A: It is not possible to store a reference as a field.
You need to hold the int in a class.


Q: GSON serialize and deserialize a list delegator I have a class that implements a List<T> and wraps an ArrayList<T> to which it delegates.
Something like that:
class ListWrapper<T> implements List<T> {
      private String id;
      private List<T> list = new ArrayList<T>();
      private transient ListListener listener;

      // all of List  interface methods are delegated here e.g.
      public void add(T t) {
           list.add(t);
           listener.onItemAdded(id);
      }
      ...
}

GSON default behavior would be to treat this thing as a List and so it doesn't invoke field level reflection.
I would like to get a json like so:
{
 id="1234",
 list=[....]
}

Any idea on how to do that elegantly?

A: You can use custom TypeAdapter in this case.
Example:
class ListWrapper<T> extends ArrayList<T>
{
    private static final long serialVersionUID = 1L;

    String id = "asd";
    List<T> list = new ArrayList<T>();
    transient T listener = null;
}

Create your custom TypeAdapter
   class CustomTypeAdapter<T> extends TypeAdapter<ListWrapper<T>>
{

    @Override
    public void write(JsonWriter writer, ListWrapper<T> value) throws IOException
    {
        if (value == null)
        {
            writer.nullValue();
            return;
        }

        writer.beginObject();

        // Add id field
        writer.name("id").value(value.id);

        // Add list field
        StringBuilder builder = new StringBuilder("");
        builder.append("list : [ ");
        for (T t : value.list)
        {
            builder.append("T : " + t.toString() + ",");
        }
        String txt = builder.substring(0, builder.length() - 1) + "]";
        writer.name("list").value(StringUtils.join(value.list, ";"));

        // Add other fields
        // TODO

        writer.endObject();
    }
    @Override
    public ListWrapper<T> read(JsonReader in) throws IOException
    {
        // Implement your deserialization logic here
        return null;
    }
}

Sample usage:
 public static void main(String[] args)
    {

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(ListWrapper.class, new CustomTypeAdapter<String>());
        Gson gson = builder.create();
        ListWrapper<String> lw = new ListWrapper<String>();
        lw.list.add("as");
        lw.list.add("is");
        System.out.println(gson.toJson(lw));
    }

Sample output JSON:
 {"id":"asd","list":"as;is"}


Q: Uncaught TypeError: Cannot call method 'contains' of undefined NOTE Please see this question for a bit of background...
So my (very basic) form validation is working - sort of.
When checking the input value for the email address field, I want to make sure that the email address has a value (i.e. is not blank) and contains @ and . characters so I did this...

        Email Address *

    <input  type="text" name="email" class="span4">

It looks a little weird but complexity as mentioned in the linked question above required me to think a little differently with my selectors.
Basically $('.' + parentname.attr('class') + ' #email') is the same as writing (in the case I'm using $('.con1 #email') as the selector which I believe to be correct based on my HTML structure.
I tried working with $('.' + parentname.attr('class').child('#email') but then kept getting an error that said the element had no method 'child'
I wrote this based on a previous form I'd created where I'd used the same principle in effect, to block emails coming from yahoo.com because I was getting a lot of spam from there:
if ($("#contact-email").val().contains("yahoo.com")) {
     $(".errmsg").text("Domain yahoo.com has been banned due to excessive spam, please use another domain.");
}
else
{
    email = 1;
}

While the 2nd sample that I've pasted here works, the first one that validates the email field more thoroughly keeps returning this error:

Uncaught TypeError: Cannot call method 'contains' of undefined

I can't understand how this could work in one site and not another. I feel like I'm missing something so would appreciate it if anyone can see what that might be.
Thanks in advance!

A: The  elements should have an id="email" to allow the selector:
$('.' + parentname.attr('class') + ' #email')


Q: ASP.NET project works on IIS server but not on localhost I have an ASP.NET project that was working fine until today.  I added a new webform (.aspx) to the project and it started giving a parse error. I spent hours fixing this issue but had no luck. I deleted all the files and cloned the repo to start from scratch but now the cloned project started giving the same error for a default aspx page that was working before.  I thought this could my local system-related issue so I tried publishing the website using Visual Studio publish profile onto the IIS website on a different server.  The site got published without any errors and the website is loading without any errors.
Please help to identify why the same project is giving "Parser Error Message: Could not load type 'sometype'" error?  I tried many solutions given in this post-https://stackoverflow.com/questions/15071220/parser-error-message-could-not-load-type-sometype but nothing works.

A: I thought I would update how I resolved the issue in case someone is facing the same issue.
There are number of things I did:

*

*Updated package.config as some of the packages were not using 4.6.1.  I'm not sure how it worked until a certain point in time.

*Deleted local repo.  Cloned the code from the repository, built the solution, and tested if the local instance is working.  At this point, it was not.

*I noticed that the solution was compiling and producing libraries but the libraries were not copied into the \bin\Debug folder even though the output path was set to bin\Debug folder.  So I updated the properties to change the output path to \bin, rebuilt the solution, and then changed the path back to bin\Debug and rebuilt it again.  The local instance launched without any issues this time.

*Added the new webform (.aspx) file again and rebuilt the solution.  This time the local instance launched without any issues.


Q: Sending Email after insertion of data using codeigniter php Sending email after inserting the data into database using codeigniter PHP is not working.Data is inserting succesfully but the MAIL functionality is not working getting as www.hostname.com page isn’t working.Can any one help me this.Thanks in advance.Here is my code.
Controller:
class Blog extends CI_Controller
{
    function __construct()
        {
            parent::__construct();
            //here we will autoload the pagination library
            $this->load->model('blogs_model');
            $this->load->library('email');
        }
        function addcomments()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('
 ','');
        $this->form_validation->set_rules('first_name','First Name' , 'required');
        $this->form_validation->set_rules('email','Email');
        $this->form_validation->set_rules('location','Location');
        $this->form_validation->set_rules('description','Description');
        if($this->form_validation->run()== FALSE)
        {
        $data['mainpage']='blogs';
        $this->load->view('templates/template',$data);
        }
        else
        {

            //insert the user registration details into database
            $data=array(
                'blog_id'=>$this->input->post('bl_id'),
                'first_name'=>$this->input->post('first_name'),
                'email'=>$this->input->post('email'),
                'description'=>$this->input->post('description'),
                'location'=>$this->input->post('location')
                );
            // insert form data into database
            if ($this->blogs_model -> insertcomments($data))
            {
                // send email
                if ($this->blogs_model->send_mail($this->input->post('email')))
                {
                    // successfully sent mail
                    $this->flash->success('msg','
You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!
');
                    redirect("blog");
                }
                else
                {
                    // error
                    $this->flash->success('msg','
Oops! Error.  Please try again later!!!
');
                    redirect("blog");
                }
            }
            else
            {
                // error
                $this->flash->success('msg','
Oops! Error.  Please try again later!!!
');
                redirect('blog');
            }
        }
        }
}

Model:
function insertcomments($data)
{
    return $this->db->insert('comments', $data);
    //$this->db->insert('comments',$data);
    //return $this->input->post('bl_id');
}

function sendEmail($to_email)
{

    //configure email settings
    $config=Array(
    'protocol'=> 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com', //smtp host name
    'smtp_port' => '465', //smtp port number
    'smtp_user' => 'xxxx@gmail.com',
    'smtp_pass' => '************', //$from_email password
    'mailtype' =>'html',
    'charset' => 'iso-8859-1',
    'wordwrap' => TRUE
    );

    //send mail
    $this->load->library('email',$config);
    $this->email->from('xxxx@gmail.com', 'Admin');
    $this->email->to('yyy@gmail.com');
    $this->email->subject('Comments');
    $this->email->message('Testing');
    $this->email->set_newline("\r\n");
    return $this->email->send();
}

A: You are using wrong method name for sending email in your controller:
$this->blogs_model->send_mail($this->input->post('email'))

Correct function name is sendEmail()
$this->blogs_model->sendEmail($this->input->post('email'))

A: Check your code:
You should change function "send_mail" in your controller because in model you used "sendEmail".
Change in to your controller :
$this->blogs_model->sendEmail($this->input->post('email'))

A: I think the problems in your code is this line
    smtp_host' => 'ssl://smtp.googlemail.com
try instead:  smtp_host' => 'http://smtp.gmail.com


Q: Weird PHP session I've got a perfectly functioning site which uses sessions. The only exception, is one particular page. The page performs some DB SELECTS, verification stuff, etc. etc.
Then, later on, in the HTML part, ive got a  tag. Between that, ive got
<?php
    $classes = explode(",", $_SESSION['classes']);
    foreach ($classes as $class) {
        echo "<option>".$class."</option>";
    }
?>

Now $_SESSION['classes'] is a comma separated string. Example: "10 A,11 D,12 C"
here's the weird part, when i load this page, everything works perfectly, and i get a drop-down select with options 10 A, 11 D and 12 C... but, when i refresh the page, I get a dropdown box with only one option: Array
Yes, it just says Array.... no other options.
And no, i haven't set the value to anything else after that PHP block. in fact, i dont have another PHP block after this one
To debug it, I added a php block with the code: echo $_SESSION['classes']; after the </select> tag, and the first page load, it said 10 A,11 D,12 C. After refresh, it said Array
Then i tried var_dump($_SESSION); and it said ["classes"]=> &string(9) "11 A,10 C" Heres the weirdest part: After refresh, it said ["classes"]=> &array(2) { [0]=> string(4) "11 A" [1]=> string(4) "10 C" } and on another refresh, it said ["classes"]=> &array(1) { [0]=> string(5) "Array" }
This only happens on my web host though, not on my local server. And, only on this page
I have no idea what's causing this, or how to fix it

A: You probably have register_globals turned on so $classes gets mixed with $_SESSION['classes'] at some point.
You should turn them off. (Here's why.)
Or, if turning them off is not possible due to whatever reason, change variable names.

A: Got it!
Here's my new code:
<?php
    $classesBeingTaught[] = explode(",", $_SESSION['classes']);
    foreach ($classesBeingTaught[0] as $classBeingTaught) {
        echo "<option>".$classBeingTaught."</option>";
    }
?>


Q: Why EXPAND_FACTOR is 2 in ImmutableCollections.java Below code comes from Java 11, java.util.ImmutableCollections.java, line 783.
 static final int EXPAND_FACTOR = 2;

 MapN(Object... input) {
            if ((input.length & 1) != 0) { // implicit nullcheck of input
                throw new InternalError("length is odd");
            }
            size = input.length >> 1;

            int len = EXPAND_FACTOR * input.length;
            len = (len + 1) & ~1; // ensure table is even length
            table = new Object[len];

Why the len is twice input.length? I think the table doesn't need to store elements more than input.length.


Q: Unique link to an artifact deployed to JFrog Artifactory I'm a new Artifactory user. My company just setup Artifactory v6.5.2 and I'm looking to use is for managing software deployed for our production team. What I need is a download link that will get documented in our product management system that directly points to the exact file that Software deployed for Production to use. I was anticipating this would look like this:
https://artifactory.mycompany.com/artifactory/myrepo/mymodule/mypkgfile_v1_b30b890becfb4a02510ed12a7283c676.tgz
I'm not seeing that Artifactory can do this for me.  What I see is I can do this:
http://artifactory.mycompany.com/artifactory/myrepo/mymodule/mypkgfile_v1.tgz
However if another artifact is deployed with the same name, it's not reflected in the download link. This means that the link could return different results.
Am I missing something or am I asking Artifactory do something it's not intended to do?

A: Artifactory returns the URL based on on the filename and the path (as any web server would do). Here are two options to achieve what you need:

*

*Name the artifacts uniquely (timestamps are the simplest). Instead of naming the artifact mypkgfile_v1.tgz, name it mypkgfile_v1-1553038888.tgz (I used the Unix Epoch time, but everything unique enough will do).

*This one is more evolved but doesn't require you to change the naming scheme.

*

*First, configure a custom repository layout to match your versioning.

*Once you've done that, every time you deploy an artifact, attach a unique identifier to the artifact as property during deployment (using matrix params, for example), deploying your artifact as mypkgfile_v1;timestamp=1553038888.

*On the revrieval, use the token for the latest release together with the timestamp you need as a matrix param:mypkgfile_v[RELEASE];timestamp=1553038888


Q: What is the best practice for packaging Lua script files to be called from C. Using CMake I'm learning to use Lua to embed in my C programs. I was wondering what they best way make sure that my C program can find the Lua files after it's built. I'm trying to make sure this works with an out of source CMake build.
Here is what I have so far.
In my c file, I have...
int runLuaHelloWorld() {

    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    luaL_dofile(L, "helloWorld.lua");
    lua_close(L);

    return 0;
}

In my CMakeLists.txt I have.
set(EMBEDDED_LUA_SRC embeddedLua.c embeddedLua.h)
add_library(embeddedLua ${EMBEDDED_LUA_SRC})
if(LUA_FOUND)
    target_include_directories(embeddedLua PRIVATE ${LUA_INCLUDE_DIR})
    target_link_libraries(embeddedLua ${LUA_LIBRARIES})
    add_custom_command(TARGET embeddedLua POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:embeddedLua> helloWorld.lua)
endif()

This successfully copies it to my build directory. But it seems to load my lua script file relative to my current working directory. In other words, I can only get the script to run if I'm running it from my build folder.
What's the best practice for including and running external lua files post build?
Perhaps I'm going about this completely the wrong way. Maybe this isn't a build issue at all. The lua script needs to run relative to the executable (or better yet, relative to a library) rather than to my working directory.
Any idea?

A: In our software we define a path to a directory where we store extensions written in Lua.  Then we use the opendir(), readir() etc. to find files in that directory, and when they end in '.lua' we load and execute them. So use just need to copy their scripts to that location.
In some applications we even store the Lua scripts in a text column of a (PostgreSQL) database table.


Q: MockMvc Integration Test with List of Object as Request Param I am working on a REST service using Spring MVC which takes List of Object as request parameter.
    @RequestMapping(value="/test", method=RequestMethod.PUT)
    public String updateActiveStatus(ArrayList<Test> testList, BindingResult result) throws Exception {
        if(testList.isEmpty()) {
            throw new BadRequestException();
        }
        return null;
    }

When I am trying a Integration test for above service, I am not able to send the list of Test object in request param.
Following code is not working for me.
List<Test> testList = Arrays.asList(new Test(), new Test());
        mockMvc.perform(put(ApplicationConstants.UPDATE_ACTIVE_STATUS)
                .content(objectMapper.writeValueAsString(testList)))
            .andDo(print());

Can anyone please help on this!

A:
@RequestParam with List or array

@RequestMapping("/books")
public String books(@RequestParam List<String> authors,
                         Model model){
    model.addAttribute("authors", authors);
    return "books.jsp";
}

@Test
public void whenMultipleParameters_thenList() throws Exception {
    this.mockMvc.perform(get("/books")
            .param("authors", "martin")
            .param("authors", "tolkien")
    )
            .andExpect(status().isOk())
            .andExpect(model().attribute("authors", contains("martin","tolkien")));
}

A: Use Gson library to convert list into a json string and then put that string in content
Also put the @RequestBody annotation with the method parameter in the controller
public String updateActiveStatus(@RequestBody ArrayList<...

A: In case of using the parameter as List by the RequestParams:

In my case, it was a list on Enum values.

when(portService.searchPort(Collections.singletonList(TypeEnum.NETWORK))
                .thenReturn(searchDto);

ResultActions ra = mockMvc.perform(get("/port/search")
        .param("type", new String[]{TypeEnum.NETWORK.name()}));


Q: Can I apply the same styling to two elements together in jQuery by grouping them like in CSS? This is simply for keeping code neater. In CSS I can group elements like this:
.element1,
.element2,
.element3,
.element4,
.element5,
.element6 {
 font-weight:bold;
}

is there anything similar in jQuery or would I have to set each separately.
$('.element1').css('font-weight', 'bold');
$('.element2').css('font-weight', 'bold');
$('.element3').css('font-weight', 'bold');
etc

I suppose I imagine something like
$('.element1', '.element2', etc).css('font-weight', 'bold);

A: Even more simple, you can use precisely the same selector in jQuery as you could in CSS:
$('.element1, .element2').css('font-weight', 'bold);

A: The simple answer is yes, you can do that. But group your selectors using CSS syntax.
$('.element1, .element2, .element3').css('font-weight', 'bold');

A: $('.element1, .element2, etc').css('font-weight', 'bold');

JQuery multiple selectors.

A: Yes you can!
Except you want it like this: $('.element1,.element2').css('font-weight', 'bold);

Source: http://api.jquery.com/multiple-selector/

A: Use multiple selectors. Example:
$("div,span,p.myClass").css("border","3px solid red");


Q: find the k-th element in a unimodal array Given a unimodal array A of n distinct elements (meaning that its entries are in increasing order up until its maximum element, after which its elements are in decreasing order), an integer p (that is the length of the increasing first part) and k (the k-th minimum element)  Give an algorithm to compute the value of the kth minimal element that runs in O(log n) time.
Example:
A= {1,23,50,30,20,2}
p= 2
k=3

Answer: 20
Edit
I tried this:
def ksmallest(arr1, arr2, k):
if len(arr1) == 0:
    return arr2[len(arr2)-k-1]
elif len(arr2) == 0:
    return arr1[k]
mida1 = (int)(len(arr1)/2)
mida2 = (int)((len(arr2)-1)/2)
if mida1+mida2<k:
    if arr1[mida1]>arr2[mida2]:
        return ksmallest(arr1, arr2[:mida2], k-(len(arr2)-mida2))
    else:
        return ksmallest(arr1[mida1+1:], arr2, k-mida1-1)
else:
    if arr1[mida1]>arr2[mida2]:
        return ksmallest(arr1[:mida1], arr2, k)
    else:
        return ksmallest(arr1, arr2[mida2+1:], k)

A: For starters have another look at your indexes. You begin with:
if len(arr1) == 0:
    return arr2[len(arr2)-k-1]
elif len(arr2) == 0:
    return arr1[len(arr1)-k-1]

But surely if arr1 is in ascending order, and arr2 is in descending order the kth minimal element will not be found in the same location.


Q: flatten dataframe containing list with multiple dictionaries I have currently a pandas dataframe with 100+ columns, that was achieved from pd.normalize_json() and there is one particular column (children) that looks something like this:
name       age    children                                               address... 100 more columns
Mathew      20     [{name: Sam, age:5}, {name:Ben, age: 10}]                    UK
Linda       30     []                                                           USA

What I would like for the dataframe to look like is:
name       age    children.name    children.age                     address... 100 more columns
Mathew      20     Sam                  5                                        UK
Mathew      20     Ben                  10                                       UK
Linda       30                                                                   USA

There can be any number of dictionaries within the list. Thanks for the help in advance!


Q: React-router Uncaught TypeError: type.toUpperCase is not a function I'm using the latest version of react, react-router, gulp and browserify
I got this in beowser console:
Uncaught TypeError: type.toUpperCase is not a function
my code in app.js:
"use strict";
var React = require('react');
var Router = require('react-router');
var Header = require('./components/Header');
var Index = require('./components/Index');
var About = require('./components/About')
var Route = Router.Route;
var IndexRoute  = Router.IndexRoute ;

var App = React.createClass({
  render: function(){
    return (

          {this.props.children}

    );
  }
})
React.render(<Router><Route path="/" component={App}>
<IndexRoute  component={Index}/>
<Route path="about" component={About}/>
</Route>
</Router>, document.getElementById('app'));

A: Just upgrade your react router version from 0.0.13 to 1.0.0-rc1(beta) coz the below code will only work for 1.0.0 beta version which is mentioned in change log.
React.render(<Router><Route path="/" component={App}>
<IndexRoute  component={Index}/>
<Route path="about" component={About}/>
</Route>
</Router>, document.getElementById('app'));

After upgrading version you have to declare router properly like below.
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter .Router;
var Route = ReactRouter .Route;

Now router is defined properly. This worked for me..give a try.


Q: Changing data on db on a specific day and time - nodejs I have a specific requirment for a web application which is build with Nodejs/MongoDb/Express/Angular. Application itself is a application for mentors and has a kind of schema like this:
var userSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },

         username: {
        type: String,
        unique: true,
        required: true
    },
        ....

        status: {type: String, enum: ["online", "offline"]},
        schedule: [{
            day: String,
            StartTime: Date,
            EndTime: Date
        }]

                ...

        })

Every user has its own schedule, for example working Every: Monday ,Wednesday ,Thursday From: 04:00 PM To: 07:00 PM.
Now, how can I change the status from Offline to Online as they submited their schedule. I mean from the example above, to change Every: Monday ,Wednesday ,Thursday at the specific time the user status on db from "offline" to "online" ?
Thanks