text:
Q: Symfony guard : access_control has no effect I'm new to symfony, and I'm trying to get a basic guard authenticator based on JWT. The work is mainly from the article here, where I have removed any user check (for now): http://kolabdigital.com/lab-time/symfony-json-web-tokens-authentication-guard
I think there's something I don't get, because I can't make it work. More precisely, it works everywhere, even in the exceptions I put in place.
Here is the Check service, basically the same as the article, without the users management, and with a bit of logging :
<?php

namespace AppBundle\Security;

use Lexik\Bundle\JWTAuthenticationBundle\Encoder\DefaultEncoder;
use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\AuthorizationHeaderTokenExtractor;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Psr\Log\LoggerInterface;

class TokenAuthenticator extends AbstractGuardAuthenticator
{
    private $jwtEncoder;
    private $logger;

    public function __construct(DefaultEncoder $jwtEncoder, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->jwtEncoder = $jwtEncoder;
    }

    public function start(Request $request, AuthenticationException $authException = null)
    {
        $route = $request->attributes->get('_route');
        $url = $request->getUri();
        $this->logger->info($route . ' : ' . $url);
        return new JsonResponse('Authentication required', 401);
    }

    public function getCredentials(Request $request)
    {

        if(!$request->headers->has('Authorization')) {
            return;
        }

        $extractor = new AuthorizationHeaderTokenExtractor(
            'Bearer',
            'Authorization'
        );

        $token = $extractor->extract($request);

        if(!$token) {
            return;
        }

        return $token;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $data = $this->jwtEncoder->decode($credentials);

        if(!$data){
            return;
        }

        $username = $data['username'];

        // TODO get user from user collection
        $user = ['username' => $username];

        // Is user is encoded in token and exists, then it's fine
        if(!$user){
            return;
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return true;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        return new JsonResponse([
            'message' => $exception->getMessage()
        ], 401);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        return;
    }

    public function supportsRememberMe()
    {
        return false;
    }

}

And the security.yml, with EVERYTHING excluded, just to check the behavior.
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/security.html
security:

    # http://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
    providers:
        in_memory:
            memory: ~

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

#################################
# Secured section
#

        # Custom authentication firewall for all request thats starts from /api
        api:
            pattern: ^/api
            guard:
                authenticators:
                    - app.token_authenticator

#################################
# Main Configuration
#

        main:
            anonymous: ~
            # activate different ways to authenticate

            # http_basic: ~
            # http://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: ~
            # http://symfony.com/doc/current/cookbook/security/form_login_setup.html

    access_control:
        #- { path: ^/auth, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        #- { path: ^/version, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        #- { path: ^/api, roles: [ROLE_USER, ROLE_API_USER] }
        - { path: ^/api, roles: IS_AUTHENTICATED_ANONYMOUSLY }

        #- { path: ^/(css|js), roles: IS_AUTHENTICATED_ANONYMOUSLY }
        #- { path: ^/(_wdt|_profiler), roles: IS_AUTHENTICATED_ANONYMOUSLY }
        #- { path: ^/, roles: ROLE_USER }

I just put the guard in place on ^/api, and put a control_access on the same path to allow ANONYMOUS. I expect that the guard service is not called on any path with that configuration, but it's called everytime. I guess I'm missing some understanding on how it works.
What I understand is:

*

*Access control is checked before anything else

*If there's a matching line, it takes it (the first one)

*If IS_AUTHENTICATED_ANONYMOUSLY is set, then the firewall is not checked

*Else, the next check is the firewall configuration, where it tells to check with the TokenAuthenticator

The initial aim is to lock /api, except /api/auth and /api/version that can be accessed without control.
Thanks for the help, I think after 1 day and a half on it, I'm not able to think straight about it.

A: Hello i recently got the same problem. There is a lack of well documentation about this use-case when we have custom guard authenticator with acces_control.
First of all:

What I understand is:

*

*Access control is checked before anything else

No, This sentence is FAIL and because of this - it projects the understanding of the rest.
As you can see for example here , the job of FIREWALL (your Token Authenticator Guard) is to start the authentication process which is the first thing the system does - to check if the given credentials (if any) will result  in authenticated token or not.
If this is determined - then system will do his second job which is authorization - for example to possibly deny access to certain resources because of insufficient role using access_control.
Knowing all of this, you can think of your guard token authenticator as some kind of (i know it is not the real thing but just for purpose of clean explanation) abstract-virtual-variation of login form mechanism, which will only run when you hit your login path. Only difference is here your guard will run not when you hit some login path, but when the request have Authorization header (and this is fully customizable as you defined it like this in getCredentials function)
Btw, in newest symfony there is new supports function which is called  before getCredentials in which you should check does request have sufficient headers to start Authentication (or whatever check you want).
So basically you said: "run guard when request have Authorization header", no matter which uri you requests. Probably because you send your basic auth credentials that way - your request (even for api/version and especially for api/auth) have this header. Then your guard is triggered before anything else which result in behavior you described.
As a one of possible solutions for this - inside your guard, you could set it to trigger when request have X-AUTH-TOKEN header (so you can use different headers for public access paths and different for private). That way your call to api/version wont trigger guard, and even call for api/auth wont do it as you will be sending credentials using Authorization header, not X-AUTH-TOKEN header.
If so your guard will not be triggered and THEN with determined unauthenticated token you hit your accesss control  which will decide if you are allowed to resource or not (yes for IS_AUTHENTICATED_ANONYMOUSLY for that path).
I hope i explained to you a bit.

A: For the record, I managed to workaround this issue.
First, Guard Authenticator is built upon real User Repository, which is not what we want. We want a fast check with Redis, and a UserRepository in Mongo. Also, we don't want PHP sessions, we want a stateless system (only the active token is in redis).
So what I did is create a dummy User object for Guard Authenticator, implementing the needed interface.
On access, we check if the user is already known by getting its token in redis, with additional data. These additional data include the needed User object.
On connection, we actually check the user in database, and if it's fine, we create the dummy User object, and push it in redis with the token.
With that system everything is fine. It's not the prettiest solution, but it allows using Guard in a stateless environment with possibly multiple instances.


text:
Q: How to disallow disposable email in firebase auth email provider signup? We are using firebase auth and firebase auth UI to authenticate a user.
We want to disallow or block those user's, who is trying to use a temporary mailbox for signing up (eg: https://www.mailinator.com).
There are 2 proposed solutions:

*

*Do a client-side validation for the email ID? (Difficult to manage a blacklist of email providers in the client. Also, people can still use API to hack it).

*After the user signs up, on onCreate user event, we can trigger a firebase function to validate the email ID against the blacklist, then we can disable or revoke the account. But here,

*

*if we are disabling the user, he/she will get access to our app for next 1 hour as the client already gained the ID token.

*If we are revoking refresh token, we'll have to again wait for 1 hour or write the rule to make a query to Firestore to check if user access is revoked. (Better if we can avoid this query)

Is there a better or native way to solve this issue?
If we are not getting any other solutions, we'll choose to go with 2nd option (revoking refresh token).

A: I would do a combination of both solutions you proposed. Doing the client side check will trip up most people and for the more tech savvy that try to get around it, your onCreate trigger will deal with them.
You could also add their uid to a blocked list in the realtime database from your onCreate trigger.
Then you can listen to it on the client and log them out. And for database rules you can check if they are in the block list and so block the read/write rule.

A: a regularly updated service to check DPA is already being maintained.
Do a simple get request to:
https://open.kickbox.com/v1/disposable/{user_email}
this would return the response
{
    "disposable": true
}
if email id is disposable.
you can send the get request with complete email id or just the domain.
e.g. https://open.kickbox.com/v1/disposable/jamond67@zdecaesgl.com
or https://open.kickbox.com/v1/disposable/zdecaesgl.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: StructureMap DBServiceRegistry and MVC-mini-profiler? If I use this code in each Repository class then I get SQL profiling to work but I want to move that code from each class into the class where StructureMap handles the DB.
Example of a Repository class:
public DB CreateNewContext()
    {
        var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
        var profiledConnection = ProfiledDbConnection.Get(sqlConnection);
        return DataContextUtils.CreateDataContext<DB>(profiledConnection);
    }

    public SqlRecipeRepository(DB dataContext)
    {
        _db = CreateNewContext();
    }

Now I want the dataContext variable to be the profiled version and so come from my DBServiceRegistry class.
Here is the DBServiceRegistry class:
public class DBServiceRegistry : Registry
{
    public DBServiceRegistry()
    {
        var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["GetMeCooking.Data.Properties.Settings.server"].ConnectionString);
        var profiledConnection = ProfiledDbConnection.Get(sqlConnection);
        For<DB>().HybridHttpOrThreadLocalScoped().Use(() => DataContextUtils.CreateDataContext<DB>(profiledConnection));

        //Original method just had this:
        //For<DB>().HybridHttpOrThreadLocalScoped().Use(() => new DB());

    }
}

This code does not cause any errors but I don't get the SQL profiling, what am I doing wrong?

A: The comment is correct, by creating the sql connection outwith the For line, you are overriding the scope command.
Far better to encapsulate the whole lot into an anonymous delegate
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;

using StructureMap;
using StructureMap.Configuration.DSL;

using Xunit;

public class DBServiceRegistry : Registry
{
    private string connString = ConfigurationManager.ConnectionStrings["GetMeCooking.Data.Properties.Settings.server"].ConnectionString;

    public DBServiceRegistry()
    {
        For<DB>().HybridHttpOrThreadLocalScoped().Use(
            () =>
                {
                    var sqlConnection = new SqlConnection(connString);
                    var profiledConnection = new StackExchange.Profiling.Data.ProfiledDbConnection(sqlConnection,  MiniProfiler.Current);
                    return DataContextUtils.CreateDataContext<DB>(profiledConnection);
                });
    }
}

You can use unit tests to verify that the scope is correct (test syntax is xunit.net)
public class DBRegistryTests : IDisposable
{
    private Container container;

    public DBRegistryTests()
    {
        // Arrange (or test setup)
        container = new Container(new DBServiceRegistry());
    }

    [Fact]
    public void ConnectionsAreSameInThread()
    {
        // Create two connections on same thread
        var conn1 = container.GetInstance<DB>();
        var conn2 = container.GetInstance<DB>();

        // Assert should be equal because hybrid thread is scope
        // and test executes on same thread
        Assert.Equal(conn1, conn2);

        // Other assertions that connection is profiled
    }

    [Fact]
    public void ConnectionAreNotSameInDifferentThreads()
    {
        var conn1 = container.GetInstance<DB>();

        // Request second connection from a different thread
        // (for < c# 4.0 use Thread instead of task)
        var conn2 = new Task<DB>(() => this.container.GetInstance<DB>());
        conn2.Start();
        conn2.Wait();

        // Assert that request from two different threads
        // are not the same
        Assert.NotEqual(conn1, conn2.Result);
    }

    public void Dispose()
    {
        // Test teardown
        container.Dispose();
    }
}


text:
Q: AttributeError: 'TFBertModel' object has no attribute 'parameters' Hello I am trying to train a Bert Model for a tokenizer I had trained. I imported
from transformers import TFBertModel

model = TFBertModel.from_pretrained("bert-base-uncased")

Now I am trying to initialise the training by defining the Optimizer like this
from transformers import AdamW

optimizer = AdamW(model.parameters(), lr=5e-5)

However I am getting the following error

AttributeError                            Traceback (most recent call last)
 in
1 from transformers import AdamW
2
----> 3 optimizer = AdamW(model.parameters(), lr=5e-5)
AttributeError: 'TFBertModel' object has no attribute 'parameters'
Following a tutorial on Youtube
https://www.youtube.com/watch?v=04oZ2P0uvp0&t=1501s&ab_channel=code_your_own_AI


text:
Q: Python 3.5: Dict value object does not support indexing I'm getting an error in python 3.5 using this code. The error is dict value object does not support indexing.
#Find frequency of appearance for each value of the list
counter=collections.Counter(myList)
#Get frequencies' list
unique_freq = counter.values()
#Get unique items' list
unique_items=counter.keys()

probs= [(0,0)]*len(unique_items)

#Initialization of probs list
for i in range (0 , len(unique_items)):
        probs[i]=(unique_items[i],np.float32(unique_freq[i]))

A: You need to cast the .values() and .keys() results to list.
unique_freq = list(counter.values())

But the better, pythonic way of doing what you want to do is iterating the dictionary with items():
result = []

for key, value in your_dict.items():
    result.append((key,value))

A: Both dict.keys and dict.values return set-like objects that don't support indexing.
In order to index them you need to change them to an object that supports it, usually a list:
#Get frequencies' list
unique_freq = list(counter.values())
#Get unique items' list
unique_items=list(counter.keys())


text:
Q: Any way around circular reference dependancy in C#? I have a solution with 3 projects
Project1 - main application
Project2 - graphing application
Project3 - graphing library

The data is accessed from objects in Project1.  Project 1 has a reference to project 2 to create a display of the data (form), and projectg 2 has a reference to project 3 to do the actual heavy lifting of rendering the graphs.
Now, project 3 needs to have access to the objects/methods of project 1 as that is where the data lives.  But when I add a reference from project 3 to project 1, I get an error about circular references.
How can I solve this issue?
Thank,
Reza

A: You need to keep the flow in one direction.. down.
To get around that, I generally have a "Models" project. Data models are stored in this project all by themselves and this project is referenced by any other project that requires them.

A: No; there is no way around this. You have a circular dependency. You will need to refactor the layers of your application.
What I find works best for me in terms of layers (from lowest to highest)

*

*Global methods & configuration (i.e. things like base type extension methods, system messages, etc).

*Data access layer. No business logic; only data CRUD logic.

*Business layer. Add business logic here.

*UI value add layer. This is where things like your graphing libraries would go. (optional)

*UI layer. This is where you build the UI that the end user sees.

A: One way to deal with circular references is to restructure your application.
Create project 4, and put the interfaces common to the projects in there. You can include project 4 from all other projects. Now implement interfaces from that project in one of the three other projects, and use implementations through a factory mechanism of some sort (an inversion of control container is good too, but it may be an overkill for simpler applications).


text:
Q: High-performance hashing without collisions? The Hashing function below was borrowed heavily from this post, but it has too many collisions in my application.
public static class Hashing
{
  private const int FNV1a_offsetBias = unchecked( ( int )0x81_1c_9d_c5 );
  private const int FNV1a_prime = 16_777_619;

  public static int FNV1a(params dynamic[] values) {
     var hash = FNV1a_offsetBias;

     foreach ( var value in values )
        hash = FNV1a_Crank(hash, value.GetHashCode());

     return hash;
  }

  private static int FNV1a_Crank(int start, int addendum) {
     unchecked {
        start *= FNV1a_prime;
        start += addendum;
     }

     return start;
  }
}

I need high-performance hashing that is guaranteed unique. I realize it will likely need to be slower than the function above, but I'm hoping to find something that is not dramatically slower. The SE post linked above is fascinating and useful, but also leaves me confused and wondering what to use.
The use case for my hashing is this: I have an app that inserts millions of records every day into my database. The tables being inserted into contain unique keys and thus any insert that violates uniqueness will throw an exception. I cannot allow these exceptions to be thrown because it's far too slow, and it's just better to avoid for other reasons. So I use the function above to hash the column values in the composite unique key of each insert and store in a hash table. Before each insert, I generate a hash and look for the hash in the hashtable. If it's not there, then I'm safe to do the insert. If it is there, the record already exists, and I skip the insert.
It's very fast, and I thought it worked at first. But then I found dozens of cases (out of millions) in which hashes collide and thus my app believes a record had already been inserted--when in fact it hadn't. So I get missing records, which is unacceptable to the business.
Here are a few examples of the sort of data I am hashing:
Hasher("Z125",  "99-8ZG10", "SpecialZ_S07181_2");
Hasher("G125");
Hasher("G99-76", "F78_XYZ_92323");

So I'm looking for a c# function that provides the fastest possible hashing algorithm that is guaranteed unique. In other words, I need a performant way to check millions of times does this record already exist in the table? Hashing seems like the fastest way, but uniqueness is paramount.
Any ideas?

A: It appears your goal is to generate a unique identifier for your database records. Usually your database system will allow you to set a primary key for your database records, which the system will then ensure is unique across the database. Such primary keys are generally enough for many applications. However, there are several other things to consider, such as:

*

*Whether identifiers have to be hard to guess, or merely "look random".

*Whether identifiers are the only thing that grants access to the record.

The best way to generate unique identifiers will depend on these and other questions, which I give in the section "Unique Random Identifiers". You should edit your question post with the answers to the six questions I give in that section; the answers will further suggest what kind of identifiers to use. However, if you can't tolerate the risk of duplicate identifiers, as in this case, then neither random numbers nor hashes of column values are appropriate as unique identifiers unless the application checks them for uniqueness.


text:
Q: I wanto to build an array with values read from a file... how can i do that? I have a file to read, then extract some values from this file and re-assign these values to write a readable ascii file. The point is that I cannot find a way to write the values in a proper way.
The file I am using is an ascii file produced by tecplot. At the end, I would like to produce the file with some header and variable description.
I tried different strategies until now, but I produce only single arrays with two values and not a "proper" matrix. Moreover, I don't manage to write each element as I would like to, I mean keep in memory the elements assigned step by step in the loop.
Here's the code:
f=open('profile_1D.dat', 'r')
data = []
outfile = open('outfile.dat','w+')

for line in f:
  line = line.split()
  data.append(line)

data=np.array(data)
arg=(data[43:])

newarr=np.zeros((len(arg),2))
for lists in arg:
  newarray=np.array((lists[2],lists[34]))
  newarray.astype(float)

print newarray
print newarray.shape

`
Like that I obviously get only the last line of the "array".
['6.17926421404682' '1.59400321081525E-11']
and its shape is (2,).
I would like to have a (300,2) array filled like that:
['5.53645484949833' '1.86479953164333E-11']
['5.55719063545151' '1.8377081954255E-11']
['5.57792642140468' '1.81061685920767E-11']
['5.59866220735786' '1.78352552298984E-11']

A: I think you get the last line because you don't append the newarray.
Try :
for lists in arg:
    newarray.append(np.array((lists[2],lists[34])))


text:
Q: I really need to restore my laptop I really need to restore my laptop back to factory settings because I screwed it up using ubuntu. How can I restore it?

A: Reinstall Ubuntu through a LiveDVD/LiveUSB, when you start the install processes you will be asked if you want to "Reinstall Ubuntu", and keep your files, or "Erase Ubuntu and reinstall" getting everything fresh and new (Everything will be deleted).
I recommend you to Erase your Ubuntu and reinstall, deleting everything, although if you need to keep your files and there is no way to backup them, then just choose to reinstall Ubuntu.
Things should be solved then!


text:
Q: Animation of menu items in ActionBar When you long click on email item in Gmail application (Honeycomb) the context-like menu is shown with it's items animated on start. How this is made? Thanks.

A: You cannot animate MenuItems, so the trick is to set a same looking View in its place with MenuItem.setActionView() and animate that view as you would normally and then unset it when animation is done with MenuItem.setActionView(null)
public class MainFragment extends Fragment {

   private Menu mOptionsMenu;

   @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
       mOptionsMenu = menu;
       inflater.inflate(R.menu.fragment_main, menu);
   }

   private void animateActionBarItem() {
       final MenuItem refreshItem = mOptionsMenu.findItem(R.id.action_refresh);
       refreshItem.setActionView(R.layout.actionbar_foo);
       refreshItem.getActionView()
            .animate()
            .setInterpolator(new AccelerateInterpolator())
            .setDuration(100L)
            .scaleX(2F)
            .scaleY(2F)
            .withEndAction(new Runnable() {

                @Override
                public void run() {
                    refreshItem.setActionView(null);
                }
            });
      }

}

XML for R.layout.actionbar_foo
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    style="?android:attr/actionButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_accept" />

A: Take a look at my answer here. It is related to the layout changes of the parent of menu items, but if you look at my idea there, you will catch a glimpse how to animate menu items.

A: Take a look here. You can animate any view calling an animation to start on it.


text:
Q: Stuck with a regex to exclude optional items I am using an application that allows the use of a regex to control the naming of entities.
I have a bunch of entities named like this (each line is the whole name):
Subsystem - CPU - Utilisation [1x]
Subsystem - CPU - Utilisation [2x]
Subsystem - CPU - Utilisation [4x]
Subsystem - CPU - Queue Length
Subsystem - Disk - Space
Subsystem - Disk - Capacity

And I need to use the regex to turn each one into this:
CPU \n Utilisation
CPU \n Queue Length
Disk \n Space
Disk \n Capacity

(the spaces around the \n are for clarity, and not in the real output)
The regex I'm using for that is:
Find:     ^Subsystem - (.*) - (.*)( \[.*\])$
Replace:  ${1}\n${2}

Which works for the ones with a [something] part, but not those without.
Essentially, I need to get part1 and part2, where part2 is terminated either by [ or the end of the line.

A: This regex should get you the matches:
^Subsystem - ([^\s-]+) - ([^\s\[]+)(?=(?:\s\[)|$).*$

Tested at this Rubular link
Edit:
Updated to include "Queue Length"
^Subsystem - ([^\s-]+) - (.+?)(?=(?:\s+\[)|$).*$

Tested at this Rubular link
Breakdown:

*

*^Subsystem - :self explanatory, matching the first few constant chars

*([^\s-]+) :capturing group of a negative charset, basically that matches anything until it hits a space or a hyphen

*(.+?)(?=(?:\s+\[)|$) :Positive lookahead to match anything (non-greedily) that is always followed by EITHER spaces and "[" OR  end of line. The ?: is a non-capturing group so that it does not match it.

*.*$ :match anything else until end of line

A: Try this (make the last part optional - zero or once):
^Subsystem - (.*) - (.*)( \[.*\])?$

That should work!
Also, I love using http://rubular.com/ to try out my regexps.

A: (Tested on Notepad++)
.+?- +([\w ]+) +- +([\w ]+) .*

Explanation:
.+?- non-greedy until first dash -
+([\w ]+) + - second word (only letters and spaces) match between 1 or more spaces
- +([\w ]+) - second word (only letters and spaces) match preceded by dash and one or more spaces
.* - the rest of the string

A: Then you can just make the [...] part optional :
^Subsystem - (.*) - (.*?)(?: \[.*\])?$

A: Just need another * before the $ sign.
Use as below:
^Subsystem - (.*) - (.*)( \[.*\])*$


text:
Q: Integral of the form $\frac{dx}{(ax^2 + bx + c)\sqrt{px +q}}$ As the title suggests, I want to evaluate: $\int \frac{dx}{(ax^2 + bx + c)\sqrt{px +q}}$ given $a,p \neq 0$.
I tried the substitution $px + q = t^2$, which yields:
 $ \int \frac{dt}{(At^4 + Bt^2 + C)}$ where $A,B,C$ are some constants such that $A \neq 0$. How do I solve this new integral, or is there an easier substitution?
($A = \frac{a}{p^2} $,
$B = \frac{bp - 2aq}{p^2} $ and
$C = \frac{aq^2 - bpq + cp^2}{p^2} $)


text:
Q: What is the Relevence of Braces in an XAML Binding Path Declaration All, the question is a simple one. The following binding does not work, that is, the ascociated Trigger does not fire
<DataTrigger Binding="{Binding dataAccess:DataGridTextSearch.IsAnyTextMatch,
    ElementName=dataGrid}" Value="false">

to fix this and make the binding work, we place the binding reference in braces, as follows
<DataTrigger Binding="{Binding (dataAccess:DataGridTextSearch.IsAnyTextMatch),
    ElementName=dataGrid}" Value="false">

Why does adding the braces resolve the reference/binding problem and what is going on?
Thanks for your time.

A: This is because The Binding cannot determine the complete Expression you want to bind to. If you put it into braces the complete expression (with namespace etc.) can be determined correctly.
If you write (dataAccess:DataGridTextSearch.IsAnyTextMatch) with braces the markup parser will take your whole binding as ONE expression. Otherwise it would stuck trying to bind to dataAccess:. With braces you will have an explicit statement that this is one single expression
I hope you finall got me :)

A: Multiple Property (Indirect Property Targeting)
<Binding Path="propertyName.propertyName2" .../>

propertyName must resolve to be the name of a property that is the current DataContext. The path properties propertyName and propertyName2 can be any properties that exist in a relationship, where propertyName2 is a property that exists on the type that is the value of propertyName.
Single Property, Attached or Otherwise Type-Qualified
<object property="(ownerType.propertyName)" .../>

The parentheses indicate that this property in a PropertyPath should be constructed using a partial qualification. It can use an XML namespace to find the type with an appropriate mapping. The ownerType searches types that a XAML processor has access to, through the XmlnsDefinitionAttribute declarations in each assembly. Most applications have the default XML namespace mapped to the http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace, so a prefix is usually only necessary for custom types or types otherwise outside that namespace. propertyName must resolve to be the name of a property existing on the ownerType. This syntax is generally used for one of the following cases:

*

*The path is specified in XAML that is in a style or template that does not have a specified Target Type. A qualified usage is generally not valid for cases other than this, because in non-style, non-template cases, the property exists on an instance, not a type.

*The property is an attached property.

*You are binding to a static property.
For use as storyboard target, the property specified as propertyName must be a DependencyProperty.


text:
Q: Replace NAs in a ffdf object I`m working with a ffdf object which has NAs in some of the columns. The NAs are the result of a left outer merge using merge.ffdf.I would like to replace the NAs with 0s but not managing to do it.
Here is the code I am running:
    library(ffbase)
    deals <- merge(deals,rk,by.x=c("DEALID","STICHTAG"),by.y=c("ID","STICHTAG"),all.x=TRUE)
    attributes(deals)
    $names
    [1] "virtual"   "physical"  "row.names"
    $class
    [1] "ffdf"

vmode(deals$CREDIT_R)
[1] "double"

    idx <- ffwhich(deals,is.na(CREDIT_R)) # CREDIT_R is one of the columns with NAs
    deals.strom[idx,"CREDIT_R"]<-0
    error in `[<-.ffdf`(`*tmp*`, idx, "CREDIT_R", value = 0) :
      ff/ffdf-iness of value and selected columns don't match

Any idea what I am doing wrong? In general I would like to learn more about replacing methods for class ff and ffdf. Any suggestion where I can find some examples about the topic?

A: The manual of package ff indicates a function called ffindexset.
idx <- is.na(deals$CREDIT_R) ## This uses is.na.ff_vector from ffbase
idx <- ffwhich(idx, idx == TRUE) ## Is part of ffbase
deals$CREDIT_R <- ffindexset(x=deals$CREDIT_R, index=idx, value=ff(0, length=length(idx), vmode = "double")) ## Is part of ff
deals$CREDIT_R[idx] <- ff(0, length=length(idx), vmode = "double") ## this one will probably also work

Also have a look at ?Extract.ff


text:
Q: Clear way of using XPath to find elements which contain a given child element? I have this XML:
<Catalog>
    <CUnit id="Bd">
        <Race value="T1"/>
    </CUnit>
    <CUnit id="Critter">
    </CUnit>
    <CUnit id="Ld">
        <Race value="T1"/>
    </CUnit>
</Catalog>

I want to use XPath to extract the CUnit elements that have a Race child element. Is there a clearer way than this?
CUnit/Race/..

A: Use a predicate instead:
//CUnit[Race]

A: Avoid using the // pseudo-operator, because with many XPath engines it is implemented very inefficiently (causes traversal of the whole subtree rooted in the context node).
Whenever the structure of the XML document is well-known, use specific paths.
In this case:
/*/CUnit[Race]


text:
Q: Why fontawesome icon does not show up? at Chrome and Safari? Why fontawesome icon does not show up? at Chrome and Safari?
Bootstrap and Fontawesome on Chrome and Safari.
They do not show anything.
Here is my code. Feel stupid struggling with this super easy task...
<link href="bootstrap.css" rel="stylesheet">
<link href="jumbotron-narrow.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

It should work but why it is not showing anything? Can anyone help me?

GitHub

A: Work's ok for me - see sample below:
http://jsfiddle.net/easwee/tmWVz/
Why are you loading the
bootstrap-combined.no-icons.min.css

file?
You only need
bootstrap.min.css
font-awesome.min.css

to make it work.

A: Try including it this way. If you are working local and not on a browser trys to fetch the files from your hard drive.
<link href="bootstrap.css" rel="stylesheet">
<link href="jumbotron-narrow.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

It's important not to forget the http: when working local.


text:
Q: Desktop Sharing and Chat open source I need library or ready to use open source desktop sharing and chat application in C#, C++ or Java. I should use this in my project.
I see real vnc is not open source anymore? don't suggest real vnc.
Please suggest most SIMPLE and easy to use library/application.

A: Take a look at TightVNC
Also take a look at these questions on stackoverflow
How can I display a VNC Viewer in a Java rich client (LGPL, Apache, MIT license)?
Java VNC Libraries


text:
Q: how to print url from html code in php when url contain spaces See i have an url in a html code
play

Now i want to print this url as it is written in a php page
http://b48.ve.vc/b/data/48/3746/05 Dabangg Reloaded_-_www.DjPunjab.Com.mp3

You can see that between the url 05 Dabangg Reloaded their is space. I made this program to print url from this html code..
$str = "play";

$pattern = '`.*?((http|ftp)://[\w#$&+,\/:;=?@.-]+)[^\w#$&+,\/:;=?@.-]*?`i';
if (preg_match_all($pattern,$str,$matches))

foreach($matches[1] as $data)
{
$str=$data;
echo $str;
}

Then i am getting this
http://b48.ve.vc/b/data/48/3746/05

please do not mention on foreach($matches[1] as $data) line bcoz i am using it with so many urls.. I just want to know how to print the whole url in this format.
http://b48.ve.vc/b/data/48/3746/05 Dabangg Reloaded_-_www.DjPunjab.Com.mp3

Spaces are become a huge matter.. Do not know how to fix it..
What i need to add inside
$pattern = '`.*?((http|ftp)://[\w#$&+,\/:;=?@.-]+)[^\w#$&+,\/:;=?@.-]*?`i';

For making it completely workable.
Please suggest me any idea.

A: $str = 'play';
$arr = explode("\"", $str);
$pattern = '`.*?((http|ftp)://[\w#$&+,\/:;=?@.-]+)[^\w#$&+,\/:;=?@.-]*?`i';
$url = preg_grep($pattern,$arr);
$url = implode('',$url);
Output: $url = 'http://b48.ve.vc/b/data/48/3746/05 Dabangg Reloaded_-_www.DjPunjab.Com.mp3'

Update: 2nd Solution [Reference-DOMElement].

$str = 'play';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
$search_item = $DOM->getElementsByTagName('a');
foreach($search_item as $search_item) {
    $url = $search_item->getAttribute('href');
}
echo $url; //Output: http://b48.ve.vc/b/data/48/3746/05 Dabangg Reloaded_-_www.DjPunjab.Com.mp3

A: You can str_replace each one -space- with %20 for encoding your URL
<?php
 $url_org = 'http://b48.ve.vc/b/data/48/3746/05 Dabangg Reloaded_-_www.DjPunjab.Com.mp3';
 $url_edited = str_replace(" ", '%20', $url_org);
?>
 <a href="<?php echo $url_edited; ?>" target="_blank"> HERE

This will work.


text:
Q: Serialize a function of a class without serializing the class itself I'm using pyro5, and I want to make a remote object function as a worker class, where a client can ask it to perform various tasks by sending it functions to execute.
For this to work, I need to serialize functions, but the serializers available through Pyro5 does not support serializing functions.
Instead, I intend to use Dill, and somehow send the already serialized function through Pyro5.
However, when trying to serialize a function, I receive errors which say that I can't serialize X, where X is the enclosing class where the function lives. How can I prevent this from happening?
Actually, I was not able to reproduce this in a small script with a class and a function. I am running the dill serializer in a Qt app, not sure if that's the problem?
Alternatively, does anyone have a better idea on how to approach this?

A: I'm the dill author.  There are several ways to approach this that may work for you.  It's hard to tell without more information on your class in question, so I'll have to make assumptions.
If assume you are working with a class that you are importing from an installed package, then you can do something like this:
>>> # Mock a unserializable builtin class "Foo"
>>> import ctypes
>>> PyObjectType = ctypes.py_object(lambda :None)
>>> class Foo(PyObjectType.__class__):
...   def __init__(self, x):
...     self.x = x
...   def bar(self, y):
...     return y + self.x
...
>>> f = Foo(1)
>>> f.bar(2)
3
>>> # serializing the method fails
>>> # dill.dumps(f.bar) #FAILS
>>> # so we create a wrapping function
>>> bar = lambda x:f.bar(x)
>>>
>>> import dill
>>> dill.dumps(bar)
b'\x80\x03cdill._dill\n_create_function\nq\x00(cdill._dill\n_create_code\nq\x01(K\x01K\x00K\x01K\x03KCC\nt\x00\xa0\x01|\x00\xa1\x01S\x00q\x02N\x85q\x03X\x01\x00\x00\x00fq\x04X\x03\x00\x00\x00barq\x05\x86q\x06X\x01\x00\x00\x00xq\x07\x85q\x08X\x07\x00\x00\x00<stdin>q\tX\x08\x00\x00\x00<lambda>q\nK\x01C\x00q\x0b))tq\x0cRq\rc__builtin__\n__main__\nh\nNNtq\x0eRq\x0f}q\x10}q\x11X\x0f\x00\x00\x00__annotations__q\x12}q\x13s\x86q\x14b.'

This works, as long as the class is available for import wherever you are going to use dill.loads to restore the function.
Or if you need to ship the class as well, you could also create a wrapping class (i.e. a derived class) that includes a __reduce__ method which informs dill how to serialize the class.  https://docs.python.org/3/library/pickle.html#object.__reduce__
There are other approaches as well, but it would help to have more information on what you are dealing with.


text:
Q: why is laravel eager loading constraint not working? I have this as the basic of what i want to do but the constraint is not applying
$this['subs'] = Cat::with([
    'children' => function($query) {
        $query -> where('parent_id', 0);
    }
]) -> get();

A: the one you are looking for, is whereHas , like this:

$this['subs'] = Cat::whereHas('children', function ($query) {
                  $query->where('parent_id',0);
               })->get();

putting a query in with just scopes the relationships it queries, not the record set cat itself.

A: Do you have a cat with id = 0?
Try:
Cat::with('children')->find(0)

Supposing you have a cat with id = 0; this will return the cat with id = 0 and its children if has any.
Or:
Cat::has('children')->get()

This will return all the cats that have children.
Or:
Cat::with('children')->get()

This will return all cats and its children if has any

A: you are using October CMS so you can just use traits nested-tree
docs : https://octobercms.com/docs/database/traits#nested-tree
class Cat extends Model
{
    use \October\Rain\Database\Traits\NestedTree;
}

Now
$model = Cat::where('slug', $param_slug)->first();

and then
$model->getEagerRoot(); // Returns a list of all root nodes, with ->children eager loaded.
// OR
$model->getEagerChildren(); // Returns direct child nodes, with ->children eager loaded.

You can have ton of options

https://github.com/octobercms/library/blob/master/src/Database/Traits/NestedTree.php

/* General access methods:
 *
 *   $model->getRoot(); // Returns the highest parent of a node.
 *   $model->getRootList(); // Returns an indented array of key and value columns from root.
 *   $model->getParent(); // The direct parent node.
 *   $model->getParents(); // Returns all parents up the tree.
 *   $model->getParentsAndSelf(); // Returns all parents up the tree and self.
 *   $model->getChildren(); // Set of all direct child nodes.
 *   $model->getSiblings(); // Return all siblings (parent's children).
 *   $model->getSiblingsAndSelf(); // Return all siblings and self.
 *   $model->getLeaves(); // Returns all final nodes without children.
 *   $model->getDepth(); // Returns the depth of a current node.
 *   $model->getChildCount(); // Returns number of all children.
 *
 * Query builder methods:
 *
 *   $query->withoutNode(); // Filters a specific node from the results.
 *   $query->withoutSelf(); // Filters current node from the results.
 *   $query->withoutRoot(); // Filters root from the results.
 *   $query->children(); // Filters as direct children down the tree.
 *   $query->allChildren(); // Filters as all children down the tree.
 *   $query->parent(); // Filters as direct parent up the tree.
 *   $query->parents(); // Filters as all parents up the tree.
 *   $query->siblings(); // Filters as all siblings (parent's children).
 *   $query->leaves(); // Filters as all final nodes without children.
 *   $query->getNested(); // Returns an eager loaded collection of results.
 *   $query->listsNested(); // Returns an indented array of key and value columns.
 *
 * Flat result access methods:
 *
 *   $model->getAll(); // Returns everything in correct order.
 *   $model->getAllRoot(); // Returns all root nodes.
 *   $model->getAllChildren(); // Returns all children down the tree.
 *   $model->getAllChildrenAndSelf(); // Returns all children and self.
 *
 * Eager loaded access methods:
 *
 *   $model->getEagerRoot(); // Returns a list of all root nodes, with ->children eager loaded.
 *   $model->getEagerChildren(); // Returns direct child nodes, with ->children eager loaded.
 *
 */

please check it out its really fast and convenient way for parent and child relations.
if any doubt please comment.


text:
Q: How to remove Scrolling Space created by Image? I added an image to my HTML and set the position to relative. Also, including new coords bottom , right , z-index, Even if the image location/position is in front of the body( overlapping it ) the scroll still extends to its Default location even if there is not space used. Is there a way to stop this?
A better explanation:
https://imgur.com/a/pPSeoLa
The Code :
.crow
{
  position: relative ;
  z-index:4;
  bottom: 950px;
  right: 502px;
  height: 900px;
  width: 1200px;
}

body
{
  font-family: "trebuchet ms", arial, sans-serif;
  font-size: .84em;
  color: #222;
  line-height: 1.4em;
  background-color: #cccccc;
  background-image: url(bruh.png);
  background-repeat: repeat;
  background-position: ;
  background-size: cover;
  height: 100%;
  overflow: scroll;
  width: 900px;
  margin: 10px auto 0px auto;
  cursor: url(cursor1.png), pointer;
}

A: according to w3 schools

position: relative;
An element with position: relative; is positioned relative to its
normal position.
Setting the top, right, bottom, and left properties of a
relatively-positioned element will cause it to be adjusted away from
its normal position. Other content will not be adjusted to fit into
any gap left by the element.

=> position relative does not remove the element from the page flow

position: absolute;
An element with position: absolute; is positioned relative to the
nearest positioned ancestor (instead of positioned relative to the
viewport, like fixed).
However; if an absolute positioned element has no positioned
ancestors, it uses the document body, and moves along with page
scrolling.

=> element is removed from the page flow

*

*src
you probably need to position with absolute


text:
Q: Nestjs - Manually instantiate a class with dependencies on useFactory suppose I have two classes like this
@Injectable({ scope: Scope.DEFAULT })
class Service {

    constructor() {}
    // ...
}

@Injectable()
class OtherService {
    param: T;

    constructor(readonly service: Service, param: T) {}

    // ...
}

And I'm triying to dinamically instantiate the last class using a factory
const otherServiceFactory = {
    provide: "TOKEN",
    scope: Scope.Request,
    useFactory: (req: Request) => {
        const param = req.headers["foo"];
        return new OtherService(/* ts expects an instance of Service here */ , param)
    },
    inject: [REQUEST]
}

As the comment said, at the moment of creating the instance ts expects, correctly, an instance of Service. The problem is I rather not mess up with the DI tree, so I don't want to instantiate Service. I was able to hack this around by setting the param later instead of asking in the constructor, so I don't need the factory anymore, but feels pretty sub-optimal. Any suggestions?
Thanks

A: You can add Service to the inject array, and get the instance of Service that Nest creates, then pass it to OtherService so that you have everything required to create the class.
const otherServiceFactory = {
    provide: "TOKEN",
    scope: Scope.Request,
    useFactory: (req: Request, service: Service) => {
        const param = req.headers["foo"];
        return new OtherServiceservice, param)
    },
    inject: [REQUEST, Service]
}


text:
Q: How do I merge days of the week using the UNION operator? I am using this WITH method so that I can combine two SELECT statements.
The problem is that When I join the results using the UNION, it is duplicating the days and combining the time column. I need it the other way around.... for example: I am trying to select results on all Mondays that are equal to 14:00 and then another set of results that equal 16:00 and have those two display in separate columns next to each other.
An example of what this is currently giving me is below this SQL query.
USE Trading;
GO

WITH
  ctetwo (CTEday, CTEtime) AS
  (
    SELECT DATENAME(WEEKDAY, M.[DateTime]) as Day,
        COUNT(M.[High] - M.[Low]) as Two
    FROM dbo.MicroES M
        WHERE CONVERT(time, M.[DateTime]) = '14:00'
        AND DATEPART(WEEKDAY,M.[Datetime]) BETWEEN 2 AND 6
        GROUP BY DATENAME(WEEKDAY, M.[DateTime])
  ),
    cteSix (CTEday, CTEtime) AS
  (
    SELECT DATENAME(WEEKDAY, M.[DateTime]) as Day,
        COUNT(M.[High] - M.[Low]) as Two
    FROM dbo.MicroES M
        WHERE CONVERT(time, M.[DateTime]) = '18:00'
        AND DATEPART(WEEKDAY,M.[Datetime]) BETWEEN 2 AND 6
        GROUP BY DATENAME(WEEKDAY, M.[DateTime])
  )

    select
  --'Monday' AS 'Day',
    CTEday AS 'Day',
    CTEtime as TimeFour
   from ctetwo

   UNION ALL

     select
  --'Tuesday' AS 'Day',
    CTEday AS 'Day',
    CTEtime as TimeSix
   from cteSix

   ORDER BY Day

Day            TimeFour
Friday      15
Friday      17
Monday      13
Monday      19
Thursday    15
Thursday    18
Tuesday     16
Tuesday     16
Wednesday   18
Wednesday   18

A: Can't you do that using a single select?
SELECT
    DATENAME(WEEKDAY, M.[DateTime]) as [Day],
    COUNT(M.[High] - M.[Low]) as Two
FROM dbo.MicroES M
WHERE CONVERT(time, M.[DateTime]) in ('14:00','18:00')
    AND DATEPART(WEEKDAY,M.[Datetime]) BETWEEN 2 AND 6
GROUP BY DATENAME(WEEKDAY, M.[DateTime])
ORDER BY [Day],Two


text:
Q: Radio button array with cloned row I have a form where a row get's clowned if a user clicks "add row". My problem is with the radio buttons, the name of the radio group stays the same and I need to get them unique for each cloned row. This is how I have it at the moment.
 <input type="radio" name="chronic_l_duration[]" value="Chronic" />
 <input type="radio" name="chronic_l_duration[]" value="Limited duration" />

What I would like is something like this:
<input type="radio" name="chronic_l_duration[1]" value="Chronic" />
<input type="radio" name="chronic_l_duration[1]" value="Limited duration" />

end when a other row gets added it goes to:
 <input type="radio" name="chronic_l_duration[2]" value="Chronic" />
 <input type="radio" name="chronic_l_duration[2]" value="Limited duration" />

Javascript I use to clone a row:
  $(document).ready(function(){
    var clonedRow = $('.row').clone().html();
    var appendRow = '
' + clonedRow + '
';

    $('#btnAddMore').click(function(){

    $('.employmentHistoryForm tr:last').after(appendRow);
    });

    $('.deleteThisRow').live('click',function(){
    var rowLength = $('.row').length;

    if(rowLength > 1){
    deleteRow(this);
    }else{
    $('.employmentHistoryForm tr:last').after(appendRow);
    deleteRow(this);
    }
    });

    function deleteRow(currentNode){
    $(currentNode).parent().parent().remove();
    }
    });

So each time the row get's cloned the radio button has a unique value.
Is there maybe a way I can do this?

A: You can access the appended row with the $('.employmentHistoryForm tr:last') and then modify the name of input:
$('#btnAddMore').click(function(){
   $('.employmentHistoryForm tr:last').after(appendRow);
   $('.employmentHistoryForm tr:last input[type="radio"]').attr('name', 'desired value');
});


text:
Q: SCSS structure versus multiple CSS classes I have just started using SCSS for the first time. I'm noticing that the resulting CSS is somewhat less optimised than it would be if I had written it by hand. For example, I am using mixins for style duplication, like this:
@mixin button {
    border-radius: 4px 20px 20px 4px;
    -moz-border-radius: 4px 20px 20px 4px;
}
.enquire {
    .live-chat {
        @include button;
        background: #21a649;
    }
    .enquire-now {
        @include button;
        background: #33b1ff;
    }
}

Then all I need on the button is the single class, "enquire-now", and all the styles are included in that one class in the CSS.
If I had written this by hand, however, I would have used 2 classes, like this:
.button {
    border-radius: 4px 20px 20px 4px;
    -moz-border-radius: 4px 20px 20px 4px;
}
.enquire .live-chat {
    background: #21a649;
}
.enquire .enquire-now {
    background: #33b1ff;
}

And then on the element, used "button enquire-now"
So by using the mixin, I am minimising the classes used in my HTML and making it pleasant to write, but am making my actual CSS file much longer! This seems somewhat counterproductive... Have I missed something?
What's the point of mixins, if doing the old fashioned way actually produces a smaller CSS file?

A: Use the @extend directive to have easier to maintain code, and prevent duplication of styles:
%button {
    border-radius: 4px 20px 20px 4px;
    -moz-border-radius: 4px 20px 20px 4px;
}
.enquire {
    .live-chat {
        @extend %button;
        background: #21a649;
    }
    .enquire-now {
        @extend %button;
        background: #33b1ff;
    }
}

Which compiles to this:
.enquire .live-chat, .enquire .enquire-now {
border-radius: 4px 20px 20px 4px;
-moz-border-radius: 4px 20px 20px 4px;
}
.enquire .live-chat {
background: #21a649;
}
.enquire .enquire-now {
background: #33b1ff;
}

A: Its a trade off. You get eaiser to author, more maintainable CSS in trade for it being more verbose. And as i found out recently there is this pesky thing in IE were you cant have more than a certain number of selectors in a single CSS file and then it also has a limit on the number of CSS files. So for large site keeping our selector count down might be just as if not more important than the size of the file(s). Especially since you can mitigate the filesize issue by minifiying and then serving compressed (gzipped) versions.

A: Indeed use @extend instead: Sass Extend Reference


text:
Q: Matrix of pixels to coordinates I have to convert a given matrix of pixels (coefficients are in a range from 0 to 255, since the matrix corresponds to a black and white image) into two lists. Both of them may be composed of lists, one containing the abscissas of the points, the other the ordinates.
As you can notice on the included picture, the first case corresponds to a single curve, whereas both the others involve multiple ones, crossing one each other. The algorithm should be able to make the difference between the two or three curves (in the two last examples), so in the two mainlists, a given sublist corresponds to a given curve.

I have absolutely no idea of what to start from...
One last thing : I'm seeking ideas on how to program this algorithm, so this is why I didn't add any specific programming language (if code may help any explanation, feel free to speak any language).
Thanks in advance >^.^<

A: Check out the Hough transform. It is a simple voting algorithm, that allows finding simple geometric shapes in images. One complication could be that your lines are not strictly straight. But it would give you equations on the lines it does find. Since your case is a little nonstandard I'd try to understand the algorithm itself and write my own implementation.
In my first implementation (centering a circle on a square in long focal depth image I took) I started with a very simple Python example I found online, rewrote it for my purposes and then later moved to C# for speed, since I needed more parameters (higher dimensional search space) than you need for this simple case.
In your case I would start with the simple assumption of a straight line. Then the Hough transform will give 1, 2 and 3 maxima respectively for your three cases.
The idea of the Hough transform is well described on wikipedia.
Here just the gist of the idea:

For a straight line think of giving each black pixel the right to vote
  for 180 possible lines that could go through it (one for each angle in
  single degree steps), then plotting the vote as histogram over  a 2d space, where one
  dimension is the angle of the line, another is the distance from
  origin (using the Hesse normal form of the line for practical reasons
  rather than the common y= m x +b) and the z-dimension is the number of votes. The actual line formed by the black
  pixels will get more votes than any other possible line, so you are
  simply looking for the Maximum vote location in the transformation
  space (say in Python/numpy it would be argmax).

If there are two lines, you will find two clear maxima, the higher one with the longer or thicker line (more votes). You can then start playing with grayscale in your image, giving non-integer votes to pixels. You can also play with the resolution of the angle, depending on the content of your problem.


text:
Q: How to get controller from within controller plugin in zendframework 2? I am writing a controller plugin in zf2.
I use the following method to get controller from within plugin, but it returns null.
$controller = $this->getController()

Any suggestion?

A: Note, this answer was based on my experience with ZF1, and a quick look at the ZF2 code. Check out this answer.
I haven't played with ZF2 yet, but if the dispatch process and plugins are similar to ZF1, a plugin can't access the controller (at least not in a trivial way) as the controller isn't even instantiated for some of the plugin hooks.
Update: Took a quick look at some of the stock ZF2 controller plugins (as I can't seem to find official docs on creating a custom plugin), and see checks like the following:
$controller = $this->getController();
if (!$controller || !method_exists($controller, 'plugin')) {
//...

So it seems like the controller may not be set in some cases. Since the plugins also support (what I understand to be) an event listener, my guess is that they still can be used at various times in the response process, which may be before a controller is assigned.
Hopefully someone who's used ZF2 can come along and set me straight; but perhaps I've at least pointed you in a somewhat reasonable direction.

A: There are two options for which you have no controller set in your plugin.

*

*You call the plugin from the plugin manager prior to dispatch, so no controller is set yet

*You call the controller inside the plugin during __construct()
For the first one, a typical example is an onBootstrap() method in a module class where obviously you have no controller:
public function onBootstrap($e)
{
  $app = $e->getApplication();
  $sm  = $app->getServiceManager();

  $plugins = $sm->get('ControllerPluginManager');
  $plugin  = $plugins->get('my-plugin');

  // $plugin->getController() === null
}

This seems an obvious example, but there are other occasions where you are mistakenly assuming a controller exists already (for example, during run of the application, at the route phase; the dispatch still has to come).
The second example is because the controller is injected with setter injection. The setter is called after construction. In pseudo code, this happens:
$plugin = new $class;
$plugin->setController($controller);

If you have a plugin like this:
use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class MyPlugin extends AbstractPlugin
{
  public function __construct()
  {
    // $this->getController() === null
  }
}

You notice there is no controller set at that phase.


text:
Q: Module error for 'beginners' in livewires MacOS - beginner I am a beginner at python and is following a book named 'Python programmming for the absolute beginner' and has issues on importing livewires.
When I write from livewires import games it pops up with the error:
line 1, in <module>
from livewires import games
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/livewires/__init__.py", line 32, in <module>
from beginners import *
ModuleNotFoundError: No module named 'beginners'

I am not sure how to deal with this as i've researched this and I've not cam back with a solution.
The way I installed livewires (I have already installed pygame)
pip install livewires

and
pip install superwires

A: It seems that LiveWires only supports Python 2. You may use SuperWires instead of LiveWires:
pip3 install superwires

from superwires import games  # Just replace `livewires` with `superwires`

References

*

*https://mail.python.org/pipermail/tutor/2011-November/086552.html

*https://askubuntu.com/questions/949054/livewires-module-isnt-working

*Installing livewires for python


text:
Q: No notifications are returned I am trying to get user's unread notifications though my controller.
This works:
public function notifications(){

    return \App\User::find(auth()->user()->id)->unreadNotifications()->limit(5)->get();
}

This doesn't, it returns an empty collection:
public function notifications(){
    return auth()->user()->unreadNotifications()->limit(5)->get();
}

Could you tell me what I am missing? Thanks in advance.
Using Laravel 5.8 with Backpack 3.5.
The default auth guard of Laravel is overwitten to use Backpack auth in backpack routes, using the UseBackpackAuthGuardInsteadOfDefaultAuthGuard middleware of the permissions manager package. In the rest of the controller auth() and backpack_auth works normally.

A: Try this:
public function notifications()
    return Auth::user()->unreadNotifications()->limit(5)->get();
}

As said in the docs:

You may access the authenticated user via the Auth facade:
Alternatively, once a user is authenticated, you may access the authenticated user via an  Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:

A: Auth and auth() likely don't work here because you're using the Backpack For Laravel authentication which uses a different guard than the default one Laravel uses.
This would probably work for you:

backpack_user()->unreadNotifications()->limit(5)->get();

If that works, here's why:
If you take a look at project/vendor/backpack/base/src/helpers.php you'll see that backpack_user() is an alias for backpack_auth()->user() and backpack_auth does a:
return \Auth::guard(backpack_guard_name());
That's the important bit because it grabs the guard defined config/backpack/base.php (which is backpack by default) and uses that instead of Laravel's default guard of web.


text:
Q: How do I move each element in an array in 1 spot? Sorry if this is a pretty basic question, but I never had this problem before. I'll show what I mean in a pretty basic way:
Let's say I have the array [1, 2, 3]. How can I turn it into [3, 1, 2] or [2, 3, 1] (move each element 1 to the right or the left)? Thanks in advance!

A: Try this:

var x = [1, 2, 3];

console.log(x);

// shift right
x.unshift(x.pop());

console.log(x);

// shift left

x.push(x.shift());

console.log(x);

Check here to see what these methods do.

A:

function shiftRight(arr) {
  if (arr.length < 2) return arr;
  return [arr[arr.length-1], ...arr.splice(0, arr.length - 1)];
}
function shiftLeft(arr) {
  if (arr.length < 2) return arr;
  return [...arr.splice(1, arr.length - 1), arr[0]];
}
console.log(shiftLeft([1, 2, 3, 4, 5]));
console.log(shiftRight([1, 2, 3, 4, 5]));


text:
Q: In Maven, how can I dynamically build a property value at runtime? In maven it is very easy to set properties in a pom with the following syntax:
...
<properties>
  <myValue>4.06.17.6</myValue>
 </properties>
...

Now I need to build a property which depends on the version of my pom. For creating the property i want to do the following (java pseudo code):
String[] parts = version.split("\\.");
String.format("V%s_%s_%s_P%s", splitted[0],  splitted[1],splitted[2],splitted[3]);
// example: 4.06.17.6 => V_4_06_17_P6

It should be dynamic, because it is used as a tag name in our repository and must always be in sync with the version of the artifact.
Any ideas how to create that "dynamic" properties?

A: You can use maven build-helper plugin, in particular its regex-property mojo. Take a look at usage examples (scroll to Set a property by applying a regex replacement to a value section).
Basically you want something like that in your pom to get myVersionTag property inferred from myValue:
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.7</version>
        <executions>
          <execution>
            <id>regex-property</id>
            <goals>
              <goal>regex-property</goal>
            </goals>
            <configuration>
              <name>myVersionTag</name>
              <value>$\{myValue}</value>
              <regex>(\d+)\.(\d+)\.(\d+)\.(\d+)</regex>
              <replacement>V_$1_$2_$3_P$4</replacement>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

A: Mojo's Build-Helper Maven Plugin can help you out here.
There are a number of goals that can be used to help transform properties.
There is

*

*build-helper:regex-property

*build-helper:parse-version

*build-helper:released-version
Probably regex-property is the one you want, but if your version numbers conform to the "standards" the other two might save you.
To use the regex-property goal you would do something like
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.7</version>
        <executions>
          <execution>
            <id>regex-property</id>
            <goals>
              <goal>regex-property</goal>
            </goals>
            <configuration>
              <name>tag.version</name>
              <value>${project.version}</value>
              <regex>^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.(-SNAPSHOT)?$</regex>
              <replacement>V$1_$2_$3_P$4</replacement>
              <failIfNoMatch>true</failIfNoMatch>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

Note: my regex might be slightly off so you should test the above.
Note: The property value will only be available for executions after the phase that this execution is bound to. The default phase that it is bound to is validate but if you are on a different lifecycle (e.g. the site lifecycle) the value will not be available.

A: Ihor Kaharlichenko's answer is basically correct except that it copies an error from the Codehaus documentation.  There should be no '\' between the '$' and the '{'.  The mojo works without it and doesn't work with it.  Truly, with a basic understanding of regex and Maven, I couldn't see what the backslash was supposed to do and indeed it's wrong.
Stephen Connolly's answer correctly omits the backslash.  Be careful.
This error has proliferated throughout SO and with Codehaus out of business will probably never get fixed.


text:
Q: Entity Framework Core, How to update if already exists, else insert I'm pulling data from an external API and storing this in my SQL Server database using Entity Framework Core. I pull data from this API every day so I want to check for rows that already exist by Id, in case the Id already exists in the database, then the row should be updated. Otherwise a new record should be added.
The data from the API is deserialized from JSON and stored in the data variable as a List<Customers>. Currently I came up with the following code but it still keeps making new records even if the row already exists.
string apiResponse = await response.Content.ReadAsStringAsync();

var data = JsonConvert.DeserializeObject<List<Customers>>(apiResponse);

foreach (Customers customer in data)
{
    if (db.Customers.Any(x => x.Id == customer.Id))
    {
        db.Customers.Update(customer);
    }
    else
    {
        db.Customers.Add(customer);
    }

    db.SaveChanges();
}

Model
public class Customers
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [JsonProperty("id")]
    public string BranchId { get; set; }

    [JsonProperty("name")]
    public string CustomerNameTopdesk { get; set; }

    public string CustomerNamePRTG { get; set; }
}

DbContext
public DbSet<Customers> Customers { get; set; }

EDIT
After running the debugger it throws the following exception, the Customer values seem to be empty but my data variable is properly filled with values.

'customer' threw an exception of type 'System.NullReferenceException'


text: Q: Import module that is called with sys args I have a python code (A) that needs parameters and modules from another python code (B) but B is run with system arguments (python B.py 30 10). How do I import B in A?


text:
Q: WPF ListBox change onMouseOver and SelectedItem color I have created a simple WPF form and added a listbox with some items on it. By default when i run the application on Windows 10 the mouseover effect is blue (the listitems background color changes) and for the selected item the same.
How can i change this color for mousover and selected item to lets say red ?

A: You can change the styles of Listbox directly (which Ayyappann's comment refers to).
Another way you can change the highlight color, if you would like it to be global, is to change the system colors.
So in your App.xaml you could put something like this:
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />

I prefer this way if i want certain actions to stay consistent (mouse over any object), OR if i would like to allow styles to be changed dynamically. I will customize the individual styles of local objects if i am looking for that object to have a typical behavior.
A list of the system colors can be found Here


text:
Q: Is there any problem due to dynamic memory allocation? #include <stdio.h>
#include <stdlib.h>

typedef struct {
    char* name;
}Student;

int main()  {

    int n,i;

    printf("Enter the number of student: ");
    scanf("%d",&n);
    Student *ptr = (Student*) malloc(n * sizeof(Student));

    for( i = 0; i < n ;i++)  {

        printf("Enter the name of student: ");
        scanf("%s", (ptr + i)->name);

    }
    return EXIT_SUCCESS;
}

I couldn't understand why this code is not working can anyone help me ? I thought the problem is dynamic memory allocation but i couldn't solve.

A: Try this code. The name is not allocated memory. This is what you made for mistakes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char* name;
}Student;

int main()  {

    int n,i;

    printf("Enter the number of student: ");
    scanf("%d",&n);
    Student *ptr = (Student*) malloc(n * sizeof(Student));

    for( i = 0; i < n ;i++)  {

        printf("Enter the name of student: ");
        char str[1024];
        scanf("%s", str);
        (ptr + i)->name = (char*)malloc(strlen(str) + 1);
        strcpy((ptr + i)->name, str);
    }
    return EXIT_SUCCESS;
}


text:
Q: I can't add texture to my custom create mesh using THREE.js I'm programmatically generating a mesh (ground). After that I'm adding a texture to it but what I ged is just plain color on this mesh.
This is my code:
var Three = new function () {
    var scene = new THREE.Scene()

    var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
    camera.position.set(-5, 5, 5);
    camera.rotation.order = 'YXZ';
    camera.rotation.y = -Math.PI / 4;
    camera.rotation.x = Math.atan(-1 / Math.sqrt(2));

    var renderer = new THREE.WebGLRenderer()
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true

    var light = new THREE.AmbientLight(0xffffff)
    light.position.set(150, 100, 100)
    scene.add(light);

    this.init = function () {
        $('body').append(renderer.domElement);
        Three.render();
    }
    this.render = function () {
        requestAnimationFrame(Three.render);
        renderer.render(scene, camera);
    }

    var xy = [],
        maxX = 7,
        maxY = 10

    for (i = 0; i < maxX; i++) {
        for (j = 0; j < maxY; j++) {
            xy.push([i, j])
        }
    }

    var river = [
        [0, 5],
        [0, 4],
        [1, 3],
        [2, 2],
        [3, 2],
        [4, 1],
        [5, 1],
        [6, 0]
    ]

    var grassGeometry = new THREE.BufferGeometry(),
        waterGeometry = new THREE.BufferGeometry()

    var grassVertexPositions = [],
        waterVertexPositions = []

    for (var i = 0; i < xy.length; i++) {
        grassVertexPositions.push([xy[i][0], xy[i][1], 0])
        grassVertexPositions.push([xy[i][0] + 1, xy[i][1], 0])
        grassVertexPositions.push([xy[i][0], xy[i][1] + 1, 0])

        grassVertexPositions.push([xy[i][0] + 1, xy[i][1] + 1, 0])
        grassVertexPositions.push([xy[i][0], xy[i][1] + 1, 0])
        grassVertexPositions.push([xy[i][0] + 1, xy[i][1], 0])
    }

    for (var i = 0; i < grassVertexPositions.length; i++) {
        for (var j = 0; j < river.length; j++) {
            if (river[j][0] == grassVertexPositions[i][0] && river[j][1] == grassVertexPositions[i][1]) {
                grassVertexPositions[i][2] = -0.5
            }
        }
    }

    waterVertexPositions.push([0, 0, -0.2])
    waterVertexPositions.push([maxX, 0, -0.2])
    waterVertexPositions.push([0, maxY, -0.2])

    waterVertexPositions.push([maxX, maxY, -0.2])
    waterVertexPositions.push([0, maxY, -0.2])
    waterVertexPositions.push([maxX, 0, -0.2])

    var grassVertices = new Float32Array(grassVertexPositions.length * 3),
        waterVertices = new Float32Array(waterVertexPositions.length * 3)

    for (var i = 0; i < grassVertexPositions.length; i++) {
        grassVertices[i * 3 + 0] = grassVertexPositions[i][0];
        grassVertices[i * 3 + 1] = grassVertexPositions[i][1];
        grassVertices[i * 3 + 2] = grassVertexPositions[i][2];
    }

    for (var i = 0; i < waterVertexPositions.length; i++) {
        waterVertices[i * 3 + 0] = waterVertexPositions[i][0];
        waterVertices[i * 3 + 1] = waterVertexPositions[i][1];
        waterVertices[i * 3 + 2] = waterVertexPositions[i][2];
    }

    grassGeometry.addAttribute('position', new THREE.BufferAttribute(grassVertices, 3))
    waterGeometry.addAttribute('position', new THREE.BufferAttribute(waterVertices, 3))

    var textureLoader = new THREE.TextureLoader();
    textureLoader.load('/img/deska_0.png', function (texture) {

        var grassMaterial = new THREE.MeshLambertMaterial({map: texture}),
            waterMaterial = new THREE.MeshBasicMaterial({color: 0x0000ff}),
            grassMesh = new THREE.Mesh(grassGeometry, grassMaterial),
            waterMesh = new THREE.Mesh(waterGeometry, waterMaterial)

        grassMesh.rotation.x = -Math.PI / 2;
        waterMesh.rotation.x = -Math.PI / 2;

        scene.add(grassMesh);
        scene.add(waterMesh);
    });
};

$(document).ready(function () {
    Three.init();
});

Why I see plain color instead of a texture?
p.s.
 Color is changing if I change texture to another.


text:
Q: Where was Chrome Extension installed from? Have an extension that has a good number of installs 10k+ and I'd like to open up a walkthrough page after it's installed from the Chrome Webstore only.
The problem is I never requested the tabs permission when I initially deployed it, so requesting that permission now (in order to lookup the focused tab's url and determine if the install happened from the Chrome Webstore host) causes problems because then all existing installs will have the extension disabled when the auto-update rolls out (due to the new permission request).
Are there any other ways of determining if the install is coming from the Chrome Webstore? I'm not trying to bypass any legit privacy/permission issues. Rather, looking for a technique that allows me to open a window only when it's needed.
Appreciate any thoughts.


text:
Q: How to improve performance of CSV upload via datatable I have a working solution for uploading a CSV file. Currently, I use the IFormCollection for a user to upload multiple CSV files from a view.
The CSV files are saved as a temp file as follows:
List<string> fileLocations = new List<string>();
foreach (var formFile in files)
{
   filePath = Path.GetTempFileName();
   if (formFile.Length > 0)
   {
       using (var stream = new FileStream(filePath, FileMode.Create))
       {
           await formFile.CopyToAsync(stream);
       }
   }

   fileLocations.Add(filePath);
}

I send the list of file locations to another method (just below). I loop through the file locations and stream the data from the temp files, I then use a data table and SqlBulkCopyto insert the data. I currently upload between 50 and 200 files at a time and each file is around 330KB. To insert a hundred, it takes around 6 minutes, which is around 30-35MB.
public void SplitCsvData(string fileLocation, Guid uid)
        {
            MetaDataModel MetaDatas;
            List<RawDataModel> RawDatas;

            var reader = new StreamReader(File.OpenRead(fileLocation));
            List<string> listRows = new List<string>();
            while (!reader.EndOfStream)
            {
                listRows.Add(reader.ReadLine());
            }

            var metaData = new List<string>();
            var rawData = new List<string>();

            foreach (var row in listRows)
            {
                var rowName = row.Split(',')[0];
                bool parsed = int.TryParse(rowName, out int result);

                if (parsed == false)
                {
                    metaData.Add(row);
                }
                else
                {
                    rawData.Add(row);
                }
            }

         //Assigns the vertical header name and value to the object by splitting string
         RawDatas = GetRawData.SplitRawData(rawData);
         SaveRawData(RawDatas);

         MetaDatas = GetMetaData.SplitRawData(rawData);
         SaveRawData(RawDatas);

        }

This code then passes the object to the to create the datatable and insert the data.
private DataTable CreateRawDataTable
{
   get
   {
       var dt = new DataTable();
       dt.Columns.Add("Id", typeof(int));
       dt.Columns.Add("SerialNumber", typeof(string));
       dt.Columns.Add("ReadingNumber", typeof(int));
       dt.Columns.Add("ReadingDate", typeof(string));
       dt.Columns.Add("ReadingTime", typeof(string));
       dt.Columns.Add("RunTime", typeof(string));
       dt.Columns.Add("Temperature", typeof(double));
       dt.Columns.Add("ProjectGuid", typeof(Guid));
       dt.Columns.Add("CombineDateTime", typeof(string));

        return dt;
  }
}

public void SaveRawData(List<RawDataModel> data)
{
       DataTable dt = CreateRawDataTable;
       var count = data.Count;

       for (var i = 1; i < count; i++)
       {
           DataRow row = dt.NewRow();
           row["Id"] = data[i].Id;
           row["ProjectGuid"] = data[i].ProjectGuid;
           row["SerialNumber"] = data[i].SerialNumber;
           row["ReadingNumber"] = data[i].ReadingNumber;
           row["ReadingDate"] = data[i].ReadingDate;
           row["ReadingTime"] = data[i].ReadingTime;
           row["CombineDateTime"] = data[i].CombineDateTime;
           row["RunTime"] = data[i].RunTime;
           row["Temperature"] = data[i].Temperature;
           dt.Rows.Add(row);
        }

        using (var conn = new SqlConnection(connectionString))
        {
           conn.Open();
           using (SqlTransaction tr = conn.BeginTransaction())
           {
               using (var sqlBulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tr))
               {
                   sqlBulk.BatchSize = 1000;
                   sqlBulk.DestinationTableName = "RawData";
                   sqlBulk.WriteToServer(dt);
               }
               tr.Commit();
           }
       }
   }

Is there another way to do this or a better way to improve performance so that the time to upload is reduced as it can take a long time and I am seeing an ever increasing use of memory to around 500MB.
TIA

A: You can improve performance by removing the DataTable and reading from the input stream directly.
SqlBulkCopy has a WriteToServer overload that accepts an IDataReader instead of an entire DataTable.
CsvHelper can CSV files using a StreamReader as an input. It provides CsvDataReader as an IDataReader implementation on top of the CSV data. This allows reading directly from the input stream and writing to SqlBulkCopy.
The following method will read from an IFormFile, parse the stream using CsvHelper and use the CSV's fields to configure a SqlBulkCopy instance :
public async Task ToTable(IFormFile file, string table)
{
    using (var stream = file.OpenReadStream())
    using (var tx = new StreamReader(stream))
    using (var reader = new CsvReader(tx))
    using (var rd = new CsvDataReader(reader))
    {
        var headers = reader.Context.HeaderRecord;

        var bcp = new SqlBulkCopy(_connection)
        {
            DestinationTableName = table
        };
        //Assume the file headers and table fields have the same names
        foreach(var header in headers)
        {
            bcp.ColumnMappings.Add(header, header);
        }

        await bcp.WriteToServerAsync(rd);
    }
}

This way nothing is ever written to a temp table or cached in memory. The uploaded files are parsed and written to the database directly.

A: In addition to @Panagiotis's answer, why don't you interleave your file processing with the file upload? Wrap up your file processing logic in an async method and change the loop to a Parallel.Foreach and process each file as it arrives instead of waiting for all of them?
private static readonly object listLock = new Object(); // only once at class level

    List<string> fileLocations = new List<string>();
    Parallel.ForEach(files, (formFile) =>
    {
       filePath = Path.GetTempFileName();
       if (formFile.Length > 0)
       {
           using (var stream = new FileStream(filePath, FileMode.Create))
           {
               await formFile.CopyToAsync(stream);
           }

           await ProcessFileInToDbAsync(filePath);
       }

       // Added lock for thread safety of the List
       lock (listLock)
       {
           fileLocations.Add(filePath);
       }
    });

A: Thanks to @Panagiotis Kanavos, I was able to work out what to do. Firstly, the way I was calling the methods, was leaving them in memory. The CSV file I have is in two parts, vertical metadata and then the usual horizontal information. So I needed to split them into two. Saving them as tmp files was also causing an overhead. It has gone from taking 5-6 minutes to now taking a minute, which for a 100 files containing 8,500 rows isn't bad I suppose.
Calling the method:
public async Task<IActionResult> UploadCsvFiles(ICollection<IFormFile> files, IFormCollection fc)
{
   foreach (var f in files)
   {
       var getData = new GetData(_configuration);
       await getData.SplitCsvData(f, uid);
   }

   return whatever;
}

This is the method doing the splitting:
public async Task SplitCsvData(IFormFile file, string uid)
    {
        var data = string.Empty;
        var m = new List<string>();
        var r = new List<string>();

        var records = new List<string>();
        using (var stream = file.OpenReadStream())
        using (var reader = new StreamReader(stream))
        {
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var header = line.Split(',')[0].ToString();
                bool parsed = int.TryParse(header, out int result);
                if (!parsed)
                {
                    m.Add(line);
                }
                else
                {
                    r.Add(line);
                }
            }
        }

        //TODO: Validation
        //This splits the list into the Meta data model. This is just a single object, with static fields.
        var metaData = SplitCsvMetaData.SplitMetaData(m, uid);
        DataTable dtm = CreateMetaData(metaData);
        var serialNumber = metaData.LoggerId;
        await SaveMetaData("MetaData", dtm);

        //
        var lrd = new List<RawDataModel>();
        foreach (string row in r)
        {
            lrd.Add(new RawDataModel
            {
                Id = 0,
                SerialNumber = serialNumber,
                ReadingNumber = Convert.ToInt32(row.Split(',')[0]),
                ReadingDate = Convert.ToDateTime(row.Split(',')[1]).ToString("yyyy-MM-dd"),
                ReadingTime = Convert.ToDateTime(row.Split(',')[2]).ToString("HH:mm:ss"),
                RunTime = row.Split(',')[3].ToString(),
                Temperature = Convert.ToDouble(row.Split(',')[4]),
                ProjectGuid = uid.ToString(),
                CombineDateTime = Convert.ToDateTime(row.Split(',')[1] + " " + row.Split(',')[2]).ToString("yyyy-MM-dd HH:mm:ss")
            });
        }

        await SaveRawData("RawData", lrd);
    }

I then use a data table for the metadata (which takes 20 seconds for a 100 files) as I map the field names to the columns.
 public async Task SaveMetaData(string table, DataTable dt)
    {
        using (SqlBulkCopy sqlBulk = new SqlBulkCopy(_configuration.GetConnectionString("DefaultConnection"), SqlBulkCopyOptions.Default))
        {
            sqlBulk.DestinationTableName = table;
            await sqlBulk.WriteToServerAsync(dt);
        }
    }

I then use FastMember for the large data parts for the raw data, which is more like a traditional CSV.
 public async Task SaveRawData(string table, IEnumerable<LogTagRawDataModel> lrd)
    {
        using (SqlBulkCopy sqlBulk = new SqlBulkCopy(_configuration.GetConnectionString("DefaultConnection"), SqlBulkCopyOptions.Default))
        using (var reader = ObjectReader.Create(lrd, "Id","SerialNumber", "ReadingNumber", "ReadingDate", "ReadingTime", "RunTime", "Temperature", "ProjectGuid", "CombineDateTime"))
        {
            sqlBulk.DestinationTableName = table;
            await sqlBulk.WriteToServerAsync(reader);
        }
    }

I am sure this can be improved on, but for now, this works really well.


text:
Q: Execute BEACON method every 100 milliseconds in Android I try do indoor navigation android application using Estimote beacons. Here is the code which I used to get distance between android device and beacons. This code sections runs approximately in every 1 second.
I need to execute this in every 100 milliseconds.
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
  @Override public void onBeaconsDiscovered(Region region, final List<Beacon> beacons) {
    runOnUiThread(new Runnable() {
      @Override public void run() {

        long time= System.currentTimeMillis();
        Log.i("###################### ", " #################");
        Log.i("Time Class ", " Time value in millisecinds "+time);

        toolbar.setSubtitle("Found beacons: " + beacons.size());
        ArrayList<Beacon> newBeacons = new ArrayList<>();

        for (int x=0; x<beacons.size();x++) {
          int major= beacons.get(x).getMajor();
          int minor = beacons.get(x).getMinor();

          if (major==3&&minor==3) {
            newBeacons.add(beacons.get(x));
            Dsi[0] = Utils.computeAccuracy(beacons.get(x));
          }
          else if (major==4&&minor==4) {
            newBeacons.add(beacons.get(x));
            Dsi[1] = Utils.computeAccuracy(beacons.get(x));
          }
          else if (major==2&&minor==2) {
            newBeacons.add(beacons.get(x));
            Dsi[2] = Utils.computeAccuracy(beacons.get(x));
          }
        }

        double[][] positions = new double[][] { { -3.4, 0.8}, { 0, 7.5 }, { 6.7, 6.7 } };
        double[] distances = new double[] { Dsi[0], Dsi[1], Dsi[2] };

        TrilaterationFunction trilaterationFunction = new TrilaterationFunction(positions, distances);
        LinearLeastSquaresSolver lSolver = new LinearLeastSquaresSolver(trilaterationFunction);
        NonLinearLeastSquaresSolver nlSolver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer());

        double[] expectedPosition = new double[] { 3.3, 15.0 };
        RealVector x = lSolver.solve();
        Optimum optimum = nlSolver.solve();
        testResults(expectedPosition, 1, optimum, x);
        adapter.replaceWith(newBeacons);

        time= System.currentTimeMillis();
        Log.i("Time Class ", " Time value in millisecinds "+time);
        Log.i("###################### ", " #################");
      }
    });
  }
});

How do I do that?

A: I got the answer for this problem. Here is the answer and explanation for the Estimote Beacon users and lovers.
There is a method called setForegroundScanPeriod in the Estimote Android SDK. This method implemented in BeaconManager class. This can be used to increase or decrease scanning time period.
This is the method definition
setForegroundScanPeriod(long scanPeriodMillis,long waitTimeMillis)

First parameter for the change the scan period and second parameter for the waiting time between two scanning period. Values of all parameters are taken as milliseconds. Example as follows.
setForegroundScanPeriod(200,5)

If you called like this, Then code section is executing in every 200 milliseconds with 5 milliseconds time interval.
Default values of the method is 1s for the scan time period and 0s  for the waiting period. 200ms is minimum scan time period and 0ms is minimum waiting period. (if you reduce the scanning period scanning period, Broadcasting interval of your Estimote Beacon should be reduced. Broadcasting interval should less than scan time period and also minimum Broadcasting interval is 100ms)
Reducing Broadcast interval is negatively effect for Battery life of Beacon and Reducing scan time period is negatively effect for Battery life of Android device.
Here is the full example which I used to scan Beacons.
BeaconManager beaconManager = new BeaconManager(this);

beaconManager.setForegroundScanPeriod(200,0);

beaconManager.setRangingListener(new BeaconManager.RangingListener() {
  @Override public void onBeaconsDiscovered(Region region, final List<Beacon> beacons) {
    runOnUiThread(new Runnable() {
      @Override public void run() {

        toolbar.setSubtitle("Found beacons: " + beacons.size());

        ArrayList<Beacon> newBeacons = new ArrayList<>();

        for (int x=0; x<beacons.size();x++) {
          int major= beacons.get(x).getMajor();
          int minor = beacons.get(x).getMinor();

          if (major==3&&minor==3) {
            newBeacons.add(beacons.get(x));
            Dsi[0] = Utils.computeAccuracy(beacons.get(x));
          }
          else if (major==4&&minor==4) {
            newBeacons.add(beacons.get(x));
            Dsi[1] = Utils.computeAccuracy(beacons.get(x));
          }
          else if (major==2&&minor==2) {
            newBeacons.add(beacons.get(x));
            Dsi[2] = Utils.computeAccuracy(beacons.get(x));
          }
        }

        adapter.replaceWith(newBeacons);
      }
    });
  }
});


text:
Q: Accessing serial port by Python 2.5 with ceserial module on windows ce 5.0 I have downloaded ceSerial and successfully communicate with serial ports. I have successfully write the data to the port but I am not able to read the data from the ports. It is getting connected to the port but it is not able to read the values. Below is my code snippet for reading the data from the port.

from time import sleep
import ceserial

ser = ceserial.Serial(port="COM1:",baudrate=9600,bytesize=8,stopbits=ceserial.STOPBITS_ONE,parity=ceserial.PARITY_EVEN)

print("connected to: " + ser.portstr)

#data = ''
while True:
    data = ser.read(9999)
    if len(data) > 0:
        print 'Got:', data
    sleep(0.5)
    #print 'not blocked'

ser.close()


text:
Q: if return statement in c# I am overriding a virtual method and I need to return a value depending on a bool expression.
  public override float Q()
    {
        return (float)Math.Sqrt(2 * A* B / C);
    }

I need to return a local member (call it D) for Q() if the calculated value shown above is less than D. I tried using regular if statements, but it won't return a value unless it's returned outside the if statement. Any help would be appreciated.

A: How about skipping the if altogether:
return Math.Max(D, Math.Sqrt (2*A*B/C));

or with ternary operator
return  Math.Sqrt (2*A*B/C) < D ? D :  Math.Sqrt (2*A*B/C); // too verbose but you get the idea

A: i would think this would work
public override float Q(){
    var returnValue = (float)Math.Sqrt(2 * A * B / C);

    if (returnValue < D){
        return D;
    }

    return returnValue;
}

EDIT :
or you can clean it up to this
public override float Q(){
    var returnValue = (float)Math.Sqrt(2 * A * B / C);

    return returnValue < D ? D : returnValue;
}

A: public override float Q()
{
    var result = (float)Math.Sqrt(2 * A* B / C);
    return result < D ? D : result;
}

A: Unless this is a trick question, since D is local to the class, the code should look like this:
public override float Q()
{
    var result = (float)Math.Sqrt(2 * A* B / C);
    return result < D ? D : result;
}

but note that D needs to be a float or cast to a float on the return if it's not. Further, if D isn't a float you may want to just do something like this because its type may not be implicitly convertable:
public override float Q()
{
    var d = (float)D;
    var result = (float)Math.Sqrt(2 * A* B / C);
    return result < d ? d : result;
}

A: Something like this:
public override float Q(){
    var r = (float)Math.Sqrt(2 * A * B / C);

    if (r < D){
        r = D;
    }

    return r;
}