text:
Q: Is it possible to use labelled data in SKLearn? Currently my code looks like:
clf = RandomForestClassifier(n_estimators=10, criterion='entropy')
clf = clf.fit(X, Y)

However X is an array like:
X = [[0, 1], [1, 1]]

I would prefer to use X like:
X = [{'avg': 0, 'stddev': 1}, {'avg': 1, 'stddev': 1}]

Simply because plotting a tree (as described here: http://scikit-learn.org/stable/modules/tree.html#classification ) makes much more sense when you read X[0]['avg'] rather than X[0][0]. Is it possible? Using dictionary or pandas?

A: You can use the DictVectorizer class to convert such a list of dicts to sparse matrices or dense numpy arrays.
scikit-learn will never use dict objects as the primary datastructure to store records internally as this not memory efficient at all compared to numpy arrays or scipy sparse matrices.

A: Here's is a great example by 'larsmans' on how to build a feature dict and use DictVectorizer before fitting a model on the data. Note that DictVectorizer class uses scipy.sparse matrix by default (instead of a numpy.ndarray) to make the resulting data structure able to fit in memory. As not all sklearn learning models support sparse matrices you might want to use sparse=False option in the constructor to obtain a dense array
dv = DictVectorizer(sparse=False)

A: Alternatively, you can specify feature names when using export_graphviz. This will generate
a tree with more meaningful labels at test nodes.
See the feature_names parameter at http://scikit-learn.org/dev/modules/generated/sklearn.tree.export_graphviz.html#sklearn.tree.export_graphviz


text:
Q: Subgroup criterion. I've been reading some stuff about algebra in my free time, and I think I understand most of the stuff but I'm having trouble with the exercises. Specifically, the following:

Prove that a nonempty subset $H$ of a group $G$ is a subgroup if for
  all $x, y \in H$, the element $xy^{-1}$ is also in H.

Proving that the identity is in $H$ is easy: just take $x=y$, so $x x^{-1} = 1 \in H$. However, I'm having trouble showing that multiplication is closed and that each element in $H$ has an inverse. Can anyone give some hints?

A: *

*by given condition for any $x\in H$ we have $xx^{-1}=e$ is in $H$, denote identity element by $e$

*take any $x\in H$ and $e\in H$ so by the given condition $ex^{-1}=x^{-1}\in H$ so every element of $H$ has inverse in $H$.

*take any $x,y\in H$ as $y^{-1}\in H$ so by given condition $x(y^{-1})^{-1}=xy\in H$, which proves the closure property.

A: For any $b \in H$, $eb^{-1} = b^{-1} \in H$, so every element has an inverse in $H$.  To show closure, note that if  $a, b \in H$, then $b^{-1} \in H$ as we have just shown.  So $a(b^{-1})^{-1} = ab \in H$.  Hence, $H$ is a subgroup.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keep a minimum amount of cells, and still use commitEditingStyle In my TableView, I wanna display always at least 3 cells. If there is no cell, show 3 dummy cells, if there is one cell, display this one and 2 "dummy cells", of there are 2 cells, show them and one dummy cell, if there are 3 cells, show those 3, if there are 4, display those for, and so on.
So I implemented commitEditingStyleForRowAtIndexPath, and it would work fine, if I wouldn't have
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   if ([self.piggyBanks count]< 3) {
       return 3;
    }
    else{
        return [self.piggyBanks count];
    }
 }

As it expects one row less after deletion, it throws an exception, if I get from 3 to 2 or less cells (and therefore return 3 again in numberOfRowsForSection).
Any idea how I can possibly achieve this?
Thanks

A: In your commitEditingStyleForRowAtIndexPath, don't delete the row that is to be deleted if it will be replaced by a dummy row. Instead, tell the tableView to reload that particular row.

A: This forum post tracked me to a solution.
It's a bit complicated, maybe I'll try edsko's version lateron too, but I think that could also become a problem, as I would have to resort the cells..
The main problem was, when i have like 1 real cell, I have 2 dummy cells, so the last returned numberOfRows was 3. If I delete the one remaining cell, commitEditing expects 2 as the new result, but it would either be 3, if I just say, if my Arrays count is less than 3, return 3, or it would be 0, if I plain return the Arrays count.
So basically I did what the forum post suggested, but also created a property, storing the last returned numberOfRows. If numberOfRows gets called from commitEditing, I'll first return the last committed number -1, than reload the data, this time with the values I really need.
This will only work if I delete one row at a time, though, but my App's setup doesn't compliment deleting more than 1 row at a time.. So this will work for me.. Not as elegant, but possible..
I'll try edskos version lateron, seeing if that will work out easier..
Thanks!


text:
Q: How can i have a fade effect on the bottom of the div? I need to set a fade effect at the bottom of the div as in the image. Please help.

A: I would use a pseudo element on your main container to achieve the desired effect.
Something like so,
html:

Content goes here

css:
.mainCont {
    position: relative;
}

.mainCont:after {
    content: "";
    width: 100%;
    height: 80px;
    display: block;
    position: absolute;
    background: rgba(150, 123, 19, 1);
    background: -webkit-gradient(linear, 0% 0% 0% 100%, from(rgba(150, 123, 19, 0.1)), to(rgba(150, 123, 19, 1)));
    background: -webkit-linear-gradient(top, rgba(150, 123, 19, 0), rgba(150, 123, 19, 1));
    background: -moz-linear-gradient(top, rgba(150, 123, 19, 0), rgba(150, 123, 19, 1));
    background: -ms-linear-gradient(top, rgba(150, 123, 19, 0), rgba(150, 123, 19, 1));
    background: -o-linear-gradient(top, rgba(150, 123, 19, 0), rgba(150, 123, 19, 1));
    bottom: 0;
    left: 0;
    z-index: 10;
}

Finally a fiddle: Demo
Fiddle with more content in .mainCont: Demo

A: .divClass {
    box-shadow: 0 80px 80px gold inset;
}

or
.anotherDivClass {
    box-shadow: 0 0 80px gold;
}

Depends on which element you put it on. The inset goes inside the box. Without the inset, it goes outside the box.


text:
Q: Ignore a property in AutoMapper? I'm using Automapper to copy one object properties to other and later will update in database using EF.
Question is how to tell Automapper copy every property but ignore a particular property (in this case it will be Id). I'm new to AutoMapper and just have done this code. I don't have other configurations or use of AutoMap in project.
Mapper.Map(lead, existingLead);

I have downloaded AutoMapper form here https://github.com/AutoMapper/AutoMapper

A: On your Mapper.CreateMap<Type1, Type2>() you can use either
.ForSourceMember(x => x.Id, opt => opt.Ignore())

or
.ForMember(x => x.Id, opt => opt.Ignore())

UPDATE:
It seems like .Ignore() is renamed to .DoNotValidate() according to the AutoMapper docs.

A: I use this extension method:
public static IMappingExpression<TSource, TDestination> IgnoreMember<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map, Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

and I use it like this
Mapper.CreateMap<MyType1, MyType2>().IgnoreMember(m => m.PropertyName);

Hope that helps.


text:
Q: Hide a javascript if user comes from an specific location I want a javascript file (<script src=" file here " >) to be hidden if a user lets say comes from China.
How can i do it?

A: You can try using a geolocation service but considering that you can defeat that by using a proxy (like a hacked machine in the US) somewhere else or by spoofing the request to look like it came from given location it may not do you much good in the end.

A: I'm Chinese and I reserve all my rights to protest. :)
Actually you have a few options, you can do it front-end or back-end.
Front-end solution
Use HTML5 Geolocation to determine the longitude and latitude of current user and check whether it's within China or not(don't forget to contain Taiwan). The defect is only modern browsers are supported, you should probably set up plan B.
//jQuery, ip-api is a RESTful service, do it in front-end
$.getJSON('http://ip-api.com/json/?callback=?', function(response){
    alert(response.country);
    if(response.country === "China"){
        $.getScript("script_for_Chinese.js");
    }
});

Back-end solution

*

*Check the user IP and find out if it's from China(there are a bunch of IP to location RESTful services)

*Check HTTP header if the Accept-Language part contains string like zh-CN or zh-TW. This may also hurt the people using Chinese in other countries.

As for example requested, I won't recommend you use front-end solution or IP-to-location back-end solution. The only one that might work is based on http header.
//PHP, if the client accept Chinese, assume he is from China
if(preg_match('/(zh-CN|zh-TW|zh)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'])){
    echo '<script src="script_for_Chinese.js" type="text/javascript"></script>';
}


text:
Q: Unit Of Work & Generic Repository with Entity Framework 5 I'm using ASP.NET MVC 4 with Entity Framework 5. I have model classes and Entity Maps to map existing tables to those model classes. All this is setup fine and works great.
Now I want to mock this. I created Unit Of Work that takes the DataContext and uses a Generic Repository. Upon that I built services to be able to get data from many repositories at once and only needing to have one instance of the DataContext. This also works great.
Now to the problem: I want to test the services, with mock data. When I create the Unit Of Work instance, I want to be able to insert a DataContext that is mocked instead of the real DataContext.
I tried to create a IContext interface and let the real and mocked DataContext implement that but ran into problems with DbSet. I tried to use IDbSet and creating a FakeDbSet but without success. I also read on the internet that mocking the context with IDbSet and using a FakeDbSet is a bad approach.
Do you have any idea what would be the best way to achieve this? What I have now is the behavior I would like to keep, but would really like to be able to mock the data from the Model classes in the DataContext.
I'm aware of that Entity Framework already comes with Unit Of Work behavior and that you don't need to add extra behavior on top of that. But I wanted to wrap that inside of another class that keeps track of all the repositories (called UnitOfWork class).
Edit: I wrote two articles explaining my solution with both LINQ and Entity Framework.
http://gaui.is/how-to-mock-the-datacontext-linq/
http://gaui.is/how-to-mock-the-datacontext-entity-framework/
Here's my code:
IRepository.cs
public interface IRepository<T> where T : class
{
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
    T GetById(long Id);
    IEnumerable<T> All();
    IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}

IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
    IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
    void Save();
}

Repository.cs
public class Repository<T> : IRepository<T> where T : class
{
    private readonly IDbContext _context;
    private readonly IDbSet<T> _dbset;

    public Repository(IDbContext context)
    {
        _context = context;
        _dbset = context.Set<T>();
    }

    public virtual void Add(T entity)
    {
        _dbset.Add(entity);
    }

    public virtual void Delete(T entity)
    {
        var entry = _context.Entry(entity);
        entry.State = System.Data.EntityState.Deleted;
    }

    public virtual void Update(T entity)
    {
        var entry = _context.Entry(entity);
        _dbset.Attach(entity);
        entry.State = System.Data.EntityState.Modified;
    }

    public virtual T GetById(long id)
    {
        return _dbset.Find(id);
    }

    public virtual IEnumerable<T> All()
    {
        return _dbset;
    }

    public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return _dbset.Where(predicate);
    }
}

UnitOfWork.cs
public class UnitOfWork<TContext> : IUnitOfWork where TContext : IDbContext, new()
{
    private readonly IDbContext _ctx;
    private Dictionary<Type, object> _repositories;
    private bool _disposed;

    public UnitOfWork()
    {
        _ctx = new TContext();
        _repositories = new Dictionary<Type, object>();
        _disposed = false;
    }

    public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
    {
        if (_repositories.Keys.Contains(typeof(TEntity)))
            return _repositories[typeof(TEntity)] as IRepository<TEntity>;

        var repository = new Repository<TEntity>(_ctx);
        _repositories.Add(typeof(TEntity), repository);
        return repository;
    }

    public void Save()
    {
        _ctx.SaveChanges();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!this._disposed)
        {
            if (disposing)
            {
                _ctx.Dispose();
            }

            this._disposed = true;
        }
    }
}

ExampleService.cs
public class ExampleService
{
    private IRepository<Example> m_repo;

    public ExampleService(IUnitOfWork uow)
    {
        m_repo = uow.GetRepository<Example>();
    }

    public void Add(Example Example)
    {
        m_repo.Add(Example);
    }

    public IEnumerable<Example> getAll()
    {
        return m_repo.All();
    }
}

ExampleController.cs
public IEnumerable<Example> GetAll()
{
    // Create Unit Of Work object
    IUnitOfWork uow = new UnitOfWork<AppDataContext>();

    // Create Service with Unit Of Work attached to the DataContext
    ExampleService service = new ExampleService(uow);

    return service.getAll();
}

A: Your ExampleService class is expecting IUnitOfWork, that means you just need another IUnitOfWork that is a Mock and its GetRepository() method will return an IRepository Mock.
For example (not really a Mock but In-Memory stub):
  public InMemoryRepository<T> : IRepository<T> where T : class
  {
        ........
  }

  public InMemoryUnitOfWork : IUnitOfWork
  {
       public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
       {
            return new InMemoryRepository<TEntity>();
       }
  }

Then:
public IEnumerable<Example> GetAll()
{
    // Create Unit Of Work object
    IUnitOfWork uow = new InMemoryUnitOfWork();

    // Create Service with Unit Of Work
    ExampleService service = new ExampleService(uow);

    return service.getAll();
}

A: You can follow the following link it is very helpful.
Generic Repository Pattern in MVC3 Application with Entity Framework
Entity Framework and Data Patterns


text:
Q: Unable to clear checkbox on same component navigation in Angular 7 I have a filter with checkboxes. The IDs of the elements in the checkbox are stored in an array called activeCheckboxes. I am checking them on ngOnInit(), from what I am getting from query params.
To get the things checked, getting from the query params, I am using this attribute:
 [checked]="activeLocation.indexOf('location._id')>-1"

Now, when I am resetting the filter, I am simply navigating to the same component with entirely different query-params / no query-params at all. It is working fine. However, the checkboxes are still checked. I have cleared the 'activeCheckboxes' array before navigating. Still, the  same is happening.
Any clue how to solve this?


text:
Q: Javascript Date getDay() format issue I'm having a issue is JS trying to get the day of the week of a specific date:
const searchDate = "2021-02-04";
const serchDateDayOfWeek = new Date( searchDate ).getDay();
console.log( serchDateDayOfWeek ) // => 3

I assumed that the result would be 4 (Thursday) but it is 3 (Wednesday).
What would be the correct way to get the day of week value without modifying the format of the seachDate?
Thanks in advance!

A: Update:
In MDN, Date constructors syntax includes
new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

"2021-02-04" is a dateString which is strongly discouraged by MDN( This reference is wildly distributed in Internet ^v^ )

Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.

Support for RFC 2822 format strings is by convention only.
Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

In brief, there are many international standards that create conflicts in dateString mode. Different browsers may use different standards, that is "browser differences". So that's why I run your code in mdn, the output is 4 which is different from yours.
There is another answer facing the same situation as yours, and the output is smaller than the correct result by 1 as yours.
If you Google, you will find many people are trapped. I think this answer should be filed with other answers like:

*

*Ambiguous behavior of javascript new Date() constructor for same different formatted string

*Why does Date.parse give incorrect results?

*Date.getDay() is returning different values

*Javascript, getDay() returning wrong number

*getDay() return wrong day if day is with leading zero

*Date.getDay() returns wrong day of the week

*...

So, I strongly recommend don't use dateString to construct Date. Just use new Date(2021, 02, 04), you will get the correct answer.

A: To solve for this, you need to make an array containing names of the days in order.  And on the index end of the array, put new Date().getDay() inside the index of the array, and should return a result.
console.log([
     "Sunday",
     "Monday",
     "Tuesday",
     "Wendesday",
     "Thursday",
     "Friday",
     "Saturday"
][
    new Date().getDay()
])

The above will assign a named day based on the index number new Date().getDay() produces.


text:
Q: Temporary queue creation from python STOMP I want to create temporary queue for python(stomp).
    In the docs they have provided the reply-to header. but its not creating any temporary queue.
    Both producer and consumer files written in python.
 Does python STOMP really has a way to implement temporary queue.
I am sending a message with reply-to header.
In subscribers on_message listener i am checking whether reply-to header exist and if it does then it sends the response to reply-to header value.
Queue Producer
import stomp
import json

class QueueProducer:

    def __init__(self):
            self.hosts = ['somevalue']
            self.ports = ['somevalue']
            self.ENCODE_FORMAT = "UTF-8"
            self.conn_param = zip(self.hosts,self.ports)
            self.conn = stomp.Connection11(self.conn_param, encoding=self.ENCODE_FORMAT)
            self.conn.start()
            self.conn.connect(wait=True)
        except Exception as ex:
            raise ex

    def send_msg(self,message,queue_name,header={"JMSDeliveryMode":"Persistent",
                                                 "JMSPriority":4}):
        try:
            message = json.dumps(message)
            self.conn.send(destination='/queue/{}'.format(queue_name), body=message,
                            headers=header)
        except Exception as ex:
            raise ex

if __name__ == "__main__":
    obj = QueueProducer()
    from datetime import datetime
    obj.send_msg(str(datetime.now()),"MessageLife",header={"JMSDeliveryMode":"Persistent",
                                                 "JMSPriority":4,'reply-to':"destination", })

QUEUE CONSUMER:
import sys
import stomp
import time
import json

ACK_CLIENT_INDIVIDUAL = "client-individual"

class CustomListener(stomp.ConnectionListener):

    def __init__(self,conn):
        self.conn = conn

    def on_error(self, headers, message):
        print('received an error::%s' % message)

    def on_message(self, headers, message):
        try:
            message = json.loads(message)
            response = [1,2,3]
            self.conn.ack(headers.get("message-id"), int(headers.get("subscription")))
            if 'reply-to' in headers:
                self.conn.send(destination='/queue/{}'.format(headers.get("reply-to")),
                                body=json.dumps(response))

        except Exception as ex:
            print("exception nack")

class QueueConsumer:

    def __init__(self):
        try:

            self.hosts = ["some value",]
            self.ports = ["some value",]
            self.ENCODE_FORMAT = "utf-8"
            self.conn_param = zip(self.hosts,self.ports)
            self.conn = stomp.Connection11(self.conn_param, encoding=self.ENCODE_FORMAT)
            self.conn.start()
            self.conn.connect(wait=True,)
            self.conn.set_listener('', CustomListener(self.conn))
        except Exception as ex:
            raise ex

    def consume_msg(self):
        try:
            while True:
                self.conn.subscribe('/queue/{}'.format(self.queue_name),1, ack=ACK_CLIENT_INDIVIDUAL,
                                headers={"activemq.prefetchSize":1}
                                )
                time.sleep(500)
                self.conn.unsubscribe(1)
        except Exception as ex:
            raise ex

    def execute(self):
        try:
            self.queue_name = "sample_queue"
            self.consume_msg()
            self.close_connection()
        except Exception as ex:
            raise ex

if __name__ == "__main__":
    obj = QueueConsumer()
    obj.execute()

I really want to know whether reply-to header create a temporary queue like java.(createTemporaryQueue method) or we have to manually create the queue(Either in sender or in consumer).
If anyone has code sample in python STOMP.py it will be very useful.

A: There is nothing special about a message header named reply-to in STOMP. The STOMP protocol specification doesn't say anything about a header named reply-to, and it also doesn't mention anything about creating temporary queues for any reason.
That said, ActiveMQ implements some extensions to STOMP so that if you send a message or create a consumer using a destination header which starts with /temp-queue/ then a temporary queue will be created.


text:
Q: Support for local single GPU debugging Which combinations of GPU hardware, operating systems and NVIDIA software / drivers support local, single GPU debugging?

A: Single-GPU debugging works:

*

*On Windows using Nsight Visual Studio edition.

*On Mac or Linux when running in console mode (e.g. without windowing environments)

Also note that both GPUs do not need to be CUDA GPUs - e.g. we have tested several Linux setups that have Intel and NVIDIA GPUs with Intel driving the OS UI.


text:
Q: Is asking wikipedia-questions good or bad? In an effort to build up knowledge on SO, I sometimes ask generic questions about obscure informatics things.
What is name mangling, and how does it work?
Design patterns NOT in the Gang of Four?
What happens when you run a program?
In some cases, answers rightfully report links to very detailed wikipedia articles, or webpages containing everything and the kitchen sink about that specific argument.
I was wondering if it makes sense to ask such questions when the argument is so extensively treated on the pedia? Should we aim at collecting knowledge on SO regardless of other sources, or not ?

A: Asking questions and then answering yourself is not disallowed and is encouraged (even though some members of the community will frown upon it).
If your question is a legitimate topic and the information you post is from Wikipedia, there isn't anything generally wrong with that.
What I would suggest, however, is you don't just link to Wikipedia and you at least make an attempt to include other sources of information as well (if not your own personal knowledge). We don't want to just be blatant content copying sites.
Edit I may have misread you at first. I thought you said that you were wondering about posting questions and providing your own wikipedia-sourced answer. My comments concerning the wikipedia answers should still hold, however.

A: I definitely don't think you need to include the preamble

I ask this question not because I don't know, but because it appears to be missing on SO and it can be an interesting question for googlers. Actually, I am oblivious of some details of the process.

That just clutters up the question.
I do think it's worth asking questions that don't already appear on SO, even if you know the answer already.  However, if all you have to add is a link to and a quote from Wikipedia, I'd say just ask the question and don't answer it.  Let others provide the answers.


text:
Q: What's the difference between $J_1=A\otimes B$ , and $J_2=A\otimes I_m+I_n\otimes B$? Consider operator $A,B$ and its tensor product $J_1=A\otimes B$ , and $J_2=A\otimes I_m+I_n\otimes B$ where $n$ and $m$ were dimension of $A$ and $B$.
It's easy to see that $J_1,J_2$ commute and thus share the same eigenstates.
Prove/disprove that there's a one to one correspondence between the eigenvalue of $J_1$ and $J_2$ in the sence of order and degeneracy.

A: One approach is as follows: let $J_3 = \exp(J_2)$, where $\exp$ denotes the matrix exponential.  We compute
$$
J_3 = \exp(A\otimes I_m+I_n\otimes B) = \exp(A) \otimes \exp(B).
$$
It now suffices to show that that there's a one to one correspondence between the eigenvalues of $J_2$ and $J_3$, and also a one to one correspondence between the eigenvalues of $J_3$ and $J_1$.


text:
Q: MacOS Sierra how to reduce priority of iCloud drive sync? I have an older Macbook air and since upgrading to Mac OS Sierra get major performance issues. I see over 1000 threads in activity monitor and am trying to understand if it is due to iCloud drive sync process. CPU intensive tasks can freeze the mac, and operations take longer than expected
It is currently uploading 100,000 files to cloud. How can I reduce the priority of this upload to make sure iCloud drive threads have absolute lowest system priority possible and do not interfere with other processes?
Bonus question - how do I exclude folders from sync?

A: Bonus question, Exclusion: In MacOS Sierra, you have one option in Apple menu > System Preferences > iCloud > iCloud Drive Options > Desktop & Documents Folders - on or off. It's all or nothing, therefore you should reconsider iCloud for small files, for example I tried it with some .dotfiles and very soon dropped that idea as my CPU time was eaten up.
Same goes for Dropbox (but my experience is 1.5 year old here, so maybe Dropbox is now better-handling small files) Other thing I tried was syncing .zipped files / containers - that was working fine but in after a while I droped that too- what I found best is TimeMachine "set it and forget it" config you can access from the outside.
I know that it's not the answer you are looking for, I can only say from my experience, after few months of cloud syncing I put it on external solution where I sync a local drive and forget about it, QoS takes care of upload priority and file sync isn't my Mac's CPU problem.
Worth remembering: if you start using iCloud, there is no way to delete certain files (which is absurd) - for example you can't delete files Applications leave in your User ~/Library, I know it sounds crazy, but just google for "iCloud delete all preferences" or similar


text:
Q: cannot coerce type 'closure' to vector of type 'character' while building shiny web interface Am trying sentiment analysis where my shiny web interface would display pie chart with positive and negative slices. But I also want to display the percentage of both the slices. Which gives me this error: cannot coerce type 'closure' to vector of type 'character'.
Please help me solve this.
Note: Its a reactive web interface.
Here is my full code for the server.r part.
    shinyServer(function(input, output) {
    #Search tweets and Clean the tweets
    TweetFrame<-function(twtList)
    {
    df<- do.call("rbind",lapply(twtList,as.data.frame))
    #removes emoticons
    df$text <- sapply(df$text,function(row) iconv(row, "latin1", "ASCII", sub=""))
    df$text = gsub("(f|ht)tp(s?)://(.*)[.][a-z]+", "", df$text)
    return (df$text)
    }

   # Function to create a data frame from tweets

   pos.words = scan('C:\\Users\\Rahul\\Desktop\\Converge\\Positive-words.txt', what='character', comment.char=';')
   neg.words = scan('C:\\Users\\Rahul\\Desktop\\Converge\\Negative-words.txt', what='character', comment.char=';')

   wordDatabase<-function()
   {
   pos.words<<-c(pos.words, 'Congrats', 'prizes', 'prize', 'thanks', 'thnx', 'Grt', 'gr8', 'plz', 'trending', 'recovering', 'brainstorm', 'leader', 'power', 'powerful', 'latest')
   neg.words<<-c(neg.words, 'Fight', 'fighting', 'wtf', 'arrest', 'no', 'not')
   }

   score.sentiment <- function(sentences, pos.words, neg.words, .progress='none')
   {
   require(plyr)
   require(stringr)
   list=lapply(sentences, function(sentence, pos.words, neg.words)
{
  sentence = gsub('[[:punct:]]',' ',sentence)
  sentence = gsub('[[:cntrl:]]','',sentence)
  sentence = gsub('\\d+','',sentence)
  sentence = gsub('\n','',sentence)

  sentence = tolower(sentence)
  word.list = str_split(sentence, '\\s+')
  words = unlist(word.list)
  pos.matches = match(words, pos.words)
  neg.matches = match(words, neg.words)
  pos.matches = !is.na(pos.matches)
  neg.matches = !is.na(neg.matches)
  pp=sum(pos.matches)
  nn = sum(neg.matches)
  score = sum(pos.matches) - sum(neg.matches)
  list1=c(score, pp, nn)
  return (list1)
}, pos.words, neg.words)
score_new=lapply(list, `[[`, 1)
pp1=score=lapply(list, `[[`, 2)
nn1=score=lapply(list, `[[`, 3)

scores.df = data.frame(score=score_new, text=sentences)
positive.df = data.frame(Positive=pp1, text=sentences)
negative.df = data.frame(Negative=nn1, text=sentences)

list_df=list(scores.df, positive.df, negative.df)
return(list_df)
}

#TABLE DATA

library(reshape)
sentimentAnalyser<-function(result)
{
#Creating a copy of result data frame
test1=result[[1]]
test2=result[[2]]
test3=result[[3]]

#Creating three different data frames for Score, Positive and Negative
#Removing text column from data frame
test1$text=NULL
test2$text=NULL
test3$text=NULL
#Storing the first row(Containing the sentiment scores) in variable q
q1=test1[1,]
q2=test2[1,]
q3=test3[1,]
qq1=melt(q1, ,var='Score')
qq2=melt(q2, ,var='Positive')
qq3=melt(q3, ,var='Negative')
qq1['Score'] = NULL
qq2['Positive'] = NULL
qq3['Negative'] = NULL
#Creating data frame
table1 = data.frame(Text=result[[1]]$text, Score=qq1)
table2 = data.frame(Text=result[[2]]$text, Score=qq2)
table3 = data.frame(Text=result[[3]]$text, Score=qq3)

#Merging three data frames into one
table_final=data.frame(Text=table1$Text, Positive=table2$value, Negative=table3$value, Score=table1$value)
return(table_final)
}

percentage<-function(table_final)
{
#Positive Percentage

#Renaming
posSc=table_final$Positive
negSc=table_final$Negative

#Adding column
table_final$PosPercent = posSc/ (posSc+negSc)

#Replacing Nan with zero
pp = table_final$PosPercent
pp[is.nan(pp)] <- 0
table_final$PosPercent = pp*100

#Negative Percentage

#Adding column
table_final$NegPercent = negSc/ (posSc+negSc)

#Replacing Nan with zero
nn = table_final$NegPercent
nn[is.nan(nn)] <- 0
table_final$NegPercent = nn*100

return(table_final)
}

wordDatabase()

twtList<-reactive({twtList<-searchTwitter(input$searchTerm, n=input$maxTweets, lang="en") })
tweets<-reactive({tweets<-TweetFrame(twtList() )})

result<-reactive({result<-score.sentiment(tweets(), pos.words, neg.words, .progress='none')})

table_final<-reactive({table_final<-sentimentAnalyser(  result() )})

#Pie
slices <- reactive ({ slices <- c(sum(table_final()$Positive), sum(table_final()$Negative))
pct <- round(slices/sum(slices)*100)
})
labels <- c("Positive", "Negative")
labels <- paste(labels, pct()) # add percents to labels
labels <- paste(labels,"%",sep="")

library(plotrix)
output$piechart <- renderPlot({
pie3D(slices(), labels = labels, col=rainbow(length(labels)),explode=0.00, main="Sentiment Analysis") })

})


text:
Q: Defining global variables in php I'm using Windows 7 Ultimate, SQL Server 2008 R2, php 5.2.6
I'm new to PHP. I have this file called globalvars.php where global variables are defined.
globalvars.php
<?
  session_start();
  include_once('database.php');

  //global vars
  $_APP["SQL_DB_NAME"]="DB_NAME";
  $_APP["SQL_DB_SERVER_NAME"]="SERVER_NAME";
  $_APP["SQL_DB_USER"]="USERNAME";
  $_APP["SQL_DB_PASS"]="PASSWORD";

  $_APP["DATE_FORMAT"] = "d-m-Y";
  $_APP["TIME_FORMAT"] = "H:i";

  //generic function for SQL composition to avoid 's errors
  function SQuoteEx($str)
  {
return "'" . str_replace("'","''",$str) . "'";
  }
  function RemoveSQuoteEx($str)
  {
return "'" . str_replace("'","",$str) . "'";
  }
  ?>

and i also have this file called database.php where the global vars are called with a snippet function that connects to the SQL Server database:
database.php
function DBConnect($sql,$debug=0)
  {
global $_APP;
//connect to db and execute query
$cnn = mssql_connect($_APP["SQL_DB_SERVER_NAME"], $_APP["SQL_DB_USER"],       $_APP["SQL_DB_PASS"]) or die(errorHandlingPage(mssql_get_last_message()));
$selected = mssql_select_db($_APP["SQL_DB_NAME"], $cnn) or die(errorHandlingPage(mssql_get_last_message()));
$debug = 0;
//if debug mode echo sql
if ($debug) echo $sql."<br>";
//execute and return rs

$return = mssql_query($sql) or die(errorHandlingPage(mssql_get_last_message()));

if($return){
    return $return;
}
  }

for some reason the global vars cannot be read by the database.php file. Any ideas what's going on? No message by mssql_get_last_message() was passed. Thank you.

A: This is because you are including the database.php file before you are declaring the global variables.  Just move include_once('database.php'); to the bottom of the declarations.
In PHP, when you include another PHP file, that file is parsed and executed immediately.  You should declare any variables you need before making the include_once('database.php'); file.

A: Which page are u calling in the browser? It looks like u will call database.php file in the browser to run the function.
Having said that, in database.php file, you should include globalvars.php on the beginning of the file.
database.php
include_once('globalvars.php');
// rest of your code...


text:
Q: Getting the items belonging to specified keywords and categories I have a keywords and a categories table with an ID and a name col (I can't merge them into a single table!)
There's an articles table with ID, name, text.
And the many-to-many connection tables:

*

*ckw for keywords, columns: key_id, article_id

*ccat for categories, columns: cat_id, article_id
I can write a query to get those articles which belong to keywords ID 5 AND ID 7:
SELECT articles.name FROM articles
JOIN ckw ON (ckw.article_id = articles.id)
WHERE ckw.key_id IN (5, 7)
GROUP BY ckw.article_id
HAVING COUNT(ckw.key_id) = 2

But what if I want to get those articles which belong to keywords ID 5 AND ID 7, and also belong to category ID 12 AND ID 18? I can't figure the right query out.

A: SELECT articles.name
FROM articles
inner JOIN ckw ON ckw.article_id = articles.id
inner join ccat on ccat.article_id = articles.id
WHERE ckw.key_id IN (5, 7)
and ccat.category_id in (12,18)
GROUP BY articles.article_id , articles.name
HAVING COUNT(distinct ckw.key_id) = 2
and count(distinct ccat.category_id) = 2


text:
Q: how to use Android Spinner with text and value? i want to use Android spinner with following data.
Spinner will display only text data not code.
code , text
1 , a
2, b
3,c

.
.
.
etc
i have stored above comma seperated data in same activity class (Hard coded form) now if user selects "a" from the dropdown then it should get its code rather then text.
can any one guide me how to achieve this?
any help would be appriciated.

A: static final String[] LANGUAGE = new String[]
     {
        "English","Urdu","French","Spanish"

     };

Spinner ddltimezone=(Spinner)findViewById(R.id.ddlTimeZone);

 ArrayAdapter<String> adapter_time = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,TIME_ZONE);
             adapter_time.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
             ddltimezone.setAdapter(adapter_time);

int indexlanguage = ddllanguage.getSelectedItemPosition() + 1;

and thats it. we have property of getting selecteditem position which sovled my problem.


text:
Q: HOTP - correct use of RFC sample I'm currently trying to realize a sample which uses the RFC4226 - HOTP: An HMAC-Based One-Time Password Algorithm as base.
I took the code sample and added:
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException {
    // Seed
    String secret = "12345678901234567890";
    byte[] secretBytes = secret.getBytes();

    int counter;
    for (counter = 0; counter < 9; counter++) {
        String strGeneratedToken = OneTimePasswordAlgorithm.generateOTP(secretBytes, counter, 6, false, 0);
        System.out.println(strGeneratedToken);
    }
}

All I'm getting is:
755224
717529
868666
023335
179456
490877
910469
467724
952310
The first one is OK, but the next one (counter=1) as per RFC (755224 287082 359152 969429 338314 254676 287922 162583 399871 520489).
I've uploaded my code to GitHub https://github.com/n0l0cale/hotp - maybe someone is able to see the issue.
This implementation seems to have the same issue:
http://read.pudn.com/downloads158/sourcecode/others/706340/MessageAuthenticationExample.java__.htm
I would nevermind, but when I try the same secret for My Java Application and My Google Authenticator App I'm also getting other codes. "12345678901234567890" of course does not work as secret, but I've tried with the same passphrase and Google Authenticator App seems to start their counter by 0, but increments their counter with it's first usage...

A: truncationOffset seems to be required to be set to 16.....
String strGeneratedToken = OneTimePasswordAlgorithm.generateOTP(secretBytes, counter, 6, false, 16);
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException {
    // Seed
    String secret = "12345678901234567890";
    byte[] secretBytes = secret.getBytes();

    int counter;
    for (counter = 0; counter < 9; counter++) {
        String strGeneratedToken = OneTimePasswordAlgorithm.generateOTP(secretBytes, counter, 6, false, 16);
        System.out.println(strGeneratedToken);
    }
}

755224
287082
359152
969429
338314
254676
287922
162583
399871
520489


text:
Q: How many times has the matter in our Solar System been recycled from previous stars? I've got a basic understanding of these facts:

*

*The Universe is a little over 13 billion years old.  Our Galaxy is almost that old.

*Our Solar System is roughly 4.6 billion years old.

*The heavier elements (carbon, oxygen, etc...) are only produced by stars.

When our Solar System coalesced, the matter that makes up the planets came from a previous generation of stars.  (Meanwhile our Sun is busy making its own slightly-heavier elements, but those aren't ours.  Those belong to the next "generation" after our star dies.)
So we're all sitting on a rock whose matter was spewed out of a star (or stars) that preceded this solar system. But what I want to know is:
How many cycles of coalescing, fusing, nucleosynthesis, exploding -- and then repeating the cycle -- have the atoms in this ball of rock I'm standing on been through?
How do you know this?  Can you tell by the make-up of the matter in the Solar System?  Looking around the Orion arm to see remnants of our former home?

A: The "generations" of the stars are surely not as sharply separated as you suggest. It's true that the percentage of heavier elements - or "metallicity" - is increasing as the stars continue in their thermonuclear fusion. But most of the stuff that our Sun burns is still Hydrogen - and it's the same "initial generation" Hydrogen as any previous stars were using. Stars are being born continuously and the metallicity is usually a little bit higher than for the previous star.
In the era of "nucleosynthesis" that ended about 3 minutes after the Big Bang, mostly light elements were created in a thermal equilibrium at huge, "nuclear" temperatures that existed at those times. A good theory of nucleosynthesis predicts that most of the elements in the Universe should be hydrogen, with a smaller amount of helium and some trace amounts of lithium and other elements. The observations confirm that the predictions are pretty much accurate.
Heavier elements were created in previous stars. But it is not correct to suggest that the Sun is "almost entirely" built out of a recycled material. Quite on the contrary: it's more accurate to say that the Sun is mostly built from the hydrogen that was created in the first minutes after the Big Bang - and it is also "contaminated" by metals and other heavier elements from the previous stars. Those impurities are important for our life - and industry - but they're not important for the ability of the Sun to burn.

A: Its likely a complicated mix, possibly including some virgin material, clouds of which occasionaly are absorbed into the galaxy, and some material that may have multiple recyclings. And not all the material that goes into a star is reacted before its blown off, so some (maybe much) of the hydrogen in the sun could have once been in the outer layers of another star. And even some first generation starts (pop III) that were low mass still haven't completed their lifecycles, so it is just a chaotic mess of gas and dust that gets pushed around by gravity and stellar winds for billions of years, plus some new gas that has recently fallen into the Milky Way all mixed up, but not so well mixed up as to be of uniform composition.

A: The elements that make up the bulk of the Earth were part of the presolar nebula. A similar (though not identical) mixture of elements is found in meteoritic material, which is thought to more accurately represent the mean abundances of that nebula (minus the volatiles) and indeed also agrees with the abundance patterns in the Sun.
There are grains of material trapped inside these meteorites that consist of solids that were already present in the presolar material. These are important because these grains were thought to have formed in individual stellar events and their isotopic compositions can be studied. These tell us that the Sun formed from material that has been inside many different stars of different types.
Stellar evolution and nucleosynthesis calculations tell us the same story. For example, whilst most of our oxygen was made in massive stars that underwent a core collapse supernova, such events do not produce much carbon. The C/O ratio tells us that most of our carbon comes via the winds from intermediate mass AGB stars. Heavy elements like Uranium are dominantly produced in supernovae (though current thinking is that merging neutron star binaries may be major contributors), but others like barium are not.
The details of how many generations have preceded the Sun and Earth has no single answer. Much of (perhaps 90%+) the solar hydrogen and helium could be pristine; some will have been through more than one star. Heavier elements (bar some lithium) will have been through at least one star. The fact that we have s-process elements like Ba, La and Ce, which are formed by neutron capture onto iron-peak elements, tells us those have been through at least two stars.
However, these are vast understimates. Mixing in the interstellar medium is reasonably effective. The material spewed out from supernovae and stellar winds 5-12 billion years ago has had plenty of time to mix throughout the Galaxy before the Sun's birth. Turbulence and shear instabilities should distribute material on galactic length scales in a billion years or less (Roy & Kunth 1995; de Avillez & Mac Low 2003), though local inhomogeneities associated with nearby recent events can persist over $10^{8}$ years. If this is the case, then the Sun is the product of the $\sim$ billion stars that died before it was born.

A: There are three general populations of stars, based on their metallicity, which is the abundance of heavy elements on their atmosphere. That abundance is an indicator of the abundance of heavy elements of the initial cloud that gave birth to the star.
So we have Population I stars that are metal-rich, Population II that are metal-poor and Population III that are metal-free. Population III stars are the first stars that formed in our universe and they must have been very massive and sort lived. Population II are the second generation of stars that created the heavier elements. Finally, Population I stars are the most recently created stars that also have heavier elements that were created in the Population II stars.
Our Sun is a Population I star, so in a sense the Sun is a third generation Star. Taking into account the age of the universe and the average life-time of the more massive stars that form the heavier elements in supernovas, then the assumption that the Sun has used the material of at least two previous stars is reasonable.

A: A very qualitative way to look at it:

*

*The Earth, and therefore you are formed of the same material that contributes to the metallicity of our Sun

*Our Sun is a population I star, which means that it has a relatively high metallicity indicative of having formed after the heavy and short lived stars of population II had already had their big blow offs.

*The population II stars divide into early and late groups, and all post-date the assumed population III stars.

From this I conclude that a non-trivial number of the nucleons in your body have been part of a few stars. Maybe as many as five. As Georg notes there has been time for the most prolific path to include many stars (dozens?).
Certainly all the carbon, nitrogen, oxygen and trace elements that make up your body have been part of at least one star.
None of these facts shed much light on the average star-membership-history of the nucleons that make up your body.

A: First of all -- check the metallicity, then the nucleocosmochronology. That gives the rough idea about the topic. And also that the topic is a currently developing area in cosmology.
It seems that the concise and experimentally confirmed theory of formation of first stars as well as theory of reionization are required to answer your question. And there no such theory (yet).


text:
Q: Converting Non English Dates to Standard Java Date I am working on project where I need to convert Non English dates to standard JAVA Calender/Date format. For example date like helmikuu 13, 2013 should be converted to 13 February, 2013.
I think its doable using Java Simple Date Format Locate Function. I tried to use this code but it throws Unparseable date: "helmikuu 13, 2013" error.
public static void main(String args[]) throws Exception {
        String dateInFin = "helmikuu 13, 2013";
        Locale localeFi = new Locale("fi", "FI");
        DateFormat dateFormatFin = new SimpleDateFormat("MMMMM dd, yyyy");
        dateFormatFin.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, localeFi);

        System.out.println("Locale: "+localeFi.getDisplayName());
        System.out.println(dateFormatFin.parse(dateInFin));

    }

A: For example you can do like this (example is how to convert from French locale to Lihuanian):
@Test
    public void testTestLocale() throws Exception {
        Date date = new Date();

        // Get a France locale
        Locale localeFR = Locale.FRANCE;

        // Create a Lithuanian Locale
        Locale localeLT = new Locale("lt", "LT");

        // Get a date time formatter for display in France
        DateFormat fullDateFormatFR =DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL,localeFR);

        // Get a date time formatter for display in Lithuania
        DateFormat fullDateFormatLT = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, localeLT);

        System.out.println("Locale: "+localeFR.getDisplayName());
        System.out.println(fullDateFormatFR.format(date));
        System.out.println("Locale: "+localeLT.getDisplayName());
        System.out.println(fullDateFormatLT.format(date));
    }

EDIT:
Working sample converting date from Finish to US format:
@Test
    public void testConvertDateFromFinToEn() throws Exception {
        String dateInFin = "helmikuu 13, 2013";
        Locale localeFi = new Locale("fi", "FI");

        DateFormat dateFormatFi = new SimpleDateFormat("MMMM dd, yyyy", localeFi);
        // Get Date object
        Date date = dateFormatFi.parse(dateInFin);

        // Convert to US date format
        Locale localeUS = new Locale("en", "US");
        DateFormat dateFormatUS = new SimpleDateFormat("dd MMMM, yyyy", localeUS);

        // Print in US format
        System.out.println(dateFormatUS.format(date));
    }

A: Using java.text.DateFormat:
DateFormat format = new SimpleDateFormat("MMMM d, yyyy");

Use the parse(String) and format() methods to parse and format dates.

A: you can use SimpleDateFormat with local
SimpleDateFormat

public SimpleDateFormat(String pattern,
                        Locale locale)

    Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

    Parameters:
        pattern - the pattern describing the date and time format
        locale - the locale whose date format symbols should be used

A: Worked! !
                Locale localeFi = new Locale("fi", "FI");
                SimpleDateFormat dateFormatFin = new SimpleDateFormat("MMMMM dd, yyyy", localeFi);
                System.out.println(dateFormatFin.parse(dateInFin));


text:
Q: Code works fine in Pycharm but gives error in IDLE? This code works in my pycharm but not in IDLE, they both are running 3.7. When I run it in IDLE I get a "<rect(0, 0, 750, 750)>" spam in the console. If I drag the window around it will grab the background color I have set.
import pygame
import random

blue = (135, 206, 250)
black = ( 0, 0, 0)
white = ( 255, 255, 255)

gravity = 1 # speed
FPS = 60 #FPS
width = 750
height = 750
snowSize = 8
snowNum = 50

varHeight = height
snowColour = white
bgColour = blue

# Intialize the pygame
pygame.init()

# create the screen
screen = pygame.display.set_mode((750, 750))

#Font
myfont = pygame.font.SysFont('Comic Sans MS', 25)

#Title and Icon
pygame.display.set_caption("Christmas Card")

#player
playerImg = pygame.image.load('C:/Users/Owner/Desktop/tammy program/untitled-2.png')
playerX = 300
playerY = 350

#player2
playerImg2 = pygame.image.load('C:/Users/Owner/Desktop/tammy program/tree.png')
player2X = 5
player2Y = 5

snowFlake = []
for q in range(snowNum):
    x = random.randrange(0,width)
    y = random.randrange(0,varHeight)
    snowFlake.append([x,y])
clock = pygame.time.Clock

def player():
    screen.blit(playerImg, (playerX, playerY))

def player2():
    screen.blit(playerImg2, (player2X, player2Y))

def greeting():
    screen.blit(textsurface, (300, 0))

# Game Loop
running = True
while running:
    # Screen Color
    screen.fill((125, 205, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    textsurface = myfont.render('Merry Christmas', False, (0, 0, 0))
    greeting()
    player()
    player2()

    for i in snowFlake:
        i[1] += gravity

    pygame.draw.circle(screen, snowColour, i, snowSize)

    if i[1] > varHeight:
        i[1] = random.randrange(-50, -5)
        i[0] = random.randrange(width)

    pygame.display.flip()

    pygame.display.update()


text:
Q: blackfin bf561 FreeRTOS implementation fail at runtime when loading a task I've implemented in Blackfin BF561 coreB FreeRTOS from the code:
http://www.freertos.org/index.html?http://interactive.freertos.org/forums/79366-analog-devices
I converted to bare metal as elf executable using gcc.
I'm close but I have a runtime error that I cannot figuer out. When the scheduler start and try to trigger the first task, the memory pointer get lost and it doesn't start the first stack, instead in start a function inside the first task and get lost when going out of the function.
this is the corresponding debug log:
COREB: end setup LED
COREB: handler declared
COREB: Initialise New TCB:NewTCB address: 3d01000
COREB: TopofStask: 0, pxTopOfStack = 3d0263c
COREB: pxTaskCode =3c033a0, pvParameters = 0
COREB: returned pxNewTCB->pxTopOfStack = 3d02588
COREB: task created:
COREB: top of stack: 3d02588
COREB: GenericListItem: 0
COREB: Event ListItem: 9
COREB: Priority: 1
COREB: start of stack: 3d02000
COREB: Task Name: BootTas
COREB: TCB number: 0
COREB: Task Tag: 0
COREB: Add the idle task at the lowest priority
COREB: Initialise New TCB:NewTCB address: 3d03000
COREB: TopofStask: 0, pxTopOfStack = 3d0431c
COREB: pxTaskCode =3c0295c, pvParameters = 0
COREB: returned pxNewTCB->pxTopOfStack = 3d04268
COREB: task created:
COREB: top of stack: 3d04268
COREB: GenericListItem: 0
COREB: Event ListItem: a
COREB: Priority: 0
COREB: start of stack: 3d04000
COREB: Task Name: IDLE
COREB: TCB number: 1
COREB: Task Tag: 0
COREB: end Add the idle task at the lowest priority
COREB: if xReturn == 1, and xReturn = 1
COREB: before disable interupt
COREB: after disable interupt
COREB: before  xPortStartScheduler
COREB: start xPortStartScheduler fn before set core timer
COREB: after ContextSwitch interupt flag
COREB: before prvSetupTimerInterrupt
COREB: after prvSetupTimerInterupt
COREB: Task Switch context called
COREB: The scheduler is running
COREB: trace switched out TCB:ff700bf8
COREB: name of switch out task:efore  xPortStartScheduler

COREB: before Task first check for stack overflow
COREB: Task first check for stack overflow called
COREB: Task second check for stack overflow called
COREB: before call get owner of next entry
COREB: get owner of next entry:
COREB: current TCB 3d01000
COREB: pxReadyTasksLists[ uxTopReadyPriority ] = 1
COREB: TCB content:
COREB: top of stack: 3d02588
COREB: GenericListItem: 0
COREB: Event ListItem: 9
COREB: Priority: 1
COREB: start of stack: 3d02000
COREB: Task Name: BootTas
COREB: TCB number: 0
COREB: Task Tag: 0
COREB: trace switched in:BootTas
COREB: write trace to buffer
COREB: task increment tick: 1
COREB: end of app init
COREB: execption 2b addr ff700be4
COREB: coreb dump stack
COREB: found fp: ff700b64

and this is the discution I started on the Analog Device forum:
http://ez.analog.com/message/38669#38669

A: Ok I finally resolve the issue. the problem was that the assembler code was not return from the vContext code interruption function with the RTI, instead it was go straight through to the next assembler code function which was the timer interrupt which had the same problem and thus the stack pointer was then going to the next address which happen to be the starting address for the app_init function.....
May the problem was due to the fact that the RTI statement was made in a MACRO called by the vContextSwitch function, I'm not sure.
I fixed it by converting those assembler function to C function and now the stack return from interrupt work properly and the problem is fixed. Note that additional error was found after that which was forgotten of hook task loader function in the scheduler when calling vContextSwhitch as well as the tag of the hook function that was never recorded in the context of the task.
All fixed now.
Best Regards,
William


text:
Q: Why do I get "System.IO.FileNotFoundException: Could not load file or assembly" when setting reference to "copylocal=false"? Here is the situation: I am trying to run unit tests using a test project that I'll call "TestProject". It is testing a class in another project that I'll call "Class1" and "Project1".
Project1 does some dynamic lazy-loading of various dll's at runtime, which I will call "TheDynamicDLLs". Project1 finds these dll's by looking in a directory relative to its own build output path.
The first part of the problem arises when TestProject references Project1. Obviously, it copies the newly built Project1.dll to its OWN build directory, and then when Project1.dll looks for TheDynamicDLLs in the path relative to its location, it can't find them, because it is running from TestProject's location, not its own.
To fix this, I went to TestProject's references, right clicked the Project1 reference, and opened up its properties. I then set "Copy Local" to "False". I also made sure that the reference's "Path" property was the same as Project1's build path.
Now I have a new problem, and I can't even figure out what it is. Whenever I run the unit test, it fails with a report of "System.IO.FileNotFoundException: Could not load file or assembly [information naming Project1 as the un-findable assembly]".
Furthermore, when I try to debug the unit test, instead of just running it, it never throws an exception, or complains, or anything, thereby preventing me from finding out any further info about the problem. I can't find any further helpful info in the test report either.
Here is the full test report with names and such swapped out for confidentiality purposes:
Test Name:  Class1_Tests
Test FullName:  TestProject.TestClass.Class1_Tests
Test Source:    c:\Code\Solution1\Tests\TestProject\TestClass.cs : line 175
Test Outcome:   Failed
Test Duration:  0:00:00.0348455

Result Message:
Test method TestProject.TestClass.Class1_Tests threw exception:
System.IO.FileNotFoundException: Could not load file or assembly 'Project1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.=== Pre-bind state information ===
LOG: DisplayName = Project1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/Code/Solution1/Tests/TestProject/bin/Debug
LOG: Initial PrivatePath = NULL
Calling assembly : TestProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Code\Solution1\Tests\TestProject\bin\Debug\TestProject.dll.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Code/Solution1/Tests/TestProject/bin/Debug/Project1.DLL.
LOG: Attempting download of new URL file:///C:/Code/Solution1/Tests/TestProject/bin/Debug/Project1/Project1.DLL.
LOG: Attempting download of new URL file:///C:/Code/Solution1/Tests/TestProject/bin/Debug/Project1.EXE.
LOG: Attempting download of new URL file:///C:/Code/Solution1/Tests/TestProject/bin/Debug/Project1/Project1.EXE.
Result StackTrace:  at TestProject.TestClass.Class1_Tests()

From the logs, it looks like TestProject is STILL trying to load Project1's dll from its OWN #$%^ing build path despite my EXPLICITLY telling it NOT to copy local. (grrrr...)
What am I doing wrong?

A: !!!PLEASE NOTE: The original question I posted was about a problem with my solution to a deeper problem. This answer is a solution to that deeper problem, not the problem the question asks about.
To further explain: The original question was how to get the runtime environment to correctly load referenced dependencies when those references were set to "CopyLocal=false".
That question was asked because I had been setting copylocal=false to keep the dependency dll running in its original build path, even when it was loaded and run as part of a different unit test project, so that it would be able to find items at runtime that were located in folder paths relative to its build path.
This answer is an answer to the FIRST problem, eliminating the need to set copylocal=false in the first place. Hence, I will NOT be choosing my answer here as the most helpful. If anyone has an answer to the direct question, they should still post it to help people who may be struggling with that problem for different reasons than mine.
That said, here is my solution to the reasons for which I needed to set copylocal=false:

*

*Added TheDynamicDLLs to Project1, but NOT as references. Simply right clicked on Project1 in the solution explorer and chose "Add Existing Item", then browsed to the each dll location and added it AS A LINK. (Is important to add as a link so that it gets refreshed whenever it is rebuilt by its DynamicDLLProject).

*Right clicked the newly added item in Project1 and chose "Properties". Set "Build Action" to "None" and set "Copy to Output Directory" to either "Copy if newer" or "Copy always".

*Repeat steps 1 and 2 for each dynamic dll that Project1 will/might load at runtime.

*Of course, in the TestProject, I set the Project1 reference back to "Copy Local = True".

The effect of this is that while the dynamic dlls are not actually referenced or compiled into Project1 (as should be the case to keep them from eager-loading when Project1 runs), any projects that reference Project1 and copy its dll to their output path, will also copy over the items that are added as part of that project's output (in this case TheDynamicDLLs).
I hope that helps anyone who has this problem for a similar reason as I did.


text:
Q: File is returned by reasteasy with additional bytes I'm trying to return a binary file as a response on HTTP POST request.
My API looks like this:
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @POST
 @Path("/{param}/path")
 public @NotNull Response exportPlayer(@NotNull @PathParam("param") Param param,
                                       @Nullable @FormParam("formParam") Param2 param2) {
 final byte[] resultFileContent = getResultContent(); //returns some binary serialized information

 return Response.ok(resultFileContent ).header("content-disposition", "attachment; filename = myfile").build();
}

In this byte array first four bytes is an integer indicating the size of the following content, like this:
**00 00 00 F0** 31 33 35 34 30 38 34 3B 36 36 3B 5C
4E 3B 5C 4E 3B 32 30 32 30 2D 30 33 2D 31 30 20
...

Here 00 00 00 F0 means that the following content block contains 240 bytes, and the rest bytes is content itself
This file is returned correctly when using curl
>curl --user user:password -X POST --data "formParam=value" "http://127.0.0.1:8085/rest/api/param/export" > testExport.bin

The problem occurs when I call thi API via browser in my web client. It starts to return some extra bytes at the beginning of the file:
**00 00 00 EF BF BD** 31 33 35 34 30 38 34 3B 36 36
3B 5C 4E 3B 5C 4E 3B 32 30 32 30 2D 30 33 2D 31

the content is the same, but first two bytes seem to be corrupted.
Here's the way I download the file:
    $.ajax({
      url: /*my url*/,
      data: data
      method: "POST",
      error: /*some handler*/,
      success: answer => {
                const link = $('<a>', {
                    href: 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(answer),
                    download: "player_" + playerId
                }).css('display', 'none')
                    .appendTo('body');
                link.get(0).click();
                link.remove();
             }
    });

Any ideas would be appreciated

A: Actually, I found a workaround, but the issue is still unsolved.
I changed my API to @GET and queried it with
[HTML]
<form class="form-horizontal" action="/rest/api/$param/method" method="get" id="my_form">

[JS]
$("#export_player_form").submit()


text:
Q: Integrating Silverlight 4 webcam functions into WPF After toying a little with the new Silverlight 4 camera features, and being really disappointed that these were not included in WPF, I looked at the Silverlight assemblies and found that they more or less delegate all work to agcore.dll.
Do you think it is a good idea to package agcore.dll with my WPF application, and copy/paste or rewrite all classes concerning cameras to WPF, to get these nice features there?

A: That particular approach isn't likely to work, unfortunately.  There's a lot more to getting C# code to work with Silverlight than just referencing the appropriate DLL.  Silverlight is actually a completely different implementation of the CLR, so you can't just call into agcore.dll from a WPF app and have it run.
If you need Silverlight features in your app, I can think of two ways to get them: (1) you could conceivably host a completely separate instance of Silverlight inside a browser control in your WPF app, though communication with that Silverlight instance becomes complicated (though not impossible); or (2) you could write your entire app in Silverlight OOB (Out-of-browser)/trusted mode.

A: You can try VideoCaptureElement in my WPF MediaKit. It will show a webcam in WPF.  It does have a different API than the Silverlight webcam API, but it should have just as many features.


text:
Q: How to install GRUB Legacy (0.97) on an USB pen-drive from Ubuntu 20.04/21.10? How to install GRUB Legacy (0.97) on an USB pen-drive from Ubuntu 20.04/21.10?
Ubuntu does no longer provide GRUB Legacy in their repository.
grub-install command will install GRUB 2.xx.
Probably I could look for an old bootable distro that ships GRUB 0.97 and grub-install from there, but maybe it can be done properly from my main OS.
Old Ubuntu's GRUB 0.97 package contains all the binary files for stage1, fat_stage1_5 (I'm using FAT32), and stage2 in data.tar.xz/usr/lib/grub/x86_64-pc/.
However running grub-install from that old Ubuntu package does not work.
How do I manually dd those files properly into the drive's MBR and following sectors?
I tried this (not to overwrite the partition table):
sudo dd if=stage1 of=/dev/sdX bs=446 count=1

What do I do with stages 1_5 and 2?

A: I've managed to use that old Ubuntu's package mentioned above to install GRUB 0.97:

*

*On the pendrive's main partition create /boot/grub directory:

cd /mnt/sdX1
mkdir -p boot/grub

*Copy all stages into it:

cd ${DATA_TAR_XZ}/usr/lib/grub/x86_64-pc
cp stage1 stage2 fat_stage1_5 /mnt/sdX1/boot/grub

*Now run GRUB 0.97 shell:

cd ${DATA_TAR_XZ}/usr/sbin
sudo ./grub --device-map=/dev/null

*And use it to setup GRUB for that pendrive:

device (hd0) /dev/sdX
geometry (hd0)
root (hd0,0)
setup --stage2=/boot/grub/stage2 --prefix=/boot/grub (hd0)
quit


text:
Q: java.io.FileNotFoundException open failed: EPERM (Operation not permitted) After modifying build.gradle with :
compileSdkVersion 28 to 32
targetSdkVersion 28 to 32
I can't write a local file from retrofit response.
I get error :
java.io.FileNotFoundException: /storage/emulated/0/DontEat/rangt_00001.jpg: open failed: EPERM (Operation not permitted)

AndroidManifest.xml contains :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

and my code is :
public static void downloadFile(SyncCalls.CallbacksDownload callbacks, final String type, final File file, final Boolean last) {
    final WeakReference<SyncCalls.CallbacksDownload> callbacksWeakReference = new WeakReference<>(callbacks);
    SyncService service = SyncService.retrofit.create(SyncService.class);
    String filename = file.toString().split("/")[5];
    Call<ResponseBody> call = service.downloadFile(filename);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
            try {
                OutputStream out = null;
                InputStream in = null;
                ResponseBody body = response.body();
                try {
                    if (body != null) {
                        in = body.byteStream();
                        out = new FileOutputStream(file);
                        byte[] fileReader = new byte[4096];
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                        while (true) {
                            int read = in.read(fileReader);
                            if (read == -1) {
                                break;
                            }
                            out.write(fileReader, 0, read);
                        }
                        out.flush();
                    }
                } catch (IOException e) {
                    if (BuildConfig.DEBUG) Log.v(Consts.TAG, e.toString());
                } finally {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                }

            } catch (IOException e) {
                if (BuildConfig.DEBUG) Log.v(Consts.TAG, e.toString());
            }
            if (BuildConfig.DEBUG) Log.v(Consts.TAG, "download " + file.toString());
            if (callbacksWeakReference.get() != null)
                callbacksWeakReference.get().onResponseSync(type, "down", last);

        }

Permissions are verified with :
// Storage Permissions variables
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static final String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};
//permission method.
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have read or write permission
    int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

Is my mistake in the code or the permissions please?
I don't develop more because of my very limited English.
(It's an app I made many years ago, for personal use only, family, but I can't scale it because of this bug that appeared with new android versions while it was working perfectly so far)
Edit:
Actually, I think I'm taking the problem upside down and I'd better use the application's internal data directory with getFilesDir() and I won't have permission problems anymore, if I understood correctly.

A: Add the line in AndroidManifest.xml, inside application tag..
Hope it'll help you.
android:requestLegacyExternalStorage="true"


text:
Q: Nginx HTTP to HTTPS redirect is not working I am running a Redmine instance which uses nginx for SSL and apache for serving content.
I'm upgrading this by installing the latest version on a new machine and I will copy the files and database once this is all working.
I've copied the config for both apache and nginx from the existing machine to the new one and yet the results are different on the two machines and I can't figure out why.
On the current production instance, Redmine is being run on port 18804 (as decreed by my boss). Currently, when someone uses a browser to access redmine.mydomain.com, they are automatically redirected to Redmine using HTTPS.  This happens whether :18804 is appended on the end or not which is how I would like this to operate.
However on the new machine, if in a browser I enter newredmine.mydomain.com, I am redirected to the nginx test page. However, if I enter either newredmine.mydomain.com:18804, or https://newredmine.mydomain.com, then I am routed to the application using HTTP.
I need this to happen simply by entering the logical URL. Clearly the redirection to HTTPS isn't working but as the config is an exact copy I don't understand why.
The current server is running Amazon Linux, Apache 2.2.31 and nginx 1.10.2. The new one is running Centos 7, Apache 2.4.6 and nginx 1.10.2.
This is my config nginx for my application:
upstream redmine {

        server 127.0.0.1:18805;

}

server {

        listen 18804;

        location / {

                return 301 https://$host$request_uri;

        }

}

server {

        listen 80;

        location / {

                return 301 https://$host$request_uri;

        }

}

server {

        listen 443 ssl;

        server_name application.mydomain.com;

        access_log /var/log/nginx/redmine.access.log;

        error_log /var/log/nginx/redmine-errors.log;

        ssl on;

        ssl_certificate_key /etc/ssl/private/key;

        ssl_certificate /etc/ssl/certs/crt;

        ssl_ciphers RC4:HIGH:!aNULL:!MD5;

        ssl_prefer_server_ciphers on;

        client_max_body_size 0;

        location / {

                proxy_set_header Host $host;

                proxy_set_header X-Real-IP $remote_addr;

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                proxy_pass http://redmine;

        }

}

And my server block from Apache in case that is required:
# Redmine 3.3.3

<VirtualHost *:18805>
  DocumentRoot /var/www/html/redmine/public
  ServerName newredmine.mydomain.com
  ServerAlias 127.0.0.1
  ErrorDocument 503 /maintenance.html
  RewriteEngine on
  RewriteCond %{DOCUMENT_ROOT}/../tmp/stop.txt -f
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ /$1 [R=503,L]

<Directory /var/www/html/redmine/public/>
  AllowOverride all
  # MultiViews must be turned off.
  Options -MultiViews
</Directory>

  ErrorLog logs/redmine_3.3.3_log

As I said the really confusing part is that the two instances are behaving differently despite there being identical config on both. The only differences are ones you would expect, for example the location of the Redmine public folder.
Can anyone see what I am missing here?

A: You are missing server_name on your redirect server blocks. Therefore the actual virtual host selection on nginx is not that clear.
First, you need to make sure that you have a server block which has the default_server attribute on the listen directive. On this block you define what the server does when it receives a request for a host which is not explicitly configured.
Then, you need to have server blocks like these for redirection:
server {
    listen 18804;
    server_name redmine.mydomain.com;

    return 301 https://redmine.mydomain.com$uri;
}

server {
    listen 80;
    server_name redmine.mydomain.com;

    return 301 https://redmine.mydomain.com$uri;
}

It is better to use explicit domain name in the return directive, since the $host variable might contain non-desired values at some point.
The SSL block can be left like it is now.


text:
Q: XMLDictionary not parsing complete XML data I'm using https://github.com/nicklockwood/XMLDictionary category to convert server XML response into NSDictionary. It only seem to work half of the time, and I'm not sure if it's a problem with the way I'm using it, or if there's a bug in XMLDictionary or what.
I'm calling the method like this:
    NSDictionary *convertedData = [NSDictionary dictionaryWithXMLData:data];
Here's an example of XML data I'd like to parse (This is directly from the "data" I'm passing):
<?xml version="1.0" encoding="utf-8"?>
<anime>
  <entry>
    <id>572</id>
    <title>Kaze no Tani no Nausicaa</title>
    <english>Nausicaä of the Valley of the Wind</english>
    <synonyms>Nausicaa of the Valley of the Wind; Warriors of the Wind</synonyms>
    <episodes>1</episodes>
    <score>8.47</score>
    <type>Movie</type>
    <status>Finished Airing</status>
    <start_date>1984-03-11</start_date>
    <end_date>1984-03-11</end_date>
    <synopsis>A thousand years after a global war, a seaside kingdom known as the Valley Of The Wind remains one of only a few areas still populated. Led by the courageous Princess Nausicaä, the people of the Valley are engaged in a constant struggle with powerful insects called ohmu, who guard a poisonous jungle that is spreading across the Earth. Nausicaä and her brave companions, together with the people of the Valley, strive to restore the bond between humanity and the Earth. <br />
<br />
(Source: Disney)</synopsis>
    <image>http://cdn.myanimelist.net/images/anime/7/42071.jpg</image>
  </entry>
</anime>

And here's what I get as a result:
Printing description of convertedData:
{
    "__name" = anime;
    entry =     {
        english =         {
        };
        id = 572;
        title = "Kaze no Tani no Nausicaa";
    };
}

The thing is that this doesn't happen with all search results. It's perfectly repeatable by using the same search results but there's certain results in which it doesn't do it at all. I can't figure out what's special about those results that makes it work where others don't. Here's an example of one that does work.
XML Input:
<?xml version="1.0" encoding="utf-8"?>
<anime>
  <entry>
    <id>329</id>
    <title>Planetes</title>
    <english></english>
    <synonyms></synonyms>
    <episodes>26</episodes>
    <score>8.42</score>
    <type>TV</type>
    <status>Finished Airing</status>
    <start_date>2003-10-04</start_date>
    <end_date>2004-04-17</end_date>
    <synopsis>In the year 2075, mankind has reached a point where journeying between Earth, the moon and the space stations is part of daily life. However, the progression of technology in space has also resulted in the problem of the space debris, which can cause excessive and even catastrophic damage to spacecrafts and equipment. This is the story of Technora&#039;s Debris Collecting section, its EVA worker, Hachirota &quot;Hachimaki&quot; Hoshino, and the newcomer to the group, Ai Tanabe. <br />
<br />
(Source: ANN)</synopsis>
    <image>http://cdn.myanimelist.net/images/anime/8/50463.jpg</image>
  </entry>
  <entry>
    <id>10735</id>
    <title>Planetes Picture Drama</title>
    <english></english>
    <synonyms>Planetes Audio Drama</synonyms>
    <episodes>9</episodes>
    <score>6.27</score>
    <type>Special</type>
    <status>Finished Airing</status>
    <start_date>2009-09-25</start_date>
    <end_date>2009-09-25</end_date>
    <synopsis>Planetes picture drama.</synopsis>
    <image>http://cdn.myanimelist.net/images/anime/9/29571.jpg</image>
  </entry>
</anime>

NSDictionary Output:
{
    "__name" = anime;
    entry =     (
                {
            "end_date" = "2004-04-17";
            episodes = 26;
            id = 329;
            image = "http://cdn.myanimelist.net/images/anime/8/50463.jpg";
            score = "8.42";
            "start_date" = "2003-10-04";
            status = "Finished Airing";
            synopsis = "In the year 2075, mankind has reached a point where journeying between Earth, the moon and the space stations is part of daily life. However, the progression of technology in space has also resulted in the problem of the space debris, which can cause excessive and even catastrophic damage to spacecrafts and equipment. This is the story of Technora's Debris Collecting section, its EVA worker, Hachirota "Hachimaki" Hoshino, and the newcomer to the group, Ai Tanabe.
\n
\n(Source: ANN)";
            title = Planetes;
            type = TV;
        },
                {
            "end_date" = "2009-09-25";
            episodes = 9;
            id = 10735;
            image = "http://cdn.myanimelist.net/images/anime/9/29571.jpg";
            score = "6.27";
            "start_date" = "2009-09-25";
            status = "Finished Airing";
            synonyms = "Planetes Audio Drama";
            synopsis = "Planetes picture drama.";
            title = "Planetes Picture Drama";
            type = Special;
        }
    );
}

Sometimes it will only omit certain tags, like the  tag. Other times it will omit mostly everything like in my first example. I'm really confused.
Also, if I pass it a large XML file (say a search result with 50 items in it), it'll only parse half of it.  I doubt anyone wants to read through all of it but just in case, here's the XML http://pastebin.com/aQTc8S9x  and here's the NSDictionary that comes out http://pastebin.com/MwuexaZV

A: Looks like it is being tripped up by ä and other html entities. Handle them first on the XML String before passing to the parser. Here is another SO question on how to do that.


text:
Q: Typescript error This condition will always return 'true' since the types have no overlap I having this condition on a form  group:
if((age>17 && (this.frType=="Infant"))
|| (age>40 && this.frType=="Grandchild")
|| (age<=5 &&
   (this.frType!="Child"
   || this.frType!="Infant"
   || this.frType!="Grandchild" || this.frType!="Cousin")))

It contain 3 main conditions:

*

*If a person aged 17, cannot be set to infant

*If a person is bigger than 40, he cannot be a grandchild

*If a person is less than 5 years, he should be child, infant, grandchild or cousin.

If one of these conditions is true, I will send an error message.
The error I am receiving is:

[ts] This condition will always return 'true' since the types
  '"Child"' and '"Infant"' have no overlap. [2367]

On this part of the if condition`:
|| this.frType!="Infant" || this.frType!="Grandchild" || this.frType!="Cousin")))

I am using the exact condition in a different component, and it does not show an error.
if((age>17 && (this.family_relation_type=="Infant"))
|| (age>40 && this.family_relation_type=="Grandchild")
|| (age<=5 &&
   (this.family_relation_type!="Child" ||
    this.family_relation_type!="Infant" ||
    this.family_relation_type!="Grandchild" ||
    this.family_relation_type!="Cousin")))

Here is how I am calculating the age in both components:
let timeDiff = Math.abs(Date.now() - this.formGroup.controls['dob'].value);
let age = Math.floor((timeDiff / (1000 * 3600 * 24))/365);

A: I struggled with this problem recently. Sharing my experience here
Basically IDE does not allow to compare an object.enum with a string. As a solution, a method in the component.ts is added to compare the enum
Details :
export enum Status {
     NEW,
     PROGRESS,
     FINISHED
}

export interface Model {
   id : number;
   name : string;
   status : Status
}

Now in the component.html, I was trying to compare the model status

Error : This condition will always return 'false' since the types 'Status' and 'string' have no overlap.ngtsc(2367)

I also tried defining the status enum in the component.ts and used that for comparison
public StatusEnum = Status;

With the above solution, there is no IDE error, but the condition never true, as the enum[value] give a numeric value.
The next option I tried was as follows

But ended up with the error again in the IDE
Error : This condition will always return 'false' since the types 'Status' and 'string' have no overlap.ngtsc(2367)

Finally what solved the issue it implement a method in the component.ts
Solution
component.ts
public StatusEnum = Status; //To refer in the HTML

 checkStatus(m: Model, status: Status): boolean {
    return Status[m.status] as unknown === status;
  }

Note : Status[m.status] as unknown
HTML

A: Define the data types of all your variables explicitly.
For example, this code has the same error mentioned in the thread title and I fixed by defining the data types of the variables explicitly.
From:
const selectedLangCulture = "en"; // or "ar-SA"
const direction = "rtl";
const languageChanged =
  (direction === "rtl" && selectedLangCulture === "en") ||
  (direction === "ltr" && selectedLangCulture === "ar-SA");

To:
const selectedLangCulture: string = "en"; // Put the datatype string.
const direction: string = "rtl"; // Put the datatype string.
const languageChanged =
  (direction === "rtl" && selectedLangCulture === "en") ||
  (direction === "ltr" && selectedLangCulture === "ar-SA");

A: Consider the standalone expression:
(this.frType!="Child" || this.frType!="Infant")

If frType is Child, the second part will be true, so the expression will evaluate to true. If frType is Infant, then the first part will be true, so the expression will evaluate to true. If frType is neither Child nor Infant, then the first part will be true, and the expression will, again, evalute to true - the logic is faulty, it'll always resolve to true.
(If you add additional || conditions for Grandchild and Cousin, the same thing keeps happening - it'll always resolve to true)
Either use && instead:
|| (age<=5 && (
   this.frType!="Child"
   && this.frType!="Infant"
   && this.frType!="Grandchild"
   && this.frType!="Cousin"
 ))

Or, to make the logic easier to follow, you might consider using an array, and use .includes:
const kidsFiveAndUnder = ['Child', 'Infant', 'Grandchild', 'Cousin'];
// ...
|| (age <= 5 && !kidsFiveAndUnder.includes(this.frType))

A: In my case, I was using a type named type for the button element with React.ComponentPropsWithRef<'button'>
type ButtonProps = {
  type?: 'submit' | 'button' | 'link'; // ❌
} & React.ComponentPropsWithRef<'button'>;

the type was overridden because React.ComponentPropsWithRef<'button'> had a type in it also. I replaced it with elementType and the problem is solved.
type ButtonProps = {
  elementType?: 'submit' | 'button' | 'link'; // ✅
} & React.ComponentPropsWithRef<'button'>;

A: Maybe i can help someone with this.
In my case the error was triggered by:
*ngIf="fooArray.length === 0"
so i modified it to be:
*ngIf="fooArray.length < 1"
Makes no sense to me, but it works.

A: In my case, I simply had to rebuild my app because the type definitions got briefly out of sync.

A: it look like typescript help to "simplify the Logic"

*

*so it help remove the unnecessary Logic code.

*

*'||' mean one true -> all true, so comparison after is not necessary

*'&&' mean one false -> all false, so comparison is a must

go trough the code below will have better understanding.


text:
Q: Mappings of triangular regions by complex variables This is Problem #30 (chapter 8) in Schaum's outline of Complex Variables :
We have a triangle with vertices at points at $i$, $1-i$, and $1+i$.
We want to sketch the region of the $w$ plane into which the interior of the triangle is mapped under the transformations
A. $w=z^2$
B. $w=iz^2 +(2-i)z$
C. $w=z+\frac{1}{z}$
Here is the problems I am facing and what I have done:
In part A, I can see that line $x=1$ maps into $u=1-\frac{v^2}{4}$, and line $y=1$ maps into $u=\frac{v^2}{4} -1$. However, line $y=-2x +1$ maps into $u= -3x^2+4x-1$, $v=-4x^2+2x$, but now my problem is how to find a relation between $u$ and $v$. I do not how this can be done.
In Part B, I can see that line $x=1$ is mapped into $v= -u^2+2u$ , but line $y=1$ maps into $v=x^2-x+1$, $u=1$ and again I cannot find a relation between $u$ and $v$.
Also line $y=-2x+1$ maps into $u=4x^2 -2x +1$ , $v=-3x^2-x+1$, and again I cannot find a relation between $u$ and $v$.
In part C, line $x=1$ is mapped to $u=1+ \frac{1}{1+y^2}$ , $v=y\left(1- \frac{1}{1+y^2}\right)$ and I cannot find a relation between $u$ and $v$.

A: In case A you have parametric form of three sides for the triangle as following:
\begin{cases}
i\to 1+i&t+i~~,0\leq t\leq1&\to&w=t^2-1+2it\\
1+i\to1-i&1-i(2t-1)~~,0\leq t\leq1&\to&w=4t(1-t)-2i(2t-1)\\
1-i\to i&1-t+i(2t-1)~~,0\leq t\leq1&\to&w=-3t^2+2t-2i(2t^2-3t+1)
\end{cases}
I draw this area by Mathematica code :

ParametricPlot[{{t^2-1,2t},{4t(1-t),-2(2t-1)},{2t-3t^2,-2(2t^2-3t+1)}},{t,0,1}]

made this


text:
Q: Free Alternative to Ubigraph I am trying to generate a large graph visualization using Ubigraph and its xml-rpc interface. However Ubigraph's xmlRPC server is not fast enough to handle the call rate generated by my python code, and freezes. I have tried all the performance tips listed on the website to no avail. The direct wrapper is not available in the free version of Ubigraph, hence my question: are there any Free (as in speech) alternatives to Ubigraph?

A: I think that you may be having the same problem I was.  It is not that ubigraph cannot handle the xmlrpc, but that there is a problem with the 64-bit release.  It kept freezing on me at completely unpredictable times (sometimes after 22 edges, sometimes after 1500 edges...).
Try the 32-bit release instead.  It has been solid for me.

A: Have you had a look at graphviz? Does this have to be a service, or could you just run it locally?


text:
Q: What kind of syntax is (round)(myFloat) in C? EDIT: Apologies for the previous mess.
I came to a code example which goes like
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

    int main(int argc, char *argv[])
    {
        int num = (round)(3.14*2 / 1.618);
        printf("test %d test", num);

        int num2 = (round)(3.0 / 2.0);
        printf("test %d test", num2);
    }

What does this (round) do? Is this a function invocation of the round function from math.h? Does this mean I am effectively invoking a function at the location of (round) pointer? Does this mean (myFun+1)(myVar) could work in some case?

A: With <math.h> included, round is a standard C rounds its argument to the nearest integer, rounding halfway cases away from zero, and returning a double.
Technically, round is a function designator: It denotes the function. (round) is merely the designator in parentheses. Like other parenthesized expressions, its type and value are the same as the expression inside it. So, functionally, (round) is the same as round, and (round)(3.14*2 / 1.618) is the same round(3.14*2 / 1.618)
One difference is that <math.h> may implement round as a function-like macro. In this case, in round(x), the macro is expanded, and the resulting expression may be something other than a function call, or it could call a function with a different name. (The C standard requires the result to be the same as if the round function had been called.) In (round)(x), the macro name round is not immediately followed by a left parentheses, so the expansion of the function-like macro does not occur. Thus (round)(x) calls the actual function even if a function-like macro is defined.
This behavior regarding putting function names in parentheses to suppress macro expansion is a deliberate feature of the C library (C 2018 7.1.4 1: "… Any macro definition of a function can be suppressed locally by enclosing the name of the function in parentheses,…"). However, there is no apparent reason to use it in this code.


text:
Q: Reconstruct 3D world position from Depth I'm trying to develop a deferred render on my own webGL engine.
I have everything ready to calculate the lightning but I can't reconstruct the position from the depth buffer properly...
Right now, I'm trying to do the calculations out of the shader at the CPU with JS, and if I'm able to get the correct position then translate it to the shader.
This is the JS code:
        var model = mat4.create();
        var view = mat4.create();
        var projection = mat4.perspective(mat4.create(), 45, gl.canvas.width/gl.canvas.height, 0.1, 100);

        var pos = [0,0,-1,1];
        var viewport = gl.getViewport();

        var modelview =         mat4.multiply(mat4.create(),    view,       model);
        var viewprojection =    mat4.multiply(mat4.create(),    projection, view);
        var mvp =               mat4.multiply(mat4.create(),    projection, modelview);

        var posScreenCoords =   vec4.transformMat4(vec4.create(),   pos,    mvp);
        var vec3unproj = vec3.create();
        vec3.unproject(vec3unproj, [posScreenCoords[0],posScreenCoords[1],posScreenCoords[2]], viewprojection, viewport);

I know there are some useless calculations, like multiplying model and view when they are at the identity, but I want them to be there just for showing the step by step.
At the identity, the camera is facing to the [0,0,-1] world coords, so when I transform this coords with the MVP matrix to get the screen coords, it should result a point at the center of the screen [0,0,Z], this is what I'm getting.
Everything OK at this point. Here is where I'm stuck. I have the same environment as if I am at the shader, I have an XY which are the screen coords, and a Z . I have to unproject this coords to the world coords.
I'm using the gl-matrix library, but it hasn't the vec3.unproject and got it from external source, but I'm not getting the desired result [0,0,-1] from it:
var unprojectMat = mat4.create();
var unprojectVec = vec4.create();

vec3.unproject = function (out, vec, viewprojection, viewport) {

  var m = unprojectMat;
  var v = unprojectVec;

  v[0] = (vec[0] - viewport[0]) * 2.0 / viewport[2] - 1.0;
  v[1] = (vec[1] - viewport[1]) * 2.0 / viewport[3] - 1.0;
  v[2] = 2.0 * vec[2] - 1.0;
  v[3] = 1.0;

  if(!mat4.invert(m,viewprojection))
    return null;

  vec4.transformMat4(v, v, m);
  if(v[3] === 0.0)
    return null;

  out[0] = v[0] / v[3];
  out[1] = v[1] / v[3];
  out[2] = v[2] / v[3];

  return out;
};

You can see the test here. Any ideas? Thanks


text:
Q: Magento 2 foreign key error saving configurable product I created a Magento 2.0.2 store and used :
https://github.com/ubertheme/magento2_data_migration/releases
to import from my 1.9.2 store.  When i try to save one of my configurable products I get this error.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`gaxle_magento2`.`catalog_product_entity`, CONSTRAINT `CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) O), query was: UPDATE `catalog_product_entity` SET `attribute_set_id` = ?, `type_id` = ?, `sku` = ?, `has_options` = ?, `required_options` = ?, `created_at` = '2013-02-07 06:18:07', `updated_at` = '2015-11-30 20:57:16' WHERE (`entity_id`=44)

I don't get this error saving all configurable products. Just this one from what i can tell.  Any ideas?

A: The error says that this configurable product is assigned to attribute set that not exists in system. Try assign it to "default" set and problem should be fixed.


text:
Q: forcing landscape mode for tablets and portrait for mobiles I have been working on a radio app and along the way i decided to force only landscape to appear for tablets and portrait mode for phones.
Here is what i have done so far to achieve that.
First i put a bool resource in res.values to check for screen size.
 //  From my res/values/bool.xml(sw600 and 720)dp.

        <?xml version="1.0" encoding="utf-8"?>
        <resources>
            <bool name="landscape_only">true</bool>
        </resources>

// res/values/bool.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="portrait_only">true</bool>
</resources>

I then forced the requested screen orientations with code by checking the boolean in Main Activity.
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // locking out landscape screen orientation for mobiles
        if(getResources().getBoolean(R.bool.portrait_only)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        // locking out portait screen orientation for tablets
        if(getResources().getBoolean(R.bool.landscape_only)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

    }
}

So far, this worked pretty well. Now here's the issue i have.
When i implemented my code to lock out portrait mode for tablets my app started in portrait for a few seconds before switching to landscape. How do i make sure that it doesn't start off first in portrait? It should start off in landscape.

A: Just add a null check before cancelling the notification.
 @Override
        protected void onDestroy() {
          if(radioService != null){
             radioService.cancelNotification();
        }
        super.onDestroy();
}

For changing the orientation correctly, you should add following to the activity tag in manifest -
<activity
    android:name="com.ABC"
    android:configChanges="keyboardHidden|orientation|screenSize">
</activity>

And be sure to call setRequestedOrientation() before setting your layout i.e.
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // locking out landscape screen orientation for mobiles
        if(getResources().getBoolean(R.bool.portrait_only)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        // locking out portait screen orientation for tablets
        if(getResources().getBoolean(R.bool.landscape_only)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }

        setContentView(R.layout.activity_main);
}

A: I have finally found the solution to my problem. I was not giving a reference to the alternative screen views inside my value resource files. When i edited my bool.xml resource file as you see below, i got the expected result.
bool.xml (mobile)
 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="portrait_only">true</bool>
    <bool name="landscape_only">false</bool>
</resources>

// bool.xml (sw600dp)
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="portrait_only">false</bool>
    <bool name="landscape_only">true</bool>
</resources>

// bool.xml (sw720dp)
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <bool name="portrait_only">false</bool>
        <bool name="landscape_only">true</bool>
    </resources>

With this, my activities now start in the requested screen orientation as required.


text:
Q: Unable to Load GloVIS using Java 8 due to Security Requirement (Windows 8, Java 8 v.40) After migrating to a new PC running Windows 8.1 (64-bit), and updating to the most recent Java 8 version (update 40), I am unable to load the GloVis website (http://glovis.usgs.gov/); every time it reports a security error and says may not load due to the risk the plug-in poses.
I have tried, not in this exact order:

*

*Updating Java

*Changing security settings from 'Medium-High' to 'Medium'

*Restarting computer / browser / site

*Installing 32- and 64-bit versions of Java

*Adding the website to site exception list

The GloVis instructions just say upgrade to the most recent Java version, which I have already done. When I access on another, older computer everything seems to run just fine.
Has anyone had this experience and been able to access GloVis using Java 8?