text:
Q: stl map operator[] bad? My code reviewers has pointed it out that the use of operator[] of the map is very bad and lead to errors:
map[i] = new someClass;    // potential dangling pointer when executed twice

Or
if (map[i]==NULL) ...      // implicitly create the entry i in the map

Although I understand the risk after reading the API that the insert() is better of since it checks for duplicate, thus can avoid the dangling pointer from happening, I don't understand that if handled properly, why [] can not be used at all?
I pick map as my internal container exactly because I want to use its quick and self-explaining indexing capability.
I hope someone can either argue more with me or stand on my side:)

A: You are right that map::operator[] has to be used with care, but it can be quite useful: if you want to find an element in the map, and if not there create it:
someClass *&obj = map[x];
if (!obj)
    obj = new someClass;
obj->doThings();

And there is just one lookup in the map.
If the new fails, you may want to remove the NULL pointer from the map, of course:
someClass *&obj = map[x];
if (!obj)
    try
    {
        obj = new someClass;
    }
    catch (...)
    {
        obj.erase(x);
        throw;
    }
obj->doThings();

Naturally, if you want to find something, but not to insert it:
std::map<int, someClass*>::iterator it = map.find(x); //or ::const_iterator
if (it != map.end())
{
    someClass *obj = it->second;
    obj->doThings();
}

A: Claims like "use of operator[] of the map is very bad" should always be a warning sign of almost religious belief. But as with most such claims, there is a bit of truth lurking somewhere. The truth here however is as with almost any other construct in the C++ standard library: be careful and know what you are doing. You can (accidentally) misuse almost everything.
One common problem is potential memory leaks (assuming your map owns the objects):
std::map<int,T*> m;
m[3] = new T;
...
m[3] = new T;

This will obviously leak memory, as it overwrites the pointer. Using insert here correctly isn't easy either, and many people make a mistake that will leak anyways, like:
std::map<int,T*> m;
minsert(std::make_pair(3,new T));
...
m.insert(std::make_pair(3,new T));

While this will not overwrite the old pointer, it will not insert the new and also leak it. The correct way with insert would be (possibly better enhanced with smart pointers):
std::map<int,T*> m;
m.insert(std::make_pair(3,new T));
....
T* tmp = new T;
if( !m.insert(std::make_pair(3,tmp)) )
{
    delete tmp;
}

But this is somewhat ugly too. I personally prefer for such simple cases:
std::map<int,T*> m;

T*& tp = m[3];
if( !tp )
{
    tp = new T;
}

But this is maybe the same amount of personal preference as your code reviewers have for not allowing op[] usage...

A: The only time (that I can think of) where operator[] can be useful is when you want to set the value of a key (overwrite it if it already has a value), and you know that it is safe to overwrite (which it should be since you should be using smart pointers, not raw pointers) and is cheap to default construct, and in some contexts the value should have no-throw construction and assignment.
e.g. (similar to your first example)
std::map<int, std::unique_ptr<int>> m;
m[3] = std::unique_ptr<int>(new int(5));
m[3] = std::unique_ptr<int>(new int(3)); // No, it should be 3.

Otherwise there are a few ways to do it depending on context, however I would recommend to always use the general solution (that way you can't get it wrong).
Find a value and create it if it doesn't exist:
1. General Solution (recommended as it always works)
std::map<int, std::unique_ptr<int>> m;
auto it = m.lower_bound(3);
if(it == std::end(m) || m.key_comp()(3, it->first))
   it = m.insert(it, std::make_pair(3, std::unique_ptr<int>(new int(3)));

2. With cheap default construction of value
std::map<int, std::unique_ptr<int>> m;
auto& obj = m[3]; // value is default constructed if it doesn't exists.
if(!obj)
{
   try
   {
      obj = std::unique_ptr<int>(new int(3)); // default constructed value is overwritten.
   }
   catch(...)
   {
      m.erase(3);
      throw;
   }
}

3. With cheap default construction and no-throw insertion of value
std::map<int, my_objecct> m;
auto& obj = m[3]; // value is default constructed if it doesn't exists.
if(!obj)
   obj = my_objecct(3);

Note: You could easily wrap the general solution into a helper method:
template<typename T, typename F>
typename T::iterator find_or_create(T& m, const typename T::key_type& key, const F& factory)
{
    auto it = m.lower_bound(key);
    if(it == std::end(m) || m.key_comp()(key, it->first))
       it = m.insert(it, std::make_pair(key, factory()));
    return it;
}

int main()
{
   std::map<int, std::unique_ptr<int>> m;
   auto it = find_or_create(m, 3, []
   {
        return std::unique_ptr<int>(new int(3));
   });
   return 0;
}

Note that I pass a templated factory method instead of a value for the create case, this way there is no overhead when the value was found and does not need to be created. Since the lambda is passed as a template argument the compiler can choose to inline it.

A: *

*operator [] is avoided for insertion, because for the same reason
you mentioned in your question. It doesn't check for duplicate key
and overwrites on the existing one.

*operator [] is mostly avoided for searching in the std::map.
Because, if a key doesn't exist in your map, then operator []
would silently create new key and initialize it (typically to
0). Which may not be a preferable in all cases. One should use
[] only if there is need to create a key, if it doesn't exist.

A: This is not a problem with [] at all. It's a problem with storing raw pointers in containers.

A: If your map is like for example this :
std::map< int, int* >

then you lose, because next code snippet would leak memory :
std::map< int, int* > m;
m[3] = new int( 5 );
m[3] = new int( 2 );

if handled properly, why [] can not be used at all?

If you properly tested your code, then your code should still fail the code review, because you used raw pointers.
Other then that, if used properly, there is nothing wrong with using map::operator[]. However, you would probably be better with using insert/find methods, because of possible silent map modification.

A:  map[i] = new someClass;    // potential dangling pointer when executed twice

here, the problem isn't map's operator[], but *the lack of smart pointers.
Your pointer should be stored into some RAII object (such as a smart pointer), which imemdiately takes ownership of the allocated object, and ensures it will get freed.
If your code reviewers ignore this, and instead say that you should avid operator[], buy them a good C++ textbook.
if (map[i]==NULL) ...      // implicitly create the entry i in the map

That's true. But that's because operator[] is designed to behave differently. Obviously, you shouldn't use it in situations where it does the wrong thing.

A: Generally the problem is that operator[] implicitly creates a value associated with the passed-in key and inserts a new pair in the map if the key does not occur already. This can break you logic from then on, e.g. when you search whether a certain key exists.
map<int, int> m;
if (m[4] != 0) {
  cout << "The object exists" << endl; //furthermore this is not even correct 0 is totally valid value
} else {
  cout << "The object does not exist" << endl;
}
if (m.find(4) != m.end()) {
  cout << "The object exists" << endl; // We always happen to be in this case because m[4] creates the element
}

I recommend using the operator[] only when you know you will be referencing a key already existing in the map(this by the way proves to be not so infrequent case).

A: There's nothing wrong with operator[] of map, per se, as long as its
semantics correspond to what you want.  The problem is defining what you
want (and knowing the exact semantics of operator[]).  There are times
when implicitly creating a new entry with a default value when the entry
isn't present is exactly what you want (e.g. counting words in a text
document, where ++ countMap[word] is all that you need); there are
many other times that it's not.
A more serious problem in your code may be that you are storing pointers
in the map.  A more natural solution might be to use a map <keyType,
someClass>, rather than a map <keyType, SomeClass*>.  But again, this
depends on the desired semantics; for example, I use a lot of map
which are initialized once, at program start up, with pointers to static
instances.  If you're map[i] = ... is in an initialization loop,
executed once at start up, there's probably no issue.  If it's something
executed in many different places in the code, there probably is an
issue.
The solution to the problem isn't to ban operator[] (or maps to
pointers).  The solution is to start by specifying the exact semantics
you need.  And if std::map doesn't provide them directly (it rarely
does), write a small wrapper class which defines the exact semantics you
want, using std::map to implement them.  Thus, your wrapper for
operator[] might be:
MappedType MyMap::operator[]( KeyType const& key ) const
{
    MyMap::Impl::const_iterator elem = myImpl.find( key );
    if ( elem == myImpl.end() )
        throw EntryNotFoundError();
    return elem->second;
}

or:
MappedType* MyMap::operator[]( KeyType const& key ) const
{
    MyMap::Impl::const_iterator elem = myImpl.find( key );
    return elem == myImpl.end()
        ?   NULL   //  or the address of some default value
        :   &elem->second;
}

Similarly, you might want to use insert rather than operator[] if
you really want to insert a value that isn't already present.
And I've almost never seen a case where you'd insert an immediately
newed object into a map.  The usual reason for using new and
delete is that the objects in question have some specific lifetime of
their own (and are not copiable—although not an absolute rule, if
you're newing an object which supports copy and assignment, you're
probably doing something wrong).  When the mapped type is a pointer,
then either the pointed to objects are static (and the map is more or
less constant after initialization), or the insertion and removal is
done in the constructor and destructor of the class.  (But this is just
a general rule; there are certainly exceptions.)


text:
Q: how to escape special characters within eval using javascript? var input;

// method 1
input = document.getElementById('address').value;
alert(input)

// method 2
eval('input = "'+document.getElementById('address').value+'"')
alert(input)

method 1 is working fine, but method 2 is not working when newline characters are inputted and it says "unterminated string literal".
I need to store values using eval anyway. So please help me.

A: Use string.replace(/\r?\n/g, "\\n") to escape the newlines.

A: That's because you are actually evaluating code that looks like this, which is ofcourse wrong in javascript
var test = "Lorem ipsum
    dolor sit amet";

Why do you need the eval? It looks not really necessary in this case. Maybe we can help you get around the eval?

A: Try:
   const address = document.getElementById('address').value
   eval('input = ' + JSON.stringify(String(address)))

String(address) will guarantee that the object is a string.
JSON.stringify will return a double quoted string parsable with eval.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to automatically combine user model to a custom user model i have this custom user model
class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200)

    def __str__(self):
        return self.name

and i use allauth package for authentication and once i sign up a new user i got this error in the main page of the website:
RelatedObjectDoesNotExist at /
User has no customer.
is there a way to combine the user to a customer automatically once the user got created?

A: You can override save() method of you user creation form and include creation of the Customer there:
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):

    class Meta:
        model = User
        fields = ['username', 'email']

    def save(self, commit=True):
        user = super(UserRegisterForm, self).save(commit=False)
        if commit:
            user.save()
            Customer.objects.create(user=user, name=user.username, email=user.email)
        return user

A: i figured it out
first import post_save and receiver
from django.db.models.signals import post_save
from django.dispatch import receiver

then
class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200)

    def __str__(self):
        return "%s's profile" % self.user

@receiver(post_save, sender=User)
def create_user_customer(sender, instance, created, **kwargs):
    if created:
        cuatomer, created = Customer.objects.get_or_create(user=instance)

post_save.connect(create_user_customer, sender=User)

at settings.py
AUTH_USER_MODULE = 'YOURAPP.Customer'


text:
Q: What should be the relative path of the csv file need I want to create an executable java program which will read a csv file at the same location  as the executable file. What should be the relative path of the csv file in the code. Im using eclipse. Will the same path will work for both windows n  Mac ?

A: Use
this.getClass().getClassLoader().getResourceAsStream("yourfile.csv")

Using this approach you don't need to specify a relative path for a file at the same level as your class. This will work on all platforms.


text:
Q: return error when run php artisan serve comand ([ErrorException] chdir(): No such file or directory (errno 2)) One laravel project works fine on host. When I download project files and wants to run it on Xampp I have some problems.
At first php artisan command works fine. But when I want to run php artisan serve it returns Error:

[ErrorException]
chdir(): No such file or directory (errno 2)

After that I tried to fix it and searched in stackoverflow questions and none of them can help me.
I tried php artisan config:clear command and it works fine. After that when I want to run php artisan returns another error that is:

[Symfony\Component\HttpKernel\Exception\NotFoundHttpException]

Laravel version: "laravel/framework": "5.5.*"
Update:
I know why return NotFoundHttpException error after config cache command. It's because APP_URL set to http://localhost:8000. Before that it's set to domain address that works on it(on host with this domain) fine.
I tested all answers in related question so please don't vote as duplicate because it's a little different with those.
Please help if you have had this problem in the past.


text:
Q: IIS Rewriting dosnt allow/breaks post requests I have an IIS instance in front of my other non-iis web server hosting the site where the IIS is doing some AAR magic which is working good but for POST requests this dont seem to work for some reasons which mean any ajax calls by the application on the non IIS webserver end up broken. Any ideas on how to solve this? Below is the current rule setup.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpRedirect enabled="false" />
        <rewrite>
            <rules>
                <clear />
                <rule name="UrlWithPimRewrite" stopProcessing="true">
                    <match url="pim.*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{CACHE_URL}" pattern="^(https?)://" />
                    </conditions>
                    <serverVariables>
                        <set name="HTTP_X_ORIGINAL_ACCEPT_ENCODING" value="{HTTP_ACCEPT_ENCODING}" />
                        <set name="HTTP_ACCEPT_ENCODING" value="" />
                    </serverVariables>
                    <action type="Rewrite" url="{C:1}://localhost:1512/{R:0}" appendQueryString="true" logRewrittenUrl="true" />
                </rule>
                <rule name="UrlWithoutPIM" enabled="true" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{URL}" pattern="/pim" negate="true" />
                        <add input="{CACHE_URL}" pattern="^(https?)://" />
                    </conditions>
                    <serverVariables>
                        <set name="HTTP_X_ORIGINAL_ACCEPT_ENCODING" value="{HTTP_ACCEPT_ENCODING}" />
                        <set name="HTTP_ACCEPT_ENCODING" value="" />
                    </serverVariables>
                    <action type="Rewrite" url="{C:1}://localhost:1512/pim/webaccess" appendQueryString="false" logRewrittenUrl="true" />
                </rule>
            </rules>
            <outboundRules>
                <clear />
                <rule name="RestoreAcceptEncoding" preCondition="NeedsRestoringAcceptEncoding" enabled="true">
                    <match serverVariable="HTTP_ACCEPT_ENCODING" pattern="^(.*)" />
                    <action type="Rewrite" value="{HTTP_X_ORIGINAL_ACCEPT_ENCODING}" />
                </rule>
                <preConditions>
                    <preCondition name="NeedsRestoringAcceptEncoding">
                        <add input="{HTTP_X_ORIGINAL_ACCEPT_ENCODING}" pattern=".+" />
                    </preCondition>
                </preConditions>
            </outboundRules>
        </rewrite>
        <urlCompression doStaticCompression="true" doDynamicCompression="true" />
        <directoryBrowse enabled="false" />
        <tracing>
            <traceFailedRequests>
                <add path="*">
                    <traceAreas>
                        <add provider="ASP" verbosity="Verbose" />
                        <add provider="ISAPI Extension" verbosity="Verbose" />
                        <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI,WebSocket" verbosity="Verbose" />
                    </traceAreas>
                    <failureDefinitions statusCodes="404" />
                </add>
            </traceFailedRequests>
        </tracing>
    </system.webServer>
</configuration>


text:
Q: Slider-Pips values to hidden input I am using Slider Pips with range. I want to set the value of 2 hidden input fields (#pricefrom, #priceto) to the choosen range. With the change function i can change 1 value but does anybody can help me how i can update the value from the 2. input to the right value?
<input id="pricefrom" type="hidden" name="pricefrom" value="">
<input id="priceto" type="hidden" name="priceto" value="">

{$(".slider")

.slider({
    min: 0,
    max: 2000,
    range: true,
    values: [200, 800],
    step: 10,
     //this updates the value of your hidden field when user stops dragging
    change: function(event, ui) {
        $('#pricefrom').attr('value', ui.value);
    }
})

.slider("pips", {
    rest: "label",
    step: 40
})

.slider("float");}

A: The ui object should have a values property which is an array. This holds all the values of each handle. So [0] will be the first handle, and [1] will be the second handle;
  change: function(event, ui) {

    $('#pricefrom').attr('value', ui.values[0]);
    $('#priceto').attr('value', ui.values[1]);

  }


text:
Q: Azure Continuous Deployment - Code First Migration seeding issue (MVC 5) I've set up the Continuous Deployment in Microsoft Azure (Web App) using a ButBucket Git repo.  Code First Migrations works well on my computer, it creates tables and seeds them, but when I sync the branch, the seed method of the migration is not run on Azure.
So Azure gets the changes from BitBucket, creates the tables as needed, but does not run the seed method (every table remains empty).
Can you suggest a solution to run the Seed method on Azure automatically when a new migration is applied (or after every time Azure builds from BitBucket if that is the only solution)?
Additional Info:

*

*MigrationHistory table contains the migrations, so they were run.

*I've set AutomaticMigrationsEnabled = true; but the problem remains

*On Azure there is a Web App which is built and migrated, and an SQL Database which is referenced in the ConnectionString in Web.config

Configuration.cs
internal sealed class Configuration : DbMigrationsConfiguration<MyInsidR.Models.ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        ContextKey = "MyInsidR.Models.ApplicationDbContext";
    }

    protected override void Seed(ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //

        context.Prophecies.AddOrUpdate(p => p.ID,
            new Prophecy() { ID = 1, Text = "Fűben iszogatós, sírva nevetős."}
        );

        context.Interesteds.AddOrUpdate(x => x.ID,
            new Interested() { ID = 1, Email = "teszt.elek@gmail.com", FirstName = "Elek", LastName = "Teszt", RegistrationDate = DateTime.Now }
        );

        var tag1 = new Tag() { ID = 1, Name = "Karaoke", ApplyTo = TagApplication.All, Type = TagType.Games };
        var tag3 = new Tag() { ID = 3, Name = "4 rooms", ApplyTo = TagApplication.All, Type = TagType.Misc };
        var tag4 = new Tag() { ID = 4, Name = "Helipad", ApplyTo = TagApplication.All, Type = TagType.Vip };

        context.Tags.AddOrUpdate(x => x.ID,
            tag1, tag3, tag4
        );

        var indicatorIcon1 = new IndicatorIcon() { ID = 1, VisualClass = IndicatorIcon.VisualClassType.Hidden, Name = "No Indicator Icon", Description = "Nothing special, just a regular place or event." };
        var indicatorIcon2 = new IndicatorIcon() { ID = 2, VisualClass = IndicatorIcon.VisualClassType.Fire, Name = "Hot", Description = "This place or event is very popular at the moment. There are big parties and a big fuss around it." };
        context.IndicatorIcons.AddOrUpdate(x => x.ID,
            indicatorIcon1, indicatorIcon2
        );

        AddUserAndRole(context);
    }

    bool AddUserAndRole(ApplicationDbContext context)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        var identityResult = roleManager.Create(new IdentityRole("Admin"));

        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        var user = new ApplicationUser()
        {
            UserName = "myinsidr@gmail.com",
        };
        identityResult = userManager.Create(user, "Qwertz1234!");
        if (identityResult.Succeeded == false)
            return identityResult.Succeeded;

        identityResult = userManager.AddToRole(user.Id, "Admin");
        return identityResult.Succeeded;
    }
}

(I've found questions and solutions related to seed method issue only for direct deployment from Visual Studio, but that's not the way I would like to go.
Also there are solutions using different SQL management projects, but I think code first migrations inside the MVC project is the cleanest solution if it works like on my local machine)

A: I have found out how to run the Seed method every server start using this technique: http://romiller.com/2012/02/09/running-scripting-migrations-from-code/
Running Seed at every server start is pretty good for me, since it will run after every build by Azure Continuous Deployment. Of course it will run in other cases as well, but my method is not too long, so it does not matter.
I put the following code to Global.asax --> Application_Start():
var migrator = new DbMigrator(new Configuration());
migrator.Update();

As
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    // CODE FIRST MIGRATIONS
    #if !DEBUG
       var migrator = new DbMigrator(new Configuration());
       migrator.Update();
    #endif
}

What this does is basically running a Code First Migration at every server start.


text:
Q: Terminal based file browser, à la mocp I'm looking for a file browser from the terminal. Ideally, a program that looks and feels like mocp (music on console player) dedicated to file browsing. Repeatedly typing in 'cd' and 'ls' in the terminal is too irksome. Also, I'm sick of aliasing commands to cd to specific highly-used folders in my filesystem.
Recommendations? I'm using Ubuntu 12.04 LTS. My terminal is bash.

A: I'm sure you'll find midnight commander very useful.
In ubuntu you should be able to install it with:
apt-get install mc

A: There are many console-based file manager, mc as Luis said above, and ranger, vifm, lfm, and many-many other.


text:
Q: How do I detect in the Windows Registry if a user has Crystal Reports installed I'm using Inno Setup to create an installer and I am unable to tell whether a user has installed the CR. I'm looking like this:
[Code]
//Check for Crystal Reports
function CheckForCrystalReports: Boolean;
var
  regresult: Cardinal;
begin
  RegQueryDWordValue(HKLM, 'SOFTWARE\SAP BusinessObjects\Suite XI 4.0\Installer\CRV','Install',regresult);
  Result := regresult = 0;
end;

[Run]
Filename: "{app}\CRViewer.exe"; Parameters: "q:a /c:""C:\Users\paulo.romeiro\Desktop\New folder\Crystal Reports 2010""install /l /q"""; Check: CheckForCrystalReports; StatusMsg: Instalando o Crystal Reports Viewer

thanks!!


text:
Q: How to change UIPageViewController direction of paging curl animation I need to display Arabic (Right To Left) content and couldn't find any method to rotate animation of the page curl found by UIPageViewController because basically Arabic books should be turned from Left to right.

A: If you are supporting only portrait mode then you should look at the UIPageViewController delegate method pageViewController:spineLocationForInterfaceOrientation: and return UIPageViewControllerSpineLocationMax.
But if you want to support both landscape and portrait then you could keep the default spine location animations but provide the pages in the opposite direction than requested like this
In the : pageViewController:viewControllerBeforeViewController: return the next page
and in the : pageViewController:viewControllerAfterViewController just return the previous one.


text:
Q: Call MySQL Stored Procedure in a C application giving an error I want to use CURSOR of MySQL in an application written in C.
I created a stored procedure
CREATE PROCEDURE curdemo(IN id INT)
BEGIN
    DECLARE a INT;
    DECLARE flag BOOL DEFAULT FALSE;
    DECLARE done INT DEFAULT FALSE;
    DECLARE cur1 CURSOR FOR SELECT test.Cars.Id FROM test.Cars;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN cur1;

    read_loop: LOOP
            FETCH cur1 INTO a;
            IF done THEN
                    LEAVE read_loop;
            END IF;

            IF flag THEN
                    SELECT test.Cars.Price FROM test.Cars WHERE test.Cars.id = a;
                    LEAVE read_loop;
            END IF;

            IF a = id THEN
                    SET flag = TRUE;
            END IF;
    END LOOP;

    CLOSE cur1;
    END//

Here is my table named Cars in database test
+------+------------+--------+

| Id   | Name       | Price  |

+------+------------+--------+

|    1 | Audi       |  52642 |

|    2 | Mercedes   |  57127 |

|    3 | Skoda      |   9000 |

|    4 | Volvo      |  29000 |

|    5 | Bentley    | 350000 |

|    6 | Citroen    |  21000 |

|    7 | Hummer     |  41400 |

|    8 | Volkswagen |  21600 |

+------+------------+--------+

When I am using the following query from a C application I am getting result = NULL and hence Segmentation fault only when id = 8 otherwise it works fine
 snprintf(statement, 100, "CALL curdemo('%d')", id);
    // Call stored procedure query
    if ( mysql_query(device_table_conn, statement) )
    {
            error_function(device_table_conn);
            //return 1;
    }

    result = mysql_use_result(device_table_conn);

mysql_use_result() returns a NULL if an error occurred.
But it should not return a NULL if CALL returns a NULL or empty result.

A: Finally got it.
Follow the steps given for handling multiple statements:
https://dev.mysql.com/doc/refman/5.0/en/c-api-multiple-queries.html
Here is the code
    snprintf(statement, 100, "CALL curdemo('%d')", id);
    if ( mysql_query(device_table_conn, statement) )
    {
            error_function(device_table_conn);
            //return 1;
    }

    do{
            // did current statement return data?
            result = mysql_store_result(device_table_conn);
            if (result)
            {
                    // yes; process rows and free the result set
                    num_fields = mysql_num_fields(result);

                    while ((row = mysql_fetch_row(result)))
                    {
                            for ( i = 0; i < num_fields; i++ )
                            {
                                    printf("%s\n", row[i]);
                            }
                    }

                    mysql_free_result(result);
            }
            else
            {
                    mysql_free_result(result);
            }
            // more results? -1 = no, >0 = error, 0 = yes (keep looping)
            if ((status = mysql_next_result(device_table_conn)) > 0)
            {
                    ;
            }
    } while (status == 0);

    mysql_close(device_table_conn);

Here it does not return anything for any wrong id (not exist in table) and when id = 8.

A: Your read_loop logic is ... interesting.
So let's walk through it:

*

*You fetch from the cursor into a;

*You test your done flag;

*You test your flag flag;

*You test the value of a against id and set flag

*You fetch from your cursor again, overwriting the value of a;

*You test your done flag;

*You test your flag flag, which is now true, at which point you do the select, but against the wrong value of a.

When your input id is 8, you wind up fetching past the last row in the table, which is why I think you're getting the null result.
You need to test the value of a against id before doing anything else:
read_loop: LOOP
        FETCH cur1 INTO a;
        IF done THEN
                LEAVE read_loop;
        END IF;

        IF a = id THEN
                SET flag = TRUE;
        END IF;

        IF flag THEN
                SELECT test.Cars.Price FROM test.Cars WHERE test.Cars.id = a;
                LEAVE read_loop;
        END IF;

END LOOP;

EDIT
I have to ask, why not just fetch the price for the specified ID, call mysql_store_result(), and then call mysql_num_rows() to see if the query actually returned anything?  If you are fetching against a specific row key, then your result set will only ever be 0 or 1 rows, so there shouldn't be an issue with storing it immediately.
Either that, or execute a select count(*) from cars where id = :id; first and only proceed if the result > 0.


text:
Q: boolean for loading different data l am working on ionic 4 project. My project is getting data json from url content flights schedules . l did button boolean when users click on button shows different data form data url in same page . When l click l got same data it is not change
  Loadearlierflights : boolean = true;

      async getData() {

        const loading = await this.loadingController.create({
          message: 'Loading'
        });
        await loading.present();

          /// flights details for today ///

        if (this.Loadearlierflights===true) {
          this.http.get('xxxxxxx/airport.json?code=bsr', {}, {})
          .then(data => {

            this.test = JSON.parse(data.data);
            const parsed = JSON.parse(data.data);
            this.items = parsed.pluginData.schedule.arrivals.data;
            loading.dismiss()

            console.log(this.items)

          }), err=>{
            this.test =err
            loading.dismiss()
          }

                   /// flights details for yesterday ///

        }else if (this.Loadearlierflights===false) {
          this.http.get('xxxxxxxx/airport.json?code=bsr&page=-1', {}, {})
          .then(data => {

            this.test = JSON.parse(data.data);
            const parsed = JSON.parse(data.data);
            this.items = parsed.pluginData.schedule.arrivals.data;
            loading.dismiss()

            console.log(this.items)

          }), err=>{
            this.test =err
            loading.dismiss()
          }

        }

html
<ion-button shape="round" (click)="getData()">load earlier flights</ion-button>

<ion-item *ngFor="let item of items" >

              item?.flight.airline.name

            {{item?.flight.identification.number.default}}
            {{item?.flight.airport.origin.position.region.city}}
            {{item?.flight.time.scheduled.arrival  * 1000 | date:"h:mma"}}

            {{item?.flight.aircraft.model.code}}
            {{item?.flight.status.generic.status.text|Status}}

      </ion-item>

any ideas please ?

A: There is mistake in if-else
use If as shown below
if (this.Loadearlierflights)
or
if (this.Loadearlierflights === true)

Use else-if as shown below
else if (this.Loadearlierflights)
or
else if (this.Loadearlierflights === false)

A: Maybe make your template's click to point to a new method:
async getEarlierFlightData() {
    this.Loadearlierflights = false;
    await this.getData():
    this.Loadearlierflights = true;
};

A:   Loadearlierflights : boolean = true; // should me global

      async getData() {

        const loading = await this.loadingController.create({
          message: 'Loading'
        });
        await loading.present();

          /// flights details for today ///

        if (this.Loadearlierflights===true) {
          this.http.get('xxxxxxx/airport.json?code=bsr', {}, {})
          .then(data => {

            this.test = JSON.parse(data.data);
            const parsed = JSON.parse(data.data);
            this.items = parsed.pluginData.schedule.arrivals.data;
            loading.dismiss()

                // Added this
                this.Loadearlierflights = false;

            console.log(this.items)

          }), err=>{
            this.test =err
            loading.dismiss()
          }
                   /// flights details for yesterday ///

        }else if (this.Loadearlierflights===false) {
          this.http.get('xxxxxxxx/airport.json?code=bsr&page=-1', {}, {})
          .then(data => {

            this.test = JSON.parse(data.data);
            const parsed = JSON.parse(data.data);
            this.items = parsed.pluginData.schedule.arrivals.data;
            loading.dismiss()

            console.log(this.items)

          }), err=>{
            this.test =err
            loading.dismiss()
          }

        }

Let me know if it works.


text:
Q: RegEx that matches a word that NOT succeeds another one How could a JavaScript RegEx be written, so that it matches for example the word cube, but only if the word small is not present in the 20 character range before this word.
RegEx should match:

*

*cube

*red cube

*wooden cube

*small................cube
RegEx should not match:

*

*small cube

*small red cube

*small wooden cube

*..........small......cube

*any sphere
Currently my regex looks and works like this:
> var regex = /(?:(?!small).){20}cube/im;
undefined
> regex.test("small................cube")     // as expected
true
> regex.test("..........small......cube")     // as expected
false
> regex.test("01234567890123456789cube")      // as expected
true
> regex.test("0123456789012345678cube")       // should be `true`
false
> regex.test("cube")                          // should be `true`
false

There must be 20 characters in front of cube, where each is not the first character of small.
But here is the problem: If cube appears within the first 20 characters of a string, the RegEx does not match of course, because there are not enough characters in front of cube.
How can the RegEx be fixed, to prevent these false negatives?

A: You can use this regex:
.*?small.{0,15}cube|(.*?cube)

And use matched group #1 for your matches.
Online Regex Demo

A: I have investigated about this since it seemed to be easy but it was definitely more difficult as I thought.
My idea was to try a negative lookbehind regex like:
(?<!small).{0,20}cube

But this didn't work and of course javascript doesn't support negative lookbehind.
So, I was trying a different technique and it could solve many cases like the following:
cube                      -> match
red cube                  -> match
wooden cube               -> match

small cube                -> not matched
small red cube            -> not matched
small wooden cube         -> not matched
..........small......cube -> not matched
any sphere                -> not matched

The idea is to do the following:
var newString = "cube" // <-- Change here the string your want to test
    .replace(/(small)?.{0,20}cube/g, function ($0, $1) { return $1?$0:"[match]"; });

and then compare newString to [match]. If it is different then your string didn't match.
I have struggled with some cases that should match but didn't, like:
small................cube
small.......cube

There is something wrong with .
I know that this doesn't fully answer to your question, but I wanted to share with you this approach since community can see this and help improving the answer, or give ideas to provide better answers


text:
Q: .htaccess mod_rewrite exchange random word for folder name I am trying to get the following url entered into the address bar:
http://localhost/ci/page/random/3
random could be anything, but will be the page title and used only for SEO purposes.
 and 3 could be any numeric value, but is used to retrieve a db record.
to be rewritten as this
http://localhost/ci/page/index/3
I tried the following in the .htaccess but didn't work:
RewriteRule ^(?)$ /page/index/$1 [L]
here is my htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
RewriteRule ^page$ /index/$1 [L]
RewriteRule ^(?)$ /page/index/$1 [L]

A: Because I couldn't get this to work the way i wanted, I changed the URL structure from:
http://localhost/ci/page/random/3
to
http://localhost/ci/page/3/random
No 404 any more :-)


text:
Q: jQuery templating to display JSON data into formatted HTML I was having difficulty displaying some json data with use of query template:
Here is my code:
This is the json:
{
    "title": "The ppt presenation",
    "date_created": "9242010",
    "last_modified": "9242011",
    "author": "Mistic Frenzies",
    "slides": [
        {
            "Slide": "1",
            "header": "sdfsdf",
            "src": "ghkkgh.jpg",
            "Content": [
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                }
            ]
        },
        {
            "Slide": "2",
            "header": "sdfsdf",
            "src": null,
            "Content": [
             {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                }
            ]
        },
        {
            "Slide": 3,
            "header": "dsggd",
            "src": "sdfsdf.jpg",
            "Content": [
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                },
                {
                    "bullet": ""
                }
            ]
        }
    ]
}

Here is the JavaScript:

Powerpoint

So, I am not sure what is wrong. When I click on the html link to display the data, nothing appears. I am wondering if the template I created is faulty. Any suggestions?

A: code seems fine. i think getJSON taking longer to return info and your code is executing appendTo command before it finishes. you can use deferred in jquery (i.e. when....then) or use $.ajax and use its success method to template over info like below:
   $.ajax({
            type: "POST",
            url: 'ppt.json',
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (info) {
                 $('#header').empty();
                $('#ititemplate').tmpl(info).appendTo('#header');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //failure function goes here..
            }
        });

hope it helps.


text:
Q: Stopping GoogleApiClient location updates Welcome,
I'm writing an app to send a location sms when an activity is triggered. I am using GoogleApi to determine the location of the device.
The location is only to be sent once, and after that I would like the location not to be downloaded anymore to save resources.
With this in mind, I have two questions:

*

*How do I download the location update information? I have the following problem, that if I put the SMS sending function in onResume(), the app was sending an empty string because the location didn't manage to update. When I put the whole send routine in onLocationChanged(), the SMS was sent every time the location was updated. I've solved this for now with a send flag that allows one SMS send, but I'm sure it can be done better and more efficiently.

*how do I stop the location update after the SMS is sent? I have tried using mGoogleApiClient.disconnected(), but to no avail. I've tried putting this call in onPause() so that the location is stopped when the activity exits, but it also didn't have the desired effect. For now, I solved this by destroying the entire activity by calling onDestory() in onPause() - solution not correct, but the location no longer updates.

Here is the sending procedure in onLocationChanged()
@Override
    public void onLocationChanged(Location location) {
        locLong = String.valueOf(location.getLongitude());
        locLat = String.valueOf(location.getLatitude());
        Log.i("wiad ", locLong + "  " + locLat);
        updateMessage();
        if(LOC_UPDATE == 0){
            sendLocationSMS(name_1, name_2, name_3, phone_1, phone_2, phone_3);
            LOC_UPDATE = 1;
        }

    }

And here is a clumsy solution for cancelling updates by destroying activity:
@Override
    protected void onPause(){
        super.onPause();
        mGoogleApiClient.disconnect();
        onDestroy();
    }

Thank you for any hints of solutions.


text:
Q: How to split a line on comma, ignoring commas within quotes? I have a file with many lines like so:
1,50,"asasd",25
2,51,"apa,asdfi",26
.....
.....

How do I split the second line by comma skipping the comma inside the string inside the double quotes?
I need the result for second line as :
[2,51,"apa,asdfi",26]

Currently I am trying:
x = line.split(',')

The result is like :
['2','51','"apa','asdfi"','26']

A: As said in comment, try to read your file as a .csv, it will do great with the coma inside the string.
If you have trouble using it, you can read the doc https://docs.python.org/2/library/csv.html orsee some examples there https://dzone.com/articles/python-101-reading-and-writing
import csv

with open(file.csv,'r') as f:
    spamreader = csv.reader(f,delimiter=",")
    for row in spamreader:
        # a row is a list containing all elements in a line
        print row

result:
['1','50','"asasd"','25']
['2','51','"apa,asdfi"','26']

A: You can also extract them with re.findall:
>>> s = '2,51,"apa,asdfi",26'
>>>
>>> re.findall(r'(\d+|".*")', s)
['2', '51', '"apa,asdfi"', '26']

Though I do recommend the method mentioned in the dup

A: You can try the following code:
line = '2,51,"apa,asdfi",26'
result = line.split(",")

length = len(result)
for i in range(length):
    if '"' in result[i]:
        result[i] += "," + result[i+1]
        result.remove(result[i+1])
        break

length = len(result)
for i in range(length):
    if result[i].isdigit():
        result[i] = int(result[i])

print(result)

Output:
[2, 51, '"apa,asdfi"', 26]


text:
Q: Networking on IOS using Alamofire I'm an IOS developer. I have a new client who wants me to teach him about Alamofire and the networking stuff, and to be honest, i'm bad at teaching.
so, can anyone suggest me a book or any tutorial that i can follow during the lecture?
thanks in advance.

A: Alamofire

*

*https://www.raywenderlich.com/35-alamofire-tutorial-getting-started

*https://codewithchris.com/alamofire/

*https://learnappmaking.com/alamofire-swift-tutorial/
iOS Networking

*

*https://learnappmaking.com/urlsession-swift-networking-how-to/

*https://www.udacity.com/course/ios-networking-with-swift--ud421
Don't forget to check out official documentation as well.


text: Q: C++ How to deal with Invalid Pointers/Zero Pointers I was given an integer pointer (passed through a function) which I can't modify that can possibly point to invalid memory or is a zero-pointer. I need to know if there's a way to check whether or not the pointer is pointing to invalid memory. Are there any ways I can do this?


text:
Q: is it possible to have InterProcess communication in Java? I have two Java Programs each running in its own JVM instance ? Can they communicate with each other using any IPC technique like Shared Memory or Pipes ? Is there a way to do it ?

A: Yes; D-BUS and Pipes are both easy to use, and cross-platform. D-BUS is useful for general message-passing IPC, and pipes for sending bulk data.
You can also open a TCP or UDP socket on localhost, if you need to support multiple clients connecting to a central server.
I also found an implementation of UNIX sockets in Java, though it requires the JNI.

A: http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp
Java Remote Method Invocation (Java RMI) enables the programmer to create distributed Java technology-based to Java technology-based applications, in which the methods of remote Java objects can be invoked from other Java virtual machines*, possibly on different hosts. RMI uses object serialization to marshal and unmarshal parameters and does not truncate types, supporting true object-oriented polymorphism.

A: Sure. Have a look at RMI or a Shared Memory concept like Java Spaces.

A: Use MemoryMappedByteBuffer in Java NIO for sharing memory between processes.

A: There is a fairly new initiative for language-agnostic IPC of columnar (i.e. array-based) data from Apache called Plasma.
As of yet (Sept '17) there are no JVM bindings, but as the project is backed by the likes of Spark, I think it won't be long before we see an implementation.
My understanding however is that there is not a general IPC system, as it is geared toward sharing arrays of primitives like double,long, for scientific computing, rather than classes/objects; though I could be wrong here.
On the plus side, it's also language-agnostic, so you could use it to communicate with another (non-JVM) runtime. However, the OP did ask for Java IPC so this could be irrelevant.


text:
Q: Change public DNS on EC2 Instance I have an EC2 Ubuntu instance running a website. I also have a domain hosted with GoDaddy. I have setup a Elastic IP address which points to my instance. I have setup my domain in GoDaddy to point to the Elastic IP. This works and entering my domain takes me to the site host on amazon. But after the site loads the URL switches from:
www.mydomain.com

to the aws public DNS:
ec2XX-XXX-XXX-XXX.compute-1.amazonaws.com

I want the domain to stay as my domain and not switch to the aws public dns. I contacted GoDaddy support and they told me that this was happening on Amazons end so I must need to fix it somewhere in the aws dashboard. Can someone please give me the steps to get this setup or point me in the right direction.

A: The issue was that the Bitnami Magento installation needed to be updated to the new web address. To do this you ssh into the webserver and then:
Moving the application to /
 If your application is running in "/magento" you can remove the prefix from the URL executing the following command:
$ sudo /opt/bitnami/apps/magento/bnconfig --appurl /

(use --help to check if that option is available for your application)
Now you will be able to access to the application at http://YOUR_DOMAIN instead of http://YOUR_DOMAIN/magento.
Updating the IP or hostname
Some applications require to update the IP/domain if the machine IP/domain changes. The bnconfig tool also has an option which updates the IP automatically during boot, called machine_hostname (use --help to check if that option is available for your application). Note that this tool changes the URL to http://NEW_DOMAIN/magento.
sudo /opt/bitnami/apps/magento/bnconfig --machine_hostname NEW_DOMAIN

If you already moved your application to the root URL you should include both options at the same time.
sudo /opt/bitnami/apps/magento/bnconfig --appurl / --machine_hostname NEW_DOMAIN

If you have configured your machine to use an static domain name or IP, you should rename or remove the "/opt/bitnami/apps/magento/bnconfig" file.
sudo mv /opt/bitnami/apps/magento/bnconfig /opt/bitnami/apps/magento/bnconfig.disabled

After all that, just reboot apache and your should be good to go.


text:
Q: Number of Combinations to make change with coins We have unlimited coins of different values - Calculate the unique combinations of how these coins can make up a specific amount. For example:
n = 4 (say, 4 cents)
coins_list = [1,2] - we have 1-cent coins, and 2-cent coins
The different combinations would be 112, 1111, and 22. (121 and 211 should be excluded since it's not unique - using one 2-cent coin and two 1-cent coin)
I have watched this video: https://www.youtube.com/watch?v=k4y5Pr0YVhg
countless number of times, and edited my codes countless number of times, but I cannot manage to get rid of the same combination of different orders.
 def make_change(n, coinlist_index=None):
    coin_list = [1, 2]

    if coinlist_index == None:
        coinlist_index = 0
#coin index position in coin_list; starts at index 0 and cycles through all the coins

    if n == 0:
        return 1

    if n < 0:
        return 0

    ways = 0

    # if I use for i in range(len(coin_list)), it returns an error message saying that index is out of range
    for coinlist_index in range(len(coin_list)):
        ways += make_change((n - coin_list[coinlist_index]), coinlist_index)
        coinlist_index += 1

    return ways

make_change(4)

Output: 5
My output was 5 (different ways to make change for 4 cents with 1 and 2-cent coins), instead of 3 (which is what I want).
I'm sure it has to do with the for loop toward the end, but when i change "for coinlist_index in range..." to a different iterator, i, I get an error that says index is out of range.
What is going on, and more importantly, how can I fix it?
EDIT: P.S. This is just a simple example that I'm working through to solve the actual assignment - Which is with 6 types of coins, in cents, (1, 5, 10, 25, 50, 100), and calculate how many ways to make change for 200 dollars. I have seen and tried the dynamic programming method out there, which worked, but we have to use recursion for assignment purposes.

A: I feel 5 is actually the correct answer.
1 1 1 1
1 1 2
1 2 1
2 1 1
2 2

Or if you want distinct result, you may store results in the list and remove the duplicate result.
def make_change(n, coinlist_index=0):
    coin_list = [1, 2]

    if n == 0:
        return [[]]

    if n < 0:
        return []

    ways = []

    for coinlist_index in range(len(coin_list)):
        res = make_change((n - coin_list[coinlist_index]), coinlist_index)
        ways += list(map(lambda x : x + [coin_list[coinlist_index]], res))

    return ways

def remove_dup(lolist):
    res = []
    for lst in lolist:
        lst.sort()
        if lst not in res:
            res.append(lst)
    return res

print remove_dup(make_change(4))

A: Looks like I got it working.  In each recursive pass you want to make sure that you aren't double counting possible ways to make the change.  My thought to do this was to make sure that you never go backwards in the coin_list.  So for the coin_list [1,2] if we ever use the 2 cent coin we never want the option to use the 1 cent coin afterwards.  I made sure it follows this order by changing your for loop a bit:
for i in range(len(coin_list)-coinlist_index):
    ways += make_change((n - coin_list[i+coinlist_index-1]), coinlist_index)

In the for loop I subtracted coinlist_index from the upper bound so we don't cycle over all coins once the index reaches 1, then added the index to where you pull from the coin_list, making sure once coinlist_index is 1 or more, we NEVER usecoin_list[0]. This got me to 3 in your sample case, hopefully it works for all cases.  Full code:
def make_change(n, coinlist_index=None):
    coin_list = [1, 2]

    if coinlist_index == None:
        coinlist_index = 0
#coin index position in coin_list; starts at index 0 and cycles through all the coins

    if n == 0:
        return 1

    if n < 0:
        return 0

    ways = 0

    # if I use for i in range(len(coin_list)), it returns an error message saying that index is out of range
    for i in range(len(coin_list)-coinlist_index):
        ways += make_change((n - coin_list[i+coinlist_index-1]), coinlist_index)
        coinlist_index += 1

    return ways

print(make_change(4))


text: Q: How do I segmentate dirty 7-seg LCD with reflections The LCD display cannot be cleaned, the light conditions cannot be changed and the background can be tricky. So, I cannot use any kind of segmentation by color, search for rectangles and use Otsu. MSER doesn't give a good result. I even tried to locate display relatively to "DEXP" logo. The logo turned out to be too small to do this with sufficient accuracy. Bilateral filtering or gaussian blur helps, but not much. Even supposing that I found ROI, local thresholding gives too noisy results. Morphological transformations don't help. Is there a way to extract digits for further OCR?


text:
Q: ListBox on change event, with one item I am using asp.net listBox, with the attribute rows=1.
I want that when I select an item in the listBox, the "onchange" method will call a javascript function.
The problem is that the "onchange" method doesn't start if I select the first item in the list box. I think that's because it's selected by default.
do you know any solution?
thanks


text:
Q: C++: Clean way to create a std::map of function pointers I want to create a shared library, which just contains a std::map to look up function pointers. The purpose is to merge several static libraries (plugins), which all offer the same type function.
Each plugin has an unique integer id.
However, only libraries which are available at compile time should be collected. Currently i am using a mix of cmake and the c++ preprocessor:
CMakeLists.txt:
if(EXISTS ${plugin1})
    message("found plugin1")
    include_directories(${plugin1}/include)
    add_definitions(-DPLUGIN1)
    find_library(plugin1Lib plugin1 ${plugin1}/lib)
    target_link_libraries(${PROJECT_NAME} ${plugin1Lib})
endif()

shared library:
#ifdef PLUGIN1
    #include "plugin1.h"
#endif

static std::map<int, pluginFunctionPtr> userPlugins= {
    #ifdef PLUGIN1
    {20, funcPlugin1} ,
    #endif
};

It works well, but i think it's really complicated. Is there a better way to achieve what i want?
Thank you!


text:
Q: multiple-value http.PostForm() in single-value context in go While using net/http and net/url for single key value I am getting this error
multiple-value http.PostForm() in single-value context

A: Your error possibly caused by single-value assignment — PostForm (both for Client and Response) returns (resp *Response, err error) (value and an error), so you need to do something like:
resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})

while you doing (my suggestion)
resp := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})


text:
Q: Process finished with exit code 1 : Unknown AVD name I have the following error that pops up when I try to run the emulator:

Emulator: emulator: ERROR: Unknown AVD name [Nexus_5X_API_27], use
  -list-avds to see valid list.
Emulator: Process finished with exit code 1

Given that I just created the avd, can you help me understand why it cannot find it and how to solve this problem?
Thanks in advance

A: When you create the AVD with Android Studio it's created in root location but our Android SDk location is set on somewhere in HOME. So you just need to move your avd folder from root location to home location path.
Root location path:

/root/.android/avd

Home location path:

/home/USERNAME/.android/avd

You don't need to keep avd folder on both the location because whenever you run your app on avd from Android Studio it's always looking it on HOME location.

A: I was having the same issue. but I did the below
I copied the folder C:\Users\USER_NAME\.android\avd and pasted inside the folder where the Sdk file located i.e  C:\Users\USER_NAME\AppData\Local\Android\Sdk and finaly it worked fine for me

A: I experienced the same issue, regardless of the AVD.  I'm too new to understand why, but it seems that Android Studio created /.android/avd directories in two locations:

*

*/root/.android/avd

*/home/USERNAME/.android/avd
The .avd and .ini created when creating a new AVD were stored in the 1st location, and the 2nd location was empty.  To resolve it, I copied and pasted both the .avd and .ini files for each AVD from 1 to 2 (they needed to be in both in order for AS to see and run the AVD).  The emulator then ran successfully.

A: I had the same issue working with Android Studio in Win64. I have tried all the above suggested solutions, but none of them worked i.e., even after config changes the emulator was in error state throwing the same error.
However, after reverting back all the config changes and restarting the Android Studio fixed the error. The emulators are up and running. To be honest, there is no custom environment variables defined.
Only exception in my case is, the .ini files are getting created/stored in the $USER_HOME/.android/avd/ directory.
Adding my answer as it may help someone who is facing the similar issue.

A: Why this happened?
When you try to start the avd, android studio will find the Nexus_5X_API_27.ini in $ANDROID_SDK_HOME/avd/. But when you create the avd by android studio, the Nexus_5X_API_27.ini is been put into $HOME/.android/avd/. So android studio can not find the ini file to start the avd.
Resolution
Copy the Nexus_5X_API_27.ini from $HOME/.android/avd/ to $ANDROID_SDK_HOME/avd/ will solve the problem.

A: For windows users, see the ANDROID_SDK_HOME path,then check the ANDROID_SDK_HOME/avd/,is there that Emulator(you just created) existed?If there's not existed,then copy the emulator.avd and emulator.ini files in ANDROID_SDK_HOME/.android/avd/ to  ANDROID_SDK_HOME/avd/, finally it did worked!

A: There are actually several environment variables that you can set:

*

*ANDROID_SDK_HOME

*ANDROID_EMULATOR_HOME (default is $ANDROID_SDK_HOME/.android/)

*ANDROID_AVD_HOME (default is $ANDROID_EMULATOR_HOME/avd/)

See https://developer.android.com/studio/command-line/variables
The default location of the Android SDK is your home directory, which depends on your operating system. For instance, on Windows it's C:\Users\*Owner*\AppData\Local\Android\Sdk.
If you have moved your home directory to a different disc, you can use the environment variables mentioned above to adjust the paths on a as-needed basis.

A: Deleting C:\Android\android-sdk and reinstalling android studio fixed this for me.

A: If your Android Studio create AVDs in the ~/.android/avd directory, here are the step by step instructions:

*

*Open control panel

*Then go to System

*Then go to Change Environment Variables of the User

*Then click create a new environment variables

*Create a new variable named ANDROID_SDK_HOME

*Set its value to your Android directory, like C:/users//.android


text:
Q: How to get syslinux to install to fat32 backup boot sector How do you get syslinux to install to fat32, and have it write the backup boot sector. It only writes to the main boot sector, and then fsck.fat complains. You can get fsck.fat to fix it, but this requires running it in interactive mode, and hence is not possible from a script.
/tmp # fallocate -l 50m test_image
/tmp # mkfs.fat -F32 test_image
mkfs.fat 4.1 (2017-01-24)
/tmp # syslinux --directory syslinux --install test_image

/tmp # fsck.vfat test -a
fsck.fat 4.1 (2017-01-24)
There are differences between boot sector and its backup.
This is mostly harmless. Differences: (offset:original/backup)
  3:53/6d, 4:59/6b, 5:53/66, 6:4c/73, 7:49/2e, 8:4e/66, 9:55/61, 10:58/74
  , 90:fa/0e, 91:fc/1f, 92:31/be, 93:c9/77, 94:8e/7c, 95:d1/ac, 96:bc/22
  , 97:76/c0, 98:7b/74, 99:52/0b, 100:06/56, 101:57/b4, 102:1e/0e, 103:56/bb
  , 104:8e/07, 105:c1/00, 106:b1/cd, 107:26/10, 108:bf/5e, 109:78/eb
------------ SNIP ---------------------------------------------------------
  , 484:0d/00, 485:0a/00, 504:fe/00, 505:02/00, 506:b2/00, 507:3e/00
  , 508:18/00, 509:37/00
  Not automatically fixing this.
test: 2 files, 353/100792 clusters

A: According to https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system :
For FAT32 file systems, the reserved sectors include a File System Information Sector at logical sector 1 and a Backup Boot Sector at logical sector 6
Which means that you can fix the issue by invoking these two commands (replace sdXX with your partition, e.g. sdb1):
sudo dd if=/dev/sdXX of=bootrec.dat bs=512 count=1
sudo dd if=bootrec.dat of=/dev/sdXX bs=512 seek=6

In case you're working with a disk image file, you must add conv=notrunc,nocreat parameters at the end of the second command or otherwise you will truncate and destroy the image.
I've tested the commands and they result in fsck.vfat being totally happy.


text:
Q: Zorin/Windows 7 Dual Boot on New Hard Drive, no GRUB! So my computer had Windows 8 originally, and my hard drive died. I was able to get a dying hard drive from work to use temporarily, and decided to go with Windows 7 this time, as HP had drivers for it.
Before I even got it installed, this hard drive completely died. For about a week, I used a Zorin 8 live disc, and found I really liked it a lot. I bought a new 500 gb hard drive today, and got Windows 7 installed and running perfectly. I then shrunk the partition to allow for about 70 gb for a Zorin dual boot, and installed Zorin to that with 1 gb swap.
When I rebooted, it directly started loading up Windows. Since I had OS Boot Manager set as the first boot device, I restarted and tried booting from "Notebook Hard Drive", which gave me a "No bootable device-please insert boot disk and press any key to continue".
Windows 7 boots with no problems.
I've tried using EasyBCD in every way possible for GRUB2 to get it to show up in the Windows boot menu, but it just leads to a "NeoGrb.mbr (or something) is missing/corrupt".
I'm also very new to Linux, and have no *nix terminal knowledge. If someone could be kind enough to suggest what I assume is most likely a simple solution that I am overlooking, I'd be eternally grateful, as I've been trying to get this work for the past 9 hours with no luck.
Also, everything is in Legacy Mode, and the installer does NOT recognize an existing Windows 7 installation.

A: I keep re-installing windows versions on my dual-boot machine for... science and... stuff... you know, so every time I install Windows I lose my bootloader and I have to install it again. Since your OS is Ubuntu-based, these steps may work:

*

*First of all, you need to boot with a live image of Zorin on your computer.

*Then you need to know in which partition Zorin is installed. Issue the fdisk -l command to list all drive's partitions. Alternatively, you can use the gnome-disks app to know which partition is the one you're looking for.

*I'm going to assume that your Zorin partition is sda2, since you said you had Windows first, and then you shrunk your partition to leave space for Zorin.

*You then have to create a mountpoint for your partition, it's recommended that you mount it inside /mnt. For this we create a folder named zorin inside the /mnt directory with this command: mkdir /mnt/zorin. Of course you need to execute it as root, so you must precede it with sudo, or login as root with su, so you won't have to be writing sudo before everything.

*Proceed to mount your system on the mountpoint you've just created:

*

*mount /dev/sda2 /mnt/zorin

*mount --bind /dev /mnt/zorin/dev

*mount --bind /dev/pts /mnt/zorin/dev/pts

*mount --bind /proc /mnt/zorin/proc

*mount --bind /sys /mnt/zorin/sys

*Once mounted we change the root to your old system: chroot /mnt/zorin

*Then we install our beloved GRUB on the HDD: grub-install --boot-directory=/boot/ --recheck /dev/sda (you may see some warnings here, but as long as the command finishes normally there shouldn't be any problem).

*Proceed to update GRUB's configuration so you'd be able to see both OSs at boot: sudo update-grub2.

*Reboot your machine and boot to Zorin.

*Install and update GRUB's configuration once again in case you were running your image from an external HDD or an USB stick, by repeating steps 7 and 8.

In case you get errors, make sure you have the grub2 package installed (apt-get install grub2).
This guide is right here (Spanish).
Update:
This is how I prepare a system's HDD for dual-boot:

*

*Boot into a live image and start gparted.

*Create a new ms-dos partition table (it's almost universally compatible).

*Create the necessary partitions for the system:

*

*Create an ntfs partition for windows

*Create an ext4 and a swap partition for linux

*Reboot and install windows:

*

*When you're prompted for the drive to install windows, select the ntfs partition and delete it so it becomes free space, that way windows can create its necessary partitions at will, but this won't mess the partiton table.

*Once windows is installed, reboot to the linux installation media.

*Install the linux system into the partitions you designated for it.

If you're using different partitions for your home, boot and other directories, I suggest to create an extended partition then create all linux partitions inside.


text:
Q: No Machine Remote Desktop Issue I use the program No Machine to open up remote desktops to my development servers. I choose No Machine because the client software reportedly runs on Windows/Linux/Mac, but I am having trouble with the Mac client.
When I startup the No Machine (also called NX) client, I get an error message saying "NX Client for MacOS/X was not able to find the Apple X11 Server. Please be sure that the Apple X11 bundle is installed in either the /Applications or the /Applications/Utilities directory and retry."
I have heard X11 is installed by default on Snow Leopard (I run Snow Leopard). I have the X11 app, when I open a terminal and type startx the X11 server appears to start up, but I get a message about a missing .serverauth file.
Any advice on how to get this working?

A: I installed the XQuartz application. It was in /Application/Utilities/XQuartz.app. I just renamed it from XQuartz.app to X11.app and everything works fine, so far.
Update: don't install XQuartz for use with No Machine. I opened a text editor and started typing, all the keys were screwy. For instance, the Delete key was now comma, all the letters were transposed, general chaos. I replaced XQuartz with the official X11User.dmg package and this keyboard problem went away. One more step I had to take: when on the remote desktop I tried to cd into a different directory, and hitting the "d" key kept showing me the desktop. If you want to cd, you will need to go into System->Preferences->Keyboard shortcuts. Scroll down, and notice an entry "Hide all windows and show desktop" which is mapped to "D". Change this to Alt+D or Ctrl+D and cd away!


text:
Q: Problems with the React components directory on Github So, I started a react project with the components directory named 'Components'
It was then renamed 'components' a few days later ...
Recently I have noticed on github that there are 2 directories, Components and components, both show active commits and seem to share the files between them.
On my text editor I can only see a components folder, on my mac finder I can only see a components folder ... I cant see a hidden file called Components ...
But its causing me issues when i rebase and it clearly exists, can anyone help ?


text:
Q: How can I break down table's cells on small screens? Here is my code:

.wrapper {
    border: 1px solid red;
    padding-left: 20px;
}

.table {
  display: table;
  width: 100%;
}

.table > div {
  display: table-cell;
  border: 1px solid green;
  min-width: 190px;
}

    share
    edit
    close

    edited May 21 16 at 11:58

      Rory O'Kane
      12.6k

    asked May 21 16 at 11:51

      vasanthkumarmani
      1

Please resize the page. As you see, green box comes out of the red box on a small screen.
Anyway I want to break down both div.author and div.editor together when the parent's width is smaller than childs' width. Is doing that possible?

A: What about this?

.wrapper {
    border: 1px solid red;
    padding-left: 20px;
}

.table {
  display: table;
  width: 100%;
}

.table > div {
  display: table-cell;
  border: 1px solid green;
  min-width: 190px;
}

@media screen and (max-width: 480px) {
  .table > div {
  display: table-cell;
  border: 1px solid green;
  min-width: 190px;
  float:left;
}
  .table > div:nth-child(1){
     clear: both;
  }
}

    share
    edit
    close

    edited May 21 16 at 11:58

      Rory O'Kane
      12.6k

    asked May 21 16 at 11:51

      vasanthkumarmani
      1

I used media queries and also nth-child of your table > div, I supposed it go overflow under 480px. I think is better for you to use display flex or bootstrap grid system  . For evry question I'm here.I hope you understand and also sorry for my english :)
Here a fiddle you can resize and see the difference : here

A: You can use display: flex instead of display: table.
To wrap editor and author divs together you can use the script below. It will be working even if you put your table into a div with restricted width.
JSFiddle

$(window).resize(function() {
  setTableDirection();
});

setTableDirection();

function setTableDirection() {
  var $table = $('.table');

  if ($table.width() <= 580) {
    $table.css('flex-direction', 'column');
  } else {
    $table.css('flex-direction', 'row');
  }
}
.wrapper {
  border: 1px solid red;
  padding-left: 20px;
}

.table {
  display: flex;
  flex-wrap: wrap;
}

.table>div {
  border: 1px solid green;
  min-width: 190px;
  flex-grow: 1;
}

      share
      edit
      close

      edited May 21 16 at 11:58

        Rory O'Kane
        12.6k

      asked May 21 16 at 11:51

        vasanthkumarmani
        1


text:
Q: Section of an invertible sheaf as a morphism between sheaves Consider an invertible sheaf $\mathscr L$ over a noetherian scheme $X$. I always knew that a local section of $\mathscr L$ is simply an element of $\mathscr L(U)$ whereas a global section, or simply a section, is an element of $\mathscr L(X)$.
Sometimes when I talk to people they say something like:

"a section is a morphism of sheaves $\mathscr O_X\to \mathscr L$"

Is it just a weird terminology or there is some kind of relatioships between the two concepts?

A: EDIT : I forgot the word "proper" in my example.
In this case the section people consider is the image of $1\in \mathcal{O}_X(X)$ which is an element of $\mathcal{L}(X)$.
This makes more sense when $X$ is a connected proper scheme over a field $k$ (e.g. a variety) : then as a consequence of Zariski's main theorem, $$\mathcal{O}_X(X)=H^0(X,\mathcal{O}_X)=k s_0$$
Then the image of $s_0$ is in $H^0(X,\mathcal{L})$.


text:
Q: two loops together in python File
sims 10 500
dettol 45 200
nims 200 540

Code:
for E, w in vb, T.readline():
    name, qty, price = w.split()
    print("you bought" + str(vb[E]) + "from" + name)

Description
I want to run two loop together, one for a file and one for an array. Also, the expected output for each iteration would be
>>> "you bought 1 from nims"

if "nims" has 1 quantity.
I used like to do
for i, k in j, T.readline:

but it's not working.

A: You haven't clarified what vb is, but I don't think that loop is doing what you think it does.  First, here's what it looks like to the interpreter:
for E, w in (vb, T.readline()):

This isn't going to take each element of vb and each line of T.  Instead, it's going to take vb and attempt to unpack it to E and w, and then do the same thing for T.readline() on the second iteration.  For example:
>>> a = (1, 2)
>>> b = (5, 6)
>>> for i, j in a, b: print(i, j)

1 2
3 4

Notice that it doesn't print the 0th element of a and b, but both elements of a followed by both elements of b.  If you wanted to combine them you would use zip:
>>> for i, j in zip(a, b): print(i, j)

1 3
2 4

Finally, T.readline() the way you are using it is not going to give you each line of T.  Rather, it's going to take the first line in T (assuming you don't read other lines prior to the loop) and iterate over the characters of that line.

A: You are probably looking for zip:
with open("test") as T:
    vb = [1, 2, 3]
    for E, w in zip(vb, T):
        name, qty, price = w.split()
        print("you bought {}  from {}".format(E, name))

Also note that there were two other errors in your code:

*

*you want to iterate all the lines in the file T, not the letters in the first T.readline()

*E is already the element from the list, not the index of that element

Note that in Python 2.x, zip will consume the entire file at once, so it that file is very large, you probably want to use itertools.izip instead, which creates an iterator. In Python 3.x, zip itself is an iterator.

A: In addition to paidhima's asnwer, you could maybe consider using enumerate() such as
for i,line in enumerate(T):
    print i, line

assuming that T is the name of your file. This would print
0 sims 10 500
1 dettol 45 200
2 nims 200 540

Is this what you want?


text:
Q: Correct configuration for SSL over 3 domains on same IP in nginx I have been working on this for several hours now, to no fruition. Right now I have three domains, for example domain1.com, domain2.org, and domain3.net. These domains are all using the same IP address.
domain1 and domain2 each have an individual SSL certificate from a trusted authority. domain3 has a self-signed certificate, which, while not ideal, is sufficient in this case (not that this should make any difference, I believe).
The problem is, the correct sites are being served when visited by domain, but when accessing via IP address, domain3 is served with domain3's certificate, and I can't for the life of me figure out how to get it to use domain1 instead... ideally any request made to the IP would be redirected to domain1.com.
Any help would be appreciated.

A: According to nginx documentation, you can specify which site will be the default one when there is no matching server name, this with the default_server parameter.
From the documentation :
server {
     listen      443 default_server;
     server_name example.net www.example.net;
    ...}

A: Add the IP address to the server_name for the server you want to serve it.


text:
Q: Logging SQL script errors I have a SQL script for postgres file with following command.
COPY product_master(productId, productName) FROM 'product.txt' DELIMITERS ',' CSV;

I want to handle errors of this command (log the error)
example

ERROR: duplicate key value violates.

Does the COPY command return any value ? If no, then how to log the output of the shell script?

A: You can log any and all messages (error, warning, ..) with a plethora of additional information in the database log file. This is standard behavior. Of course your database cluster has to be configured to do so. Read the fine manual here.
Dpending on your client you should also be able to get error messages as direct answer from the database server. Note that errors are reported on a different stream than data output. Like stout and stderr in the shell.
From the shell you would probably call psql -f to execute a script. See what happens in this demo:
Create a dummy SQL script in the shell:
vim test.sql

Put something like this into it:
CREATE temp table x (a int primary key, b int);
insert into x values (1,2),(3,4);
COPY x TO '/var/lib/postgres/dev/test.out';
COPY x FROM '/var/lib/postgres/dev/test.out';

Execute it:
psql mydb -f test.sql

Output depends on various settings like client_min_messages:
psql:test.sql:2: NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "x_pkey" for table "x"
CREATE TABLE
INSERT 0 2
psql:test.sql:4: ERROR:  duplicate key value violates unique constraint "x_pkey"
KONTEXT:  COPY x, line 1: "1    2"

Since I have configured log_statement = all (among others) my server log reads:
2011-11-15 22:36:23 CET postgres LOG:  statement: CREATE temp table x (a int primary key, b int);
2011-11-15 22:36:23 CET postgres LOG:  statement: insert into x values (1,2),(3,4);
2011-11-15 22:36:23 CET postgres LOG:  statement: COPY x FROM '/var/lib/postgres/dev/test.out';
2011-11-15 22:36:23 CET postgres ERROR:  duplicate key value violates unique constraint "x_pkey"
2011-11-15 22:36:23 CET postgres CONTEXT:  COPY x, line 1: "1  2"
2011-11-15 22:36:23 CET postgres STATEMENT:  COPY x FROM '/var/lib/postgres/dev/test.out';

I would not use log_statement = all on a productive server. That produces huge log files.


text:
Q: Is the trapezoidal approximation of an integral exact in a symmetrical case? I'm taking a calculus II class and doing pretty well in it, but I have no other background in formal mathematics or proofs. I saw the Wikipedia page for the Trapezoidal Rule, here. The picture seems to depict a situation where treating the curve within its bounds, in addition to the line forming the top of the Trapezoid, as a single shape, would produce a shape that's symmetric (or at least, it suggests it enough that I could imagine it). So you could cut one piece off at the intersection point and lay it down on top of the other and they'd fit perfectly. Again, I don't have any more formal language to describe this, I'm just curious and my professor doesn't seem to know anything about the theory. So here's the question:
If the intersections of line formed by the top of a single, non-composite trapezoidal approximation, and the curve that it is approximating, form a shape with a certain kind of symmetry, is it possible that that approximation becomes exact? Not just "so good you can't tell the difference," but definitionally the same value?
Again, I hope this isn't a stupid question. I'm just taking this course for compsci.

A: Yeah, that can totally happen. In fact, you might know from your calc course that the integral is linear. That is, $$\int_a^b f(x) + g(x) \ \text{d}x = \int_a^b f(x) \ \text{d}x + \int_a^b g(x) \ \text{d} x$$ Well, if you're not doing a whole trapezoidal Riemann sum, and just looking at one trapezoid as part of the approximation, then you're approximating $$ \int_a^b f(x) \ \text{d}x \approx\int_a^b h(x) \ \text{d}x $$ where $f(x)$ is the function you want to get the area under and $h(x)$ is a linear function giving the height of the trapezoid. Well, by the linearity of the integral, those two terms are equal exactly when $$ \int_a^b \left(f(x) - h(x)\right) \ \text{d}x = 0$$ Intuitively, this makes a lot of sense. The approximation will be exact if and only if the distance between them has as much positive contribution as negative contribution (and therefore integrates to $0$). In the case you're describing, the simplest case, your saying $$ \int_a^{a + b/2} (f(x) - h(x)) \ \text{d}x = -\int_{a + b/2}^{b} (f(x) - h(x)) \ \text{d}x$$ holds because the difference between the curves has the same shape in the first region as the second, just on different sides, so the total integral becomes $0$. And that means the approximation will  be exact. Althought it won't happen often without constructing it, it's easy to construct many similar cases where the curve might exhibit much less clear symmetry, but the difference integrates out to 0. In the symmetric case though, it's nice and easy to see the difference integrates away, so the approximation becomes exact.

A: That is a very interesting question.
I think you are talking about cases like the one shown in the diagram below:

There is definitely some symmetry going on here. However, the term "symmetric function" is already reserved for something else in mathematics.
Suppose that a function $G$ is a symmetric function.
If $G(1) = \pi$, then $G(\pi) = 1$.
The numbers $1$ and $\pi$ are not special.
Saying that a function is symmetric is equivalent to saying that $G(G(x)) = x$
(for all $x$ which are valid inputs to function $G$).
Let us say that a function with your special property is called, "Temmetric"
Mathematicians invent new words in almost every paper they public. If you ever write a proof someday, then I hope that you to feel free to invent new words. If you think it would be useful to have a name for something, then give that thing a name. This is fine, as long as you write down an explanation (definition) of what your made-up word means.
Definition of Temmetric

We define a continuous real-valued function $F$ to be Temmetric if there is a point on the x-axis and there is a non-zero distance Δ, such that if $d$ is any distance smaller than Δ, then $F(x - d) = F(x + d)$.

In this context, a distance is a non-negative decimal number, such as $0, 0.5, 1, 712 + \pi, \text{etc.}$

Example of a Temetric Function
Let $\mathtt{P}$ be a function such that for any decimal number $x$, $\mathtt{P}(x) = x^3 + 5*x^{2}$
We shall show that $\mathtt{P}$ is a Temmetric function.

We have a point on the x-axis, $x = \frac{-5}{3}$, such that:
  if
    $Δ = \frac{-5}{3}$
  then
   if
    $\delta$ satisfies $0 \leq \delta \leq Δ$
   then
      $P(x - \delta) = P(x + \delta)$
The indentation above might look a little funny. However, I find that indentation  makes it easier to read run-on sentences (long sentences). Computer programmers use indentation to format very long clause written in computer code. Otherwise, computer programs would be unreadable.
Conjecture Regarding Temmetric Functions
Let $F$ be a Temmetric function
Suppose that $s$ is a point on the x-axis such that Δ is a decimal number (real number) such that for any decimal number $\delta$ if $0 \leq d \leq Δ$ is any distance smaller than Δ, then $F(x - d) = F(x + d)$.
Let $a$ be an arbitrary positive decimal number smaller than Δ.
Then,
  the area under curve $F$ from $x = s - a\quad$ to $quadx = s + a$
    is equal to
  the surface area of the trapezoid whose four corners are the points:
    $(s - a, 0)$
    $(s - a, F(s - a))$
    $(s + a, F(s + a))$
    $(s + a, 0)$


text:
Q: Calling startActivity() from outside of an activity context requires the FLAG_ACTIVITY_NEW_TASK I am trying to start an activity inside a service class. I have a following code:
public class SendLinkService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle bundle = intent.getExtras();
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
    getApplicationContext().startActivity(Intent.createChooser(shareIntent, "Share via"));
    return super.onStartCommand(intent, flags, startId);
}
}

It gives exception on following line of onStartCommand() :
getApplicationContext().startActivity(Intent.createChooser(shareIntent, "Share via"));

A: @hariharan answer works. However it also work without setting Intent.FLAG_ACTIVITY_NEW_TASK in the first case. More accurate answer is:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
Intent new_intent = Intent.createChooser(shareIntent, "Share via");
new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(new_intent);

A: Try this.
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
Intent new_intent = Intent.createChooser(shareIntent, "Share via");
new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(new_intent);

A: For (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) it is mandatory to add Intent.FLAG_ACTIVITY_NEW_TASK while calling startActivity() from outside of an Activity context.
Docs
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, bundle.getString("URL"));
Intent new_intent = Intent.createChooser(shareIntent, "Share via");
new_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(new_intent);


text:
Q: How does CURLOPT_FOLLOWLOCATION work? What happens when CURLOPT_FOLLOWLOCATION is set false? Can the server detect my CURLOPT_FOLLOWLOCATION is set false? When I send GET/POST request, Does libcurl send head request or GET/POST when CURLOPT_FOLLOWLOCATION is set false?

A: CURLOPT_FOLLOWLOCATION says to Curl request, that should do a redirect if a 304 or similar header is received.
It has nothing to do with server, but Curl as client should go further if a redirect response is received.


text:
Q: Autofac + MVC5: Resolving a Service's Dependencies I've gotten the basics done with resolving controller dependencies with Autofac + MVC5.  However, I'm wondering how to inject dependencies into services.
Given a sample definition as such, how can I create/get an instantiated copy of the class with Autofac resolving the necessary dependencies?
Bar : IBar
{

  Public Bar(IFoo foo, IPanda panda)

{}

}

A: Ultimately it just comes down to registering the type in the Container. Such as:
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().As<IBar>();
var container = builder.Build();

I'm assuming you have similar code using the Builder somewhere during your initialization.
There are several different ways to register and configure dependencies, lifetimes, interceptors etc, more info here:
http://docs.autofac.org/en/latest/register/registration.html
Once everything is registered, whenever Autofac tries to instantiate your controller, it'll inspect your controller's constructor, and when it finds an IBar as dependency, it'll look for it's container registration and instantiate accordingly.
The same applies when it tries to instantiate IBar, it'll notice IFoo and IPanda and repeat the same process.
The main difference is that Autofac supports automatic registration of your controllers, just to spare you the hassle of registering each one manually.
So in the end, it'll all be chained in that manner, dependencies created as needed.
I tend to avoid using ServiceLocator style of instantiation by requesting a dependency directly, and just let Autofac provide the dependencies during construction.


text:
Q: How does ASP.NET MVC 3 know to put https on links even when F5 (big-ip) is handling the ssl? On our site, we have F5's Big IP handling the SSL encrypting and decryption, and sending the request to port 80 on our server.
Since this is the first site we are doing with ASP.NET MVC, I was curious how it would handle @HTML.ActionLink's in the views.  Surpisingly, it is putting https://.  On our CI environment (which doesn't do the SSL), it is putting http:// on all the links.
We have other links to bring in javascript files, css files and images, and we are using a custom HTTP header added by F5 to the request so we can tell.
Does anyone know how ASP.NET MVC3 knows whether or not the links should have http:// or https://, as I would rather not have a custom HTTP header coming in, if there is a way we can use the same method.

A: IF you use RequireHttpsAttribute in your controller, this is one way. As it'll redirect to Https if called with Http.
Another important way that is likely your case is that it uses the current request path (Request.AbsoluteUrl) to make the links, so, if the original page is called using HTTPs, the links will be Https (from quick look at the code).
So, maybe the raw URL is coming to IIS to port 80 but with indicating that the URL includes Https. Try to output something like Request.ServerVariables[ "HTTP_URL" ] to confirm. I assume that Request.ServerVariables["HTTPS"] in your case as you describe it.


text:
Q: How to test that SNI is supported by given webbrowser? I just want to test this:
https://secure.wikimedia.org/wikipedia/en/wiki/Server_Name_Indication
on different webbrowsers. (if it's working or not)
I know I could Google HTTPS sites using the:
inurl:https

But how can I search for HTTPS domains that's on a shared hosting? (I mean that 1 IP is behind many-many domains.)

A: There's a website just for that: https://sni.velox.ch/


text:
Q: Why my error is not being handled in express.js? I am learning express.js, and I am thinking why I receive UnhandledPromiseRejectionWarning and no error response is being sent after executing http api call..
For error handling I have created helper class and middleware:
/helpers/errorHander.js
------------------------------------
class ErrorHandler extends Error {
  constructor(statusCode, message) {
    super();
    this.statusCode = statusCode;
    this.message = message;
  }
}

const handleError = (err, res) => {
  const { statusCode, message } = err;
  res.status(statusCode).json({
    status: 'error',
    statusCode,
    message
  });
};

module.exports = {
  ErrorHandler,
  handleError
};

I have enabled this middleware in app.js file:
/app.js
------------------------------------
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const config = require('./config/init');
const cors = require('cors');
const { handleError, ErrorHandler } = require('./helpers/errorHandler');

//routes
const apiRoutes = require('./api');

// connect db
config.initializeDB();

// configure bodyParser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Enable Cors
app.use(cors());

// Set Routes
app.use('/', apiRoutes);

app.get('/error', (req, res) => {
  throw new ErrorHandler(500, 'Internal server error');
});

// Enable error handling middleware
app.use((err, req, res, next) => {
  handleError(err, res);
});

module.exports = app;

When I perform request to the /error endpoint, it works correctly:
/error endpoint
But when performing request to the endpoint which performs operations with mongoose I am not getting desired result:
/v1/users/ endpoint
user.route.js:
const router = require('express').Router();
const userController = require('./user.controller');

router.get('/', userController.getUsers);
router.post('/', userController.createUser);

module.exports = router;

user.controller.js:
const userService = require('../../../services/user');

module.exports = {
  getUsers: (req, res, next) => {
    return res.json(userService.getUsers());
  },
  createUser: (req, res, next) => {
    const username = req.body.username;
    const password = req.body.password;
    res.json(userService.createUser(username, password));
  }
};

user.service.js:
const User = require('../models/user');
const { ErrorHandler } = require('../helpers/errorHandler');

module.exports = {
  getUsers: async () => {
    return User.find({});
  },
  createUser: async (username, password) => {
    const user = new User({ username, password });
    try {
      await user.save();
      return user;
    } catch (err) {
      if (err.code === 11000) {
        throw new ErrorHandler(409, 'Username already exists!');
      }
      throw new ErrorHandler(500, 'Internal server error');
    }
  }
};

Console gives such a warning:
Console Output
Why it is not working as I want, and how can I make it work?
=========================================================
Update #1
As user - jfriend00 suggested, I tried to await the promise, and here my code looks like on user.controller.js:
const userService = require('../../../services/user');

module.exports = {
  getUsers: (req, res, next) => {
    return res.json(userService.getUsers());
  },
  createUser: async (req, res, next) => {
    const username = req.body.username;
    const password = req.body.password;
    try {
      let user = await userService.createUser(username, password);
    } catch (err) {
      next(err);
    }
  }
};

And Now I get the desired outcome.


text:
Q: Matching Dots in Java I`m developing a new robot for a Rescue Competition, and we want to use SLAM to do the mapping and Localization.
One of the main problems is to match a list of dots with another list of dots.
We are running the robot on an Android 2.4Ghz, with a self made app.
Does anyone know about any Java Library for ICP (Iterative Closest Point) or PSM (Polar Scan Matching) algorithm?
If not, do you know how to implement it in Java?
Thanks

A: This is a pretty vague answer, but you could try your luck with the MITK (Medical Imaging Toolkit) Framework. Some filters there employ the ICP Algorithm. Since the whole thing is open source you should be able to find what you need there. It's all written in C++ though. Plus Side: They are working on an improved version, the Anisotropic ICP. Also check the point based registration module from the 3m3 branch of MITK: The Point Based Registration Module


text:
Q: Which PDO SQL Server drivers do I use for FreeBSD? Our systems administrator is no longer with our organization and I'm trying to take over managing a PHP Laravel project that has a MS SQL Server database.
I see that Microsoft has driver extensions available for various operating systems, but I'm a little confused because our server is FreeBSD.
I can't do the PECL install, so I'm guessing I have to copy the extensions to the appropriate directory manually and then add the extension reference to the php.ini file.
I'm just not sure what drivers I'm supposed to use from this list:
https://github.com/Microsoft/msphpsql/releases/tag/v5.6.0
CentOS7
Debian8
Debian9
Mac
Suse12
Suse15
Ubuntu16
Ubuntu18
Ubuntu1810
Windows
I'm guessing its one of the Ubuntu ones, but I don't know how to ensure that I have selected the correct one.