Why is the color of my text not changing?

Question: I am desperately trying to change the color of "hero-text" in CSS.
It does not work (unless I style in the HTML). Google Dev Tools did not help me find out why. I just need to know why.

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  }

h1,h2,h3,h4 {
  font-family: 'Fjalla One', sans-serif;
}

p{
  font-family: 'Merriweather Sans', sans-serif;
}

/* Navbar */

.sm-logo{
font-family: 'Fjalla One', sans-serif;
font-size: 50px;
margin-left: 20px;
color: white;

}

.navbar {
  background-color: transparent;
  display: flex;
  justify-content: space-between;
  padding-bottom: 0;
  height: 100px;
  align-items: center;
}

.nav-menu {
  display: flex;
  margin-right: 10px;
  flex-direction: row;
  list-style: none;
}

.nav-links {
    margin-left: 50px;
    margin-right: 20px;
    color: white;
    padding: 8px;
    display: inline-block;
    list-style: none;
    text-decoration: none;
    font-family: 'Merriweather Sans', sans-serif;
    text-transform: uppercase;
  }

.burger {
  display:  none;
  }

/* Hero image */

#hero-image {

  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("../images/hero.png");
  height: 100vh;
  width: 100vw;
  max-width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  };

/* Hero text */

#hero-overlay {
  color: white;
  font-size: 100px;
  };

/* Simple Responsive Framework. */
.row {
  width: 100%;
}

                Christine Grän

Über Mich

Bücher

Termine

Kontakt

 Lorem ipsum......

Please help. I want to learn from this but it has been hours and Id love to move on to something else.
This is my js fiddle : https://jsfiddle.net/6rqy85bx/7/
Comment: Welcome. Please take the [tour] to learn how to use this site.
Answer: For that we need to select .hero-text in CSS and apply color property.
Also I have removed certain unwanted ; in your CSS.

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  }

h1,h2,h3,h4 {
  font-family: 'Fjalla One', sans-serif;
}

p{
  font-family: 'Merriweather Sans', sans-serif;
}

/* Navbar */

.sm-logo{
font-family: 'Fjalla One', sans-serif;
font-size: 50px;
margin-left: 20px;
color: white;

}

.navbar {
  background-color: transparent;
  display: flex;
  justify-content: space-between;
  padding-bottom: 0;
  height: 100px;
  align-items: center;
}

.nav-menu {
  display: flex;
  margin-right: 10px;
  flex-direction: row;
  list-style: none;
}

.nav-links {
    margin-left: 50px;
    margin-right: 20px;
    color: white;
    padding: 8px;
    display: inline-block;
    list-style: none;
    text-decoration: none;
    font-family: 'Merriweather Sans', sans-serif;
    text-transform: uppercase;
  }

.burger {
  display:  none;
  }

/* Hero image */

#hero-image {

  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("../images/hero.png");
  height: 100vh;
  width: 100vw;
  max-width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  }

/* Hero text */

#hero-overlay {
  color: red;
  font-size: 100px;
  }

/* Simple Responsive Framework. */
.row {
  width: 100%;
}
/*Hero-Text*/
.hero-text {
  color: white;
  font-size: 25px;
  }

                Christine Grän

Über Mich

Bücher

Termine

Kontakt

 Lorem ipsum......

Answer: You are not targeting the hero-text class at all, so I'm guessing there is a style on that class or element that overrides what you do.
This should target the text:
.hero-text {
color: white;
font-size: 100px;
}

If this still doesn't work, try #hero-overlay .hero-text {}
Comment: Its really not that I tried it and it just wont work. I also can't target hero-overlay at all.
Comment: This answer is wrong because you has errors in your css, remove ; after }
Comment: Yes I had copied OP's code and failed to remove the semicolon.
Answer:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  }

h1,h2,h3,h4 {
  font-family: 'Fjalla One', sans-serif;
}

p{
  font-family: 'Merriweather Sans', sans-serif;
}

/* Navbar */

.sm-logo{
font-family: 'Fjalla One', sans-serif;
font-size: 50px;
margin-left: 20px;
color: white;

}

.navbar {
  background-color: transparent;
  display: flex;
  justify-content: space-between;
  padding-bottom: 0;
  height: 100px;
  align-items: center;
}

.nav-menu {
  display: flex;
  margin-right: 10px;
  flex-direction: row;
  list-style: none;
}

.nav-links {
    margin-left: 50px;
    margin-right: 20px;
    color: white;
    padding: 8px;
    display: inline-block;
    list-style: none;
    text-decoration: none;
    font-family: 'Merriweather Sans', sans-serif;
    text-transform: uppercase;
  }

.burger {
  display:  none;
  }

/* Hero image */

#hero-image {

  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("../images/hero.png");
  height: 100vh;
  width: 100vw;
  max-width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  };

/* Hero text */

#hero-overlay {
  color: white;
  font-size: 100px;
  };

#hero-overlay .hero-text{
  color:white
 };

/* Simple Responsive Framework. */
.row {
  width: 100%;
}
Comment: Your answer should include some explanation. Please see [answer].
Comment: Please try to add  #hero-overlay .hero-text{color: white;} in your css code as shown
Comment: Your _answer_ should have some explanation. It should not be down here in a comment.


If T is a normal operator, prove that characteristic vectors for T which are associated with distinct characteristic values are orthogonal.

Question: The question is that
If $T$ is a normal operator, prove that characteristic vectors for $T$ which are associated with distinct characteristic values are orthogonal.
my proof is,
let $W_i=$ eigenvector space associated with eigenvalue $c_i$
each $W_i$ is invariant under $T^*$
Would give a hint for this problem?
and
Is is okay with space is not finite?
Comment: Are characteristic values eigenvalues?
Comment: [Related](https://math.stackexchange.com/q/778946/81360) (I'll leave it to someone else to decide if it's a duplicate).
Answer: Suppose that $T(u)=\lambda u$ and that $T(v)=\mu v$, with $\lambda\neq\mu$; you want to prove that $\langle u,v\rangle=0$. Well,\begin{align*}\lambda\langle u,v\rangle&=\langle T(u),v\rangle\\&=\langle u,T^*(v)\rangle\\&=\langle u,\overline{\mu}v\rangle\\&=\mu\langle u,v\rangle.\end{align*}Since $\lambda\neq\mu$, $\langle u,v\rangle=0$.


How to disable large title shrink when scrolling

Question: I want to use large title navigation bar. But navigation bar is getting smaller when I scroll screen. How can I disable shrink to NavigationBar.
<code>        self.navigationController?.navigationBar.prefersLargeTitles = true
</code>
Answer: I solved the problem:
Make sure there is no scrollview at the top of your view hierarchy. If you have scrollView(TableView, CollectionView) it is shrink.


How to mock a class in C# unit testing project

Question: I have a class I want to moq :
<code>    public class ODriver
    {
        public int DriverId { get; set; }

        public virtual bool CanDrive()
        {
            return false;
        }
    }
</code>
She is used like this in the method I want to test :
<code>    var driver = new ODriver();

    // Must be false except in the unit test
    var canDrive = driver.CanDrive();
</code>
I mock the method like this in my unit test :
<code>  var driverMoq = new Mock<ODriver>();
  driverMoq.Setup(d => d.CanDrive()).Returns(true);
</code>
When the test is runned, the result of the CanDrive method returns false. What do I have to do in order to have the mocked class used ?
Thank you all !
Comment: Sounds like you don't use `driverMoq.Object` for the unit test and instead use `new ODriver()`
Comment: 404 is right. Just made a try and driverMoq.Object.CanDrive() returns true.
Comment: Please, share your test and `driverMoq` usage
Comment: Yes I don't use the driverMoq.Object, I use the new ODriver() in the method I want to test, this method doesn't know the moq and I don't want my production code to use a Moq. Maybe mocking a class is not what I expected.
I thought mocking a class will "replace" all calls to the class with my moqs methods. It's not how it works ?
Comment: No. When you create a mock you create a fake with the behavior you want (in that case returns true instead of false). But that behavior is only available if you use the mock itself.
And you should never user a mock in production code of course, only in tests.
Comment: If you want to change the behavior of your production code for a test, you should consider to create your mock and inject it (see dependency injection).
Comment: @Pierre-Luc no, you create a mock object and pass it instead of real instance
Comment: Yes Acord I am agree with you, the depency injection pattern will return the moq object. I thought it will be automagical the moqs, my bad :(
Answer: So the answer is :
I adapted the code of the method I tested and added the ODriver object as parameter.
Thank you for your help, I didn't know how it works.
PierreLuc


Add many element into list without instantiate too many object

Question: I have a for loop like and an ArrayList as follow:
List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();
for(int i = 0; i < input.getNoVehicles(); i++) {
                                            //Name vehicle by index
    VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle " + String.valueOf(i+1))
            //The first location - depot location is indexed as 0 in Matrices
            .setStartLocation(Location.newInstance(i))
            .setBreak(lunch)
            .setLatestArrival(input.getOperating())
            .setType(type)
            .build();
    vehicles.add(vehicle);
}

So, I want to ask: Is there any way I instantiate the VehicleImpl outside the loop and use the ONLY ONE instance. For each iteration, I modify the instance add the new version of instance to the list.
Comment: No. You would modify everything you add to the list, as the reference would be the same for all objects. You must have one separate instance for each different object.
Comment: You might want to revisit the meaning of "object" and "instance". If you have only one instance that means you have only one object. And if you add that to the list multiple times you'd still have only one element referenced by multiple "slots". What makes you want to reduce the number of objects in the first place?
Comment: If you instantiation your vehicle outside the loop you will add the same vehicle to the list on each iteration step
Answer: Yes but you have to clone the first intance at leat (By using BeanUtils for example).
Then you just update the startLocation attribute.
Answer: You could instantiate the builder outside the loop, which would halve the number of objects you're creating, but only if you were to change the builder's constructor to have zero arguments, moving the vehicle name into a setter. For example:
List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();

VehicleImpl.Builder builder = VehicleImpl.Builder.newInstance();

for(int i = 0; i < input.getNoVehicles(); i++) {

    VehicleImpl vehicle = builder
            //Name vehicle by index
            .setName("vehicle " + String.valueOf(i+1))
            //The first location - depot location is indexed as 0 in Matrices
            .setStartLocation(Location.newInstance(i))
            .setBreak(lunch)
            .setLatestArrival(input.getOperating())
            .setType(type)
            .build();
    vehicles.add(vehicle);
}

This is somewhat more error prone because values in the builder are not reset on each new iteration. That's not necessarily a problem for you right now, but if you were to add conditional logic, you'd probably start having a lot of problems. However, if your goal is to reduce the number of objects created, this will satisfy that.
Comment: That only works if the builder doesn't have any invisible internal state that needs to be reset after `build`, though.
Comment: @MalteHartwig Sure. I think I'd be surprised if a builder functioned that way and it's the kind of thing that ought to be documented if it did. It looks like OP is the author of the vehicle and its builder so he'll know whether or not that's the case.
Comment: Right, just wanted to point out the possibility. If, for example, the builder creates an empty Vehicle instance internally, and set its attributes with each setter call, then it would have to create a new instance after the call to `build`, otherwise it will override the previous instance's attributes. That's an assumption, of course; the builder might be perfectly fine.


Attempted import error: 'shouldUseActivityState' is not exported from 'react-native-screens'

Question: I'm getting this error :
C:/Users/Mobile/node_modules/@react-navigation/drawer/lib/module/views/ResourceSavingScene.js
Attempted import error: 'shouldUseActivityState' is not exported from 'react-native-screens'.
before i was able to do login authentication and now it says 405 error i don't know if this is related to this error or not.I'm creating project using react native expo.
Comment: do you actually have a repro where you get this error in react-native? regarding web, this error is from ts-loader if you use it, and will go away if you use babel-loader instead
Comment: @satya164 I have this error in web. how should I use babel-loader? I even don't know whether I'm using ts-loader or no
Comment: what are you using? CRA? see https://github.com/react-navigation/react-navigation/issues/8993#issuecomment-717233195
Comment: @satya164 I've seen this issue. Isn't babel-plugin-react-native-web enough? I'm using react-app-rewired
Comment: You need to make sure to use babel-loader like in the comment.
Comment: Refer to this Github issue for more info https://github.com/react-navigation/react-navigation/issues/9129
Answer: Assuming you are using Expo 40,
I can confirm that per this comment on 'warnings printing to console for un-exported members of react-native-screens',
you can make the compile/console warning go away if you upgrade react-native-screens to newer version — if you are ok with expo warning you that your react-native-screens version number is out of range (Expo 40 wants screens version ~2.15.0, actual current version 2.17.x)
Answer: upgraded expo to 41.0.1 and react-native-screens to 3.0.0
~~removed warning


The best and simple way to convert labeled text classification data to spaCy v3 format

Question: Let's suppose we have labeled data for text classification in a nice CSV file. We have 2 columns - "text" and "label". I am kind of struggling to understand spacy V3. documentation. If I understand the correctly main sources of examples of spacy v3 documentation are THIS PROJECTS ()https://github.com/explosion/projects/tree/v3/tutorials).
However, the training data are already prepared in the expected JSON nested structure format.
If I want to perform costume text classification in spacy v3 I need to convert the data to the example structure - e.g LIKE HERE (https://github.com/explosion/projects/blob/v3/tutorials/textcat_docs_issues/assets/docs_issues_eval.jsonl).
How to get from pandas data frame to here? Does prodigy support labeled data to spacy format? Let's have small example of the dataset
pd.DataFrame({
    "TEXT":[
    "i really like this post",
    "thanks for that comment",
    "i enjoy this friendly forum",
    "this is a bad post",
    "i dislike this article",
    "this is not well written",
    "who came up with this stupid idea?",
    "This is just completely wrong!!",
    "Get out of here now!!!!"],
    "LABEL": [
        "POS", "POS", "POS", "NEG", "NEG", "NEG", "RUDE", "RUDE", "RUDE"
    ]

})

Answer: In spaCy v3 training data is basically what you want your output to look like. So for text classification you create a doc with your text and then set doc.cats for your categories. After you've trained a model it'll do the same thing for new docs.
Whether your data is in a dataframe or not is irrelevant. You just need to iterate over the underlying values.
You can do something like this.
texts = ... list of texts ...
labels = ... aligned list of labels ...

for text, label in zip(texts, labels):
    doc = nlp(text)
    doc.cats[label] = True

# save the docs as a DocBin (.spacy file)

The project you linked to has a similar script here.


RDBMS results return, ordering and returning sets/hashmaps instead of arrays/lists

Question: Most/all SQL based RDBMS connector libraries I've come into contact with will return results in array form. Why? If the order is arbitrary (without a sorting SQL modifier), then could the natural data return be in the form of something like a Set or Hashmap? These data structures would, in some cases, be more computationally favorable at scale than a typical array/list return in languages like C++ (with standard template library usage), JavaScript/Node, Go, and any other language that supports associative data types or pure Sets.
In particular, do libraries such as knex.js offer such a feature in the form of a connection flag (I haven't found it yet)?
Do any of the major RDBMS systems (MySQL, PostgreSQL, ...), offer the ability to return results in a set/hashmap form?
Concretely, what I think would make sense using node.js and a library like knex.js, is to specify a flag like:
knex.forceMap('keycolumnpattern') Or, knex.forceSet()...
Again, the underlying assumption here would be that you are not imposing order on the SQL (or other) query by adding a sort directive i.e. ORDER BY
The justification for this is in environments were scaling and computational complexity are important concerns.
Comment: That is a curious question.  It is possible to iterate through hashmaps.  And if the query has an `order by`, then the result *is* ordered.  And, lists and arrays generally occupy less space.
Comment: The RDBMS has little to no say about how the results are passed to your language of choice. That's up to the library/driver. You should tag your question with the language that you would like to do this with. For example, PHP's mysqli and PDO libraries allow the results to be loaded into an associative array (kind of similar to a hashmap).
Comment: But what would the keys in your Hashmap be? The PK wouldn't be an option because that's not always present. Also, you'd end up deal with two different representations of the results depending on the SQL used (unless you wanted to use the ORDER BY values (possibly compound values) as keys). Hashmaps being ordered is fairly recent in most environments and not even present everywhere. Furthermore, an array is a common representation of a set where all elements are implicitly unique so it is a natural fit for the result of an SQL query.
Comment: In this case, knex.js is javascript/node.js specific. I tried to tag the question with that but stackoverflow limits to 5 :(. The key could default to a PK, or, to a key that is specified as part of the original query (we are talking about query builders, so by definition...).  The point would _not_ be to take advantage of any ordering in a hashmap, that's the point of the original question, that if the return order is not important, then just return a data type that is order independent.
Comment: I have edited my question to address it being put on hold.
Answer: Good question.
This is by no means a comprehensive answer, but just my opinion on this curious question.
Usually databases return a series of rows, that most documentation refers to as "result set".
The database
Now, this result set is assembled when the query is executed and may take different forms. Most likely the database sends it as an "enumeration": this is, a list-like entity that produces rows when you request them. In order to save resources database will try not to materialize the whole result set at once, but to produce rows as you read them from your client application. Well, this happens as long as the query can be "pipelined".
When the query cannot be pipelined, then the whole data set (in the database side) is materialised.
The driver
You client driver does not retrieve rows one by one but in groups of them by the use of buffering. Even when the query cannot be pipelined your client driver will also retrieve the rows in groups according to the "fetch size" and "buffer size".
The client technology
Your application can use basic driver primitive operations, or a more sophisticated ORM. It's common that ORMs will hide all inner workings of the driver and will offer you a "simple" result like an array, list, or map, i.e., hiding the "streaming" an enumeration provides.
If you don't use an ORM, then you will probably call the driver primitives yourself and therefore you can get access to all inner, ugly details. The upside is that you can assemble the result set rows in any data structure you prefer.
In any case, the repertoire of data structures will depend on the specific query since a "map" or a "set" will require some king of unique identifier, while a list won't.
Comment: Thank you for your response, it helps clarify my question to me and I have updated my question after it was put on hold.


How do I display elements vertically using Java FX?

Question: I have a hashSet of a class of type Message with a working toString() method. The "refresh" button is correctly created, but there is an issue in its implementation.
Note:
//Menu is an ObservableList<String>
//Mymail contains the hashset
//refresh() is a method that adds a random message to the hashset
//GetMessages() returns the hashSet
//the toString() method below is hashset's toString()

refresh.setOnAction(e -> {
    menu.setAll(myMail.refresh().getMessages().toString());
});

results in the following being printed in the window:

What should I do in order that the messages be displayed vertically like so:
"Message One Text"
"Message Two Text"
"Message Three Text"

Comment: Is the node, to which you are adding text, a `ListView`?
Comment: What kind of element is `menu`? Looks like a `ListView`?
Comment: Sorry about that. menu is an ObservableList
Comment: and Menu is set to which node?
Comment: ListView menuView = new ListView(menu);
Answer: From what we can guess, this should do the trick:
refresh.setOnAction(e -> menu.setAll(myMail.refresh().getMessages()));

Since menu is a Collection and can / should be added as one so each element gets added accordingly.
Edit: Second try:
refresh.setOnAction(e -> myMail.refresh().getMessages().stream().map(Message::toString).forEach(menu::add));

Comment: The following implementation is giving me the following error:                   "error: no suitable method found for setAll(HashSet)"
Answer: You can addAll of the ObservableList:
refresh.setOnAction(e -> menu.addAll(myMail.refresh().getMessages()));

and use toString inside the Message, to convert message to String instead of using it in Mymail.
Comment: That is also giving me the same error as below. I'm not sure why, but  the error states that "no suitable method found for setAll(HashSet) ...HashSet cannot be converted to Collection


Flutter - Exclude specific linter rule in analysis_options.yaml for a folder

Question: I have a bigger project with different rules for the linter written down in the analysis_options yaml file. I want to exclude a subset of rules for certain folders.
Example: I want to exclude the hole "lib/application" folder for the rule "prefer_relative_imports"
analyzer:
  exclude:
    - lib/injection.dart

linter:
  rules:
    - discarded_futures
    - prefer_relative_imports

How can i explain a folder location to ignore a subset of rules?
Excluding them in each file individually is not practical when there are a large number of files in said folder.
I tried to have multiple analysis_options.yaml files in the corresponding exluding folders to declare rules which needs to be excluded. This has no effect to the linter cause only the file in root directory seems to be noted.
Answer: Try adding a new analysis_options.yaml file in that directory and customize its analyzer, linter... as you want.
Comment: As written I tried exactly this, but no file changed the result. It seems like no other analysis_options file is regarded.


Can I use a busbar as a ground in my travel trailer?

Question: I need to ground my inverter and a few other items from my fuse box. Can I use a single busbar, mounted to the floor, as a ground. If not, can you offer suggestions?
Comment: NEC 551 covers trailers. 551.30 allows generators to be bonded to the frame or chassis. 551.32 covers inverters, generators and says must be listed for use in RV and comply with the rest of the article parts 1,2,3,4&5.
Comment: I can't tell if you're serious, or joking...  Is the floor bonded to the main grounding conductor? Does the floor provide an electrical path to ground?
Comment: That's a GREAT question.  How do you handle grounding in a vehicle?
Comment: What are these "few other items"?
Answer: You can use a bus bar, yes.
But you should never assume that the entire trailer is bonded together in such a way that you can use any of it separately as a connection to the bus bar.
Think of how many pieces it takes to build the trailer.  Screws rust and aluminum reacts to the oxygen in the atmosphere to produce resistance.  That's the last thing you want in a ground system.
So if you use a bus bar, be sure that your "things" are grounded directly to it, and that you have a good thick copper wire connection between the bus bar and the service entrance.


How to update existing column values in data.table?

Question: I just started this programming, apologize for asking this simple question but I am stuck.
I have a data.table called s3:
s3:
ClaimID           dx      dxgroup
15nhbfcgcda       113.8   NA
15nhbfcgcda       156.8   NA
15nhbfcgcda       110.8   059
15nhbfcfssa       135.8   NA
15nhb4dfgda       V70.3   NA
15nhbf644da       118.8   042

S3 has 30000 rows.

I want to apply this logic:
If dxgroup = NA(
    If dx (fisrt 4 characters match with)= (2024, 2967, 9786,9788,8263)
        then dxgroup = (first 4 character of dx)
    else dx (fisrt 3 characters match with) = (V70, 042,897)
        then dxgroup = (first 3 character of dx)
else dxgroup = dx
)

Result should be like :
ClaimID           dx      dxgroup
15nhbfcgcda       113.8   113.8
15nhbfcgcda       156.8   156.8
15nhbfcgcda       110.8   059
15nhbfcfssa       135.8   135.8
15nhb4dfgda       V70.3   V70
15nhbf644da       118.8   042

Please advice ?
I apologize: It is my first time I am asking something here, so not used to yet. So I did something like this(I have no if this is correct and I got error as well):

sample4<-sample3[, dxgroup := { if (dxgroup == NA)

{ if (substring(sample3$dx,1,4) == list (2501,2780,4151,5301,5751,6860,7807,7890,9898,9955,9970))  substring(sample3$dx,1,4)
else if (substring(sample3$dx,1,3) == list (042,493,682,850,V72))     substring(sample3$dx,1,3)
else if (substring(sample3$dx,1,4) == list (8540, 8541)) substring(sample3$dx,1,3)
else if (substring(sample3$dx,1,3) == list (043, 044)) 042
else if (substring(sample3$dx,1,3) == list (789) & substring(sample3$dx,1,3) !=  list(7891,7893,78930)) 7890
else if (substring(sample3$dx,1,4) == list (7865) & substring(sample3$dx,1,4) !=    list(78651,78652,78659)) 78650}
else sample3$dx}]
  Error in if (dxgroup == NA) { : missing value where TRUE/FALSE needed
  In addition: Warning message:
  In if (dxgroup == NA) { :
  the condition has length > 1 and only the first element will be used
Comment: Please share what you've tried so far rather than just asking for code.
Comment: I apologize: It is my first time I am asking something here, so not used to yet. I have added in my question.
Comment: `letters[]` is a built-in vector of letters of the alphabet. So `letters[1:4]` is just `"a" "b" "c" "d"`. You can see this by typing it at the command line.
Comment: I am sorry for being a slow learner.
Comment: hi, you mentioned data.table in your question. Make sure that you are using the `data.table` package or are you confounding it with data.frame?
Comment: Thanks Ricardo, I was able to do it. Thanks for help and advice. I have one more simple question which I am not bale to find any where....: Can I return 0.00 instead of NA while joining two data.table?
Answer: You have the logic all set.
Note that with data.table (well, almost all of R), you can wrap the j in {curly brackets} and the final statement in the brackets is what will be assigned.   eg:
DT[,  dxgroup :=  { if (clause1)
                     {if (foo) beebar else bar}
                  else chewybar
                  }
  ]

Answer: This is a more data.table friendly solution:
library(data.table)
s3 <- data.table(s3)
s3[is.na(dxgroup) & (substring(ClaimID, 1, 3) %in% ("V70", "042", "897")), dxgroup := substring(dx, 1, 3)]
s3[is.na(dxgroup) & (substring(ClaimID, 1, 4) %in% ("2024", "2967", "9786", "9788", "8263")), dxgroup := substring(dx, 1, 4)]
s3[is.na(dxgroup), dxgroup := dx] #Default

Basically, you work from the most specific condition to the most global condition, as each line in the above script potentially overwrites matches from the previous line.
(I assume you're using the data.table package.  data.tables are different than data.frames, and in my opinion much better.)
Comment: Hi @Zach - doesn't the 3rd line fill all dxgroup values, thus rendering the last 2 lines impotent? Unless I'm misunderstand, I think the order must be reversed.
Comment: @RobertMuil I fixed my code— please double check! =D
Comment: Looks good! The description should prob. also be updated to reflect that too (most specific to most global)... Impressive response time BTW :-)
Comment: @RobertMuil Done, and thanks!  Next time try the "suggest edit" feature.
Comment: Welcome - that feature sounds cool, but I don't seem to have it - reputation points required?
Comment: @RobertMuil Maybe.  At some point an "edit" link appears next to the "share" and "flag" links in the bottom left of a question


Does getting live/neutral the right way round actually matter?

Question: I was replacing an electrical socket in my (UK) house, and I noticed that the previous occupant had wired live and neutral backwards.  However, I've used a variety of appliances and devices on that socket in the past without any issue.
So - does it actually matter which way around they are connected?  As long as you obviously don't connect live from one part of the ring with neutral from the other, what difference does it make?
Comment: The answer is fairly clear. Yes it matters, because it reduces the possibility of an appliance/device becoming a shock hazard.
Comment: Because when it's the wrong way around, the device is energized (the internal wiring is at a voltage potential higher than 0). So if there's a fault somewhere, you could potentially become a path to ground.  Also in some older appliances, the grounded (neutral) conductor was bonded to the chassis of the device. If this type of appliance was plugged into a reversed receptacle, the entire chassis would be energized.
Comment: Yep - it's a similar question, but it doesn't really give a straight answer.  Does it matter - if so, why?
Comment: Thanks - but _why_ does it?  Why does having them the wrong way around make something a shock hazard?
Comment: Live/neutral swap plus neutral earth swap = live case. Either on its own, no immediate hazard.
Answer: Not for many appliances, but for some that are sensitive it could cause problems.
Comment: for function, backwards often works, but for safety it is always a bad idea ... do it right
Comment: many UPSes will refuse to accept it


IDE for react with .net web api

Question: I try to find out what is the best way to develop react app with .net web api as the api service.
I realized that using visual studio 2015 won't work since its lack of es6 support.
I really liked atom as the "client" side programming and visual studio 2015 but I foresee issues working with 2 IDEs opened, especially for those whose computer is not strong enough..
I have also heard of visual studio code but I don't have much experience with it and how exactly to debug in it.
Would like to here your suggestions, thanks
Comment: What do you mean by 2 IDE's opened?
Comment: I'm still using vs 2015 for backend development and vscode for frontend stuff. If you want to try out vscode for react debugging check out this [boilerplate](https://github.com/skolmer/react-hot-boilerplate-vscode). For asp.net web api Visual Studio 2015 has still the best tooling support.
Comment: I meant visual studio for backend development and atom for frontend development. I work in a fullstack developers team so that means both will probably be opened simultaneously..
Answer: You can try to use Rider from jetbrains - A fast & powerful,
cross-platform .NET IDE.
I use that IDE daily and have support for ES6 and JSX Typescript and more.

IDE for react with .net web api


How to close existing handle on file in C#

Question: How can I close an existing handle on a file in C#? Is it possible?
Suppose I run code with administrator account? Can I just force the file to be closed?
In another post, one of the answer was to use interop:
[Flags]
enum MoveFileFlags {
    MOVEFILE_REPLACE_EXISTING = 0x00000001,
    MOVEFILE_COPY_ALLOWED = 0x00000002,
    MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004,
    MOVEFILE_WRITE_THROUGH = 0x00000008,
    MOVEFILE_CREATE_HARDLINK = 0x00000010,
    MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);

static void delete() {
    string fileName = @"c:\temp\test.xlsx";
    bool success = false;
    foreach(var e in Enum.GetNames(typeof(MoveFileFlags))) {
        success = MoveFileEx(fileName, null, (MoveFileFlags) Enum.Parse(typeof(MoveFileFlags), e));
        MessageBox.Show(string.Format("{0} success : {1}", e, success));
    }
}

This solutions is not working. We need to reboot to delete the file.
Another example tells to kill the process:
string fileName = @"c:\aaa.doc"; //Path to locked file

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName;
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern)) {
    Process.GetProcessById(int.Parse(match.Value)).Kill();
}

The problem is I don't want to kill the process, since the process that locks the file is IIS or Explorer.
I need to refresh file of a web site.
This is the solutions that I'm using and it is working fine:
static void delete(string fileName) {
    string handleTools = Path.Combine(Application.StartupPath, "handle.exe");
    Process tool = new Process();
    tool.StartInfo.FileName = handleTools;
    tool.StartInfo.Arguments = fileName;
    tool.StartInfo.UseShellExecute = false;
    tool.StartInfo.RedirectStandardOutput = true;
    tool.Start();
    tool.WaitForExit();

    string outputTool = tool.StandardOutput.ReadToEnd();
    Regex reg = new Regex(@"(?<pid>pid:\s+[0-9]*)\s*(?<type>type:\s+\w*)\s*(?<handle>[A-F0-9]*:\s+)");
    Match match = reg.Match(outputTool);
    string pid = null;
    string handle = null;

    if (match.Groups["pid"].Value != null) {
        pid = match.Groups["pid"].Value;
        if (!string.IsNullOrEmpty(pid)) {
            pid = pid.Replace("pid: ", string.Empty);
        }
    }
    if (match.Groups["handle"].Value != null) {
        handle = match.Groups["handle"].Value;
        if (!string.IsNullOrEmpty(handle)) {
            handle = handle.Replace("handle: ", string.Empty).Replace(":", string.Empty);
        }
    }
    if (!string.IsNullOrEmpty(handle) && !string.IsNullOrEmpty(pid)) {
        tool = new Process();
        tool.StartInfo.FileName = handleTools;
        tool.StartInfo.Arguments = string.Format("-p {0} -c {1} -y", pid, handle);
        tool.StartInfo.UseShellExecute = false;
        tool.StartInfo.RedirectStandardOutput = true;
        tool.Start();
        tool.WaitForExit();
        File.Delete(fileName);
    }
}

To use this solutions you will need to use handle.exe from sysinternal
Comment: How are you getting the handle ?
Comment: exact dup as well... http://stackoverflow.com/questions/3526802/forcing-closed-an-open-file-by-c-sharp
Comment: @parapura rajkumar , actually i dont know how to get the handle. But i imagine there a way to get the handle and close it
Comment: Why is this getting voted down?  Just flag it as a dup.
Comment: @CédricBoivin http://www.google.com/search?gcx=w&sourceid=chrome&ie=UTF-8&q=force+close+file+C%23
Answer: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/04a1e899-2a38-4d95-8ed5-6d53344e4d76


My save data is not being stored in Wildtangent's Game FATE

Question: I recently downloaded the game again for nostalgia's sake on my pc. I was attempting to save my game and it doesn't appear to work. You start a game, click "Save and Exit", and then the game goes back to the menu and does not contain the "Continue" option, only the New Game one. I have tried a few things:
First, a common suggestion was to start the game as an administrator, and that didn't work.
The next one was to check the file location for the save file and see if the folder was there. I checked and the file was there.
Here is the file location:
Local Disk (C:) > Program Files (x86) > Wild Tangent > Fate > Persistent > SAVE
However, no data is being saved to the folder.
I have also tried changing some compatibility settings in the game properties, but none of them seem to work either.
If I need to provide more information about this issue please do not hesistate to ask. I do also understand that this is an old game, but all help is appreciated.
Thanks!
Answer: Sorry, I have actually managed to solve it. I was being a bit silly. I just needed to reinstall. That seemed to work.


windows guests on ubuntu virtualbox not starting

Question: My windows guests have stopped working on VirtualBox. They only boot up to black screen with the blue window logo and the rotating thing. After a short while the rotation stops and then the window disappears. After the second try, it says "Automatic repair is being prepared" but the same thing happens.
My linux guests still work.
VirtualBox 6.1.16
Windows 10
Comment: How is this related to Ubuntu?
Comment: Have you tried loading a previous snapshot of the Windows machine to see if it's just this snapshot that is corrupted?
Comment: @vidarlo: Virtualbox is dependent from the Ubuntu kernel version (as you regulary have to reinstall the VBoxGuestAdditions every time the kernel has changed.
Comment: @Eagle_Mike: my second windows guest is a clone from the first and doesn't work either.
Comment: But it's your guest that fails to boot. This suggests that it's a problem with the guest OS installation. We generally don't know fault finding tricks for Windows.
Comment: @vidarlo: My second windows guest is a clone that I had kept for backup and that I haven't touched for months. So why wouldn't it boot anymore? The only things changed are Ubuntu and perhaps Virtualbox installed and updated by Ubuntu.
Comment: Do any other VB guests open correctly?
Comment: @Eagle_Mike I have an Ubuntu and an Android guest which run without any problem.
Comment: It appears that your Windows guest is somehow corrupt and if you are cloning it, the second one would also be corrupt. Try going back to a previous snapshot of the guest (prior to whatever corrupted it). Advise if any of the snapshots are unable to boot up. --- You do take snapshots of the guests regularly?
Comment: The clone was produced months ago, and both the original and the clone were working.
Answer: Yesterday I did a manual update of Ubuntu. When I tried again today to start my Windows guest system, it worked! Which proves that the Windows system was not corrupt, but that there was a problem somewhere with Ubuntu. Unfortunately I don't know how it was corrected.


Javascript Date issue, incorrect timezone

Question: I got this strange JavaScript bug that I can seem to work arround or fix.
I am using some code to make 2 JavaScript dates, to insert events into a calendar component.
The dates are built the following way:
var endDate = new Date();
var startDate = new Date();

startDate.setDate(startDateDay);
startDate.setMonth(startDateMonth);
startDate.setFullYear(startDateYear);
startDate.setHours(2, 0, 0, 0);

endDate.setDate(endDateDay);
endDate.setMonth(endDateMonth);
endDate.setFullYear(endDateYear);
endDate.setHours(2, 0, 0, 0);

So, the dates are built using integers. These integers are determined by input, and using the debugger I can see 100% positive they are coming in correctly.
Now, ill describe 3 walkthroughs, 2 where it goes correctly and 1 where it goes wrong.

Using the following input:
endDateDay = 20
endDateMonth = 9
endDateYear = 2014

Gives the following date object as result:
Tue Oct 20 2014 02:00:00 GMT+0200 (W. Europe Daylight Time)

Using this input:
endDateDay = 13
endDateMonth = 9
endDateYear = 2014

Gives the following date object as result:
Tue Oct 13 2014 02:00:00 GMT+0200 (W. Europe Daylight Time)

Now, using this input:
endDateDay = 27
endDateMonth = 9
endDateYear = 2014

Gives the following date object as result:
Mon Oct 27 2014 02:00:00 **GMT+0100** (W. Europe Standard Time)

As you can see, for some strange reason the TimeZone is off. This gives errors in my application, and I need to find a way to get it fixed. Though, I cannot find any solution to it, let alone understand why it is actually happening.
PS: I am using Google Chrome
Comment: In what way is it off? The clocks in Western Europe go back to standard time on October 26th... what did you expect, and why?
Comment: Look at the tiemzones, one is **Daylight** time, the other is **Standard** time (though the timezone names may be different to what you're used to).
Answer: The answer was indeed the difference in the daylight savings time, which I completly oversaw. Thanks to finding this out I also found a solution to my problem.
I used this link to further assist me, might it help someone in the future:
http://javascript.about.com/library/bldst.htm
Cheers!


Logical question with a balance and flour

Question: The problem is: I have a balance of $9$ kgs of flour and two weights; $250$g and $50$g. In the matter of $3$ steps I have to divide them into $2$ bags of $7$ and $2$ kg, respectively. I know that after I have measured a bag with $250$g I can combine it with the $250$ weight, so $500$g in total for example. Using the balance counts as a step! So you can use the balance only 3 times.
I hope you understand my English :]
Comment: For reference: what counts as a step? Just using the balance, or would combining multiple bags (see my answer) count as a step? Also, can we use as many bags as we want?
Comment: @DylanSp I assume only a weighing counts as a step. If so, under a reasonable interpretation of "weighing", it can be done in three steps. If combining two bags is a step, we would need more information; for example, is combining three bags one step or two?
Answer: The problem is really to measure out $2$ kg of flour in one bag.
The second bag simply receives all the remaining flour.
If you are allowed to put two bags on the scale and then transfer flour
between them until the scale balances, you can use the scale to
divide a bag of flour in half in one step.
Put the bag to be divided on one side of the scale,
put an empty bag on the other side,
and transfer flour between the bags until they balance.
Assuming you can divide a bag as described above,
here is a hint about how to measure $2$ kg
from the original $9$ kg in three steps:
$$ 9 = 2.25 \times 4. $$
Answer: I can see how to do it in five steps; maybe someone else can suggest how to condense it further.

Start with all the flour in bag $A$. Put the $250$ g weight on one side of the scale. Pour flour from $A$ into bag $B$ on the other side of the scale until it balances the weight. $B$ now contains $250$ g of flour.
Put $B$ and the $250$ g weight on one side of the scale. Pour flour from $A$ into bag $C$ on the other side of the scale until it balances. $B$ has $250$ g, $C$ has $500$ g.
Put $B$, $C$, and the $250$ g weight on one side of the scale. Pour flour from $A$ into bag $D$ on the other side until it balances. $B$ has $250$ g, $C$ has $500$ g, $D$ has $1000$ g.
Repeat step 1 with a new bag $E$ in place of $B$. $B$ has $250$ g, $C$ has $500$ g, $D$ has $1000$ g, $E$ has $250$ g.
Combine bags $B, C, D, E$ into one bag, which will have $250 + 500 + 1000 + 250 = 2000$ g. $A$ started with $9000$ g; with $2000$ g removed, it's left with $7000$ g, and we're done.

(We can also get $1000$ g in $E$ in step 4 by weighing it against $D$, then condense $D$ and $E$ into our $2$ kg bag, and recombine $A, B, C$ for $7$ kg. This doesn't save any steps, though.)
Answer: I'm not sure if I am allowed to answer on my question but I solve it.
First I combine the 250 and 50g weight and I got a bag of 300g.
Then I combine the bag of 300g and the weights of 250g and 50g - I get a bag of 600g. Then lastly I combine the 600g and 300g bag the 250 weight and put the 50g weight on the other side of the balance. I got a bag with 1100g.
1100g + 600g + 300g = 2000g = 2kg.


In Spring WebFlow, is it possible to continue the same flow after calling an external service?

Question: One of my subflows need extra information from a service provider page, I will redirect the user to that page to insert his information and then return back to the same place he was in the flow.
The view-state takes the user to an externalRedirect, and this page will then do a callback to a static URL I give them, so how I can continue the flow from there?
Answer: You have all information you need to continue in your flowRequestContext.
 You can restore the last state (snapshot and execution)
Comment: An example would be useful. Maybe if I thought about it further, it would be apparent, but I'm wishing for specifics. You'd have the static URL be the flow/subflow URL and have the start state detect something to skip to current? Or maybe it's another approach I'm not envisioning? I'm intrigued.


Sort a PSCustomObject by date in powershell

Question: I have a pscustomobject I created:
$data = [pscustomobject]@{
    CatWeeklyFiles = @()
}

I used a custom function to generate dates for items I am appending to it.
The following is the appending code I run in a for loop.
 #Append to the data object
    $data.CatWeeklyFiles += @{
        FileName = $item.ToString()
        Exists = 1
        Date = $CatDate.ToString("MM-dd-yyyy")
    }

I export this at the end as JSON and this is an example of the first few lines.
How can I sort this in powershell before exporting to JSON so that I can have the date ascending or descending? (Note: it already is in order ascending but I need to know how to change it).
{
    "CatWeeklyFiles":  [
                           {
                               "Date":  "04-13-2015",
                               "FileName":  "Week1615CatUpdate.exe",
                               "Exists":  1
                           },
                           {
                               "Date":  "04-20-2015",
                               "FileName":  "Week1715CatUpdate.exe",
                               "Exists":  1
                           },
                           {
                               "Date":  "04-27-2015",
                               "FileName":  "Week1815CatUpdate.exe",
                               "Exists":  1
                           },
                           {
                               "Date":  "05-04-2015",
                               "FileName":  "Week1915CatUpdate.exe",
                               "Exists":  1
                           }
]
}

Edit - Adding full code
####Setup
$curDir = Get-Location
$filename = "files.txt"
$pathtocheck = "C:\path\In\Cat_Weekly"
#Create array from the files.txt file
$array = Get-Content $filename

##Function to get date from week/year
Function FirstDateOfWeek
{
param([int]$year, [int]$weekOfYear)

$jan1 = [DateTime]"$year-01-01"
$daysOffset = ([DayOfWeek]::Thursday - $jan1.DayOfWeek)

$firstThursday = $jan1.AddDays($daysOffset)
$calendar = ([CultureInfo]::CurrentCulture).Calendar;

$firstWeek = $calendar.GetWeekOfYear($firstThursday, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [DayOfWeek]::Monday)

$weekNum = $weekOfYear

if($firstweek -le 1) { $weekNum -= 1 }

$result = $firstThursday.AddDays($weekNum * 7)
return $result.AddDays(-3)
}
##Create data structure for making JSON
$data = [pscustomobject]@{
    CatWeeklyFiles = @()
}

#TEST

#Main Loop
for($i=0; $i -lt $array.Length; $i++){

$item = $array[$i]
#This is for cat weekly files that DO exist.
if((Test-Path -Path $pathtocheck\$item -PathType Leaf) -eq $True){

    write-host $i " Update: " $item "exists"
    #Extract Week and Year Values
    $extWeek = $item.Substring(4,2)
    $extYear = "20"+$item.Substring(6,2)
        #This handles a bug where the year appears as '99 when it should be '19
        if ($extYear -eq 2099){
        $extYear = 2019
        }

    #Run Function
    $CatDate= FirstDateOfWeek -year $extYear -weekOfYear $extWeek

    #Append to the data object
    $data.CatWeeklyFiles += @{
        FileName = $item.ToString()
        Exists = 1
        Date = $CatDate.ToString("MM-dd-yyyy")

    }

}

#This is for cat weekly files that DON'T exist.

elseif((Test-Path -Path $pathtocheck\$item -PathType Leaf) -eq $False){

    write-host $i " Update: " $item "is missing!"
    #Extract Week and Year Values
    $extWeek = $item.Substring(4,2)
    $extYear = "20"+$item.Substring(6,2)
        #This handles a bug where the year appears as '99 when it should be '19
        if ($extYear -eq 2099){
        $extYear = 2019
        }

    #Run Function
    $CatDate= FirstDateOfWeek -year $extYear -weekOfYear $extWeek

    #Append to the data object
    $data.CatWeeklyFiles += @{
        FileName = $item.ToString()
        Exists = 0
        Date = $CatDate.ToString("MM-dd-yyyy")

    }
   }
}

#Output data object as json
$json = $data | ConvertTo-Json | Out-File $curDir\tracking.json

Comment: So if I did Date = $CatDate.ToString("yyyy-MM-dd") it would sort it?
My end goal is that the exported json is always sorted by the date
Comment: `#Output data object as json

$json = $data |Sort-Object -Property Date | ConvertTo-Json | Out-File $curDir\tracking.json
`

Tried doing this. I changed the `Date = $CatDate.ToString("MM-dd-yyyy")` to `Date = $CatDate.ToString("yyyy-MM-dd")`

No luck, I can't get it to sort in descending order
Comment: I added that switch

`$json = $data |Sort-Object -Property Date -Descending | ConvertTo-Json | Out-File $curDir\tracking.json`

The json is still in the same order as my original post
Answer: Our comment talk has gotten a little confusing I guess. ;-)  Here to show what I meant ... If you have unsorted data input like this:
$InputData = @'
{
    "CatWeeklyFiles": [
        {
            "Date": "2015-04-27",
            "FileName": "Week1815CatUpdate.exe",
            "Exists": 1
        },
        {
            "Date": "2015-05-04",
            "FileName": "Week1915CatUpdate.exe",
            "Exists": 1
        },
        {
            "Date": "2015-04-13",
            "FileName": "Week1615CatUpdate.exe",
            "Exists": 1
        },
        {
            "Date": "2015-04-20",
            "FileName": "Week1715CatUpdate.exe",
            "Exists": 1
        }
    ]
}
'@ |
    ConvertFrom-Json

And you output it like this ...
$InputData.CatWeeklyFiles

it looks like this:
Date       FileName              Exists
----       --------              ------
2015-04-27 Week1815CatUpdate.exe      1
2015-05-04 Week1915CatUpdate.exe      1
2015-04-13 Week1615CatUpdate.exe      1
2015-04-20 Week1715CatUpdate.exe      1

Now you can use Sort-Object to sort it the way you want and safe it to a new vairable...
$NewData =
    [pscustomobject]@{
        CatWeeklyFiles =
            $InputData.CatWeeklyFiles |
                Sort-Object -Property Date -Descending
    }

When you output it now
$NewData.CatWeeklyFiles

It looks like this
Date       FileName              Exists
----       --------              ------
2015-05-04 Week1915CatUpdate.exe      1
2015-04-27 Week1815CatUpdate.exe      1
2015-04-20 Week1715CatUpdate.exe      1
2015-04-13 Week1615CatUpdate.exe      1

Now you can convert it to JSON and export it
$NewData |
    ConvertTo-Json |
        Out-File $curDir\tracking.json

And all of that just because we choose the proper format for the date. ;-)


How do I update a module script's variables in roblox studio?

Question: So I have scriptOne (module) and scriptTwo (local script I think). I use scriptTwo to require() and change the variables with that. But how do I update the values in scriptOne (that I also want to access from other scripts as well) to these new values?
scriptOne code
local module = {}

module.test = 100

while true do
    wait(1)
    print(module.test)
end

return module

scriptTwo code
local data = require(workspace.playerStats)

data.test = 0

Comment: it is not quite clear to me what you're asking here. `data` and `module` refer to the same table. how does your code's behaviour differ from what you expect?
Answer: changing variables inside of a modulescript is global, change a variable and every script using the module gets the new variable
the reason why the code you provided doesnt work is because of the while loop. the loop yields and cant proceed, meaning it cant also return the module so the server script is waiting forever.
Answer: The problem is the while loop in the ModuleScript. ModuleScripts are used by require() to share variables. In your case, your ModuleScript has a infinite loop, which doesn't let require() return, and gets the second script stuck. You are probably using the while loop for debugging the variable, so I'd recommend moving it to the second script.


How do I redirect a pop-up to a normally loaded page?

Question: I am trying to implement something like this:

Clicking on a link, a pop-up will be opened, something like sign-up page.
On submission, if data is unfilled, an error message will be generated.

But on successful submission, it will be redirected to the main page opened earlier in the browser.
Im using thickbox for the pop-up feature. On redirecting using the following code:
<meta http-equiv="refresh" content="1;url=http://localhost/cgi-bin/Ajax/index.pl/">

The main page is being redirected, but in the pop-up itself I want the pop-up to die after successful submission and the main page gets refreshed.
Comment: This is actually something you cannot acomplish in perl. You will need HTML/Javascript features to do it. Please show the code you're using to open the popup window and the code making stuff happen there.
Comment: This is da code for POPUP: print '
';
 print 'Add New Platform';
Comment: So it is not a real popup window, but an overlay thing? That's should make it easier.
Answer: I'll asume you're using the iFrame solution from the thickbox website. It looks to me that you have to set the modal=true part in the URL and use the tb_remove() function once the login is completed. The same goes for the AJAX version.

Optionally you may add modal=true to the query string (e.g.
  ?KeepThis=true&TB_iframe=true&height=400&width=600&modal=true) so that
  closing a ThickBox will require calling the tb_remove() function from
  within the ThickBox iframe (self.parent.tb_remove()). See the iframe
  demo for an example, where you must click "ok" to close the ThickBox.

You should therefore just add something like this to your javascript (that you print from perl iirc).

<meta http-equiv="refresh" content="1;
      url=http://localhost/cgi-bin/Ajax/index.pl/">

Please note that I have not tested this and I'm only referring to the documentation.
Comment: can u help me wid how to call thickbox on submit button in perl ??
Comment: Again, this is not perl. You are talking about JavaScript. I think you could add an ``onsubmit`` handler to your form. Something like ` ... `. But if you're talking about something else, you should open a new question and consider daxim's and my edits to this question for the way you phrase it. ;-)


Finding largest prime factor for checking if a number is squarefree

Question: I'm working on project Euler problem 203 that reads like this:

[...]
A positive integer n is called square-free if no square of a prime divides n.
  Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are square-free.
[...]
Find the sum of the distinct square-free numbers in the first 51 rows of Pascal's triangle.

I basically understand how to solve this, what was bugging me was how to find the largest prime factor that I need to check against.
I found online a solution that says:

Only a few primes are required. For example, $51!$ is the biggest numerator $(\binom{n}{k} = \frac{n!}{k! (n-k)!} )$ and the largest prime factor required is $≤ √51$ which is 7.

Why does this work - how can I know that I only need to check divisibility by prime number squares up until $7^2$? The next prime number is 11, so how would I know that I don't need to check the numbers of pascals triangle against e. g. $11^2$, $13^2$, etc. given that I only need to check the numbers up until row 51 of pascals triangle?
Answer: As with every PE problem, this is true because when you compute your answer using this and enter it on a certain website, you see that victorious guy proudly brandishing a green sign.
Seriously, the highest power of a prime $p$ dividing $n!$ is
$$\left\lfloor{n\over p}\right\rfloor+\left\lfloor{n\over p^2}\right\rfloor+\left\lfloor{n\over p^3}\right\rfloor+\dots$$
Now, when $n<p^2$, all terms except the first are reduced to $0$. The same applies to the smaller factorials of $k$ and $n-k$, so the power of $p$ in $\binom nk$ is simply
$$\begin{aligned}
\left\lfloor{n\over p}\right\rfloor-\left\lfloor{k\over p}\right\rfloor-\left\lfloor{n-k\over p}\right\rfloor & = \left({n\over p}-\left\{{n\over p}\right\}\right)-\left({k\over p}-\left\{{k\over p}\right\}\right)-\left({n-k\over p}-\left\{{n-k\over p}\right\}\right) \\
& = \left({n\over p}-{k\over p}-{n-k\over p}\right)+\left(\left\{{k\over p}\right\}+\left\{{n-k\over p}\right\}-\left\{{n\over p}\right\}\right) \\
& = \left\{{k\over p}\right\}+\left\{{n-k\over p}\right\}-\left\{{n\over p}\right\} \\
& \leqslant\left\{{k\over p}\right\}+\left\{{n-k\over p}\right\} \\
& \color{red}{\mathbf<\ 1+1=2}
\end{aligned}
$$
i.e., strictly less than 2, so if $\binom nk$ happens to not be squarefree, this is not because of $p$.
Comment: Thanks for your answer, can you expand a bit on the part "Now, when n < p^2", all terms except the first are reduced to 0" - is there an example?
Comment: What kind of example would you like? If $b>a$, then $a/b<1$, hence $\lfloor a/b\rfloor=0$ - it is as simple as that.
Comment: I understand that part now, thank you. What does "strictly less than 2, so if (nk) happens to not be squarefree, this is not because of p" mean?
Comment: If $\binom nk$ is not squarefree, that is, divides by some square, it can't be the square of $p$.
Comment: Thank you for your answer and follow up explanations!


Swift CKQuery with multiple record types

Question: So I'm in good shape on querying specific record types and parsing their data.  What I can't figure out though is how to search across all record types for, as an example, everything that was modified today, regardless of what record type it is.
Thoughts?
Answer: The terms that comes to mind is TRUEPREDICATE and metadata. You can read all about them on the apple documentation page. Most of the examples are surprisingly in Objective C, but translating them to swift is easy. The one you need becomes...
In Swift
let predicate = NSPredicate(format: "TRUEPREDICATE")
 let query = CKQuery(recordType: "Blah", predicate: predicate)
Which will fetch all records of type Blah, if you want to search multiple databases than you need to do multiple queries, one against each schema I believe.
Comment: Ok, so I would still need to fetch all of the different record types individually then parse them.  There isn't a way to pull all records regardless of `recordType`?
Comment: You already know all the record types, you would have set them up within the iCloudKit dashboard. But yes, I don't think there is a CKQuery that doesn't ask/expect a record type.
Comment: That's really what I was getting at.  Is there a CKQuery that doesn't require a record type.
Comment: No, I don't find any references to building a CKQuery without a record type, its a limitation/feature of cloudkit.


"Error #2038" : while file upload in flex

Question: I figured out an error as Error #2038 for IOEvent while file uploading in flex.
I googled out but i didn't find any proper solution may be how to implement that. The code is working properly before. But now its showing this error.
This is working in IE but in other browsers its showing error.
Any body having idea ?
Okay here is the AS3 code...please check it out
package com.firstplanet.views.actions
{
import com.adobe.serialization.json.JSON;
import com.firstplanet.events.ErrorLogEvent;
import com.firstplanet.events.SaveAdminItemEvent;
import com.firstplanet.model.ModelLocator;
import com.firstplanet.views.modules.admin.winProgress;

import flash.display.DisplayObject;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.KeyboardEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.FileReferenceList;
import flash.net.Responder;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.ui.Keyboard;

import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;

public class FileUploader
{
    public function FileUploader()
    {
    }

    [Bindable]private var theModel:ModelLocator = ModelLocator.getInstance();
    private var urlRequest:URLRequest;
    private var fileReference:FileReference;
    private var fileReferenceList:FileReferenceList;
    private var fileList:Array;
    private var isLargerFile:Boolean;
    private var _winProgress:winProgress;
    private var __errorEvt:ErrorLogEvent;

    [Bindable] public var photoName:String;
    [Bindable] public var theExtension:String;
    private var thePhotoTypeID:Number;
    [Bindable]public var file_name:String="";
    public var theAdminItem:Object = new Object();
    public var serverSideScript:String = "assets/php/FileUploader.php";
    private var max_file_size:Number;
    public var saveDet:Object;
    public var theAdminObj:Object;
    public var isUpload:Boolean;

    public function chooseFiles(fileType:String,fileFormat:String,max_size:Number):void
    {
        fileReferenceList = new FileReferenceList();
        fileReferenceList.addEventListener(Event.SELECT, onSelectFile);
        fileReferenceList.addEventListener(Event.CANCEL,onCancel);
        var arr:Array = [];
        arr.push(new FileFilter(fileType, fileFormat));
        fileReferenceList.browse(arr);
        max_file_size = max_size;
        if(fileType == "All")
        {
            isUpload = true;
        }
    }
    private function onCancel(event:Event):void{
        theModel.tempFlag = false;
    }
    private function convertBytestoMB(maxFileSize:Number):Number
    {
        var theMb:Number;
        theMb = maxFileSize/1024;
        theMb = theMb/1024;

        return theMb;
    }
    public function onSelectFile(event:Event):void
    {
        var fileReferenceList:FileReferenceList = FileReferenceList(event.target);
        fileList = fileReferenceList.fileList;

        // get the first file that the user chose
        fileReference = FileReference(fileList[0]);
        file_name = fileList[0].name;
        //newFileLabel.label=fileList[0].name;

        //if(fileList[0].size > maxFileSize)
        if(fileList[0].size > Number(max_file_size))
        {
            //var theMB:Number = convertBytestoMB(maxFileSize);
            var theMB:Number = convertBytestoMB(max_file_size);
            theModel.uploadStatusMessage = "Selected file is around "+Math.round(convertBytestoMB(fileList[0].size))+" MB. Please select a file that must not exceed "+theMB+ " MB. ";
            theModel.saveErrorLogs("CertificateUpload",theModel.uploadStatusMessage);
            Alert.show(theModel.uploadStatusMessage);
            isLargerFile = true;
            return;
        }
        else
        {

            theModel.uploadStatusMessage = "";
            isLargerFile = false;
            theModel.saveErrorLogs("CertificateUpload","This is not a large file");
            //saveBtn.enabled = true;

        }

        //previewfileName=fileList[0].name;
        if(isUpload)
        {
            if(theModel.fileManagerVO!=null)
            {
                uploadFile("../../"+theModel.fileManagerVO.folderPath,null,null);
                theModel.saveErrorLogs("CertificateUpload","Upload file path : ../../"+theModel.fileManagerVO.folderPath);
            }
        }
    }

    public function uploadFile(path:String,theAdminItem:Object,saveDetObj:Object):void
    {
        saveDet = saveDetObj;
        theAdminObj = theAdminItem;

        if(fileList!=null)
        {
            if(isLargerFile)
            {
                Alert.show(theModel.uploadStatusMessage);
                return;
            }
            theModel.deleteOldFile = false;
            if(theAdminItem!=null)
            {
                theModel.deleteOldFile = true;
                if(theAdminItem.url!=null)
                {
                    theModel.oldFileName = theAdminItem.url;
                }
            }

            _winProgress = winProgress(PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject, winProgress, true));
            _winProgress.btnCancel.removeEventListener("click", onUploadCanceled);
            _winProgress.btnCancel.addEventListener("click", onUploadCanceled);
            //_winProgress.title = "Uploading file to " + domain;

            if(fileList!=null)
            {
                _winProgress.txtFile.text = fileList[0].name;
                file_name = fileList[0].name;
            }
            _winProgress.progBar.label = "0%";
            PopUpManager.centerPopUp(_winProgress);

            // Variables to send along with upload
            var sendVars:URLVariables = new URLVariables();
            sendVars.action = "upload";
            sendVars.path = path;

            var request:URLRequest = new URLRequest();
            request.data = sendVars;
            request.url = serverSideScript;
            request.method = URLRequestMethod.POST;
            fileReference = new FileReference();
            fileReference = FileReference(fileList[0]);
            fileReference.addEventListener(Event.OPEN, onUploadOpen);
            fileReference.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
            fileReference.addEventListener(Event.COMPLETE, onUploadComplete);
            fileReference.addEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
            fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
            fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadCompleteReturn);
            fileReference.upload(request);
        }
        else
        {
            //saveItem();
            theModel.deleteOldFile = false;
            submitData(saveDet,theAdminObj);

        }
    }
    private function onUploadOpen(evt:Event):void
    {
        _winProgress.uploadProgressMessage.text = "Uploading please wait..."
    }
    // Get upload progress
    private function onUploadProgress(event:ProgressEvent):void
    {
        var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
        _winProgress.progBar.setProgress(numPerc, 100);
        _winProgress.progBar.label = numPerc + "%";
        _winProgress.progBar.validateNow();
        if (numPerc > 90)
        {
            _winProgress.btnCancel.enabled = false;
            //_winProgress.uploadProgressMessage.text = "Cropping your photo..Please wait..."
        }
        else
        {
            _winProgress.uploadProgressMessage.text = "Uploading please wait..."
            _winProgress.btnCancel.enabled = true;
        }
    }
    private function onUploadComplete(event:Event):void
    {
        PopUpManager.removePopUp(_winProgress);
        _winProgress.uploadProgressMessage.text = "Please wait..."
        theModel.uploadStatusMessage="File have been uploaded.";
        theModel.saveErrorLogs("CertificateUpload",theModel.uploadStatusMessage);
        if(isUpload)
        {
            theModel.fileManagerVO.gatewayConnection.call( "data.files.getFiles", new Responder(theModel.fileManagerVO.onFileResult, theModel.fileManagerVO.onFault),theModel.fileManagerVO.folderPath);
        }
    }
    public function onUploadCompleteReturn(evt:DataEvent):void
    {
        if(evt!=null)
        {
            if(evt.data!=null)
            {
                try
                {
                    theModel.saveErrorLogs("CertificateUpload","came to onUploadCompleteReturn");
                    var rawData:String = evt.data as String;
                    var manager:Array  = JSON.decode(rawData);
                    if(manager!=null && manager[0]!=null)
                    {
                        var tempObj:Object = manager[0] as Object;
                        var status:Boolean = tempObj.theStatus as Boolean;
                        if(status)
                        {
                            if(tempObj.FileName!=null)
                            {
                                photoName = tempObj.FileName as String;
                            }
                            if(tempObj.theExtension!=null)
                            {
                                theExtension = tempObj.theExtension as String;
                            }
                            theModel.uploadStatusMessage="File have been uploaded.";
                            theModel.isPhotoUploaded = true;
                            if(!isUpload)
                            {
                                submitData(saveDet,theAdminObj);
                            }
                        }
                        else
                        {
                            photoName = "";
                            theModel.uploadStatusMessage="That file was not a recognised type or was unable to be decoded.";
                        }
                    }
                    PopUpManager.removePopUp(_winProgress);

                }
                catch(e:Error)
                {
                    Alert.show("Error in uploading the file");
                }
            }
            else
            {
                Alert.show("Error in uploading the file");
            }
        }
    }
    private function onUploadIoError(event:IOErrorEvent):void
    {
        theModel.uploadStatusMessage="IO Error in uploading file.";
        PopUpManager.removePopUp(_winProgress);
        theModel.saveErrorLogs("CertificateUpload",event.text);
        //Alert.show("IO Error in uploading file.", "Error");
    }
    // Called on upload security error
    private function onUploadSecurityError(event:SecurityErrorEvent):void
    {
        theModel.uploadStatusMessage="Security Error in uploading file.";
        theModel.saveErrorLogs("CertificateUpload",theModel.uploadStatusMessage);
        //Alert.show("Security Error in uploading file.", "Error");
        PopUpManager.removePopUp(_winProgress);
        _winProgress == null;
        fileReference.cancel();
    }
    // Called on upload cancel
    private function onUploadCanceled(event:Event):void
    {
        PopUpManager.removePopUp(_winProgress);
        theModel.uploadStatusMessage = "You have cancelled the operation";
        _winProgress == null;
        fileReference.cancel();
        //clearUpload();
    }

    private function submitData(theObj:Object,theAdminItem:Object):void
    {
        if(photoName!=null)
        {
            theObj["url"] = photoName;
        }
        else
        {
            theObj["url"] = theAdminItem.url;
        }
        if(theExtension!=null)
        {
            theObj["type"] = theExtension;
        }
        else
        {
            theObj["type"] = theAdminItem.audio_type;
        }

        theModel.updateCourseDetails(theObj,'image');
    }

}

}
The error
 [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2038"]

Comment: Could you post some code? Otherwise, there's nothing to work with.
Comment: @JasonMc92 I have edited & added the code. Please check.
Comment: What line does the compiler say the error is showing up on?
Comment: Hey i already mentioned Its an IOEvent error. The Line at fileReference.addEventListener(IOErrorEvent.IO_ERROR, onUploadIoError); In this method the "event.text" says Error #2038
Comment: Thank you. I knew what error it was, but the line number helps narrow in.
Comment: Okay what to do any idea ?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/44776/discussion-between-ria-dev-and-jasonmc92)
Comment: If it's working on IE and not in other browsers, I would check the network HTTP transactions to see what is happening, and compare what IE is sending and what Chrome does. Then you may found out some clue about what is happening.
Comment: Thanks for your reply. Can you please elaborate. I dont know where to check the HTTP transaction.
Comment: Okay i checked it out HTTPStatusEvent.HTTP_STATUS it saying as error as [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=404 redirected=false responseURL=null]
Comment: No, I mean checking the HTTP request/responses, through developer tools in chrome, tab network. Or using Charles proxy.
Comment: Okay ...i got the solution.
Answer: Hey finally i got the solution. If any body facing like this problem please follow the some basic steps
Here the problem i faced is the file is uploading in IE(All version) but its not working in other browsers.
Then follow these steps

-- First try dispatching the HTTPStatusEvent
-- Check what error is coming. If the URL is valid it will not give error other wise it will show error responseURL=null
-- Then check your server side script path (what you are using to upload the file)
-- In my case i have passed the full URL for the file as a    path not like (assets/.../fileuploader.php)
-- Then the error will be solved

You will find many solution on internet. But the most of the cases to check filereference.IOerrorevent & filereference.HTTPStatusEvent
Refer this link :
http://help.adobe.com//en_US/FlashPlatform/reference/actionscript/3/flashnet/FileReference.html#includeExamplesSummary
Comment: The url says the page is not available
Answer: look:
Maximum value of maxRequestLength?
I had a same problem I solved with that code below into the web.config to 1Gb file
<system.web>
<httpRuntime maxRequestLength="2097152" />
</system.web>
<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" />
     </requestFiltering>
 </security>
</system.webServer>

Answer: I tried do this and resolved my problem
Right after the Flex application initializes, call the remote server method to retrieve the server-session ID. In Java the remote method will look like this:
public String getSessionInfo()
{
return FlexContext.getFlexSession().getId();
}


Konsole hide tab bar

Question: Is it possible to hide konsole tab bar?  If so how. I've looked through the settings in the options panel for the profile, but nothing jumps out at me.  Does a command line setting exist, or configuration file modification help with this?  I use tmux so tabs are really useless to me.
Thanks
Answer: It is certainly possible on my system from:
<code>Settings --> Configure Konsole --> Tab Bar --> Tab Bar Visibility
</code>
Screenshot of this setting with Tab Bar hidden:

Konsole hide tab bar