text:
Q: How do these two ES6 functions access "this" differently? I'm curious why functionA returns an error while functionB has a correct reference to "this" and works. What is the reason for the difference?
class MyComponent extends Component {
  ...

  render() {
    return (
      <input ref="myInput" type="text" />
      <button onClick={this.functionA} />
      <button onClick={this.functionB} />
    );
  }
}

This throws an error "Can't read property 'refs' of undefined:
functionA() {
  const val = this.refs.myInput.value;
  console.log(val);
}

While this correctly shows the value:
functionB = () => {
  const val = this.refs.myInput.value;
  console.log(val);
}

A: The difference between the two functions is the use of the arrow expression added on es6 that allow the use of lexycal this.
Until arrow functions, every new function defined its own this value, preventing you from accessing the correct value.
One of the common workaround is to define a reference to the this on the correct context level and the use it inside your function:
var that = this; //creating a reference to the this we will need in a function
that.refs.myInput.value; // in our function we refer to 'that' variable

Arrow functions instead capture the this value of the enclosing context, so the this you are referring in FunctionB is actually taken from the "correct" context.
for more information please check:
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions/Arrow_functions

A: In JavaScript function context is defined while calling the function, not while defining it.
You pass both function as callbacks to other component. They are called outside of object they are defined. Thus, they do not share it's class context.
What makes difference here is definition of functionB. Using arrow function binds current context to underlying function.
You can read more here http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/
... or google more if you are interested.

A: In traditional function declaration i.e. function keyword this inside function scope refer to the object to which the function belong , or undefined if there is no hosting object .The point is function form a new scope different from outside
In new => syntax ,there is a different story .the function do not from the new scope (quite different the old way) ,rather,its scope is the same as the outside scope
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions


text:
Q: D3.js: end-of-line labels for lines of various length I have data consisting of a series of values that I load as such:
vars = d3.keys(data[0]).filter(function(key) { return key !== 'round'; });
color.domain(vars);

var seasons = vars.map(function(name) {
    return {
        name: name,
        values: data.map(function(d) {
            return { round: d.round, position: +d[name] };
        })
    };
});

I then do the following to draw a line per series:
var line = d3.svg.line()
    .defined(function(d) { return d.position !== 0; })
    .x(function(d) { return x(d.round); })
    .y(function(d) { return y(d.position); })
    .interpolate('linear');

var season = svg.selectAll('.season')
    .data(seasons)
    .enter().append('g')
    .attr('class', 'seasons');

var lines = season.append('path')
    .attr("class", function(d, i) { return "season" + i + " line"; })
    .attr('d', function(d) { return line(d.values); })
    .style('stroke', function(d) { return color(d.name); })
    .on('click', function(d,i) { highlight(d, i, this); });

As apparent, I have zero-values in my data that I don't want to plot, which is why I used the defined function for the line. However, I later want to add a label with the final data value per series at the end of the corresponding line, I get some issues. For the series ending with a zero-value, this label ends up showing the zero-value in the position where the line would end if the zero-value were included.
season.append('text')
    .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
    .attr("transform", function(d) { return "translate(" + x(d.value.round) + "," + y(d.value.position) + ")"; })
    .attr('dy', '.2em')
    .attr('class', 'label')
    .text(function(d) { return d.value.position; });

Anyone has any idea how I solve this?

A: There's no idiomatic way to do this, but you can just search for the first non-zero value, starting from the end of the array:
season.append('text')
  .datum(function(d) {
    var j = d.values.length - 1;
    while(d.values[j].position == 0 && j > 0) { j--; }
    return {name: d.name, value: d.values[j]};
  })
  .attr("transform", function(d) {
    return "translate(" + x(d.value.round) + "," + y(d.value.position) + ")";
  })

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use scrapy to crawl multiple pages? (two level) On my site I created two simple pages:
Here are their first html script:
test1.html :

<title>test1</title>

cool

test2.html :

<title>test2</title>

I want scraping text in the title tag of the two pages.here is "test1" and "test2".
but I am a novice with scrapy I only happens scraping only the first page.
my scrapy script:
from scrapy.spider import Spider
from scrapy.selector import Selector

from testscrapy1.items import Website

class DmozSpider(Spider):
name = "bill"
allowed_domains = ["http://exemple.com"]
start_urls = [
    "http://www.exemple.com/test1.html"
]

def parse(self, response):

    sel = Selector(response)
    sites = sel.xpath('//head')
    items = []

    for site in sites:
        item = Website()

        item['title'] = site.xpath('//title/text()').extract()

        items.append(item)

    return items

How to pass the onclik?
and how to successfully scraping the text of the title tag of the second page?
Thank you in advance
STEF

A: To use multiple functions in your code, send multiple requests and parse them, you're going to need: 1) yield instead of return, 2) callback.
Example:
def parse(self,response):
    for site in response.xpath('//head'):
        item = Website()
        item['title'] = site.xpath('//title/text()').extract()
        yield item
    yield scrapy.Request(url="http://www.domain.com", callback=self.other_function)

def other_function(self,response):
    for other_thing in response.xpath('//this_xpath')
        item = Website()
        item['title'] = other_thing.xpath('//this/and/that').extract()
        yield item

You cannot parse javascript with scrapy, but you can understand what the javascript does and do the same: http://doc.scrapy.org/en/latest/topics/firebug.html


text:
Q: Number of $n$-length sequences such that... Find the number of sequences of length n such that every number $i \in \{1, 2, · · · , n\}$ appears exactly
twice and two consecutive numbers are always different.
That's from a homework set, although isn't it incorrect? I mean if you make a sequence that contains all of this i numbers twice then wouldn't its' length be 2n? Besides from that i cannot solve it anyway.

A: As a hint  consider inclusion-exclusion.  The nodes of  the poset here
contain the sequences  where some subset $Q\subseteq [n]$  or more are
adjacent. With  $q=|Q|$ there  are ${n\choose q}$  such sets.  We then
have
$$\sum_{q=0}^n {n\choose q} (-1)^q \frac{(2n-q)!}{1^q 2^{n-q}}
= \sum_{q=0}^n {n\choose q} (-1)^q \frac{(2n-q)!}{2^{n-q}}.$$
This will produce
$$0, 2, 30, 864, 39480, 2631600, 241133760,
\\  29083420800, 4467125013120\ldots $$
which is OEIS A114938.

A: I believe that there are two possible interpretations for the problem:

*

*The length of the sequence is $2n$, and $n$ was a typo.

*The possible elements of the sequence are the numbers $\{1, \dots, n\}$ and if a number is contained in the sequence, it must be contained exactly twice. However, not every number must be part of the sequence. E.g. for $n = 4$ we get solution set:
$\{1212, 1313, 1414, 2121, 2323, 2424, 3131, 3232, 3434, 4141, 4242, 4343\}$
This would mean that there are no solutions for odd $n$.

A: We treat this problem as a question about balls: Given a bag of balls of $n$ different colors where each color occurs exactly twice, how many possibilities are there to draw all the balls out of the bag, without drawing two times the same color in a row. Clearly the answer to this answer is the total number of drawings ($2n!$) minus the number of rows in which two balls occur one after the other.
The number of cases in which two balls occur one after the other can be found by gluing two balls that are the same to each other (Since they have to be drawn one after the other), which leaves $$(2n-1)!$$ possibilities. This has to be multiplied by 2 for there are in fact two possibilities for the balls we draw one after the other, and multiplied by $n$ because it could be any ball. This make the total here $$2n(2n-1)!$$ Which gives a total of possibilities with no consecutive balls of $(2n)!-(2n)! = 0$.
We now remember we are in fact doing inclusion-exclusion and have removed  all cases with two consecutive pairs now, and have to compensate for that, the same approach as before now yields
$$2^2\begin{pmatrix}2n\\2\end{pmatrix}(2n-2)!$$.
Continuing this approach gives up to $n$ pairs being drawn one after the other, provides the answer
$$\sum_{i=n}^{2n} (-2)^{2n-i}\begin{pmatrix}2n\\2n-i\end{pmatrix}i!$$.

A: Let's follow the suggestion in comments: we use inclusion-exclusion principle to calculate $A$, the Answer. Call $A_k$ the set of sequences in which the number $k$ appears two times consecutively. We don't want to count these sets, right? So we take them out. But if we just subtract them from the total number of sequences, we take out two times, for instance, the set of sequences in which both 1,2 appears consecutively (i.e. $A_1 \cap A_2$). That's why we apply inclusion exclusion, and we get:
$$A =\sum_r (-1)^r \sum_{i_1, \ldots, i_r} |A_{i_1} \cap \ldots \cap A_{i_r} |$$
Let's evaluate $|A_{i_1} \cap \ldots \cap A_{i_r} |$. It is the cardinality of the set of sequences in which $r$ numbers are forced to stay together: they constitute a block of 2 bricks. The other bricks are free, but every number occur twice. Thus we have the permutations of $2(n-r)+r = 2n-r$ blocks, and we have to divide by $2^{n-r}$,the number of possible swaps among free bricks. Putting into the formula, and noticing that there are $\binom{n}{r} $ summands of "type r", we get
$$A = \sum_r (-1)^r \binom{n}{r} \frac{(2n-r)!} {2^{n-r}} $$
You can verify that the result is correct for $n=1,2,3$. For $n=3$,you can suppose that the first two numbers in the sequence are 1,2,and then multiply by 6 (why?).


text:
Q: Windows 10 v1809 use custom WIM for "Reset this PC" In Windows 7, 8 and 8.1, after capturing a well-audited image as OS restoration image, I use run this command in my running OS to instruct WinRE to use this image when resetting:
reagentc.exe /setosimage /path R:\Recovery\WindowsRE\install.vim /index 1

Then when I reboot the computer to recovery environment and select "Reset this PC" (resetting from WinRE, not Settings -%gt; Reset), it wipes out the whole C: partition and applies that image, in a manner similar to
DISM.exe /Apply-Image /ImageFile:R:\Recovery\WindowsRE\install.wim /Index:1 /ApplyDir:C:

However, this no longer works with Windows 10. Even if I tell WinRE to use my custom image with REAgentC, it just resets to a fresh Windows install, completely ignoring my prepared install.wim.
Any solution?

Related: Here's a thread with the identical question on Microsoft TechNet, with a stupid moderator posting a few non-answers.

A: Windows 10 uses different system for PBR - Push-Button Reset. And the option /setosimage was removed from the ReAgentC program.
Why
Before in 8 and 8.1, (or Win 7 if you provided your own restore tool in Win Recovery) the a complete image was made. After restore, you end up with the exact state as it was when the computer was manufactured, or when you yourself created the recovery WIM.
This means you will need to go through possibly years of updates again. Half-yearly updates would take hours to finish.
Microsoft came up with dusted down User State Migration Tool (USMT). The resulting file is still WIM, but it's not a complete disk image. It's a "saved state". Contains all files and registry entries, which are not part of the Windows itself. There is no Windows in the image.
How
When you do Reset, Windows will check integrity of each package (and its files) of the active Windows installation. If it finds corrupted file, it shall download that package and do a fix (never had myself opportunity to see this in action), than it will save current drivers and put them aside. It will rename Windows to Windows.old and "reinstall" clean Windows using packages from previous one. Then drivers are applied and lastly your USMT.PPKG (actually renamed WIM) file.
You'll end up with a system state as it was when you (or factory) created the recovery, but with updated Windows. And the Recovery file itself is only 200-300MB big.
If you include Office or some other Apps and have expensive disk space, there is a feature called Single Instance, which will link real files to this PPKG file.
The process of creating PBR is described on MS docs page.
What changed
If the above link is TL;DR and you already are familiar with the process from Win8.1,
what has changed is that

*

*instead of DISM /capture you run: N:\ScanState_amd64\scanstate.exe /apps /config:"$PSScriptRoot\ScanState_amd64\Config_AppsAndSettings.xml" /ppkg C:\Recovery\Customizations\USMT.ppkg /o /c /v:13 /l:C:\ScanState.log
The scanstate is on ADK and you need WinPe files from it too to make it run. Update the paths as needed, but this part is fixed: C:\Recovery\Customizations*.ppkg

*There is no separate Recovery partition and the rest of files, which were needed before: ResetConfig.xml and diskpart scripts are needed only if you plan on nonstandard disk partitioning or ResetConfig scripts. If so, those files goes into C:\Recovery\OEM
You don't use ReAgentC to register your ppkg file. All files in C:\Recovery\Customizations*.ppkg are applied after Reset.

*You run scanstate (the capture) from running OS (best to use Audit mode). It's not possible to do a capture from WinPe.
But I think it might be possible to create an additional option in WinRe, to restore using a full disk image WIM file and have both options work in parallel. I'm just exploring this, might come back here and edit my answer later.


text:
Q: Run Only Subclasses of a Type in an Ant JUnit test run Hi is it possible with Ant to define a target that will only run JUnit tests that are a subclass of a given type.
The scenario is: in the project I have joined we have a large number of Integration tests that are not run separately from the Unit tests, and I'd like to define an Ant task to run them in a separate build stage from the unit tests, and ultimately in a separate Jenkins build.  However, there are no naming or packaging conventions for these Integration Tests so the standard Ant path matching won't work in this scenario.
What I think I need to achieve what I want, is a task def that will allow me to say something like:
<include name="? extends IntegrationBaseTest"/>
This is obviously a contrived example, but I belive it communicates what I want.
Has anyone implemented something like this or is it possible with Ant out-of-the-box?

A: I don't think you can do this with Ant. Perhaps JUnit categories can help segregate your tests.


text:
Q: save the output of each for loop iteration to split a nested list I have a list of lists that looks like this mylst
[[('Salmon', 9), ('Fish&Chips', 3), ('Pasta', 8), ('Shrimp', 10)],
 [('Shrimp', 8), ('Fish&Chips', 10), ('Salmon', 9), ('Pasta', 7)],
 [('Shrimp', 10), ('Fish&Chips', 6), ('Salmon', 8), ('Pasta', 5)],
 [('Shrimp', 7), ('Pasta', 9), ('Salmon', 8), ('Fish&Chips', 8)],
 [('Fish&Chips', 10), ('Shrimp', 8), ('Salmon', 9), ('Pasta', 3)]]

I can access the sublists if I print the desired index
mylst[0]
which returns
[('Salmon', 9), ('Fish&Chips', 3), ('Pasta', 8), ('Shrimp', 10)]

But I would like to store each sublist in a new list.
Because eventually I would like to extract the items(tuple index 0) and the quantity ordered (tuple index 1) for each sublist and store them in two separate lists. But I can't do this if I can't split the lists
I tried to iterate through the main list
newlst=[]

for sublst in mylst:
    newlst.append(sublst)

and
newlst=[]

for i in range(len(mylst)):
    for sublst in mylst:
        newlst.append(mylst[i])

I am not sure how to split then store multiple outputs from each iteration of the for loop.
The desired output is to have the 5 sublists as seperate lists. For example
lst1=[('Salmon', 9), ('Fish&Chips', 3), ('Pasta', 8), ('Shrimp', 10)]

lst2 = [('Shrimp', 8), ('Fish&Chips', 10), ('Salmon', 9), ('Pasta', 7)]

and so on.
note: my question is not duplicate of this one, as I have read the solutions. I want to store my sublists in seperate lists. which is different.

A: If you just want to unpack the list then you can do what Chris said above and just do a,b,c,d,e = mylst, but if what you want is to repackage the data in a more usable way, then I suggest storing this in a pandas dataframe. You can do that with the following code
import numpy as np
import pandas as pd

my_df = pd.DataFrame(np.array(mylst).reshape(-1, 2),
    columns=['item', 'quantity'])

A: You can make one massive nested list by using a for loop each containing the desired list.
for each in lst:
seplist = [] #splitted list of each digit of every integer
for eachagain in str(each):
    seplist.append(integer)
nestedlist.append(seplist)

Here the nested list can be separated and stored by using another for loop


text:
Q: Add margin when using I'm using Bootstrap and a navbar with navbar-fixed-top class on it.
Below that is a div with an image inside (full width of the screen, height 400px).
The problem is that, since my navbar has a background-color, the navbar goes onto the image. I tried to add a margin-top:80px on the image, it works fine, but when I go below 769px x XXXpx, a space appears between my navbar and my image. I know this space is coming from the margin-top when resizing the window, but what could I do to set the image below the navbar without adding a margin-top for it to appear correctly ?
I thought this was simple issue so I didn't add code to my post, I will if needed.

A: Try to wrap CSS rule for image in
@media (min-width: 768px) {
    your CSS rule for image margin-top: 80px here
}


text:
Q: Dell PERC 6/i RAID Performance Testing We recently received a new Dell R710 with a PERC 6/i RAID controller and six 15k SAS drives. I have been doing some performance testing using hdparm and seeker on two different configurations and I'm not quite sure what to make of the results.

Configurations:
6 Disk RAID 10 - 64k stripe - Write through, no read ahead - RHEL 5.5
Results:
Timing buffered disk reads:  1024 MB in  3.01 seconds = 340.69 MB/sec
Results: 206 seeks/second, 4.848 ms random access time (137662331 < offsets < 436165962118)

4 Disk RAID 10, RAID 1 for OS - 64k stripe - Write through, no read ahead - RHEL 5.5
Timing buffered disk reads:  956 MB in  3.01 seconds = 318.13 MB/sec
Results: 209 seeks/second, 4.771 ms random access time (58179688 < offsets < 292314580383)

My first question is whether these results are within the expected range for our hardware. Using a RAID calculator it seems that I should be able to get higher speeds out of either configuration.
Also, while the first configuration performs slightly better, the second configuration would allow us to separate our MySQL databases from and isolate other IO to the RAID 1. I feel like that isolation would prove more beneficial than a few more MB/s.
Thoughts? Any input is appreciated.

A: Yeah. You TOTALLY focus on the wront number. Nothing cares about MB/s on a server. The ONLY relevant item is IOPS. Because moves destroy IO.
Make a check that checks random IO of appropriate size for your database server. Because most of the time you will have various processes hit the discs with different requests, so it is purely random.
So, what IOPS numbers di you have?


text:
Q: CSS display: block, animate H1.. jQuery How to slideDown h2 using jQuery?
HTML

Text

JS
$(window).load(function(){
    $("h2").slideDown();
});

not working

A: You need to:

*

*Use $(document).ready() function.

*First hide() the h2 programmatically.

*The slideDown().

First hide, then slideDown and in ready:
$(document).ready(function(){
  $("h2").hide().slideDown();
});

Snippet

$(document).ready(function(){
  $("h2").hide().slideDown();
});

Text

A: To apply slideDow h2 should be hidden. Try like below.

$(window).load(function () {
    $("h2").slideDown();
});

Text


text:
Q: How to properly configure tx:annotation-driven? I am very new to JavaEE using SpringMVC and i am developing a simple JavaEE project(Spring + Hibernate) however i am stuck on configuring some stuff. I tried to search how to solve but i cannot find a right solution.
This is my dispatcher-servlet.xml
 ...
<context:component-scan base-package="com.springmvcpattern.controller"/>
<context:component-scan base-package="com.springmvcpattern.dao"/>
<context:component-scan base-package="com.springmvcpattern.dao.impl"/>
<context:component-scan base-package="com.springmvcpattern.service"/>
<context:component-scan base-package="com.springmvcpattern.service.impl"/>

<bean id="viewResolver"          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

 <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/resources/database/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}">
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven />
<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="dataSource" ref="dataSource" />
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
....

My hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
      <session-factory>
          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springhib?zeroDateTimeBehavior=convertToNull</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password">root</property>
          <property name="hibernate.current_session_context_class">thread</property>
          <mapping class="com.springmvcpattern.model.Student"/>

    </session-factory>
  </hibernate-configuration>

My DAO
@Repository("studentDao")
public class StudentDaoImpl implements StudentDao{

@Autowired
private SessionFactory session;

@Override
public List<Student> getAllStudents() {
    return session.getCurrentSession().createCriteria(Student.class).list();
}

@Override
public void create(Student student) {
    try {
        session.getCurrentSession().persist(student);
    } catch (Exception e) {
        throw e;
    }
}

@Override
public Student find(String studentId) {
    return (Student) session.getCurrentSession().createCriteria(Student.class).add(Restrictions.eq("studentId", Integer.parseInt(studentId)));
}

@Override
public void update(Student student) {
    try{
        session.getCurrentSession().merge(student);
    }catch(Exception e){
        throw e;
    }
}

@Override
public void delete(Student student) {
    try{
        session.getCurrentSession().delete(student);
    }catch(Exception e){
        throw e;
    }
}
}

My Service
@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentDao stDao;

    @Override
    public List<Student> getAllStudents() {
     return stDao.getAllStudents();
    }
    @Override
    public void create(Student student) {
     stDao.create(student);
    }
    @Override
    public Student find(String studentId) {
       return stDao.find(studentId);
    }
    @Override
    public void update(Student student) {
       stDao.update(student);
    }
    @Override
    public void delete(Student student) {
       stDao.delete(student);
    }

}

My Controller
@Controller
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService stService;

    @RequestMapping(method = RequestMethod.GET)
    public String getAllStudents(Model model){
        model.addAttribute("hello", "Hello World");
        model.addAttribute("students",stService.getAllStudents());
        return "students";
    }
}

When I tried to run the application and clicked the List link(which point to students page) on the page, the server says:
 25-Mar-2016 00:00:26.404 SEVERE [http-apr-8080-exec-113] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/springmvcpattern] threw exception [Request processing failed; nested exception is   org.hibernate.HibernateException: createCriteria is not valid without active transaction] with root cause
      org.hibernate.HibernateException: createCriteria is not valid without active transaction

If I removed hibernate.current_session_context_class in hibernate.cfg.xml
the server says:
25-Mar-2016 09:03:37.581 SEVERE [http-apr-8080-exec-96] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/springmvcpattern] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread] with root cause
 org.hibernate.HibernateException: No Session found for current thread

Thanks for any help.
P.S. I am using Netbeans 8.0.2, Spring4.0.1 and Hibernate4.3


text:
Q: In uwp when i changes data in c# code it is not updating on front view I am implementing List view in uwp. I bind data to list view  from collection object. when i changes data in collection, it is not updating.Listview remain as it is? Please suggest me what to do to update data?
Thanks in advance.

A:
when i changes data in collection, it is not updating.Listview remain as it is?

When your property's value is changed, you need to notify the binding clients. So, how to notify?
You need to implement the INotifyPropertyChanged Interface
 for your custom class and raises a PropertyChanged event when the property is changed.
I've made a simple code sample for your reference:
<Grid>
    <ListView ItemsSource="{Binding tests}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <Button Content="update" Click="Button_Click"></Button>
</Grid>

public sealed partial class MainPage : Page
{
    public ObservableCollection<Test> tests { get; set; }
    public MainPage()
    {
        this.InitializeComponent();
        tests = new ObservableCollection<Test>();
        for (int i=0;i<10;i++)
        {
            tests.Add(new Test() { Name="Name "+i});
        }
        this.DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var t in tests)
        {
            t.Name = t.Name +" " +DateTime.Now;
        }
    }
}

public class Test:INotifyPropertyChanged
{
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set
        {
            if (_Name != value)
            {
                _Name = value;
                RaisePropertyChanged("Name");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string PropertyName)
    {
        if (PropertyChanged!= null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
        }
    }
}


text:
Q: Machine learning: which algorithm fits for questions answering I want to build a ml program who talks to user and get some inputs from the user.
The ml program analyze the input data(keywords) then predict the best solution.

A: So, you are looking at an AI application which needs some sort of machine intelligence for processing natural language.
Let us say the language of choice here is English. There are many things to be considered before building such a system.

*

*Dependency parsing

*Word Sense Disambiguation

*Verb Sense Disambiguation

*Coreference Resolution

*Semantic Role Labelling

*Universe of knowledge.

In brief you need to build all the above essential modules before you can generate your response.
You need to decide what kind of problem you are working on? Is it an open domain or closed domain problem, meaning what is the scope of knowledge of this application.
For example: Google now is an open domain problem which can practically take any possible input.
But some applications pertain to a particular task like automating food orders in an app etc where the scope of questions which can be asked is limited.
Once that is decided, you need to parse your input sentence and dependency parsing is the way to go. You can use Stanford core NLP suite to achieve most of the NLP tasks which were mentioned above.
Once the input sentence is parsed and you have the subjects, objects, etc it is time to disambiguate the words in the sentence as a particular word can have different meanings.
Then disambiguate the verb meaning identifying the type of verb (like return could mean going back to a place or giving back something )
Then you need to resolve coreference resolution meaning mapping the nouns and pronouns and other entities in a given context. For example:
My name is John. I work at ABC company.
Here I in the second sentence refers to John.
This helps us in answering questions like where does John work. Since John was only used in the first sentence and his work was mentioned in the second sentence coreference resolution helps us map them together.
The next task at hand is semantic role labelling, which basically means labelling all the arguments in a sentence with respect to each of its verb.
For example: John killed Mary.
Here the verb is kill, John and Mary are the arguments of the verb kill. John takes the role A0 and Mary the role A1. Where the definitions of these roles for each verb are mentioned in a huge frame and argument annotation framework created by the NLP community. Here A0 means the person who killed, A1 means the person who was killed.
Now once you have identified A0 and A1 just look into the definition of the kill frame and return A0 for killer and A1 for the victim.
Another important task at hand is to identify when your system must respond with an answer. For which you need to know if the given sentence is a declarative or assertive sentence or an interrogative sentence. You can just check that by seeing if the input sentence ends with a question mark.
Now to answer your question:
Let us say your input to the application is:
Input 1: John killed Mary.
Clearly this is an assertive sentence so just store it and process it as mentioned above.
Now the next input is:
Input 2: Who killed Mary?
This is an interrogative sentence so you need to come up with a reply or a response.
Now find the semantic role labels of input 1 and input 2 and return the word  of input 1 which matches the argument of Who in sentence 2.
Here in this case who would be labeled as A0 and John would be labeled as A0, simply return John.
Most of the NLP modules mentioned can directly be implemented using Stanford core NLP however if you want to implement some algorithms on your own you can go through the recent publications in EMNLP, NIPS, ICML, CONLL etc to understand them better and implement the one which best suits you.
Good luck !


text:
Q: How to upload a file and submit the form in one action Here is the code I have so far:
<form method="POST" id="frmProduct" name="frmProduct" action="" enctype="multipart/form-data">
    <a onclick="uploadAvatar();" href="#"> <img src"path-to-image"/> </a>
    <input type="file" name="mediafile" id="mediafile" style="display: none;">
</form>

function uploadAvatar() {
    let element = document.getElementById('mediafile');
    let form = document.getElementById('frmProduct');

    element.click();

    element.onchange = function() {
        form.submit();
    }
}

Can this be written more elegantly using vanilla JS?

A: You don't need to use Javascript. Just use a button with type submit.  I would consider it a bad practice to auto submit a page without user confirming the selection.  When this is done in other places, data is submitted via ajax to avoid a page load.


text:
Q: Any way for localized ABPersonViewController? Can't get any information about localized ABPersonViewController...
I use Russian language on my iPod but when I call ABPersonViewController it always appears in English. I check other apps in AppStore - the same result.
Is there any way to call localized ABPersonViewController?
thx

A: Project->Info->Localization->+  choose your language.
That's all.

A: From ABPersonViewController docs

displayedProperties Optional.
  Identifies the set of properties (such
  as name or telephone number) of
  displayedPerson the receiver displays.
@property(nonatomic, copy) NSArray
  *displayedProperties Discussion The default value of this property is
  NULL.
The properties are specified using an
  array of NSNumber objects representing
  ABPropertyID values.
To have the receiver display a single
  property for displayedPerson, such as
  telephone number, set
  displayedProperties to an array with a
  single value, such as
  kABPersonPhoneProperty.
Availability Available in iOS 2.0 and
  later. Declared In
  ABPersonViewController.h

From ABPerson docs

ABPersonCopyLocalizedPropertyName Returns the localized name of a person
    property

CFStringRef
  ABPersonCopyLocalizedPropertyName (
  ABPropertyID property ); Parameters
  property The person property whose
  localized name is being returned.
  Return Value The localized name of
  property.
Availability Available in iOS 2.0 and
  later. Declared In ABPerson.h

Edit,
The internationalization is made automat for you, You just need to create in your bundle Directory "ru.lproj" directory.
Then from File - > New File - > Resource -> Strings File.
Save it in ru.lproj with "Localizable.strings". And there you go.

A: You can set "Localization native development region" to your region in the .plist file.


text:
Q: Fade from iPhone default bitmap into main app What's the easiest/fastest/most efficient way to perform a gradual (0.5 sec) fade from Default.png to the initial app view?
My initial try, which doesn't work so well .. it's Saturday night, let's see if we can do better :)
UIImageView* whiteoutView = [[UIImageView alloc] initWithFrame:self.view.frame]; // dealloc this later ??
whiteoutView.image = [UIImage imageNamed:@"Default.png"];
whiteoutView.alpha = 1.0;
[self.view.frame addSubview:whiteoutView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelay:0.5];
whiteoutView.alpha = 0;
[UIView commitAnimations];

A: What about:
UIImageView* whiteoutView = [[[UIImageView alloc] initWithFrame:self.view.frame] autorelease];
if (whiteoutView != nil)
{
    whiteoutView.image = [UIImage imageNamed:@"Default.png"];
    [self.view addSubview:whiteoutView];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 0.5];
    whiteoutView.alpha = 0.0;
    [UIView commitAnimations];
}

(The things you had wrong were setAnimationDelay vs setAnimationDuration, not properly releasing the view and trying to add the view to self.view.frame instead of self.view. The compiler should have caught that last one. Did it?)

A: Here's a simple view controller that fades out the default image and removes itself from the view hierarchy. The advantage to this approach is that you can use this without modifying your existing view controllers...
@interface LaunchImageTransitionController : UIViewController {}
@end
@implementation LaunchImageTransitionController

- (void)viewDidLoad {
  [super viewDidLoad];

  self.view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default.png"]] autorelease];
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:.5];
  [UIView setAnimationDelegate:self];
  [UIView setAnimationDidStopSelector:@selector(imageDidFadeOut:finished:context:)];
  self.view.alpha = 0.0;
  [UIView commitAnimations];

}
- (void)imageDidFadeOut:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
  [self.view removeFromSuperview];
  //NOTE: This controller will automatically be released sometime after its view is removed from it' superview...
}
@end

Here is how you might use it in your app delegate:
- (void)applicationDidFinishLaunching:(UIApplication *)application {

  //create your root view controller, etc...
  UIViewController *rootController = ....

  LaunchImageTransitionController *launchImgController = [[[LaunchImageTransitionController alloc] init] autorelease];

  [window addSubview:rootController.view];
  [window addSubview:launchImgController.view];

  [window makeKeyAndVisible];
}

A: Other than using setAnimationDelay: instead of setAnimationDuration:, it looks pretty good. What don't you like about the results?
Edit: Wow beaten hard.


text:
Q: javascript changing radio button value based on user selection I need to create a js that can select radio buttons based on the values of radio buttons the user clicks. The conditions are the following:
Question 39: Yes must be selected if Yes is selected for one of questions 41 - 45. Otherwise, it's No.
Question 40: Yes must be selected if Yes is selected for ALL of questions 41-45. Otherwise it's No.
This is what I have:

function CBR() {
  for ($i = 41; $i < 46; $i++) {
    if ($('input[name=' + $i + '][id=Yes]').checked == true) {
        $('input[name=39][id=Yes]').click();
    }
  }
}

  <input type="radio" id="Yes" name="<?php echo $question['id']; ?>" value="1" onClick="CBR()">Yes

  <input type="radio" id="No" name="<?php echo $question['id']; ?>" value="0">No

  <input type="radio" id="NA" name="<?php echo $question['id']; ?>" value="1" checked="true">N/A

What I know the code does as of now is that it checks if any one of 41-45 is selected yes, and if so, it selects Yes for 39. I was just testing to see if this worked and it doesn't look like it, so I can't really move forward. Can anyone help?
To clarify: I have used document.getElementbyID, but if I do, I can't refer to the question number in the js, which is the "name" in html.

A: You'll find the way of checking if a radio button is checked here (StackOverflow question).
Here is a snippet of how to check a radio button with JavaScript:
document.getElementById(elementID).checked = true;


text:
Q: pytest, user input and exception I'm very new to unit testing so sorry for my newbie question.
I've written a small class with one instance attribute, "name".
The goal here is to ask the user for input if no "name" parameter is passed when the class is instantianted, and to verify if the name is formatted as expected.
Here is the class definition:
class Customer:
    def __init__(self, name=None):
        self.name = name

    @property
    def name(self):
        return self._name.upper()

    @name.setter
    def name(self, value):
        while True:
            try:
                if not value:
                    value = str(input("Please enter the customer's name: "))
                else:
                    print("Customer name found: {}".format(value))
                if not bool(re.match("^[A-Za-z0-9 _-]*$", value)) or value == "":
                    raise (ValueError)
            except ValueError:
                print("Invalid customer name.")
                value = None
                continue
            break
        self._name = value

It's working as expected:
>>> customer = Customer()
Please enter the customer's name: &&invalid
Invalid customer name.
Please enter the customer's name: valid
>>> customer.name
'VALID'
>>>

My test file is as follows:
import script
import pytest

class TestCustomer:
    def setup_method(self):
        self.customer = script.Customer("validname")

    def teardown_method(self):
        self.customer = ""

    def test_valid_name(self):
        self.customer.name = "validname"
        assert self.customer.name == "VALIDNAME"

    def test_invalid_name(self):
        with pytest.raises(ValueError):
            self.customer.name = "&invalidname&"

However, when I'm trying to test this with pytest, this happens:
========================================================================= FAILURES =========================================================================
______________________________________________________________ TestCustomer.test_invalid_name ______________________________________________________________

self = <test_script.TestCustomer object at 0x7f1ad68f39a0>

    def test_invalid_name(self):
        with pytest.raises(ValueError):
>           self.customer.name = "&invalidname&"

test_script.py:18:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
script.py:17: in name
    value = str(input("Please enter the customer's name: "))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <_pytest.capture.DontReadFromInput object at 0x7f1ad693d2e0>, args = ()

    def read(self, *args):
>       raise IOError(
            "pytest: reading from stdin while output is captured!  Consider using `-s`."
        )
E       OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.

/usr/local/lib/python3.8/dist-packages/_pytest/capture.py:732: OSError
------------------------------------------------------------------ Captured stdout setup -------------------------------------------------------------------
Customer name found: validname
------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------
Customer name found: &invalidname&
Invalid customer name.
Please enter the customer's name:
================================================================= short test summary info ==================================================================
FAILED test_script.py::TestCustomer::test_invalid_name - OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
=============================================================== 1 failed, 1 passed in 0.07s ================================================================

When I'm using the -s option, and enter a valid name, the exception is not raised:
test_script.py Customer name found: validname
Customer name found: validname
.Customer name found: validname
Customer name found: &invalidname&
Invalid customer name.
Please enter the customer's name: test
F

========================================================================= FAILURES =========================================================================
______________________________________________________________ TestCustomer.test_invalid_name ______________________________________________________________

self = <test_script.TestCustomer object at 0x7f4f2e1f6640>

    def test_invalid_name(self):
        with pytest.raises(ValueError):
>           self.customer.name = "&invalidname&"
E           Failed: DID NOT RAISE <class 'ValueError'>

test_script.py:18: Failed
================================================================= short test summary info ==================================================================
FAILED test_script.py::TestCustomer::test_invalid_name - Failed: DID NOT RAISE <class 'ValueError'>
=============================================================== 1 failed, 1 passed in 1.96s ================================================================

I can't get my head around this ...
Any help would be very appreciated :).


text:
Q: Mounting a raw hard drive read-only in Virtualbox Is it possible to give a VirtualBox VM read-only access to a physical HDD? I've read up on the createrawvmdk documentation, but it seems that it can only give it full read-write access.

A: You can use StarWind VSAN for that purpose. While creating a Device check physical disk and configure ISCSI Read-Only Disk bridge.


text:
Q: How to write values of __EVENTTARGET and __EVENTARGUMENT in log file of POST request I want to write the value of __EVENTTARGET and __EVENTARGUMENT in log file. I have tried to write value of Request.Form.ToString() into log by doing so I got the values of __EVENTTARGET and __EVENTARGUMENT into logs. But I also got the value of __VIEWSTATE (which I don't want in my logs file).
Is there any another way of logging __EVENTTARGET and __EVENTARGUMENT  into log file?

A: Try to use
string target= Request.Params["__EVENTTARGET"];
string args= Request.Params["__EVENTARGUMENT"];


text:
Q: How to prevent `sbt dist` to ask for [Enter]? I want to provide an easy copy-paste install manual for my play application.
 sbt dist
 cp target/universal/my-app-1.0-SNAPSHOT.zip  /tmp
 unzip my-app-1.0-SNAPSHOT.zip
...

This works when copied line-by-line, but not when pasted as a whole. The problem appears to be, that the newline behind sbt dist causes the current session to switch into the sbt console, kindly asking:
For better performance, hit [ENTER] to switch to interactive mode...
After entering interactive mode (caused by pasted newline), it then fails on the following commands like cp, and unzip.

A: While writing down the question above I found an answer myself under this thread.
sbt -batch dist
worked for me
sbt dist < /dev/null
shows another alternative.


text:
Q: Can't get second radio button selected value I have two pair of Radio Button. One pair for Gender and other for User type.
My problem is I cant get the selected value of second pair of Radio button that is User type.
Only get the selected value of first pair of radio button that is Gender.
Can u help me?
$('input:radio[name=user[user_type_id]]:checked').val();
$('input:radio[name=user[gender]]:checked').val();

A: Check jQuery(':radio') Selector
If you use val() then it will not give value of the input:checked, it will return on or off only. To get get value of the radio button use the use the attr method:
//Html

<input type="radio" name="gender"  value="Male"/>
<input type="radio" name="gender" value="Female" />

    <input type="radio" name="user" value="admin"/>
    <input type="radio" name="user" value="user" />

<input type="button" id="clickMe" value ="Click Me" />

//js
$('#clickMe').click(function(){

alert($('input[name=gender]:radio:checked').attr('value'));
    alert($('input[name=user]:radio:checked').attr('value'));

});

Ref:
Get attribute name value of <input>
jquery get attribute value when property is not set
Check this jsFiddle example


text:
Q: The machine that Syncer is in is broken and the directory of the `syncer.meta` file is lost when using TiDB Syncer GTID synchronously updates syncer.meta. If the machine that Syncer is in goes down, the directory of syncer.meta is lost. And I did not find the record information of GTID in TiDB. How to deal with this?

A: When you synchronize data using Syncer GTID, the syncer.meta file is constantly updated during the synchronization process. The current version of Syncer does not contain the design for high availability. The syncer.meta configuration file of Syncer is directly stored on the hard disks, which is similar to other tools in the MySQL ecosystem, such as Mydumper.
Two solutions:

*

*Put the syncer.meta file in a relatively secure disk. For example, use disks with RAID 1.

*Restore the location information of history synchronization according to the monitoring data that Syncer reports to Prometheus regularly. But the location information might be inaccurate due to the delay when a large amount of data is synchronized.


text:
Q: Attachments missing on the EWS server for draft email saved via Outlook OfficeJS I am using the Office.context.mailbox.item.saveAsync method for saving a draft email. This method returns itemId which I later use to make a call to the EWS server to retrieve the email eml content, but the returned eml content is missing some of the attachments.
This is only happening on the Desktop App (Outlook 2013) with cache mode enabled. When using Outlook on the Web it works correctly.
I am using ews-java-api to retrieve the email from the EWS.
Is there a way to know when the email saving is finished?
I can't use the Office.context.mailbox.item.saveAsync.makeEwsRequestAsync because of the 1MB response limitation.

A:
Is there a way to know when the email saving is finished?

If the following: "Is there a way to know when the email saving is finished?" is your question, than the answer is No. You may try the ugly solution, when you use sub-sequential EWS query with Id you've got from saveAsync in the loop and wait for success. This may take, depend on environment, from a few seconds to like half a minute easily. Not sure if your customers (users) will wait for so long, when add-in finally respond.
You may get more information from the topic: App for Outlook: EWS request failed with item Id returned by item.saveAsync on compose new message
EDIT:
Simple GetItem request can be used as follow ...
<GetItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">
    <ItemShape>
        <t:BaseShape>IdOnly</t:BaseShape>
    </ItemShape>
    <ItemIds><t:ItemId Id="' + itemId + '"/></ItemIds>
</GetItem>

The request should return ChangeKey if item was created on exchange.

A: In Cached mode it will take time for the item to sync up to the server. People usually poll until the data they want is there.
Also, they can write a custom property, and check for that property to make sure their item is up to date if necessary.
You can find some details about custom property here: Client Extension Message Object Protocol, Mail App Custom Properties and Mail App Accesses Custom Properties


text:
Q: Why there is no reveal token when i making discord bot? Im just a new in discord bot and i want to learn how to create ones. Every youtube and google tutorial, there is a button to reveal and copy the token but there is no reveal and copy discord bot token in my discord. Anyone know how to solve this?

A: As of very recently (this is not documented in their changelog so I cannot provide an exact date), you can only view your token when creating your bot for the first time.
If you have lost or forgotten your token, you can go to:
https://discord.com/developers/applications/{your_application_ID}/bot
There, you would have to regenerate a token by clicking "Reset token" (see image below), which will stop the old one from working and provide you with a new one. Once again, this new one will only visible the first time you reset it.

Note: users with 2FA will have to authenticate with their chosen authenticator.

A: Try another browser.
I had the same issue (token not showing no matter how many times I clicked on that reset button) on firefox. I tried with another browser (I happened to have a windows with edge on hand) and the token showed up when I reset it.

A: Have you tried accessing the bot using the https://discord.com/developers/applications page.
Also, in the Discord client (app), these is an option in Advanced that you can turn on Developer Mode.
I hope this help solving your problem!


text:
Q: Got error dbus: Failed to determine seats of user "1000": Too many open files - why and how to fix? I'm running Ubuntu 16.04.6 LTS with all updates installed.
Currently I see strange behavior: I can't start new GTK applications and Qt ones.
For GTK-based applications I get:
$ atril file.pdf
Failed to get bus connection: GDBus.Error:org.freedesktop.DBus.Error.LimitsExceeded: Failed to determine seats of user "1000": Too many open files

For Qt-based applications I get:
$ konsole
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
KUniqueApplication: Cannot find the D-Bus session server:  "Failed to determine seats of user \"1000\": Too many open files"

KUniqueApplication: Pipe closed unexpectedly.

I cant guess why this happens.


text:
Q: "unrecognized expression node array index linq" exception in LINQ to SQL Here is my LINQ in which I comparing a DateTime type of field with current date-
 var srs = (from s in dcDistrict.ScheduledReportStatus
            where s.ReportConfigId.Equals(ConfigId)
            && s.Status.HasValue && s.Status.Value
            && (Convert.ToString(s.SentDate).Split(' ')[0]).Equals(Convert.ToString(DateTime.Now.Date).Split(' ')[0])
            select s).FirstOrDefault();

this code is giving the excpetion "unrecognized expression node array index linq", Am I doing something wrong?

A: I got the solution, what I need to do is to use "AsEnumerable()", Here is the resolved version of my LINQ-
 Var srs = (from s in dcDistrict.ScheduledReportStatus.AsEnumerable()
                                         where s.ReportConfigId.Equals(ConfigId)
                                         && s.Status.HasValue && s.Status.Value
                                         && (Convert.ToString(s.SentDate).Split(' ')[0]).Equals(Convert.ToString(DateTime.Now.Date).Split(' ')[0])
                                         select s).FirstOrDefault();

AsEnumerable() done some part of the code client side that resolves my issue.

A: Filter as much as you can on the server and then, what you can't on the client.
var startDate = new DateTime(DateTime.Today.Year, 1, 1);
var endDate = startDate.AddYears(1);
var serverQuery = from s in dcDistrict.ScheduledReportStatus
    where s.SentDate >= startDate && s.SentDate < endDate
        && s.ReportConfigId.Equals(ConfigId)
        && s.Status.HasValue && s.Status.Value
    select s;
var clientQuery = from s in serverQuery
    where // whatever client side filtering
    select s;


text:
Q: display of metadata hyperlink on list and views For a column on my list, data is drawn from a metadata field. It works nicely, a tree is displayed, and the item is selected from the tree. An underlined value then goes into the column (presumably some kind of hyperlink) when a new item is added or in update mode. However, when the value is displayed in a list or in view mode it decomposes to text.
What is going on? How can the hyperlink be retained in the list, or in the item view? Additionally, how can I create a calculated column that can be used to display that column into decomposed text?


text:
Q: Why is Edge fetching every module/component as http request? We have a SPA built with React and bundled with Webpack.
The server only has the index.html and javascript bundle files located.
Behaviour Chrome/Firefox/Opera

*

*Loads index.html

*Fetches bundles

*Boots React page

Behaviour Edge

*

*Loads index.html

*Fetches bundles

*Boots React page

*Starts loading every module and component as an independent file using HTTP requests (they are not even on the server, the response is index.html)

The bundle does not have this information. This information must be fetched from the source map. But why does Edge do this?

A: This is similar like SAP application, those JavaScript library has their own logic to preload source codes to optimize the performance/network requests. It's a compatibility issue with React library for Edge browser.
The next version of Edge browser don't have this issue. Maybe you want to try this: https://www.microsoftedgeinsider.com/en-us/


text:
Q: Rendering component via query parameter with react router For some requirements of my project I would need to display different page types via query parameter (something like):
http;//myweb.com?parameter=value
Is there a way to do that?

A: Yes this is possible with react-router-dom
Sample Code:
    const queryParams = [];
    for(let i in this.state.someData){
     queryParams.push(encodeURIComponent(i) + "=" + encodeURIComponent(this.state.someData[i])); // this will create a array of property name and value//
    }
    const queryString = queryParams.join("&"); // Will join the Params with & //

       this.props.history.push({
          pathname:'/yourURL',
          search:'?'+ queryString
       });
    }

A: One way to display a diffrent component based on the query parameter, you can use switch in the render :
import * as qs from "query-string";

import ComponentA from "./CmponentA";
import ComponentB from "./CmponentB";

...

render(){
  return(
    {
        (() => {
            const parsed = qs.parse(location.search);

            switch(parsed.parameter){
                case 'a' :
                    return <ComponentA />;
                case 'b' :
                    return <ComponentB />;
            }
        })();
    }

  );
}


text:
Q: CSS3 Fixed header table interferes with hover element I am making a table with a fixed header using Javascript and it works nicely. But I have problems with my hover icons in the last column of the table's body, when I scroll down, I can't click on the hover icons in the last column of the table's header because the icons of the table row below the header suddenly appear.
I've already tried changing the z-index of the table's header but it didn't change anything.

document.getElementById("wrap").addEventListener("scroll", function() {
  var translate = "translate(0," + this.scrollTop + "px)";
  this.querySelector("thead").style.transform = translate;
});
.table-parent {
  overflow-y: auto;
  margin-top: 25px;
  height: 500px;
}

table {
  width: 100%;
  min-width: 800px;
  overflow-x: auto;
}

thead {
  background: #708F9C;
  color: #FFFFFF;
  font-weight: 600;
  font-size: 1.25rem;
  transition: transform 0s !important;
}

thead,
thead tr,
thead th {
  z-index: 1;
}

tbody {
  z-index: 0;
  font-size: 1rem;
  max-height: calc(100vh - 200px);
}

td,
th {
  padding: 15px 20px;
}

thead tr {
  background: inherit;
}

tr {
  background: #EBEBEB;
}

td {
  border-bottom: 1px solid #DADADA;
}

tr td:last-child {
  opacity: 0;
  transition: opacity 0.25s;
  text-align: center;
}

tr td:last-child i {
  padding-left: 5px;
  padding-right: 5px;
  z-index: 0;
}

tbody tr:hover {
  background: #FAFAFA;
  transition: none;
  cursor: pointer;
}

tr:hover td:last-child {
  opacity: 1;
}

th:first-child {
  border-top-left-radius: 10px;
}

th:last-child {
  border-top-right-radius: 10px;
}

td:first-child,
th:first-child {
  padding-left: 15px;
}

td:last-child,
th:last-child {
  padding-right: 0;
}

tr:last-child td {
  border-bottom: none;
}

tr:last-child td:first-child {
  border-bottom-left-radius: 10px;
}

tr:last-child td:last-child {
  border-bottom-right-radius: 10px;
}

th:last-child {
  text-align: center;
}

.table-style-selector {
  color: #FFF;
  padding-right: 10px;
  cursor: pointer;
  transition: none;
}

.table-style-selector.active {
  color: #DFDFDF;
}

.table-style-selector:hover {
  color: #EFEFEF;
}

table.medium td,
table.medium th {
  padding: 10px 15px;
}

table.small td,
table.small th {
  padding: 5px 10px;
}
Here's the code: ```

        Kunde
        Auftragsbeschreibung
        Bestellnummer

        Ferchau Gmbh (Bremen)
        Change Workshop 13.-14. August 19

        Haufe Akademie
        Change Seminar offen Berlin Juli 19

        Haufe Akademie
        Haufe Trainertreffen 12.7.19

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

        herwig consulting GmbH
        Pluss V1
        19051001

I don't want the icons below the header to be visible and to interfere with the header on hover.

A: It is a bit weird behavior because all of your elements are actually relative position
you could use following
table {
  position: relative;
  padding-top: 55px;
}

thead {
  position: absolute;
  width: 100%;
  top: 0;
}

Problem with this is that you will need to set manually column widths.
https://jsfiddle.net/w6teknf7/


text:
Q: soapclient not found in phpinfo I know the same question is exist but i do all of the answer but they aren't helpful for me.plz help
I change all of my php.ini and uncommented the extension=php_openssl.dll and extension=php_soap.dll my php.ini address is:
/home/mychanneladminbot/etc/php.ini
/home/mychanneladminbot/etc/php7.0/php.ini
/etc/php7ts/conf.d/php.ini
/etc/php/7.0/fpm/php.ini
/etc/php/7.0/cgi/php.ini
/etc/php/7.0/cli/php.ini

also I install again the soapclient with:sudo apt-get install php7.0-soap and then i restart apache server.
and my php version is 7.1.9;
but there isn't soap section in phpinfo yet.

A: You are editing the wrong php.ini file. Those from /etc/php/VERSION/ folder are for php-cli. The one used in apache server is different. Look into /etc/php/VERSION/apache2/php.ini


text:
Q: CSS hacks for different browsers Can anyone please help me with this. I am new to  css styling. I have a css file where all my styling resides for the asp.net website that I am trying to build. However it works fine on the server that has IE 7 installed on it and when I try to view it using chrome, firefox or IE 8 and above it kinda distorts the look of the website.
I need to change my margin according to the client browser. How do I achieve this? Ive heard that there is an "if" condition solution to this. Means I have to write seperate css files in my project and include the right one according to the browser?? Cant I just change the basic css to detect the browser and select the appropriate styles?
i want to choose different  positioning for a division according to client browser. I am working on asp.net 2.0 by the way.
existing code:
#page
{
background-image: url('C:/Program Files (x86)/some-path-here/Images/img1.jpg');
}

I am trying to do this:
html>/**/body #page
{
background-image: url('C:/Program Files (x86)/some-path-here/Images/img1.jpg');
}

But the img1 does not load up for IE 8 and firefox. It does for IE 7.
I tried to target just IE 7 for my testing purposes with the following code in my html file:

However when I test the page on IE 7 it just show me the  "background-color: Red;" text. Why is that? Am i missing something here in this conditional statement? It is only taking the text and doing nothing with the background color. Thanks.

A: You can code for standards compliant browsers (Chrome, Safari, Firefox etc.) and then add conditional comments for internet explorer.
EDIT:
As a side point, look at Eric Myers' CSS reset. It's an excellent resource.

A: Conditional formatting for IE: http://www.quirksmode.org/css/condcom.html
In terms of Hacks you can write invalid markup for some browsers (such as IE) by using _ in front of the CSS attributes for IE 6/7 but it makes your CSS invalid per specifications - it will still run properly.

A: Instead of Conditional Comments and non-standards ompliant CSS hacks, check out the CSS Browser Selector plugin. This jQuery will allow you to write different rules for each browser inside the CSS file itself with no inaccuracies for standards and no Conditional comments. It can even allow you to target different browsers on different OS's.
For IE you'd write:
.ie .myDiv
{
   background-color: #f00;
}

And for webkit browsers:
.webkit .myDiv
{
   background-color: #bar;
}

Then IE (all versions) and Webkit browsers will display different background colors. You have a big choice of browsers to select as well :)

A: I going to mention below some of the CSS hacks I know for the Browsers that I learn while working here at Oodles Technologies.
I'm gonna list them out here as there are some properties which creates issue in webkit based browsers like safari, chrome and IE. Let us suppose that we can using this css code:
CSS targeting Chrome and Safari:
 @media screen and (-webkit-min-device-pixel-ratio:0) {
    /* Safari and Chrome, if Chrome rule needed */
    .selector { property:value; }

    /* Safari 5+ ONLY */
    ::i-block-chrome, .selector { property:value; }
}

CSS target Safari 9 but ONLY on iOS
 /* Safari 9+ (iOS Only) */
@supports (-webkit-text-size-adjust:none) and (not (-ms-accelerator:true)) {
     .selector { property:value; }
}

CSS target Firefox only
 @-moz-document url-prefix() {
    .selector { property:value; }
}

CSS target IE10 only
 @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* IE10+ specific styles go here */
    .selector { property:value; }
}

CSS target IE9 only

CSS target IE8 only

CSS target IE7 only

Hope you find these useful

A: CSS Hacks are decreasing in popularity. You should instead start your css by using a CSS Reset. You can read more about reset options in this thread.


text:
Q: Dealing with grouped data in a regression Suppose I have the following database where I have, for each age, the average years of experience and income of the group and the number of individuals observed for such age (but not the income/experience of each individual):
----------------------------------------------------------------------------
| Average income | Age | Average years of experience | number of individuals
----------------------------------------------------------------------------
|     105.40     | 18  |            2.1              |          23
----------------------------------------------------------------------------
|     205.50     | 19  |            3.4              |          12
----------------------------------------------------------------------------
|     465.40     | 20  |            4.5              |          33
----------------------------------------------------------------------------
|     678.40     | 21  |            5.1              |          57
----------------------------------------------------------------------------
|     815.40     | 22  |            6.6              |          11
----------------------------------------------------------------------------
|     902.56     | 23  |            6.7              |          20
----------------------------------------------------------------------------
|     997.13     | 24  |            7.3              |          13

I want to get a regression [not necessarily a linear one] of the form:
$(Avg\_income) = \beta_0 + \beta_1 * (age) + \beta_2 * (Avg\_years\_xp)$
or
$(Income) = \beta_0 + \beta_1 * (age) + \beta_2 * (Years\_xp)$
The first approach I thought of was ignoring the "number of individuals" column and doing the regression as if I had only 7 observations, but this seems to be a waste of information, right?
The second was replicating each row by "number of individuals", but is this approach really correct? Also, I'd like to have this work in a more generalized way such that I can work a non-integer "number of individuals" (ok, doesn't make any sense in this example, but it does in my real problem).
Obs.: I'm planning doing a Bayesian inference, but Frequentist approaches are welcomed too. R syntax is good too.

A: Starting from your first approach: If you treat the data as if it had only 7 observations, you need to weight them with the size of the group.
Refer to this question for how to do regression with weights in R.
If you multiply every line by the number of individuals, you would assume that all individuals of an age group have the same income and experience, which will substantially bias your standard errors downwards.
Theoretically, if you expand the table and treat that as 23, 12 … number of observations, you have stochastic variables as regressors. Unfortunately, you do not know their variances, so you cannot use methods that account for that. See for example the wikipedia page for errors-in-variables.


text:
Q: novell netware benefits I am in the process of moving a business' servers to a virtualized solution; so far so good, but the main problem is an old novell server (v4.something, from 1999)
it seems to me that its functions are more like active directory's --> auth users, map shares depending on group membership, fileserver
are there any other functions of this ancient program which I should be aware of ? can it be replaced with AD or a samba deployment ?
supposing I have to keep this solution, is it possible to install a higher version (I have found 5.11 on some torrents) and import somehow the old config ?
(the fact of seeing its ancient-ms-dos-like console makes me stay away from this ... software :))
thanks

A: There is a good upgrade path to this technology. While Netware as an OS is EOL, the services it provided included eDirectory (which provides great user management and authentication plus very solid LDAP services) and NCP file sharing have been migrated to Linux. They are part of a product called Open Enterprise Server (OES) that is very much a going concern.
The marketing materials are here: http://www.novell.com/products/openenterpriseserver/
I would recommend taking whatever the Netware 4 server is used for, and migrating those services to an OES server for the following reasons:

*

*An upgrade preserves the existing server services better.

*OES and eDirectory is easier to support than openldap.

*It is more cost-effective than AD.
Who knows? You might fall in love with the technology.

A: If you're the support guy, and you know nothing about it, my first advice is to stay away from it. My second advice is to learn it well enough to migrate off of it.
Novell Netware and NDS was great, it was better than AD, but it's not the wave of the future. But it does what you asked - centralized user auth, fileserving, printing (you forgot that), even database and applications. Make sure you know what you're doing - you could find out that they have an accounting application that depends on BTrieve after you've migrated the fileshares and print queues and turned off the Netware machine.

A: How much data, how many users? You may find it easier to start over :)
Tom

A: netware was pretty cool, actually.
unfortunately, it is no longer used (much) in the SME environment it sounds like you're in - so a change to active directory makes more sense. the process of setting up the netware server again is going to require resources that aren't going to be that cheaply/easily available...


text:
Q: Loading a HTML page without waiting for certain parts to load I have a simple HTML page which contains many parts, out of which one part

...

renders data from an external source and loads. It takes a very long time to load, and thus all the other parts of the page also wait till this section is loaded.
Is there way using jQuery or something else, to set the content of
 to a loading image and load the rest of the page without depending on that one section ? and How do I achieve this?

A: If the content of that div is rendered server-side and served with the rest of the page, there's two options you could go for:
1) Serve the page with the div containing the loading graphic you mentioned, and then use jQuery to load the contents of the div with a $.post or $.get when the page loads. This will allow the page to be served without whatever back-end logic you have holding up everything else.
2) If you don't like using $.post or $.get, you can put an iFrame in that div that references another page which has the div contents. This will load separately from the page, thus not holding things up. However, be advised that iFrames sometimes behave strangely between browsers in terms of sizing, borders, etc. Make sure your code is tested in all major browsers (mainly IE) to make sure it looks ok in all of them.


text:
Q: Use icon in jqGrid column header? I want to use the jQuery UI icon ui-icon-comment as a column header in one of my columns. Is there a way to do that?
Alternatively, if that's not possible, is there a way to use a PNG image in the header?

A: Items from colNames array can contain any HTML fragments: So you can place for example the following  text as the column header:
"<span class='ui-icon ui-icon-comment' style='display:inline-block'/>"

I think that it will do what you need.


text:
Q: Cohen-Macaulay and descent Let $X$ be a Cohen-Macaulay scheme and $f:X\rightarrow Y$ a morphism. Under which "non trivial conditions" on $f$ can we conclude that $Y$ is also Cohen-Macaulay? By "trivial conditions" I mean smooth+surjective or étale surjective. Is it true under flatness?

A: Direct summands
There are several direct summand conditions which imply this.
For example if $f$ is finite and $O_Y \to f_* O_X$ splits in the category of $O_Y$-modules, then $Y$ is also Cohen-Macaulay.  The summand condition is much weaker than flatness for finite maps.  This is easy, use the local cohomology criterion for Cohen-Macaulayness.
Another related condition is the following.  Now suppose we are working over a field of characteristic zero.  Suppose further that $X$ has rational singularities (which is Cohen-Macaulay + a little more), then if $O_Y \to R f_* O_X$ splits in the derived category, then $X$ Cohen-Macaulay (even more has rational singularities).  See a paper of Sandor Kovacs in Duke.
If $X$ and $Y$ are schemes over a field (ie, equal characteristic) and $X$ is regular and $O_Y \to f_* O_X$ splits, then $Y$ is Cohen-Macaulay.  This is open in mixed characteristic if I recall correctly (see a paper of Hochster and Roberts).

A: It is sufficient that $f$ be faithfully flat. This is a local question (I'm assuming everything is Noetherian). If you have a flat map of local rings $(R,\mathfrak{m})\to (S,\mathfrak{n})$, then we have $dim~S=dim~R+dim~S/\mathfrak{m}S$ and $depth~S=depth~R+depth~S/\mathfrak{m}S$. Since depth is bounded by dimension, this implies that $S$ is Cohen-Macaulay if and only if both $R$ and $S/\mathfrak{m}S$ are Cohen-Macaulay; cf. Bruns-Herzog, 2.1.7.


text:
Q: Text of anchor tag does not change using javascript I execute an ajax function that takes 3 seconds + so in this time I would like the text of the a link (code below, and 1 in image) to change to "Please wait...". I tried the JavaScript code below but what happens is the text does not change and the function executes as normal. Please if someone could point out my mistake.
HTML :
Email Garage List...

Screenshot :

Javascript :
function EmailGarageList(fId) {
    $('#emailGarageList').text('Please wait...');
    $.ajax({
        type: "POST",
        url: "Default.aspx/EmailGarageList",
        data: "{'fId':" + fId + ",'userId':" + userId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert("Garage List Emailed!");
        },
        error: function () {
            alert("Error :(");
        }
    });
    $('#emailGarageList').text('Email Garage List...');
};

A: put the $('#emailGarageList').text('Email Garage List...'); inside your success function. Otherwise it changes, then changes right back.

A: Move $('#emailGarageList').text('Email Garage List...'); inside $.ajax call back function. $.ajax is an async call and your text below is updated right away before completing the ajax call.
function EmailGarageList(fId) {
    $('#emailGarageList').text('Please wait...');
    $.ajax({
        type: "POST",
        url: "Default.aspx/EmailGarageList",
        data: "{'fId':" + fId + ",'userId':" + userId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert("Garage List Emailed!");
            $('#emailGarageList').text('Email Garage List...');
        },
        error: function () {
            alert("Error :(");
        }
    });
};

A: My guess is that jQuery Mobile (which I assume you are using), is modifying the DOM sso your selector cannot find $('#emailGarageList') the way you think it is.

A: I think you are looking for the beforeSend callback:
$.ajax({
    // other stuff ...
    beforeSend: function () {
        $('#emailGarageList').text('Please wait...');
    }
});


text:
Q: why my pyspark linear regression model always chooses the smallest parameters as the best model? I am trying to use pyspark to run a linear regression with cross validation. But there is something that I do not understand: my model always chooses the model with the smallest parameters as the best model.
I download the data from https://vincentarelbundock.github.io/Rdatasets/datasets.html. There is a data set called SLID.

It looks like this:

I delete the first column, the column sex and language. Then I delete the rows with NA in it. Then I changed the column names. In the end, the data looks like:

Then, here is my code:
import findspark
findspark.init()
import pyspark
from pyspark.sql import SparkSession
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.regression import LinearRegression
from pyspark.sql.functions import col
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder

spark=SparkSession.builder.getOrCreate()
#please change it to your own path
df = spark.read.csv("/home/feng/Downloads/SLID.csv",header=True)
df1=df

df1=df1.select(*(col(c).cast("float").alias(c) for c in df1.columns))
df1=df1.withColumnRenamed('x2','label')
assembler = VectorAssembler(
    inputCols=['x1','y1'],
    outputCol="features")
output = assembler.transform(df1)
output1=output.select(output.label,output.features)

output2=output1.randomSplit([0.3,0.7])
training=output2[0]
testing=output2[1]

lr = LinearRegression(maxIter=10, regParam=0.01)

paramGrid = ParamGridBuilder() \
    .addGrid(lr.maxIter, [1,2,5,10,20]) \
    .addGrid(lr.regParam, [0.05,0.1, 0.3,0.5,0.7]) \
    .addGrid(lr.elasticNetParam, [0, 0.5, 1])\
    .build()

crossval = CrossValidator(estimator=lr,
                          estimatorParamMaps=paramGrid,
  evaluator=RegressionEvaluator(predictionCol="prediction",labelCol="label",
                               metricName="rmse"),
                      numFolds=5)  # use 3+ folds in practice

# Run cross-validation, and choose the best set of parameters.
cvModel = crossval.fit(training)

a=cvModel.bestModel.extractParamMap()
for keys,values in a.items():
    print(keys)
    print(values)

Then I have the result like this:
LinearRegression_a0560f768ad8__labelCol
label
LinearRegression_a0560f768ad8__aggregationDepth
2
LinearRegression_a0560f768ad8__epsilon
1.35
LinearRegression_a0560f768ad8__standardization
True
LinearRegression_a0560f768ad8__maxIter
1
LinearRegression_a0560f768ad8__regParam
0.1
LinearRegression_a0560f768ad8__loss
squaredError
LinearRegression_a0560f768ad8__predictionCol
prediction
LinearRegression_a0560f768ad8__solver
auto
LinearRegression_a0560f768ad8__tol
1e-06
LinearRegression_a0560f768ad8__featuresCol
features
LinearRegression_a0560f768ad8__elasticNetParam
0.0
LinearRegression_a0560f768ad8__fitIntercept
True

This result is an example. I have actually changed a lot of different parameter sets. You can see in paramGrid, I have three parameters which have different values: maxIter, regParam, elasticNetParam. No matter which values I choose, the algorithm just gave me the best model with the smallest parameters employed. I do not think this is correct. But I cannot figure not why.
Could anyone explain this to me, telling me where I do wrong and how to revise?


text:
Q: using aggregation in Javascript function with MongoDB I am using Javascript to do queries to mongodb shell, I have the following function:
function myFunction(dbName, colName, name)
{
    var col = db.getSiblingDB(dbName).getCollection(colName);
    col.aggregate(
    [
        {$match: {title: name}},
        {$group:
           {_id : "$name",
           likes: {$sum: "$likes"}}
        }
    ] );
}

the document looks as follows:
`{ "title" : "NoSQL", "likes" : 400 }
 { "title" : "MongoDB", "likes" : 100 }
 { "title" : "MongoDB", "likes" : 150 }
 { "title" : "MongoDB", "likes" : 50 }
 { "title" : "Neo4j", "likes" : 50 }
 { "title" : "Neo4j", "likes" : 150 }
 { "title" : "Neo4j", "likes" : 250 }`

When I call the function in the mongodb shell, I do not receive output however. I call it like this:
myfunction("myDb", "myCol", "Neo4j")

Before I do this I do load the Javascript file using the load() function.
Any idea what I could be doing wrong?
Any help would be appreciated:)


text:
Q: How to fit content of a DIV with fixed height Consider that we have a DIV with fixed height. Without a defined width, the content will spread to the width of 100%. How to adjust the width to fill the DIV. Definitely, it is not posible with CSS, thus, I am looking for a solution with Javascript.
In this example, the text is spread across the width of 100% and leaves lots fo empty space in the fixed height. I need to set a width of 130px by javascript to fit the content to the entire DIV. But how to calculate the width?
NOTE: This value (130px) was estimated for the example text. Depending on the DIV content, javascript needs to calculate the width required to fit the content within the DIV.
Is there any way to estimate the 2D size of a DIV content?
CSS actually does this for height; when we have a fixed width, it continues the height to fill the DIV. Is it possible to do so for width too?
Clarification: How to vertically fill the DIV without knowing the width (we have a fixed height)?

A: If I understand your requirement correctly, you can do this using Javascript.
The trick is to use a helper
 within which you let the browser flow the content to a specific width and see what height it comes up with. If the height of the helper
 is more than that of the outer
, adjust the width to compensate.
Meanwhile, the outer
 has overflow: hidden so all those flowing experiments don't produce jarring changes to your page layout.
See it in action.

A: This is an alternate approach.. While less efficient, it may be more accurate than my other answer.
see example here:
Basically loop the width down until the desired height is reached

        I dont know how wide i am, I dont know how wide i am, I dont know how wide i am, I dont know how wide i am, I dont know how wide i need to be

The CSS:

#AA {
    height: 300px;
    border: 1px solid black;
    width: 100%;
}

#A {
   display: inline;
}

The Script:
    height = $('#AA').height();
minWidth = 300;

currentWidth = $('#A').width();
currentHeight = $('#A').height();
stop = false;

if (currentWidth >= minWidth) {

    while (stop === false) {
        if (currentWidth >= minWidth) {
            newWidth = currentWidth - 1;
            $('#AA').width(newWidth);
            currentHeight = $('#A').height();
            currentWidth = $('#A').width();
            if (currentHeight < height) {
                stop = false;
            }
            else {
                stop = true;
            }
        }
        else {
            stop = true;
        }
    }
}


text:
Q: Breaking Up Data Set into Individual Worksheets by Identifier I have a large data set with an identifier attributed to each row. There around 10 different identifiers for the whole dataset but this can be variable. The aim is to break the main dataset up into individual worksheets for each group of identifiers. I have written this code below which does the job but seems very clunky with a loop to make all the worksheets and another to go through each row.
    ...

    '--> Get list of Area Codes
    ws1.Range("N:N").Copy
    Set TempWS = Sheets.Add
    With TempWS
        With .Range("A:A")
            .PasteSpecial
            .AdvancedFilter xlFilterInPlace, Unique:=True
            .SpecialCells(xlCellTypeVisible).Copy
        End With
        .Range("B:B").PasteSpecial
        .ShowAllData
        .Range("A:A").Delete
        .Rows(1).Delete
        tmpLR = .Range("A" & Rows.Count).End(xlUp).Row + 1
    End With

    '--> Create Worksheet for Each Code
    i = 1
    Do Until i = tmpLR
    Set ws = Sheets.Add
    ws.Name = TempWS.Cells(i, 1).Text
    ws1.Range("A1").EntireRow.Copy
    ws.Rows("1:1").PasteSpecial
    i = i + 1
    Loop

    TempWS.Delete

    '--> Break Up Main Data Sheet into Area Code Sheets
    Set rng = ws1.Range("N2:N" & LRws1)
    For Each c In rng
        shname = c.Text
        c.EntireRow.Copy
        Set oWS = Sheets(shname)
        oLR = oWS.Range("A" & Rows.Count).End(xlUp).Row + 1
        oWS.Rows(oLR).PasteSpecial
    Next

    ...

Is there a more efficient way of completing this process instead of looping multiple times?
I also noticed that with this line c.entirerow.copy it is not possible to use a cut instead of copy, what's the reason for this?
Format is like this:

A: if I can read well, the original main table would look something like this in a simplified form:
HEADER1          HEADER2          HEADER3          AREACODES
Area1_Value1     Area1_Value2     Area1_Value3     Area1
Area2_Value1     Area2_Value2     Area2_Value3     Area2
Area3_Value1     Area3_Value2     Area3_Value3     Area3

You want to create a new sheet for each of the Areacodes (named Area1,2,3) and fill in the headers + corresponding line.
The code written below is merely a framework on the table form that I have drawn, you can customize this code the way you want it.
Sub Area_Codes()

Dim oRange                  As Range
Dim oRange_Headers          As Range
Dim vArray_Headers          As Variant
Dim oRange_Area             As Range
Dim vArray_Area             As Variant
Dim oRange_Area_Dest        As Range

Dim lRange_Rows             As Long
Dim iRange_Cols             As Integer
Dim vArray                  As Variant

Dim oSheet_Main             As Excel.Worksheet
Dim oSheet                  As Excel.Worksheet
Dim lUse_Row                As Long

Dim lCnt                    As Long
Dim lCnt_B                  As Long
Dim bExists                 As Boolean

Const AreaCodes_Col = 4

Set oSheet_Main = ThisWorkbook.Sheets(1)
Set oRange = oSheet_Main.UsedRange
lRange_Rows = oRange.Rows.Count
iRange_Cols = oRange.Columns.Count
ReDim vArray(1 To lRange_Rows, 1 To iRange_Cols)
vArray = oRange

'load your headers into a separate range
Set oRange_Headers = oRange.Rows(1)
'Set dimensions of the array equal to dimensions of the range and load range into memory (array)
ReDim vArray_Headers(1 To 1, 1 To iRange_Cols)
vArray_Headers = oRange
'Clear the range from memory
Set oRange_Headers = Nothing

'Start as from row 2 (Row 1 = header)
For lCnt = 2 To lRange_Rows
    'Clear the row containing the area code info from memory - reload on every loop
    Set oRange_Area = Nothing
    'Exceptional activate
    oSheet_Main.Activate
    'Set row of Area + load into memory
    Set oRange_Area = oSheet_Main.Range(Cells(lCnt, 1), Cells(lCnt, iRange_Cols))
    ReDim vArray_Area(1 To 1, 1 To iRange_Cols)
    vArray_Area = oRange_Area

    'Check if sheet exists, load result into boolean value
    bExists = False
    For Each oSheet In ThisWorkbook.Sheets
        If oSheet.Name = vArray(lCnt, AreaCodes_Col) Then
            bExists = True
        End If
    Next oSheet

    'Add sheet if sheet doesn't exist + name
    Set oSheet = Nothing
    If Not bExists Then
        Set oSheet = Sheets.Add
        oSheet.Name = (vArray(lCnt, AreaCodes_Col))
    Else
        'Define sheet object if sheet already exists
        Set oSheet = ThisWorkbook.Sheets(vArray(lCnt, AreaCodes_Col))
        oSheet.Activate
    End If

    'Define destination range of headers; You could name this otherwise, to avoid confusion
    Set oRange_Headers = oSheet.Range(Cells(1, 1), Cells(1, iRange_Cols))
    oRange_Headers = vArray_Headers

    'Check last row used, +1 sets the last row + 1 -> the destination row
    lUse_Row = oSheet.UsedRange.Rows.Count + 1
    Set oRange_Area_Dest = oSheet.Range(Cells(lUse_Row, 1), Cells(lUse_Row, iRange_Cols))
    'Fill in the destination row
    oRange_Area_Dest = vArray_Area
Next lCnt

End Sub


text:
Q: How to access a property that only exists on one of my two return types? I have a function being called:
const accountDetails: IAccount | ISmallError = getAccount()

It might return IAccount or ISmallError.
On the next line I want to do this:
if (accountDetails.error) return response.json({ error: error.error });

But under .error it says
Property 'error' does not exist on type 'IAccount | ISmallError'.
  Property 'error' does not exist on type 'IAccount'.ts(2339)

what do I do about this?
One solution that does work is:
const err = accountDetails as ISmallError;
if (err.error) return response.json({ accountDetails: "No account found" });

but is this the best way?

A: Assuming the property is meant to be a discriminant property something as simple as 'error' in accountDetails will be sufficient:
type IAccount = { payload: 2 }
type ISmallError = { error: Error }
declare const getAccount: () => IAccount | ISmallError;

const accountDetails: IAccount | ISmallError = getAccount()

if ('error' in accountDetails) {
  accountDetails.error // No longer an error
}

Using a property existence check is better (in my opinion) because it uses the type system instead of overriding it (as the cast does), ensuring we will get an error in more circumstances in future.
Even better would be to introduce a proper discriminant property to  IAccount and ISmallError so that you can switch on the tag.  That helps avoid the case where IAccount grows its own error field in the future (fewer places for collisions makes for an easier-to-maintain codebase):
type IAccount = { type: 'accountDetails', payload: 2 }
type ISmallError = { type: 'prodError', error: Error }

// ... snip ...

if (accountDetails.type === 'prodError') {
  // Full narrowing here and no potential overlapping fields later
}


text:
Q: Reflection should not move at hover with underline My goal is that when the user hovers over the nav the underline should not move the reflection. It should just overlay the reflection. At the moment as soon i hover over the nav elements the underline pushes down the reflection. How can I change this?
I have this code:
HTML

Hagartenstrasse 16  T 032 672 35 84

4562 Biberist  F 032 672 15 22

info@malerei-hubler.ch  M 079 251 23 22

HOME

ANGEBOT

TEAM

UMWELT

KONTAKT

CSS
* {
    margin: 0px;
    padding: 0px;
}

body, html, ul, li, h1 {
    font-family: 'Titillium Web', sans-serif;
    font-size: 100%;
    line-height: 1em;
}
.container {
    width: 900px;
    height: 100vh;
    margin: 0 auto;
}
h1, h2, h3 {
    font-weight: 600;
}

.txtRot {
    color: #e60004;
}
.txtOrange {
    color: #f28e00;
}
.txtGelb {
    color: #f0d80e;
}

.txtGruen {
    color: #009836;
}
.txtBlau {
    color: #0068b5;
}

header {
    margin-top: 56px;
}

ul {
    padding: 0px;
}

/* HEADER */
#logo {
    height: 100%;
    float: left;
}

#header-address {
    font-weight: 400;
    font-style: italic;
    font-size: 14px;
}
#header-address ul {
    list-style: none;
    float: right;
}
#header-address ul li {
    line-height: 19px;
    text-transform: uppercase;
}#header-address ul li span {
    line-height: 19px;
    float: right;
    padding-left: 5px;
}
nav {
    float: left;
    margin-top: 60px;
    margin-left: 0px;
}
nav ul li  {
    display: inline-block;
    list-style: none;
    height: 100%;
}
nav ul li h1  {
    font-size: 40px;
    font-weight: 600;
    height: 100%;
    padding:0px;
}
/* PADDING FOR NAV */
.navp {
    padding-right: 46.4px;
    height: 100%;
}

#reflect h1:hover {
    border-bottom: 4px solid;

}
#reflect {
    position: relative;
    -webkit-box-reflect: below -3px -webkit-linear-gradient(bottom, rgba(255, 255, 255, 0.1) 0%, transparent 70%, transparent 100%);
}

#reflect:before {
    background: -moz-linear-gradient(center top, #FFFFFF, #FFFFFF 30%, rgba(255, 255, 255, 0.9) 65%, rgba(255, 255, 255, 0.7)) repeat scroll 0 0 padding-box, -moz-element(#reflect) no-repeat scroll 0 -127px content-box rgba(0, 0, 0, 0);
    content: "";
    height: 140px;
    left: 0;
    position: absolute;
    top: 277px;
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
    width: 360px;
}

Here is the codepen:
http://codepen.io/patrickhofer/pen/JKdgVN
Any help much appreciated.
It should look like this:

A: You have to give a specific height to navp. You can try changing your .navp like this:
.navp {
   padding-right: 46.4px;
   height: 40px;
   margin-bottom:7px;
 }

A: Set
#reflect h1 {
    border-bottom: 4px solid transparent;

}
#reflect h1:hover{
    border-bottom: 4px solid currentcolor;

}

Note you can not have multiple ID in the same document read ID selectors

Defines a unique identifier (ID) which must be unique in the whole
  document. Its purpose is to identify the element when linking (using a
  fragment identifier), scripting, or styling (with CSS).

so the final result shall look like this

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

/*Reset Safari User Agent Styles*/

* {
  margin: 0px;
  padding: 0px;
}
body,
html,
ul,
li,
h1 {
  font-family: 'Titillium Web', sans-serif;
  font-size: 100%;
  line-height: 1em;
}
.container {
  width: 900px;
  height: 100vh;
  margin: 0 auto;
}
h1,
h2,
h3 {
  font-weight: 600;
}
.txtRot {
  color: #e60004;
}
.txtOrange {
  color: #f28e00;
}
.txtGelb {
  color: #f0d80e;
}
.txtGruen {
  color: #009836;
}
.txtBlau {
  color: #0068b5;
}
header {
  margin-top: 56px;
}
ul {
  padding: 0px;
}
/* HEADER */

#logo {
  height: 100%;
  float: left;
}
#header-address {
  font-weight: 400;
  font-style: italic;
  font-size: 14px;
}
#header-address ul {
  list-style: none;
  float: right;
}
#header-address ul li {
  line-height: 19px;
  text-transform: uppercase;
}
#header-address ul li span {
  line-height: 19px;
  float: right;
  padding-left: 5px;
}
nav {
  float: left;
  margin-top: 60px;
  margin-left: 0px;
}
nav ul li {
  display: inline-block;
  list-style: none;
  margin-bottom: 50px;
}
nav ul li h1 {
  font-size: 40px;
  font-weight: 600;
  height: 100%;
  padding: 0px;
}
/* PADDING FOR NAV */

.navp {
  padding-right: 46.4px;
  height: 100%;
}
.reflect h1 {
  border-bottom: 4px solid transparent;
}
.reflect h1:hover {
  border-bottom: 4px solid currentcolor;
}
.reflect {
  position: relative;
  -webkit-box-reflect: below -3px -webkit-linear-gradient(bottom, rgba(255, 255, 255, 0.1) 0%, transparent 70%, transparent 100%);
}
.reflect:before {
  background: -moz-linear-gradient(center top, #FFFFFF, #FFFFFF 30%, rgba(255, 255, 255, 0.9) 65%, rgba(255, 255, 255, 0.7)) repeat scroll 0 0 padding-box, -moz-element(#reflect) no-repeat scroll 0 -127px content-box rgba(0, 0, 0, 0);
  content: "";
  height: 140px;
  left: 0;
  position: absolute;
  top: 277px;
  -webkit-transform: scaleY(-1);
  transform: scaleY(-1);
  width: 360px;
}

Hagartenstrasse 16  T 032 672 35 84

4562 Biberist  F 032 672 15 22

info@malerei-hubler.ch  M 079 251 23 22

HOME

ANGEBOT

TEAM

UMWELT

KONTAKT

you can use box-shadow too
.reflect h1:hover {
    box-shadow: 0 4px;
}

that will look like this

* {

  margin: 0px;

  padding: 0px;

}

body,

html,

ul,

li,

h1 {

  font-family: 'Titillium Web', sans-serif;

  font-size: 100%;

  line-height: 1em;

}

.container {

  width: 900px;

  height: 100vh;

  margin: 0 auto;

}

h1,

h2,

h3 {

  font-weight: 600;

}

.txtRot {

  color: #e60004;

}

.txtOrange {

  color: #f28e00;

}

.txtGelb {

  color: #f0d80e;

}

.txtGruen {

  color: #009836;

}

.txtBlau {

  color: #0068b5;

}

header {

  margin-top: 56px;

}

ul {

  padding: 0px;

}

/* HEADER */

#logo {

  height: 100%;

  float: left;

}

#header-address {

  font-weight: 400;

  font-style: italic;

  font-size: 14px;

}

#header-address ul {

  list-style: none;

  float: right;

}

#header-address ul li {

  line-height: 19px;

  text-transform: uppercase;

}

#header-address ul li span {

  line-height: 19px;

  float: right;

  padding-left: 5px;

}

nav {

  float: left;

  margin-top: 60px;

  margin-left: 0px;

}

nav ul li {

  display: inline-block;

  list-style: none;

  margin-bottom: 50px;

}

nav ul li h1 {

  font-size: 40px;

  font-weight: 600;

  height: 100%;

  padding: 0px;

}

/* PADDING FOR NAV */

.navp {

  padding-right: 46.4px;

  height: 100%;

}

.reflect h1:hover {

  box-shadow: 0 4px;

}

.reflect {

  position: relative;

  -webkit-box-reflect: below -3px -webkit-linear-gradient(bottom, rgba(255, 255, 255, 0.1) 0%, transparent 70%, transparent 100%);

}

.reflect:before {

  background: -moz-linear-gradient(center top, #FFFFFF, #FFFFFF 30%, rgba(255, 255, 255, 0.9) 65%, rgba(255, 255, 255, 0.7)) repeat scroll 0 0 padding-box, -moz-element(#reflect) no-repeat scroll 0 -127px content-box rgba(0, 0, 0, 0);

  content: "";

  height: 140px;

  left: 0;

  position: absolute;

  top: 277px;

  -webkit-transform: scaleY(-1);

  transform: scaleY(-1);

  width: 360px;

}

Hagartenstrasse 16  T 032 672 35 84

4562 Biberist  F 032 672 15 22

info@malerei-hubler.ch  M 079 251 23 22

HOME

ANGEBOT

TEAM

UMWELT

KONTAKT