Regaining Steamwheedle reputation?

Question: I've somehow managed to ruin my reputation with the Steamwheedle goblins, and they don't talk to me anymore. What should I do to quickly and easily regain their support?
Answer: As of patch 4.2 on August 18, 2011, the answers listed here are largely out-of-date; Dire Maul no longer offers a way of repairing Steamwheedle rep, and many of the linked guides have not been updated to reflect changes from Cataclysm.
The fastest way to repair rep with the Steamwheedle Cartel is to do the "Bloodsail Forgiveness" quests with the goblins standing outside each of the towns. These quests are Making Amends outside Everlook (requiring 40 Runecloth and 4 Coal with each turn-in), Mending Old Wounds near Ratchet (requiring 40 Linen Cloth and 4 Crystal Vials per turn-in), Traitor to the Bloodsail outside Booty Bay (requiring 40 Silk Cloth and 4 Red Dye), and finally War at Sea outside Gadgetzan (requiring 40 Mageweave Cloth and 4 Strong Flux).
Each quest contributes 500 rep to the adjacent city and 250 to the other three cities. This means that, starting from maximum hatred, you can complete a specific quest 84 times (requiring 168 stacks of relevant cloth and 336 of the extra material) to raise your reputation to neutral with that city; the next quest can be exhausted after 42 turn-ins (requiring 84 stacks of cloth and 168 materials). The third quest is finished in a mere 21 attempts (requiring 42 stacks and 84 materials), while the fourth quest is done after just 11 turn-ins (requiring 22 stacks and 44 materials). Each of these quests is no longer available once your rep with the associated city becomes neutral, so don't over-stock on materials!
If you want to minimize your cost, you should complete the quests in this order: Ratchet, then Booty Bay, then Gadgetzan, then Everlook. This is the most cost-effective way of achieving neutrality in the fastest possible way. However, if you want to subsequently raise your Steamwheedle rep to exalted (whatever the reason), you'll actually want to do Everlook first, followed by Ratchet, then Booty Bay, then Gadgetzan. The reason for this is because the spillover rep from subsequent quests will continue to raise your rep with the earlier cities, and the location of farm-worthy pirates is such that Everlook (and, to a lesser degree, Ratchet) are considerably harder to raise than Booty Bay or Gadgetzan.
If you don't want to buy the cloth outright, the next best option is to farm pirates in one of three locations: in Lost Rigger Cover in Tanaris, on the three ships south of Booty Bay in Stranglethorn Vale, or on the ship that appears in Booty Bay proper during Bloodsail attack on the city. The pirates in Tanaris and Stranglethorn will drop cloth that can be turned in outside their city in addition to the rep you gain from outright kills, but it's still a much longer process than just buying everything you need outright.
If you're trying to get rep past neutral, though, those three farming locations are really your only options. They each come with their own sets of advantages and disadvantages. A particular note about farming: when one or more other players is also in the area killing mobs, the respawn rate will try to increase to match the rate they're being killed at. In general, if you can get in a group with somebody else killing guys in the same spot as you, you'll have much higher rep-per-hour gains.

Lost Rigger Cove has lots of pirates in fairly high density spread over a large area; additionally, there's a pseudo-rare spawn on the south-easternmost ship that will award considerably more rep than pirates or even named pirate NPCs; however, he has a long respawn timer. Pirates here award ~5 rep toward Gadgetzan and ~2.5 rep toward the other cities.
The ships south of Booty Bay have a very high density of pirates and named pirate leader NPCs that can award a lot of rep pretty quickly, but their respawn rate is just low enough to be frustrating; the presence of another player on the opposite faction will particularly exacerbate this. The rank-and-file pirates here award about 5 rep to Booty Bay and about 2.5 rep to the other three.
The ship that spawns in Booty Bay has a lot of pirates and a very high respawn rate, but having Booty Bay's normal services and functions phased out can be kind of a hassle. There's a lot of chaos here, and I actually died on more than one occasion as a level 85 character just because I ran out of mana and didn't notice that my health had gotten so low. The other benefit of this method is that, like all Steamwheedle quests, doing the quest chain to start the phased event will award a little bit of rep all by itself. Low-level pirates here award about 5 rep to Booty Bay and about 2.5 to the rest of the Cartel.

You should probably try each location and determine which one works best for you. It's important to note that killing mobs for rep in one location alone cannot get you to exalted with the associated city; when I was doing it, I farmed Lost Rigger Cove until I stopped getting Gadgetzan rep, moved to the Bloodsail ships and farmed until exalted with Gadgetzan, and then moved back to Tanaris to get exalted with the other three factions.
Lastly, as I mentioned briefly above, any quests you can get in the various Steamwheedle cities will award a little bit of rep as well, but you'll have to be at least neutral or better to even have the opportunity to take them. Since this method isn't repeatable, and many people will have already done these quests prior to this situation, it's not as important as the methods above.
Answer: There is a very good guide linked from a similar question on Epic Advice that details killing a bunch of Bloodsail Buccannears to gain reputation quickly with the Steamwheedle.

I would like to point out a faster (and as yet unmentioned) way to get Steamwheedle rep. Specifically, grinding Southsea Freebooters (just south of Ratchet) and Wastewander (and/or Southsea Pirates*) in Tanaris. I find the rep/hour is much better than grinding shackle keys in Diremaul -- at least for me, who averages just over 2 keys/hour in DM (despite killing all 5 guards/captains 5 times an hour). And this can actually be done all the way to Exalted, if you are smart about when you grind what.

The rest of the guide details the order in which to farm reputations to get the best bonuses possible, and also includes many alternate methods you may find useful.
Answer: Besides killing thousands of Pirates you can spend 20Mageweave Cloth + 4 Strong Flux for 500rep each time until Neutral. The Npc is in Tanaris north of Gadgetzan.
Answer: The short answer is that the most efficient way to do this is killing some Bloodsail Buccaneers NPC.
There are more ways (Diremaul grinding, repetable quests) but they are more tedious.
A full explanation of all possiblities are detailed on WoWWiki

Regaining Steamwheedle reputation?


Play WebSockets don't work on Apache Tomcat

Question: I was trying to use WebSockets in my Play project, but seems, that play2war package I am using  does not support websocket handling. Now I wonder, whether there is any alternative way to deploy play project on tomcat or maybe some good substitute to websockets?
Thanks in advance
Comment: Is it vital that you use Tomcat?
Comment: I suppose so, actually, my aim is being able to deploy the project to wide spread servers, and for sure Tomcat is one of those.
Answer: It seems as though there is no support for WebSockets (yet). https://github.com/dlecan/play2-war-plugin
You could try and implement socket.io which has an active Java implementation here. Socket.io supports a variety of mechanisms for realtime communication in your browser.


Comparing two large dataframes w/ pySpark

Question: This post mentions symmetric difference and leveraging code df1.except(df2).union(df2.except(df1)) and/ordf1.unionAll(df2).except(df1.intersect(df2)) but I'm getting syntax errors when using except.
I'm trying to compare two dataframes who can have up to 50 or 50+ columns. I have the working code below but need to avoid hard coding columns.
sample code and example
# Create the two dataframes
df1 = sqlContext.createDataFrame([(11,'Sam',1000,'ind','IT','2/11/2019'),(22,'Tom',2000,'usa','HR','2/11/2019'),
                                 (33,'Kom',3500,'uk','IT','2/11/2019'),(44,'Nom',4000,'can','HR','2/11/2019'),
                                 (55,'Vom',5000,'mex','IT','2/11/2019'),(66,'XYZ',5000,'mex','IT','2/11/2019')],
                                 ['No','Name','Sal','Address','Dept','Join_Date'])
df2 = sqlContext.createDataFrame([(11,'Sam',1000,'ind','IT','2/11/2019'),(22,'Tom',2000,'usa','HR','2/11/2019'),
                                  (33,'Kom',3000,'uk','IT','2/11/2019'),(44,'Nom',4000,'can','HR','2/11/2019'),
                                  (55,'Xom',5000,'mex','IT','2/11/2019'),(77,'XYZ',5000,'mex','IT','2/11/2019')],
                                  ['No','Name','Sal','Address','Dept','Join_Date'])
df1 = df1.withColumn('FLAG',lit('DF1'))
df2 = df2.withColumn('FLAG',lit('DF2'))

# Concatenate the two DataFrames, to create one big dataframe.
df = df1.union(df2)

#Use window function to check if the count of same rows is more than 1 and if it indeed is, then mark column FLAG as SAME, else keep it the way it is. Finally, drop the duplicates.

my_window = Window.partitionBy('No','Name','Sal','Address','Dept','Join_Date').rowsBetween(-sys.maxsize, sys.maxsize)
df = df.withColumn('FLAG', when((count('*').over(my_window) > 1),'SAME').otherwise(col('FLAG'))).dropDuplicates()
df.show()

Comment: https://github.com/AbsaOSS/hermes has a DatasetComparison module. A stand-alone spark-job. In scala, it can be used as a library as well.
Comment: Do you have to code it yourself or can you use a tool for it?
Comment: @Saša Zejnilović, i can use packages and helper libs. I haven't found any in pySpark yet
Answer: You can get all column names from df and use that list as parameter for the Window function:
cols = df.columns
cols.remove('FLAG')
my_window = Window.partitionBy(cols).rowsBetween(-sys.maxsize, sys.maxsize)

The remaining code stays unchanged.
Comment: why use ```cols.remove('FLAG')``` ?
Comment: `FLAG` is the column that contains the information whether a row was orgininally coming from df1 or df2. You don't want this column to be part of the window definition.
Comment: I'm using the same code, but getting different output, https://stackoverflow.com/questions/62272046/customize-large-datasets-comparison-in-pyspark @werner


How can I give my App one interface for iPhone and another for iPad?

Question: So here is my problem....
I did develop an app for the iPhone. I'm done so far and everything works fine.
But I don't won't iPad users to get annoyed because of bad graphics on their screen.
Anyway iPad is not just a big iPhone, I also would like to give iPad users a special iPad-interface.
Do I have to distribute two different apps to solve this issue?
And if I have to, how can I tell itunesconnect that one app is just for iPhone/iPod and the other one just for iPad?
Can anybody please tell me which way I have to go?
I would be very thankful for some help!!!
Thanks!
Comment: Look at Universal Application - http://stackoverflow.com/search?q=ios+universal+app
Answer: this will help you
http://www.raywenderlich.com/1111/how-to-port-an-iphone-application-to-the-ipad
Answer: You can build a universal app what will be valid for both iPhone and iPad devices. In this way you just distribute a single app. Itunes connect and the app store will be aware that your app is valid for both devices.
You can find info on how to create a universal app from an iPhone app here for example: http://iphonedevelopment.blogspot.com/2010/04/converting-iphone-apps-to-universal.html


Call method after ear start

Question: I need to run ejb component and call a method after start application as early as possible. Does anyone know best solution, please help.
Answer: I am assuming it's a EJB application, in that case you can use singleton session bean, it can be used for application initialization in a portable, vendor-independent way.
And if it's a Web application then you need to use ServletContextListener
Comment: Ok, but how can I start it as first? For testing I want to write log "Start app".
Comment: you need to use @Startup annotation on the EJB
Answer: If you're using EJB 3.1, you can use @Singleton and @Startup as described in this blog entry.
If you're using older versions of the specification, a common way to achieve this is to register a ServletContextListener that does the initialization you want. This obviously requires to to create a war within your ear, if you don't have it already.

Call method after ear start


How do i redirect to a page from button click in react from a component?

Question: this is my app.js

  <Switch>
    <Route path="/" exact render={() => <DashBoard store={main} />} />
    <Route path="/newprocess" render={() =>
DEFG
} />
    <Route path="/release" render={() =>
ABCD
} />
  </Switch>

this is my process.jsx

New Process

this the function
 handleNewProcess = () => {
        //HOW DO I REDIRECT THE CLICK FROM HERE TO "/newprocess" page
    }

Comment: Does this answer your question? [programmatically-navigate-using-react-router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router)
Answer: You can use useNavigate().
    import { useNavigate} from "react-router-dom";

    const MyCompo= () => {

      let navigate = useNavigate();
      handleNewProcess = () => {
         navigate(`/newprocess/`);
        //HOW DO I REDIRECT THE CLICK FROM HERE TO "/newprocess" page
    }

And as nos nart mentioned, this solution is fit only from react-router v6.
Comment: v5 doesn't have `useNavigate` hooks
Comment: See the render props on Route comp. OP use react-router-dom v5 not v6
Comment: Hi @nosnart, can you please explain what do you mean? you mean useNavigation is working only on version 5?
Comment: i have used useHistory but its not working do i have to render anything ?
Comment: UseHistory is deprecated see the link https://github.com/frontarm/navi/issues/137
Answer: You can also solve this issue using useHistory hook
    import { useHistory} from "react-router-dom";

    const MyCompo= () => {

      let history = useHistory();
      handleNewProcess = () => {
         history.push('/newprocess/');
        //HOW DO I REDIRECT THE CLICK FROM HERE TO "/newprocess" page
    }

checkout this page ,  it has mentioned all the methods of redirection in react:
Link


Python save images with open CV to an array in a sorted way according to the image name

Question: I have 50.000 in a folder that have names "1.png" to "50000.png". And I want to save them to some array in spesicfic order, because I have labels for them in order to classify them. So when order of the images get messed up, labels become useless. (i.e: 1.png will be saved to first index and 2.png will be saved to second index etc.). I try this code for this purpose:
#Read and save all Images to images array.
images=[]
image_folder=[img for img in glob.glob("C:/Users/yazilim1/Desktop/Jupyter/cifar-10/train/*.png")]
image_folder.sort()
for image in image_folder:
    images.append(cv2.imread(image))
    print(image)
print("Number of Images added:" + str(len(images)))

However, print(image) output looks like this:

How can I achive to save that images to "images" array with order?
Comment: Why you don't use `dict`?
Answer: It is in order though.
Since image_folder is a list of strings, image_folder.sort() will perform lexicographical sorting, where "1" < "10" < "100" < "1000" < "1001" < ... < "2" < "20" and so on.
If you want to treat "100.png" like "integer 100 + file extension", do this:
image_folder.sort(key=lambda file_name: int(file_name.split('.')[0]))


Displaying JSON data from web-service on WP7

Question: I'm trying to parse and display JSON data retrieved using a webclient in my app. Here is the json string I want to display
<code>{"metadata":{"page":1,"perPage":23,"count":23},"results":[{"id":9,"name":"Breaks","slug":"breaks","subgenres":[]},{"id":10,"name":"Chill Out","slug":"chill-out","subgenres":[]},{"id":12,"name":"Deep House","slug":"deep-house","subgenres":[]},{"id":16,"name":"DJ Tools","slug":"dj-tools","subgenres":[]},{"id":1,"name":"Drum & Bass","slug":"drum-and-bass","subgenres":[]},{"id":18,"name":"Dubstep","slug":"dubstep","subgenres":[]},{"id":17,"name":"Electro House","slug":"electro-house","subgenres":[]},{"id":3,"name":"Electronica","slug":"electronica","subgenres":[]},{"id":40,"name":"Funk \/ R&B","slug":"funk-r-and-b","subgenres":[]},{"id":49,"name":"Glitch Hop","slug":"glitch-hop","subgenres":[]},{"id":8,"name":"Hard Dance","slug":"hard-dance","subgenres":[]},{"id":2,"name":"Hardcore \/ Hard Techno","slug":"hardcore-hard-techno","subgenres":[]},{"id":38,"name":"Hip-Hop","slug":"hip-hop","subgenres":[]},{"id":5,"name":"House","slug":"house","subgenres":[]},{"id":37,"name":"Indie Dance \/ Nu Disco","slug":"indie-dance-nu-disco","subgenres":[]},{"id":14,"name":"Minimal","slug":"minimal","subgenres":[]},{"id":39,"name":"Pop \/ Rock","slug":"pop-rock","subgenres":[]},{"id":15,"name":"Progressive House","slug":"progressive-house","subgenres":[]},{"id":13,"name":"Psy-Trance","slug":"psy-trance","subgenres":[]},{"id":41,"name":"Reggae \/ Dub","slug":"reggae-dub","subgenres":[]},{"id":11,"name":"Tech House","slug":"tech-house","subgenres":[]},{"id":6,"name":"Techno","slug":"techno","subgenres":[]},{"id":7,"name":"Trance","slug":"trance","subgenres":[]}]}
</code>
UPDATE
I am now getting a NullReferenceException when it gets to the foreach loop. For some reason it doesn't recognize "data"
<code>    // Deserialize the Data
    void beatportTest_GetDataCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        DataContractJsonSerializer serializer = null;

        try
        {
            serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Result>));
            ObservableCollection<Result> data = serializer.ReadObject(e.Result) as ObservableCollection<Result>;

            // foreach loop to display data
            foreach (Result genre in data)
            {
                string name = genre.name;
                listGenres.Items.Add(name);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code>
Here are my Classes.
<code>    public class Genres
    {
        public Metadata metadata { get; set; }
        public List<Result> results { get; set; }
    }

    public class Metadata
    {
        public int page { get; set; }
        public int perPage { get; set; }
        public int count { get; set; }
    }

    public class Result
    {
        public int id { get; set; }
        public string name { get; set; }
        public string slug { get; set; }
        // public List<object> subgenres { get; set; }
    }
</code>
Going off of L.B's updated class' what do I need to do to display textblocks of all the genres using the "name" field? Here is my xaml below.
<code>        <controls:PanoramaItem x:Name="genres" Header="genres">
            <!--Single line list-->
            <Grid
                <ListBox x:Name="listGenres" Margin="0,95,0,0">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Width="432" Height="78">
                                <TextBlock Text="???"  Style="{StaticResource PhoneTextExtraLargeStyle}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
        </controls:PanoramaItem>
</code>
Thanks again.
Answer: Here are the class definitions I used to deserialize your json string
<code>public class Genres
{
    public Metadata metadata;
    public Result[] results;
}

public class Metadata
{
    public int page;
    public int perPage;
    public int count;
}

public class Result
{
    public int id;
    public string name;
    public string slug;
    //public subgenre[] subgenres;
}

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Genres));
Genres data = serializer.ReadObject(e.Result) as Genres;
</code>
Comment: Thanks for the help! I'm trying to display all of the genres using a listbox. See update above.


Prove that two non-bald residents of NYC have exactly the same number of hairs.

Question: In New York City there are two non-bald people who have the same number of hairs ( the human head can contain up to several hundred thousands with maximum of about 500,000)
How can I prove the pigeonhole principle of the two non-bald people in New York City ?
The pigeonhole principle: if k is a positive integer and k+1 or more objects are placed into k boxes then there is at least one box containing two or more of the objects.
Comment: How many people are there in New York? What if they all had different numbers of hairs?
Comment: @Betty, you already had an existing account which you were using a few minutes ago.  Why did you create a new account?
Comment: Don't delete this question any more.  There is already an answer and it would be rude to the answerer if you delete the question.  Just go back to your original account for your next question.
Comment: Also, you forgot to include in the question the information that you already know.  Explain to the users what your idea of the pigeonhole principle is.  Then find out how many people there are in New York (Try typing "population of New York City" in [Wolfram Alpha](http://www.wolframalpha.com/).) then put that in your question.
Comment: Sorry I didn't remember my password, I try to delete and ask the question again.
Comment: I will correct my question. Thank you.
Comment: It seems that your question has been satisfactorily answered, so I won't answer it any more.  (Recall that I earlier said that I would answer your next question.)
Comment: I don't have information about New York City population .
Comment: As I said in my comment above, try typing "population of New York City" in Wolfram Alpha.  (Go to http://www.wolframalpha.com/)
Answer: Let's say the max number of hairs is 500,000 (which i think is rreeaallyy high..) so the claim is true for any city with 500,000+ (non bald)  people.
(there should be an assumption that there are more then 500,000 non bald people).
proof: try to give each person a different number of hairs, 1,2,3...
After 500,000 people, you've run out of different numbers. meaning the 500,001th person will have to get a number of hairs which is equal to some other person's number of hairs. These two are in the same pigeonhole
Comment: You actually have to assume that there are more than $500,000$ people with hair on their head. But that's not very difficult, since you would only need that more than $5\%$ of the people of New York has hair in their heads, which seems like a safe assumption.
Comment: @Arthur you're right I just came back to add this..
Comment: I don't have any detail about New York City population . Thank you for the other answer.
Comment: @Betty  The Census Bureau estimated the [population of New York City](http://www.nyc.gov/html/dcp/html/census/popcur.shtml) to be approximately 8.5 million in July 2014.


Please verify that my thinking about this struct related thing is correct

Question: struct Person *person_create(char *name, int age, int height, int weight)
{
    struct Person *who = malloc(sizeof(struct Person));
    assert(who!=NULL);

    who->name=strdup(name);
    who->age=age;
    who->height=height;
    who->weight=weight;
    return who;
}

I'm going through ex16 on http://c.learncodethehardway.org/book/ex16.html, and I am not entirely sure I understand this block of code.
As far as I can tell, going line by line, this code does the following:

Declare function that returns a Person, which takes the arguments *name, age, height and weight.
Declare a pointer of type Person the points to the top on a section of memory big enough to hold a struct of type Person.
Look at the pointer and determine if it is of type NULL.
Assign stuff.
Return the who pointer back to main(), so that stuff can happen.

To be honest, I do not understand why main() can then access this struct by a name other than who. How is the pointer passed? Or is the pointer global somehow?
Or, am I over thinking this?
Answer: A pointer is just a number.  It is a memory address.
Suppose you wrote down the address of your house on a piece of paper, put that piece of paper in an envelope, and wrote "who" on the outside. Then, you gave it to someone else, and that person put it in a different envelope, and wrote something different on the outside of the envelope.
Your actual address wouldn't change.  The contents of your house wouldn't change.
It is the same here, in C code.  You are putting the memory address returned by malloc in a variable called who (analogous to our "envelope".)  You are then modifying something in the memory the address points to.  You are then returning the address to someone who can put it in an entirely different variable with an entirely different name.
Answer:

Declare function that returns a Person, which takes the arguments
  *name, age, height and weight.

The function does not return a Person. It returns a pointer to a Person. The arguments are name, age and weight, not *name. The star in *name means that the argument name is of pointer type; it is not part of the argument's name.

Look at the pointer and determine if it is of type NULL.

NULL is not a pointer type. The pointer who is a pointer to struct person. Here, we are determining if the pointer value is NULL.
Note that strdup() can return NULL if no memory is available, just like malloc(). The code should probably check for that too.
As for how the pointer is passed to main: you return it from person_create() back to main(), so main() gets to choose how to access it. main() can do something like this:
/* ... */
struct Person *new_person = create_person(...);

/* Use new_person->age, etc. */

The point is, main() is free to choose the name it wants to give to whatever person_create() returns. It doesn't matter what you had inside person_create(), since as soon as you return, local variable names are destroyed.


Can't append inputs to the DOM

Question: I have to build a calculator using only JS, no HTML. I'm creating the basic input fields for the numbers, but I can't seem to append them to the DOM. I get the following error:
> Uncaught TypeError: Cannot read property 'append' of null.

This is my code:
var firstInput = document.createElement('input');
firstInput.setAttribute("type", "text");
firstInput.innerHTML = "";
document.body.append(firstInput);

CLARIFICATION: There is an HTML file, and I'm working on an external Javascript file that's linked to the HTML. However, they won't let me create elements from HTML and get them with Javascript. I can only create Elements using JS.
What am I doing wrong?
Comment: Using "the DOM" with "no HTML" is doesn't make sense. The DOM is a tool for using JavaScript to access, navigate, and alter the HTML. Without HTML, there is no DOM.
Comment: I'm going to guess that your code is in the `` without being wrapped in an `onload`, thus you're trying to access the `` before it exists.
Comment: Possible duplicate of [Why is document.body null in my javascript?](https://stackoverflow.com/questions/9916747/why-is-document-body-null-in-my-javascript)
Comment: @AndrewRay I would imagine that OP means they are using solely JS to construct the page elements, as opposed to the page "not being HTML". That said, we shouldn't have to guess, so your point brings to light that the question could certainly use some clarification.
Comment: @TylerRoper, right then, not sure why you would want to do that, but I guess it's just another homework assignment that does a terrible job approximating anything resembling the real world. I was thinking we were dealing with Node or similar "headless" JS.
Answer: When your code is executed, the body is not necessarily loaded yet. It is a good practice to wait for the DOM to be ready before using it in any way.
Your script should be placed at the very end of the HTML body.

(function() {
  // The DOM will be available here
  var firstInput = document.createElement('input');
  firstInput.setAttribute("type", "text");
  firstInput.innerHTML = "";
  document.body.append(firstInput);
})();

This answer gives you more details on how it works.
Comment: The key point is that the script tags with the snippet above are placed just before the body end tag () and after all the other html markup.

Can't append inputs to the DOM


Side-effect on upgrading kernel from generic to low-latency?

Question: I am using Ubuntu 14.04 in embedded
And I want to change Linux generic-kernel to Linux low-latency-kernel.
But i think if i change the kernel, some programs already installed and devices(for example touch pad) may not work, and i have to build and re-install.
Current My Linux version is 3.10.17, So
How about changing to low-latency-kernel which is same version(3.10).
It could also have some side effect?
And additionally, is there any command to upgrade kernel to low-latency-kernel, like apt-get....
Actually i found 'deb' file to upgrade kernel to low-latency for version 3.16 but i couldn't find 3.10.
Answer: The low latency kernel is not needed by most people as of kernel 2.6.31 .
It is (was) used as far as I know mainly for audio recording, although there may have been other uses. It is difficult to find detailed discussions on the patch but I suggest you look at

Kernels >= 2.6.31 seem to work pretty good without RT patch, also for real-time pro audio usage. It's not strictly necessary anymore to install a real-time ('rt') kernel to get good results. Although the best results are still expected when using a real-time kernel. Try it, test it and decide for yourself.

http://wiki.linuxaudio.org/wiki/system_configuration#the_kernel
NOTE: From this link they are discussing audio and "good" and "best" are extremely subjective and sometimes they are measuring things in very small time units and all the measurements on the web are old, pre 2.6.31 kernel.

Some confusion persists about the purposes of -lowlatency and -realtime kernels.

The goal of -realtime and -rt (hard real-time) kernels is to achieve the lowest possible latency at every cost. In technical slang "hard realtime systems should always meet their deadlines". Thus developers should use the most advanced programming techniques (sleeping spinlocks, PI Mutex, Full preemption, IRQ Threads and others) and sacrifice things like reliability, power-saving and throughput.
https://help.ubuntu.com/community/UbuntuStudio/RealTimeKernel
Fedora also has some quality documentation on this issue
https://docs.fedoraproject.org/en-US/Fedora/17/html/Musicians_Guide/sect-Musicians_Guide-Real_Time_Linux_Kernel.html
https://docs.fedoraproject.org/en-US/Fedora/15/html/Musicians_Guide/chap-Musicians_Guide-Real_Time_and_Low_Latency.html
Note the fedora links are somewhat dated and Fedora no longer maintains low latency kernels.
So a better question is, what makes you think a real time kernel is going to help you ? It does not appear you are doing anything (such as audio recording) that requires a RT kernel and the RT patch is unlikely to solve your problems with embedding.
You can always try a low latency kernel and if you have problems switch back, install and remove them with apt-get
sudo apt-get install linux-lowlatency

sudo apt-get remove linux-lowlatency

Personally I have not had any problems with the low latency kernel patch, but did not see any advantage either (I have used for audio recording only, Ardour 3 with multiple track play back, monitoring via headphones, and recording a new track).
Answer: That is the linux-lowlatency package from standard Ubuntu repository. Should not affect any software (I mean it won't need explicit recompile and adaptation).
But investigate some other options if you have time: the cgroups feature of the linux kernel can provide finer control without customizing kernel binaries.
Comment: Your comments are very valuable to us. So, leave them.
Comment: The low latency kernel is is not necessary for most people. See http://wiki.linuxaudio.org/wiki/system_configuration#the_kernel and vhttps://help.ubuntu.com/community/UbuntuStudio/RealTimeKernel
Comment: That's okay. I thought you had something about cgroups.
Comment: It depends on what you are doing, I am not sure how you would use cgroups here. I also advise at lease some discussion before installing the low latency kernel. Discussions on the low latency patch sometimes are more opinionated (IMO) then technical and the patch sacrifices stability and possibly security. I would advise the patch to someone who has a use for it (audio recording) but probably not on a standard desktop or server.
Comment: Also, while fast, the actual latency with a low latency kernel is more variable, the latency is not constant. With a standard kernel, the latency, although longer, the latency is more constant. It is sometimes easier to compensate for a longer, but predictable latency then a faster by unpredictable latency. One can never make the latency 0 ;) For these reasons most people are going with a standard kernel. Most peole can not detect the difference between 1 ms and 1.1 ms ;)
Comment: the actual latency is going to vary with hardware and needs to be benchmarked with and without the rt kernel - see https://ccrma.stanford.edu/~matt/latencytest/


A Finite Field of Order $125$ has a Subfield of order $25$?

Question: How to prove that every finite field of order $125$ has a subfield of order $25$. In general what is the strategy to attack such kind of problems?
Comment: You'll never prove it, it's not true.
Comment: See: http://math.stackexchange.com/questions/91087/subfields-of-finite-fields
Comment: Consider objects of the form $x^5$, where $x$ ranges over the big field.
Answer: Consider a field $F$ with $q$ elements, $q$ being a power of some prime. Suppose $L$ is a field containing $F$, with $[L\colon F]=m$. Since $L$ is an $F$-vector space of dimension $m$, $|L|=q^m$. Thus $[\mathbb F_{125}\colon\mathbb F_5]=3$. Now do you see why there's no field strictly between these two fields?
Comment: You don't need to consider $\Bbb F_5$, simply $[\Bbb F_{125}:\Bbb F_{25}]$ would have to be $3/2$, which is absurd.
Comment: Thank you. I understand your argument. I didnt in the least feel this could be a false statement.
Answer: So if there is a subfield G of size 25, you can remove the zero element and it becomes a group under multiplication. Specifically, it is a subgroup of F-{0}, but F-{0}=124, and 24 doesn't divide 124. All subgroup sizes must divide the size of the group they come from, therefore you can never have a subfield of size 25.


Expand matrix to orthogonal matrix ( Gram Schmidt)

Question: How can I complete a matrix to a orthogonal matrix?
Consider for example A given by
$
\begin{pmatrix}
1/\sqrt 6 & -1/\sqrt 2   \\
1/\sqrt 6 & 1/\sqrt 2  \\
2/\sqrt 6 & 0
\end{pmatrix}
$
Then there is written that one can complete this matrix with Gram Schmidt to get a orthogonal matrix given by
$
\begin{pmatrix}
1/\sqrt 6 & -1/\sqrt 2 & -1/\sqrt 3   \\
1/\sqrt 6 & 1/\sqrt 2  & -1/\sqrt 3\\
2/\sqrt 6 & 0 & 1/\sqrt 3
\end{pmatrix}
$

Could someone explain how to complete this matrix?
Answer: The Gram-Schmidt procedure is for the orthonormalization of a basis of a vector space. I never hear about "orthogonalize a matrix". If you "orthogonalize" a matrix as you are trying to do you will had a completely different matrix.
In any case not all matrix are "orthogonalizable", you need previously that the column or row vectors of the matrix define a basis for some vector subspace, otherwise your matrix will be not "orthogonalizable". In this case just extend this basis to a basis of the whole vector space and after apply the Gram-Schmidt procedure to this extended basis. Then the matrix defined by this basis, as columns or rows, will be orthogonal.
However observe that the orthogonalization is not unique because each orthonormal vector that you add can have at least two distinct directions.
Answer: You have already two columns: $v_1=\begin{pmatrix}\frac{1}{\sqrt{6}}\\\frac{1}{\sqrt{6}}\\\frac{2}{\sqrt{6}}\end{pmatrix}$ and $v_2=\begin{pmatrix}-\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}\\0\end{pmatrix}$. Add a new column just to make $(v_1,v_2,u)$ linearly independent. You have a lot of freedom there, choose whatever is the easiest for the subsequent calculation. For example, set $u=\begin{pmatrix}1\\0\\0\end{pmatrix}$.
Now:

Calculate the new vector:

$$\overline{v_3}=u-\langle u,v_1\rangle v_1-\langle u,v_2\rangle v_2=\begin{pmatrix}1\\0\\0\end{pmatrix}-\frac{1}{\sqrt{6}}\begin{pmatrix}\frac{1}{\sqrt{6}}\\\frac{1}{\sqrt{6}}\\\frac{2}{\sqrt{6}}\end{pmatrix}+\frac{1}{\sqrt{2}}\begin{pmatrix}-\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}\\0\end{pmatrix}=\begin{pmatrix}\frac{1}{3}\\\frac{1}{3}\\-\frac{1}{3}\end{pmatrix}$$

Calculate $\|\overline{v_3}\|=\sqrt{\langle \overline{v_3},\overline{v_3}\rangle}=\frac{1}{\sqrt{3}}$
Set $v_3=\frac{1}{\|\overline{v_3}\|}|\overline{v_3}\|=\begin{pmatrix}\frac{1}{\sqrt{3}}\\\frac{1}{\sqrt{3}}\\-\frac{1}{\sqrt{3}}\end{pmatrix}$. That is your third column.

You may get two different solutions (both are valid), depending on your choice of $u$ - just like in $3$-dimensional space you can have two different unit vectors orthogonal to an already given pair of orthonormal vectors. (If the two vectors are in a "horizontal" plane, the third vector may go "up" or "down".) It seems that you have one solution in your question, and I have found the other one.
In general, the Gramm-Schmidt process goes as follows: when adding a new vector to an already orthonormal set of vectors $v_1,v_2,\ldots,v_n$, you will choose $u$ to not be in the span of $v_1,v_2,\ldots,v_n$, and then you will set:
$$\overline{v_{n+1}}=u-\sum_{i=1}^n \langle u, v_i\rangle v_i$$
This will give you $\overline{v_{n+1}}$ which is already orthogonal to all of $v_1,v_2,\ldots,v_n$, but may not have the norm equal to $1$. Then you will "normalise" it:
$$v_{n+1}=\frac{1}{\|\overline{v_{n+1}}\|}\overline{v_{n+1}}=\frac{1}{\sqrt{\langle \overline{v_{n+1}},\overline{v_{n+1}}\rangle}}\overline{v_{n+1}}$$


Rewriting old and new urls to same page with .htaccess

Question: Have a page currently with the URL /results-details.php?mls_number=stringofnumbers.
I want it to re-write to: /results-details/stringofnumbers
However I want that to basically resolve back to the original page.
I'm also changing all the URLs on the site internally to point to the URL. So I have two re-write rules:
RewriteCond %{QUERY_STRING} mls_number=([0-9]+)$
RewriteRule (.*) /new-homes/results-details/%1? [R=301,C]
RewriteRule ^results-details/([0-9]+)$ results-details.php?mls_number=$1

The second rule works fine on it's own with internal links in the /results-details/stringofnumbers form, but the first one doesn't chain properly to the second one and not sure what I'm doing wrong.
Basically trying to retain any links to the old URLs that might be out there but start using the new URS internally.
Suggestions?
Answer: YOu need to match against the actual request and not the URI, because the rewrite engine loops:
RewriteCond %{THE_REQUEST} \ /new-homes/results-details\.php?mls_number=([0-9]+)
RewriteRule ^ /new-homes/results-details/%1? [L,R=301]

RewriteRule ^results-details/([0-9]+)$ results-details.php?mls_number=$1

Comment: Tried this and it doesn't seem to do anything. Not sure if it's failing to match or failing to re-write the URL or just looping.


Avoiding CPU race condition/cache invalidation of RNG on multi thread path tracing

Question: I'm implementing my path tracer using C++ and OpenMP partially based on the design of Small Paint (using a globally available RND function to generate random floats) and PBRTv2 (uses a single RNG across all threads). I notice that due to the fact there can can be multiple threads accessing the same RNG. Race condition and CPU cache invalidation will occur caused by the RNG writing to memory to store/update it's current state. Thus dragging the performance down and mess up the RNG(makes it unpredictable).
How come this is in one of the top grade educational renderer? Or it's just a minor issue that isn't important?
If it's important, is there a known good way to fix this without breaking PBRT's rendering/threading architecture?
Answer: You need to implement your own RNG class and not use the clib RNG implementation that shares the state across threads. What I'm using is a simple & efficient multiply-with-carry RNG by George Marsaglia, that I initialize with a seed based on pixel coordinates (e.g. simple x+y*width) that I'm calculating (state per pixel instead of global state)
Comment: This is more than thread safety. A mutex would make any global RNG thread safe but still slow and unpredictable with multiple threads. Per-pixel seed is indeed the way to go for reproducibility, although per-thread state is enough to fix the performance problem.
Comment: With thread-safe I don't mean use of mutex etc. but just making of an RNG class that has no static members. The clib version is bad as it has a global state shared across threads. I'll fix the answer to be more clear
Comment: PBRT already [has that](https://github.com/mmp/pbrt-v2/blob/master/src/core/rng.h) so the problem is likely how it is used (shared ?). I unfortunately don't know the PBRT code well enough to know what's going on.
Comment: A thread-safe RNG is not enough because that it only solves the race condition. But it serializes the execution and cache invalidation will still be present.
Comment: I'm not suggesting thread-safe implentation of a RNG class but implemeting RNG class that you use thread-safely, by not sharing the state across threads.


With image sliders on websites, is it bad to not allow user the option to manually control it?

Question: When implementing image sliders/carousels on websites, is it a necessity to put controls to allow the user to optionally click through the images if they desire, or is it okay to leave them transitioning in an infinite loop?
For more specific context, on the website I'm working on I plan to not have more than 4-5 images in the slider; if there were more images I could see the benefit of the controls, but for a small number of images (that don't link to other pages on the site) for display purposes only, is it acceptable to leave the option out?
Also, if you should add optional controls, when the user chooses to use them to go to another image, should you disable the automatic rotation, or leave it transitioning? Thanks.
Answer: yeah though there are only 4 - 5 images but it will take a minimum of 20 secs to see the picture again once animation started.it will be irritating for the user to wait for such long times. although the amount of content it has plays a major role
so it is preferable to include carousel or scroll bar at the bottom so that he can see whatever he wants.
you may want to animate the screens with picture transitions but you should provide controls with the user.

Also, if you should add optional controls, when the user chooses to
  use them to go to another image, should you disable the automatic
  rotation, or leave it transitioning?

you should allow the animation to run. Pause it only at times when the pointer is hovered over the image.
Edit
It's one of the 10 Heuristics of User Interface Design

User Control and Freedom:
  This principle talks about giving the user the freedom to navigate and perform actions. The freedom to undo
  any accidental actions. This principle can be best illustrated by the
  Gmail's flash message with undo action when we accidentally delete an
  email.


Join two dataframe

Question: I have to collect values from one dataframe and place in another. I have tried to use merge function but that mess up order in second dataframe.
This is how my data looks like.
<code>> df<-as.data.frame(cbind(letters[1:4],1:4))
> df
  V1 V2
1  a  1
2  b  2
3  c  3
4  d  4

> dflist <- data.frame("home"= sample(df[,1],15, replace = TRUE))
>
> dflist$away <-sample(df[,1],15, replace = TRUE)
> dflist
   home away
1     a    b
2     a    a
3     d    c
4     d    a
5     c    c
6     a    c
7     b    d
8     b    b
9     a    b
10    b    d
11    b    a
12    a    a
13    a    c
14    c    b
15    d    a
</code>
Desired result should look like this.
<code>   home away value1 value2
1     a    b 1 2
2     a    a 1 1
3     d    c 4 3
4     d    a 4 1
5     c    c 3 3
.
</code>
Outcome table will be lose its order if I use merge here.
Comment: Please use `set.seed` for the reproducibility of the sample.
Comment: Assuming you want to keep the order in `dflist`, you could create an index column (e.g. `dflist$idx <- 1:nrow(dflist)`, yes, there are many ways to do this, but this is just an example). Then sort the final result by the `idx` column.
Answer: You could try this:
<code>dflist[c("value1", "value2")] <- t(apply(dflist, 1, function(x)
    c(df[match(x[1], df$V1),2], df[match(x[2], df$V1),2])))
dflist
   home away value1 value2
1     a    b      1      2
2     a    a      1      1
3     d    c      4      3
4     d    a      4      1
5     c    c      3      3
6     a    c      1      3
7     b    d      2      4
8     b    b      2      2
9     a    b      1      2
10    b    d      2      4
11    b    a      2      1
12    a    a      1      1
13    a    c      1      3
14    c    b      3      2
15    d    a      4      1
</code>
Comment: This is exactly what I want. But I get an error msg when I copy your text.

> dflist[c("value1", "value2")] <- t(apply(dflist, 1, function(x)
+ c(df[match(x[1], df$V1),2], df[match(x[2], df$V1),2])))
Error in if (inherits(X[[j]], "data.frame") && ncol(xj) > 1L) X[[j]] <- as.matrix(X[[j]]) :
  missing value where TRUE/FALSE needed
Comment: My apologize. Works like a charm :)
Comment: Glad to hear that :-)

Join two dataframe


Fire event when changing route before DOM changes and outside the route itself?

Question: I opened a similar topic a few days ago, where I was suggested to use beforeRouteLeave within the route component definition.
However, I'm creating a Vue component and I won't have control over how developers wants to define their route components. Therefore, I need a way to fire an event within my own component and don't rely on external route components.
When changing from one route to another, the beforeDestroy gets fired after the DOM structure changes.
I've tried using beforeUpdate and updated events on my component definition, but none seems to fire before the DOM changes.
import Vue from 'vue'
import MyComponent from '../myComponent/' // <-- Need to fire the event here
import router from './router'

Vue.use(MyComponent)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
}).$mount('#app')

Comment: I don't understand why you can't define a `beforeRouteLeave` inside of your `MyComponent`?
Comment: `beforeRouteLeave` is a [navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards). It seems they can only be used within route components.
Comment: Sorry for asking, but what is it that you need to accomplish? Because i dont understand. If you build a component why not add a event handler which can be assigned, so the end developer can assign a `beforeRouteLeave` event to the component, and you can write the code for this even already, then you only need to check if the event handler is assigned.
Answer: In the Vue instance lifecycle, the hook beforeDestroy gets called once the DOM has changed.
You are most likely looking for a beforeUnmount hook, which would be in-between mounted and beforeDestroy, but that is not available:

However, you could take advantage of JavaScript hooks. There is a JavaScript hook called leave, where you can access the DOM before it changes.
leave: function (el, done) {
  // ...
  done()
},

For this to work, you would need to wrap your element in a <transition> wrapper component.
ie.
<transition
  :css="false"
  @leave="leave"
>

</transition>

...
methods: {
  leave(el, done) {
    // access to DOM element
    done()
  }
}


How can I declare this variable if it can be one of three different classes?

Question: Ive created three classes, a SportsCar Class, MuscleCar Class and a Car Class. In my code I give the user a choice of which car class they want to create
if(carType.equals("A")){
    SportsCar car1 = new SportsCar(year,make);
}
else if(carType.equals("B")){
    MuscleCar car1 = new MuscleCar(year,make);
}
else if(carType.equals("C")){
    Car car1 = new Car(year,make);
}

I made a GUI so that the user can interact with the car but i keep on getting an error saying it cannot find the variable car1
if(choice == 0){
    car1.accelerate();
    System.out.println("Your speed: " + car1.getSpeed);
    System.out.println("Your gas level: " + car1.getGasLevel);
}

I know that if there was only one car class i could just declare car1 before the if statement, but it can be one of three different classes. How can I fix this error?
Comment: Did you use `extends` with your car classes?
Answer: Each of those car1 variables is only visible within the scope of the if block containing it. You need to declare the car1 variable as a type which is common to all three options (I'm guessing Car) before the first if block is entered; eg
Car car1;

if(carType.equals("A")){
    car1 = new SportsCar(year,make);
    ...

Comment: It's not that the *cars* are visible, it's that the *variables* are visible within that scope...
Comment: Yeah, worded that badly didn't I.. Updated
Answer: The car is improperly scoped.  I'm assuming all class other than Car you referenced are a subclass of Car.  In this case you need to move the declaration of car out of the if blocks, into the method or class you are attempting to use it from.
Answer: There's a feature in Java just for that. It's called inheritance.
Basically, you can make one class a subclass of another. You use extends for that:
public class SportsCar extends Car {

or
public class MuscleCar extends Car {

This allows you to treat any SportsCar or MuscleCar as a Car. So you can declare the variable outside of the if statement:
Car car1;

and just assign to it from the if statement:
if(carType.equals("A")){
    car1 = new SportsCar(year,make);
} // etc.

The only problem is that the Java compiler will get scared that variable car1 might not be initialized. If carType is not "A",  "B", or "C", that will actually happen. So just shut it up:
Car car1 = null;

Before you do anything, please read the Java tutorial on inheritance.
Answer: Sounds like you need the other cars to inherit from a base Car class. Then you can do Car car1; if{...} car.accelerate()... Otherwise, you need a "default" clause in the if statement so that no matter what, car1 gets initialized.


Remove CSS atribute from body::after

Question: I'm trying to remove the background-image attribute with jQuery but I had no success until now. The '::after' don't let me remove-it. How I can do that?
body::after {
     background-image: url(../images/16_sm.jpg);
}
Comment: What do you mean by "The '::after' don't let me remove-it."?
Answer: Try like this,
Html:

Css:
.test::after{
 background-image: url(../images/16_sm.jpg);
}

Js:
$('body').removeClass('test');

Answer: Try this.
$(body).css("background-image", "");

or
$(body).css("background-image", "none");

Remove CSS atribute from body::after


list bucket content by name GCS go

Question: I'm trying to read the content of a bucket on Google Cloud Storage using GO.
I'm able to do that, but is is very slow.
The content of the bucket is like this:
bucket name
-> folders with alphanumeric characters
----> 5 files into each of the folder
--------> each file has a json array inside

what I want to do is to inspect the content of the jsons files for all the folders in the bucket and look for a specific value. The following code work, but it is very slow:
package backend

import (
    "encoding/json"
    "fmt"
    "golang.org/x/net/context"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/appengine"
    "google.golang.org/appengine/file"
    "google.golang.org/appengine/urlfetch"
    "google.golang.org/cloud"
    "google.golang.org/cloud/storage"
    "io"
    "io/ioutil"
    "net/http"
)

var bucket = "bucket_Name"

type jsonStruct struct {
    Gender string `json:"gender"`
    Age    string `json:"age"`
    ID     string `json:"id"`
    Done   int    `json:"done"`
}

type saveData struct {
    c       context.Context
    r       *http.Request       //http response
    w       http.ResponseWriter //http writer
    ctx     context.Context
    cleanUp []string // cleanUp is a list of filenames that need cleaning up at the end of the saving.
    failed  bool     // failed indicates that one or more of the saving steps failed.
}

func init() {
    http.HandleFunc("/", handleStatic)
    http.HandleFunc("/listBuckets", listBuckets)
}

func handleStatic(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Cache-Control", "no-cache")
    http.ServeFile(w, r, "static/"+r.URL.Path)
}

func listBuckets(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    if bucket == "" {
        var err error
        if bucket, err = file.DefaultBucketName(c); err != nil {
            // log.Errorf(c, "failed to get default GCS bucket name: %v", err)
            return
        }
    }
    hc := &http.Client{
        Transport: &oauth2.Transport{
            Source: google.AppEngineTokenSource(c, storage.ScopeFullControl),
            Base:   &urlfetch.Transport{Context: c},
        },
    }
    ctx := cloud.NewContext(appengine.AppID(c), hc)

    // structure to holds information needed to run the various saving functions
    d := &saveData{
        c:   c,
        r:   r,
        w:   w,
        ctx: ctx,
    }

    d.listBucket(bucket)
}

func (d *saveData) errorf(format string, args ...interface{}) {
    d.failed = true
    // log.Errorf(d.c, format, args...)
}

func (d *saveData) listBucket(bucket string) {
    io.WriteString(d.w, "\nListbucket result:\n")

    query := &storage.Query{}
    for query != nil {
        objs, err := storage.ListObjects(d.ctx, bucket, query)
        if err != nil {
            d.errorf("listBucket: unable to list bucket %q: %v", bucket, err)
            return
        }
        query = objs.Next
        for _, obj := range objs.Results {
            d.readFile(obj.Name)
        }

    }
}

func (d *saveData) readFile(fileName string) {

    rc, err := storage.NewReader(d.ctx, bucket, fileName)
    if err != nil {
        d.errorf("readFile: unable to open file from bucket %q, file %q: %v", bucket, fileName, err)
        return
    }
    defer rc.Close()
    slurp, err := ioutil.ReadAll(rc)
    if err != nil {
        d.errorf("readFile: unable to read data from bucket %q, file %q: %v", bucket, fileName, err)
        return
    }
    var userDetails jsonStruct
    err1 := json.Unmarshal(slurp, &userDetails)
    if err1 != nil {
        d.errorf("readFile: %v", err1)
        return
    }
    fmt.Fprintf(d.w, "done is: %v\n", userDetails.Done)
}

Basically now I'm reading the folder name from the bucket and then I read the content using the folder name. It would be possible to cache all the bucket content in a go variable and then work on that variable instead of read the bucket for each folder?
I really need this to be faster because I need to present the result back in real time.
Thanks a lot
Comment: Seems like Datastore would be more suitable for this kind of job. Is there a reason you're using GCS? If the objects change infrequently and are read frequently, look at memcache.
Comment: I'm using GCS because the app was built with that so It will be hard to rewrite everything. I'm sure there is a way to read the content returned by rc, err := storage.NewReader(d.ctx, bucket, fileName) and decomposed it as needed.
Answer: See below a simple Go sample code to list the bucket content on Google Cloud Storage:
package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "cloud.google.com/go/storage"
    "google.golang.org/api/iterator"
)

func main() {
    os.Setenv("GOOGLE_APPLICATION_CREDENTIALS",
              "C:\\Users\\Shubham Snehi\\Downloads\\awacs-dev-160bf0e57dc1.json")

    ctx := context.Background()

    client, err := storage.NewClient(ctx)
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }
    defer client.Close()

    // Sets the name for the new bucket.
    bucketName := "balatestawacs"

    // Creates a Bucket instance.
    bucket := client.Bucket(bucketName)

    it := bucket.Objects(ctx, nil)
    for {
        attrs, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            panic(err)
        }
        fmt.Println(attrs.Owner)
    }
}

list bucket content by name GCS go


How to #define variable in C

Question: I have a file called config.h with the following...
#define GL_DOOM

Then I have the following in another file m_misc.c...
#include "config.h"
...
#if ((defined GL_DOOM) && (defined _MSC_VER))
LOGD("Using glboom-plus.cfg");
#define BOOM_CFG "glboom-plus.cfg"
#else
LOGD("Using prboom-plus.cfg");
#define BOOM_CFG "prboom-plus.cfg"
#endif

But it says...

05-02 14:40:24.789: D/Doom(2966): Using prboom-plus.cfg

What is the deal here? I am new to C so what am I missing?
Comment: `&& (defined _MSC_VER)` <- `_MSC_VER` seems to not be defined.
Comment: which compiler are you using?
Comment: Is the line `#define GL_DOOM` in config.h getting parsed? For example, are there `#if`'s or `#ifdef`'s around it?
Comment: @DanielFischer seems the right answer why you did not put it as an answer ?
Comment: As for compiler I am using the gcc compiler on Android NDK (So bionic)
Comment: Sorry missed the _MSC_VER thing, let me try to remove then I will update
Answer: Let's take the following code:
#define GL_DOOM
#define _MSC_VER

#if ((defined GL_DOOM) && (defined _MSC_VER))
LOGD("Using glboom-plus.cfg");
#else
LOGD("Using prboom-plus.cfg");
#endif

I can compile that code with g++ -E which will output the result of the preprocessor. Let's look at that output.
# 1 "blah.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "blah.c"

LOGD("Using glboom-plus.cfg");

So, to me, this implies that you probably don't have both GL_DOOM and _MSC_VER defined.

You might verify this with a test that looks something like:
#include "config.h"

#ifndef GL_DOOM
#error GL_DOOM is not defined
#endif

#ifndef _MSC_VER
#error _MSC_VER is not defined
#endif

It's also worth noting something. _MSC_VER is a preprocessor symbol that is defined almost strictly by Microsoft Visual Studio. If you're not compiling with that software, then the expectation would be that it would not be defined.
Comment: +1 for educating on `-E` and `#error` to debug preprocessing step.
Answer: #include "config.h"

that includes the #define GL_DOOM.
...
#if ((defined GL_DOOM) && (defined _MSC_VER))

That checks whether both, GL_DOOM and _MSC_VER are defined.
Since GL_DOOM is defined, either your preprocessor is totally broken, or _MSC_VER is not defined.
Answer: The check
#if ((defined GL_DOOM) && (defined _MSC_VER))

will only evaluate to true if both the conditions are met. You have not specified whether you have defined _MSC_VER in the header file. That is probably the reason why it is executing the else condition.
If you want to log when either of those are defined in the header file, use the OR operation instead:
#if (defined (GL_DOOM)) || (defined (_MSC_VER))

How to #define variable in C


Are Wii games multilanguage (EU Region)?

Question: Are Wii games multilanguage in EU region?
I live in Italy but I found some very good prices on UK sites, so I am wondering if games sold there have Italian language included.
If there is no general rule and it depends on the publisher where can I find more information?
Comment: ...do you really care about the horrible dubs and translations usually seen in games? :) (I say this as an active member of the VALVe translation team for Italian.)
Comment: They are not for me, but for my nephew (6 years old). :D
Answer: Games are locked by television regions. NTSC-U/C applies to USA & Canada, NTSC-J to Japan and PAL applies to a set of countries, which include the United Kingdom and Italy.
The language depends on the publisher/game; I have seen games have different amount of languages...
Comment: @Drake: That depends on the publisher/game; I have seen games have different amount of languages...
Comment: Thank you @Tom I know the region restrictions, but I am trying to understand if Wii games sold in EU contains multiple languages or not.
Answer: From my experience working on localized games, usually Europe territory (which sometimes includes Australia too) is known as EFIGS, or English French Italian German Spanish.
So most localized games you might find in UK would be also in Italian. But they need to be localized, something that is usually stated on the box (which you might be able to look at even in Internet shops).
Hope this helps!
Answer: You could look in the Nintendo Wii games database which language are included in the UK version. (The UK version should be the PAL one that include the English language.)


size a steel beam

Question: What size beam do I need to span 21'.
Beam supported at both ends.
Beam resting and attached on concrete wall at both ends.
Beam will hold one end of a floor system - so stabilized by floor system.
Floor system rests on concrete wall at one end and on the beam at the other.  No support along the sides of the floor.
Uniform load of 8000# so the beam will need to hold 4000#.
Static loan - will be used for storage.
Comment: You need to get a structural engineer to do this, not rely on some unspecified website... if it goes wrong the insurance will hang you out to dry.
Comment: Voting to close. The question may seem simple, but probably isn't, and OP hasn't been back.
Comment: While I agree that before you actually purchase anything you'll want to have a registered engineer approve and stamp your plans.  In fact, that may be necessary in order to obtain a permit.  But it may be useful to calculate the needed beam size for planning and budgetary purposes.  I don't, however, see that you've provided enough information.  First of all, is the load 8000# or 4000#?  You seem to indicate both.  Second, what is the maximum deflection you can tolerate?  It's common that the deflection drives the design more so than the max. load capacity.
Answer: Use a A992-50 W10x19 steel beam. By saying it's a 8000# uniform load over 21 feet, the OP is telling us that it's 381# per lineal foot. 381# multiplied by 10.5 feet is 4000#, that's why he said there's 4000# at each end. This beam will deflect L/384, or about 0.66" at max deflection, which is on par for anything that spans 21'. Code minimum is L/240, so it's above that too. No, you don't need an engineer. An inspector might want a calc, so ask your lumber yard or steel beam supplier if they won't let you start without one.
Comment: @DanielGriscom Using a W10x19 seems grossly over sized. It supports a uniform load of 19,700 lbs.  It would be nice to have the OP clarify the 8,000# and 4000# issues. Dotes thinks it's 8000# uniformly distributed over the 21', but it could be 8000# per foot. Nowhere does the OP say the reaction is 4000# at each end. The OP just says the BEAM will need to hold 4000#. That could be a point load. (The beam doesn't "hold a reaction. ) At 381# plf contributing to load, the floor span can only be about 3', because storage requires a minimum of 100 psf by Code.

size a steel beam


How to handle effect way of JSON parsing from Firebase Remote Config in Android using Kotlin?

Question: I have various set of configuration in firebase with JSON format.
From App side, i am using data class to parse the firebase remote config.
Data classes:
val object1: SampleData1
val object2: SampleData2

I am reading the response with below code. Here if any issue with parsing JSON for object1 it will throw exception so object2 parsing will not happen in this situation.
What is the best way to handle these scenarios?
try {
    object1 = ......
    object2 = .....

} catch(e: Exception) {

}

Comment: Hi, did you try parsing `object2` in a separate try-catch?
Comment: Is that good way? because if i have 10 object classes, then i need to add try and catch for each and every class?
Comment: If we have 10 different classes it will be very less efficient even while fetching data, so in those cases either we should do try-catch in the loop on the array or try storing data in fewer classes.
Answer: This question has nothing to do with firebase remote config and is more generally a programming question.


Convient way to convert int(yyyymmdd) to datetime object and str

Question: using python 3.8, pandas 1.14
I have an integer value 20210126
I want to create an datetime object and str object of it.
current method:
dt = 20210126
dt_dt = datetime(year=d_i//10000, month=(d_i%10000)//100, day=d_i%100)
str_dt = dt_dt.strftime("%Y%m%d")

Alternative:
dt = 20210126
dt_dt = datetime(year=int(str(d_i)[:3]), month=int(str(d_i)[3:5]), day= int(str(d_i)[5:])
str_dt = str(dt)

This works fine however wondering if there is convient way.
Comment: @ti7 Not quite, after some tweaks yes however answer below is more intuitive for Non-pandas uses also so I prefer leaving it,
Comment: Does this answer your question? [Convert Pandas Column to DateTime](https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime)
Answer: Use strptime and strftime
value = 20210126
d = datetime.datetime.strptime(str(value), "%Y%m%d")
# datetime.datetime(2021, 1, 26, 0, 0)
d.strftime("%a, %b %m, '%y")
# "Tue, Jan 01, '21"

Format codes listed here!: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
If you are working within Pandas, it may actually be easier to keep these as some simple integer type until you need them, but you can convert the values similarly with its .to_datetime() method
import pandas as pd
df = pd.DataFrame({"dates": [20010101, 20020202]})
#       dates
# 0  20010101
# 1  20020202
pd.to_datetime(df.dates, format="%Y%m%d")
# 0   2001-01-01
# 1   2002-02-02
# Name: dates, dtype: datetime64[ns]

These can also then be represented as strings of some form by using the .dt.strftime method of the Series
Note .dt is from the df.dates column in this case and is a special accessor for datetime Series
df.dates = pd.to_datetime(df.dates, format="%Y%m%d")
#        dates
# 0 2001-01-01
# 1 2002-02-02
df.dates.dt.strftime("%a, %b %m, '%y")
# 0    Mon, Jan 01, '01
# 1    Sat, Feb 02, '02
# Name: dates, dtype: object

Answer: You can use strptime():
import time

dt = 20210126
str_dt = str(dt)
dt_dt = time.strptime(str_dt, '%Y%m%d')

Comment: Thanks! Your method is clean and simple however I don't want to avoid importing a library.


Dynamic CSS content filling

Question: I know from "Dynamic" CSS id names? How to add them to the CSS file? that you can have the following:

This allows for dynamic css stanza names, but not dynamic content.
Is there a way that I can have say...

Where the attribute of the style element is determined by the name of the object itself? In this case, using a substring of the id of the div element, attempted to be obtained via a bastardised form of regex, to determine it's color.
Answer: Going through W3C and MDN,  it is clear that you can't do that using color css property. even in CSS3.
Hence you need to do that dynamically.
Using JS
el.style.color = "#" + el.id.match(/[^_]+$/)[0];

Working fiddle
Comment: @glasnt yeah seems better... I can't think of anything else rather than for loop though :)
Answer: No you can't do it with just pure CSS. But you can use JavaScript to handle this.
Comment: Could you please provide a link or an example?

Dynamic CSS content filling


Where do gifts spawn in Eyeaduct?

Question: Dual to the question for Mann Manor, where can gifts spawn in the 2011 Halloween map Eyeaduct?  The couple I've found have just been in the middle while fighting for the point, never seen them "behind enemy lines" or the like.
Apparently gifts can spawn in the underworld as well; are they different and do they only spawn when actually accessible (MONOCULUS is alive)?
Answer: Here's an image gallery with the gift locations on Eyeaduct.
The gifts that spawn in the underworld give Haunted versions of the same 2011 Halloween items. There's no special difference between Haunted and non-Haunted versions other than the item name and name color (Haunted items are purple, like unusuals).
According to commenters, gifts can always spawn in the underworld or on the main Eyeaduct map. Apparently there is a difference in the "gift has appeared" message between underworld and non-underworld gifts but I have yet to confirm what the difference actually is.
Comment: Actually the underworld ones can spawn at any time, and it becomes a race to see who's the first through the portal once monoculus spawns.
Comment: I can confirm Mr Smooth's comment is true, I've seen it too

Where do gifts spawn in Eyeaduct?


Errors with htaccess

Question: Today I tried to write a .htaccess file for first time in order to remove .html extension from url bar along with some other things that I wanted to do. Since I was unfamiliar with all this I read several articles before coding.
I ended up with the following code. I also removed .html from all links. The problem is that when visiting my domain I get the following error.
//The resource you are looking for has been removed,
//had its name changed, or is temporarily unavailable.

Is my code correct?
UPDATED .htaccess
//Rewrite to www
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

//Remove .html UNTIL NOW THIS IS THE ONLY PART
//OF THE CODE THAT ACTUALLY WORKS.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

//Caching schema
<FilesMatch "\.(jpg|png)$">
Header set Cache-Control "private, max-age=160704000"
</FilesMatch>

//Prevent viewing of .htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>

In a separate .htaccess
//Prevent directory listings
Options All -Indexes

MAIN ERRORS
If I click on link like:
Home

Then I get the same error.
Thank you all in advance.
Comment: Did you have success with my answer?
Comment: I am working on it :)
Comment: See https://stackoverflow.com/questions/1992183/how-to-hide-the-html-extension-with-apache-mod-rewrite
Answer: This is native in Apache without using mod_rewrite by using MultiViews option.
Documentation states:

The effect of MultiViews is as follows: if the server receives a request for /some/dir/foo, if /some/dir has MultiViews enabled, and /some/dir/foo does not exist, then the server reads the directory looking for files named foo.*, and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements.
Comment: I tried the code suggested in the post but with no results. I still get the same error.
Answer: I finally managed to resolve  a part of the problem. For starters I changed my server from windows to linux.
Then to remove html extension I used this code in .htaccess (the other codes didn't work well, giving me an error message)
//Remove .html
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]

I also removed any .html instances from all links.
Now it works like a charm.

Errors with htaccess


Changing relative layout programmatically

Question: I've relative layout i.e. main.xml which I set as follows. But now I've to put view1 on view2 with width=200dp and height =100dp, so that view2 will be large one and  view1 will be small one on it.
public void onCreate(Bundle savedInstanceState)
         {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
         }

main.xml
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
    android:id="@+id/MainPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/panel_bottom"
    android:layout_gravity="center_horizontal" >

    <com.proj.demo.view1
        android:id="@+id/sheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignWithParentIfMissing="true"
        android:layout_centerInParent="true"
        android:layout_toLeftOf="@+id/panel_quick_buttons"
        />

    <com.proj.demo.view2
        android:id="@+id/sheet2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignWithParentIfMissing="true"
        android:layout_centerInParent="true"
        android:layout_toLeftOf="@+id/panel_quick_buttons"
      />

</RelativeLayout>
</RelativeLayout>

Answer: What do you want to achieve? If you just want to change width and heigh than:
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.yourId);
    rl.getLayoutParams().height = 100;
    rl.getLayoutParams().width = 100;

Comment: @bagusflyer you can use rl.requestLayout();
Comment: then call invalidate() from rl afterwards.
Comment: Nothing happen when I call rl.invalidate(). But it will change after I scroll the screen. Anyway to refresh the whole screed?
Answer: I have found some void changes when try to change multiples times the size like this :
relativeLayout.layoutParams.width = size
relativeLayout.layoutParams.height = size

So, insted you can use this kotlin function

Executes block with the View's layoutParams and reassigns the
layoutParams with the updated version.

relativeLayout.updateLayoutParams {
    width = size
    height = size
}


Recurring functions in Node JS

Question: I try to develop a little browser game based on NodeJS and Angular 4.
I have an API server running on NodeJS which is connected to a MongoDB and a second server running Angular 4.
I want to execute recurring standard functions (like every 15 minutes) in the background.
Do I need a third server which runs that functions? Or can I run that functions independently on my API server - no matter which route is open?
Comment: you mean calling the certain api every 15 minutes
Comment: I mean, getting data from the DB and do something with it and save the update; e.g.: check all 15 mins if a player has a mine, then increase his/her resources by 1
Answer: You might want to have a look to this library node-cron. You can set it up to work with your services. You will need to initialise the job right after your sever is initialised. An example:
var CronJob = require('cron').CronJob;
var job = new CronJob({
  cronTime: '00 30 11 * * 1-5',
  onTick: function() {
    /*
     * Runs every weekday (Monday through Friday)
     * at 11:30:00 AM. It does not run on Saturday
     * or Sunday.
     */
  },
  start: false,
  timeZone: 'America/Los_Angeles'
});
job.start();

Comment: Thanks for helping out. It help that you told me where to place the code. I go with setInterval, but CronJob looks like a good tool too.
Answer: You can use setTimeout() and setInterval() in Node just like in the browser:
setInterval(() => {
  // this runs every 15 minutes
}, 15 * 60 * 1000);

Comment: sure, thanks for your comment! but I worry about the function when the API is on "/whatever". Is it still working?

Recurring functions in Node JS


Time complexity of binary tree traversal( pre order)

Question:         PreorderTraversal(root)----T(n)
        {
          //Base case
          If(root equals null)-------------------O(1)
             return errormsg; ------------------O(1)
         else
             print root;---------------------------------O(1)
            //Recursive case
            PreorderTraversal(root.left);--T(n/2)
           PreorderTraversal(root.right)-T(n/2);
         }

Time complexity calculated based on back substitution method
Base case  assumed as 1
        T(1)=O(1)
        T(n) = O(1)+T(n/2)
        T(n/2)=O(1)+T(n/4)
        T(n/4)=O(1)+T(n/8)
        T(n)=1+T(n/2)
               =1+1+T(n/4)
               =2+T(n/4)
               =2+1+T(n/8)
               =3+T(n/8)
        Pattern follws like
              = K+T(n/2^k).     I.e. n/2^k =1
                                             n = 2^k
                                             K= logn
              =log n + 1
              =log n

In my understanding time complexity of binary tree(pre order traversal) is log n most of them said time complexity of binary tree(pre order) is
    O(n)
I don't know which one is correct??
Kindly guide me for above issue??
Answer: The time complexity for pre-order traversal is O(n) because you visit each node only once.
Answer: The reason you get T(n)=log(n) is that your equation for complexity is incorrect.
It should be T(n)=O(1)+2T(n/2) (because you are applying the same algorithm for the left and the right child). And this will be the case only when the tree is balanced, if the tree is linear then you would have T(n)=O(1)+T(n-1) which will give you clearly a linear time. Also the first case will give you a linear time. By applying your method you would get T(n) = O(2^k * T(1)) where k = log(n) so T(n)=O(n).
To make it easy to compute time complexity just imagine what the algorithm does, here the preorder will visit all the nodes, and each node only once, so it is intuitive that is O(n) time complexity
Answer: I had the same question today. Your equation is slightly wrong. That's why you're getting log(n) complexity.
T(n) = T(n/2) + T(n/2) = 2T(n/2) //equation 1
T(1) = O(1) //base case
T(n/2) = T(n/4) + T(n/4) = 2T(n/4) //equation 2

On solving them, we get,
T(n) = 2T(n/2)
T(n) = 2*2(T(n/4)) = 4(T(n/4))
T(n) = 2^k * T(n/2^k) //equation 3

On solving for the value of k, we get,
n/2^k = 1
n = 2^k
log n = k

On using the value of k in equation 3, we get,
T(n) = 2^logn * T(1) // 2^logn is n.
T(n) = O(n) * O(1)
T(n) = O(n)

And that is how you get O(n) time complexity.
Comment: wh 2^logn is n ?
Comment: `2^log(n) = n` -To prove it, apply log to both sides. It would be equal to `log(n) = log(n)`. Because `log(2^log(n) = log(n) * log(2)` and `log(2) = 1`.


Faction Membership Limits in Fallout 4

Question: Are there any limitations to the faction memberships you can have in Fallout 4?
I'm brand-new to the Fallout universe, and just got to the point of being invited to the Brotherhood of Steel. However, I'm a bit concerned about their politics and how it may affect my standing with other factions I may encounter.
If I join the Brotherhood, will there be other factions that I can't join? Are there any other factions that have such limitations?
Note: I'm still not very far into the game, and not very familiar with the Fallout 4 universe in general, so please make liberal use of spoiler markdown in your answers. Essentially, the only things that need to be un-spoilered are Yes/No answers for the questions asked above.
Answer: If I join the Brotherhood, will there be other factions that I can't join?
No.
Are there any other factions that have such limitations?
No, but they're not friendly with each other and you will be forced to choose in order to finish the game (contains spoilers).
Comment: Also: **If I join the Brotherhood, will I lose a little favor with companions who are allied with an opposing faction?** Yes. Im not sure how much, or what actions actually "displease" them, but Preston had something to say about me joining the Brotherhood.
Comment: Piper disliked me joining the Brotherhood, but it did not affect the romantic relationship level enough to really change anything.  And she's easy to keep happy by picking locks.
Comment: The dislike penalty for a companion doesn't appear to be sufficient enough to stop you romancing them although I'm still testing what happens if you destroy the institute with the courser as a companion

Faction Membership Limits in Fallout 4


.mdf file does not respond to SqlCommand.ExecuteNonQuery

Question: I have a weird problem with my local database. I added it as a .mdf file, and created 2 tables in it.
I tested the connection and the message box states that the connection is working properly.
The problem appears when I try to insert data into that database from my C# application. I tried 2 different ways:

By using SqlCommand.ExecuteNonQuery("INSERT INTO ....")
By using .dbml file (Linq-to-SQL) datacontext

When I try to insert data, no error is thrown, but no data is inserted into the database either. What could be the problem?
I'm using C# in VS 2010 and SQL Server 2005 to make my application
Comment: Have you tried refreshing the view of the database in SQL Management Studio. Go to the database that should have the new tables, select it and then hit F5. There you have your tables! Alternatively if this does not work, post your `ExecNonQuery` code...
Comment: Can you show us your **connection string**? I have a hunch - but I need to see if you really use that approach ...
Comment: This is my connection string: `Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MDC.mdf;Integrated Security=True;User Instance=True`
I found one very weird thing: I tried to display the data directly from the application by using dataGridView, and it works properly. But still when I close the application and try to query the database manually from VS 2010, it shows that it is empty.
Comment: @NDraskovic when you are looking in VS2010, you are probably looking in the **source** folder. When it executes, it is in a **different** folder (typically the "bin"). And if you run it *again*, it typically copies the file from source to the execute folder (depending on the project settings). Different files in different folders, all different versions of MDC.mdf
Comment: If I'm correct, this should not be the problem when I publish my application and install it on another computer. The database should fill/empty normally like any other, right?
Answer: most perceived problems with MDF files tend to boil down to one of:

what file have I actually opened?
is my build/run process actually copying over that file every time I run the application?
do I have gratuitous error-handling that is swallowing an exception?

Check your connection string, and look in the execution folder (not the project folder), until you are very sure which file is being opened. It should get updated after your work (make sure you dispose the connection etc properly).
Also: try fetching the data in a new data-context immediately after the insert, so see if it made it in or not.
Comment: Yes that occurred to me to. Please take a look at the comment I posted in my question.
Comment: @NDraskovic indeed; replied on that


"Uncaught TypeError: $(...).tinymce is not a function " error on JQuery ajax load

Question: Hi there I try load tinyMce plugin with jQuery load ajax.
I try this:
index.php

Also in editor.php
 <textarea></textarea>

But I got this error on console:

VM1647:2 Uncaught TypeError: $(...).tinymce is not a function

how can handle these error?
Comment: Seems that you need to load the `tinymce.min.js` after loading JQuery library..!
Comment: Mostly it happens due to not loading the required js library file on time.!
Comment: I thought  getScript do that! So how can I load 'tinymce.min.js'
Answer: Here is working code for what you want to accomplish :
Tested Myself:
index.php :

<button id="go">Load</button>

editor.php :

<textarea>Easy! You should check out MoxieManager!</textarea>

Comment: because it's a  part of big forms and I want load it with ajax (if user needs it)...I want smaller html size for index.php


Distance to a plane question?

Question: Find all points with a distance of 5 units away from the plane defined by the equation $2x - 3y + 4z + 5 = 0$.
My solution was to use: $\frac{|Ax + By + Cz + D|}{\sqrt{A^2 + B^2 + C^2}} = 5$. The result I got were:
$|2x - 3y + 4z + 5| = 5\sqrt{29}$.
Answer 1: $2x - 3y + 4z + 5 = 5\sqrt{29}$.
Answer 2: $-2x + 3y - 4z - 5 = 5\sqrt{29}$.
Are these correct? If not, how would one go about solving this question?
Comment: There must be two answers, namely the two parallel planes with distance 5 to the given one.
Answer: Draw a perpendicular line (in both directions) of length 5 starting at your original plane. This describes the set of points at distance $5$ from your plane. Can you see it?

Distance to a plane question?


Copy files from multiple sub-directories to the same destination directory

Question: We have almost 300 subdirectories in main directory. Now we want to copy all files from subdirectories in a single command to Destination directory. Is it possible?
Main Directory
     SubDirectory
        SubsubDirectory1
           xx.jpg
           xx,jpg
        SubsubDirectory2
           xx.jpg
           xx,jpg
     SubDirectory
        SubsubDirectory1
           xx.jpg
           xx,jpg
        SubsubDirectory2
           xx.jpg
           xx,jpg
     SubDirectory
        SubsubDirectory1
           xx.jpg
           xx,jpg
        SubsubDirectory2
           xx.jpg
           xx,jpg

I found below command can do work. But it is hard to mention each and every subdirectory name in the command.
cp "Main Directory"/*/Subsubdirectory1/* destdir

Answer: The find command is a good tool for that kind of operation, best in combination with xargs.
Try something like:
find "Main Directory" -type f -print0 | xargs -0 cp -t destdir

and have a look at man find, man xargs and man cp for details on how this works.
Answer: Like this, using bash in recursive mode (**) :
shopt -s globstar

cp -l **/*.jpg 'Main Directory'/

I use -l switch to avoid wasting disk space, it create hard links
Comment: Yes, post edited accordingly


Does a roommate count as being married for Grandpa's Evaluation?

Question: I'm talking about

 Inviting Krobus to live with you

Being married with a fully upgraded house is worth 1 point in Grandpa's evaluation. Does this roommate count in the same way?
Comment: Calling that character a "roommate" was probably just to avoid the obvious implication should they be called "married" (i.e. that the farmer and character were doing adult stuff to one another) along with all the IRL drama it might or might not cause. As far as the game is concerned, it is the same.
Answer: According to a comment on Reddit, it is enough to have a roommate instead of being married.

When I put my housemate-Krobus save file through Stardew Checkup, it said it does.


How to add custom music?

Question: I've heard that you can add your own custom music to be played through the iDroid if you have the PC version of MGSV. If it's possible, how do you do it? Can it be done on the console versions?
Comment: you might wanna take a look at that http://www.gamepur.com/guide/20188-mgs-v-phantom-pain-how-add-custom-music-idroid.html
Answer: Adding custom music is only possible in the PC release of Metal Gear Solid 5.
To add your custom music, copy your audio files to the CustomSoundtrack within your Metal Gear Solid 5 folder (defaults to C:\Programs (x86)\Steam\Steamapps\common\MGS_TPP) and these will be picked up in game.
Comment: Do you have any idea for consoles too? i did some research but didn't find anything consistent, it seems like this is not possible.
Comment: @JohnnyBgud, you could just run the Spotify app in the background. Not quite the same... but at least you can listen to what you want while you play console.

How to add custom music?


How can I download my disc games onto PS4 without needing to put discs in again?

Question: Are there ways to download a game onto your PS4 so you don't need the disc without paying for it on the store?
Answer: No, otherwise people would do this and then return or redistribute the discs
Comment: I thought most retailers do not accept opened discs as returns. The logic seems to be more around the resale of discs, or, the "circulating disc" where one person buys the game and lets ten other people use it. Either way, downloading the game from disc would certainly be abused by many and thereby lower physical copy sales.
Comment: @ARich there's also PS4 game disc rental service somewhere out there.
Comment: Actually yeah by 'return' I was making the assumption of a rental but I guess that business isn't as big as it used to be


How to I unlock the Comedy Specs?

Question: How do I unlock the Comedy Specs in Lego Harry Potter years 5-7? Is it in the Weasley shop?
Answer: According to the Lego Game Blog, the Comedy Specs are already unlocked when you start the game, and just need to be purchased in the Leaky Cauldron.

How to I unlock the Comedy Specs?


Fractional parts in base number systems other than base-10?

Question: A long-standing question I've asked myself over and over again is how one might express fractional parts of a whole in base number systems other than 10. Is it truly as simple as base-10's x/y system? Or is it even possible? If it is, how might a computer express a fractional part of, say, binary or hexidecimal?
Comment: I think that this link: http://mathforum.org/library/drmath/view/55744.html will be of help to you.
Answer: I guess it should be as straightforward as x/y
for example 1/3 in base 10 would be 1/11 in binary
adding 1/3+ 1/3 =2/3 base 10 would be 1/11+1/11 = 10/11 in binary
adding 2/3+1/3 =1 should be 10/11+ 1/11= 11/11=1 in binary
Comment: Hmm... Interesting. I'll accept this answer for now- if anyone has anything else they'd like to add, feel free. Thanks.
Comment: This answer is not correct, $1.11 = 1*2^0 + 1*2^{-1}+1*2^{-2}$ this is analog to the decimal system where for example $1.57=1*10^0+5*10^{-1}+7*10^{-2}$
Comment: @Eliot - See my comment


What's the proper procedure for replacing ungrounded circuits?

Question: I have a house that has several ungrounded circuits that uses the older 2 wire romex (pvc insulation, black woven jacket).
I'd love to have AFCI protected circuits for the bedrooms, and grounded outlets for some other rooms, but I don't want to have somebody rip the old cable that runs horizontally between the outlet boxes (also don't want to attempt that myself).
Would this be a proper procedure for replacing ungrounded circuits?
I was thinking something like:

Disconnect old circuit
Take out old boxes, put bigger rework boxes in (current boxes are small)
Drill new hole up from basement under boxes
Fish wire up, secure in box with tab/clamp and with staple in basement*
Connect each outlet run for the room together with a junction box*
Run to panel*

*Assuming proper support according to 334.30
I also had a question with regards to NEC 334.30(B)(2):

334.30 Securing and Supporting Nonmetallic-sheathed cable shall be supported and secured by staples, cable ties, straps, hangers, or
  similar fittings designed and installed so as not to damage the cable,
  at intervals not exceeding 1.4 m (4 1⁄2 ft) and within 300 mm (12 in.)
  of every outlet box. junction box, cabinet, or fitting. Flat cables
  shall not be stapled on edge. Sections of cable protected from
  physical damage by raceway shall not be required to be secured within
  the raceway.
(A) Horizontal Runs Through Holes and Notches. In other than
  vertical runs, cables  installed in accordance with 300.4 shall be
  considered to be supported and secured where such support does not
  exceed 1.4-m (4 1⁄2-ft) intervals and the nonmetallic-sheathed cable
  is securely fastened in place by an approved means within 300 mm (12
  in.) of each box, cabinet, conduit body, or other nonmetallicsheathed
  cable termination.
FPN: See 314.17(C) for support where nonmetallic boxes are used
(B) Unsupported Cables. Nonmetallic-sheathed cable shall be permitted to be unsupported where the cable:
(1) Is fished between access points through concealed spaces in finished
  buildings or structures and supporting is impracticable.
(2) Is not more than 1.4 m (4 1 ⁄2 ft) from the last point of cable
  support to the point of connection to a luminaire or other piece of
  electrical equipment and the cable and point of connection are within
  an accessible ceiling

Does 334.30(B) allow for this type of installation?
Would 334.30(B) allow for a fished dropwire from an attic, with an unsupported vertical "run" of more than 4.5 feet down to an outlet box?
Comment: [This answer](http://diy.stackexchange.com/a/36427/33) might be helpful.
Comment: It's better to use the device box as a junction point, rather than having all the cables spliced in a single junction box.  Star topology doesn't work well in electrical wiring. You'll end up with huge junction boxes (box fill), and using terminal blocks instead of twist-on wire connectors. Also, using the tab clamps on plastic boxes as the only support method is not usually a good idea.
Comment: What is the goal of this project, why are grounding conductors required?  Neither Arc-Fault Circuit Interrupters (AFCI), nor Ground-Fault Circuit Interrupters (GFCI) require grounding conductors.
Comment: @Tester101 Its two-fold
1. I'd like to AFCI's on the bedroom/living room circuits (sounds like I can do this already so +1)

2. I'd like to have a few grounded outlets for things that require long term use of a three-prong plug.  The boxes are tight already without a GFCI outlet.
Comment: Based on your comments I will not do the star-topology replacement in the bedrooms. I do have a few outlets that have direct runs from the basement with nothing else in the series, so I may replace one of those in the future if needed.
Answer: I seem to recall (not from a handy chunk of code, just from talking with an electrician I work with sometimes) that abandoning wire is generally a no-no (not sure if that applies when  it's inaccessible and impractical to remove, which might make the exception.)
Fishing wires up or down exterior walls that have insulation in them will be potentially frustrating, to say the least.
334.30(B)(1) would appear to allow this, and 334.30(B)(2) only says it applies in accessible ceiling spaces. 334.30(B)(1) (an inaccessible, impractical to support space in an existing finished structure that wire is fished through) appears to apply, without a specific length limit. But they don't get a lot of points for clarity.
If you are opening up to put in larger boxes, you may be able to staple the ends of the cables before you set the box (reaching through the box hole.) Doing so won't really buy much though, since that end will be supported at the box. You definitely want to fish the wire before you set the new box.
Comment: Old house, no exterior wall insulation. Usually sucks but in this situation it seems to be a boon.
Comment: What I prefer doing with abandoned wires that I can't remove is to twist the conductors together so that it can never be energized. I also connect one end to ground.
Answer: Before going through all that I'd check:

If the existing metal boxes are already grounded (See How should I connect to a short ground wire in a metal box? and maybe Should old knob and tube wiring be replaced? )
If the old cables will come out cleanly from below.  Fish a string as you yank out the old cable.

Note:

The NEC's unsupported rule does not apply inside walls.  You get a free pass on that one.
You can put an AFCI breaker on the two wire circuits, no problem.
You can put a three prong GFCI on the two wire circuits, as long as they are labeled as such.
Comment: Thanks!  I'm going to put GFCI's as the first outlet in the series and replace the remainder with Tamper-Resistant 3-prongs with the appropriate stickers.  Also going to put in AFCIs.  Looking forward to make this house safer.
Comment: Caution: unless the chain has three wires, your first GFCI won't protect the chain of outlets.  Install a GFCI at each location.  Or just be happy with the AFCI on the chain (and install a real grounded outlet for anything near water).
Comment: @Bryce -- no, a GFCI will protect ungrounded outlets downstream of it.
Comment: @ThreePhaseEelm a GFCI will not protect downstream outlets if there are only two wires between the points.


Replacing a switch with something that is always on

Question: I recently installed a dusk to dawn light for the front porch and would like to keep the switch Always On at all times. This is more for the overzealous kind at home who want to switch everything off at night :)
I am thinking of replacing the normal switch on the wall with a stationary plate and making the wires hardwired at all times. Is there a specific term for this type of plate?
I've searched all over but could not find this in the store.
Comment: Or  wire 120 VAC to the switch itself so Mr. (or Mrs.) Overzealous quickly learns to leave the switch alone.   **JOKE** do not actually do this!  :-(
Answer: If you're trying to cover the whole box

Blank plate
Blank cover plate
Blank wall plate
Blank electrical box cover
Blank switch cover

If you're trying to cover one slot of a multi-gang box

Blank insert
Blank switch insert
Blank toggle insert
Blank Decora insert

If you just want to lock the switch in the ON/OFF position

Switch guard
Switch lockout
Switch shield
Answer: This is what I got for covering one slot in a multi-gang box.

Leviton 80706-W 2-Gang, 1-Toggle 1-Blank Device Combination Wallplate, Standard Size (White)
https://www.amazon.ca/gp/product/B000U3BXBM/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1

The guy at my hardware store said what I posted didn't exist! The internet shall provide :). I think my answer looks cleaner then a blank single insert, but if you have more then a 2 switch gang box, that might be the only option. Update: I actually tried using a single blank with my double gang setup and it didn't work, a double gang box is not 2x the size of a single gang box, so the single blank cover was too big. Glad I found my solution! Also, be careful to look, is your blank switch on the left or right!
Answer: Your switch guard is your best option . Most run by switch to reset light and if you want it to stay on. then you shut off it resets back to dust to dawn or motion.
Answer: I would recommend not fully removing the switch, as your lights are most likely on the same circuit as other lights. So if you change your mind down the road, want to switch the dusk to dawn for a motion sensor, or are having issues with the light that require you to cut the power, there is a good chance you will also be in the dark somewhere else in your house. For motion sensors, for example, they often have a function where you can flip the switch twice to make them stay on permanently, and flip it again to revert to motion sensing mode.
A good option, similar to the switch guard, but easier to flip if need be, would be a lock switch. You'll see these in a lot of commercial settings. It basically takes the spot of a regular switch, but it doesn't have a handle. Instead, there is a little key that you insert if you need to flip the switch. They look like this: