text:
Q: How to get used theme color in android I have a screen that lists all my customs themes. I want to show theme's colors next to its name. So I need unused(not current) theme colors.
Normally, we can do like this way,
Resources.Theme theme = context.getTheme();

theme.resolveAttribute(themeColor, typedValue, true);

But in this situation I must write something like that getTheme(R.style.foo).
How can I go with it?

A: After lots of searching, I realized this, this not about the theme, it is all about style. Shame on me. So now, because of opening this question, I answer my question.
Firstly you must define what you want
int[] attrs = {R.attr.color_1, R.attr.color_2, R.attr.color_3, R.attr.color_4};

and then you can get them by index
TypedArray ta = holder.itemView.getContext().obtainStyledAttributes(R.style.AppTheme_Pink, attrs);

ViewHelpers.Companion.changeBackgroundSolidColor(holder.color1ImageView, ta.getColor(0, Color.GRAY));
ViewHelpers.Companion.changeBackgroundSolidColor(holder.color2ImageView, ta.getColor(1, Color.GRAY));
ViewHelpers.Companion.changeBackgroundSolidColor(holder.color3ImageView, ta.getColor(2, Color.GRAY));
ViewHelpers.Companion.changeBackgroundSolidColor(holder.color4ImageView, ta.getColor(3, Color.GRAY));

dont forget to recycler
ta.recycle();


text:
Q: How to implement a basic pointer I know here is no pointer in Java. But how do I change a value in the calling scope? For instance, I want to write a function that takes an integer num, set the integer to 0 if it's greater than 21, otherwise do nothing.
In the main, my code is as follow:
int a=34;
KillOver21(a);
System.out.print(a);

I expect an 0.

A: Java is pass by value, so a copy of the parameter a is sent to the method, so modification to a in the method will not affect the original argument a in main
The max you can do is return int from KillOver21(a) method
int z = KillOver21(a); // This will return 0
System.out.print(z);

But you can achieve something like that with custom objects, say you have a class
class AHolder {

    public int a;

}

then you can expect AHolder instance to change
public static void main(String [] args) {
     AHolder a = new AHolder();
     a.a = 34;
     killOver21(a);
     System.out.println(a.a);
}

public static void killOver21(AHolder b) {
    if(b.a > 21) {
       b.a = 0;
    }
}

Since in the latter (even if its Pass by Value) , the reference is copied and both reference point to same object. So changes made inside the killOver21 method actually changes the object.

A: It is simply not possible, Java supports pass by value. int a's value will be copied to the function.
You could use Object instead of primitive where the reference value will be copied to your function by which you can get the actual object and modify it.

A: Fundamentally impossible in Java, period. int are immutable, and passed by value. You would need to create a mutable int type:
class MutableInt {
    private int value;

    public MutableInt(int value) { this.value = value; }

    public getValue() { return this.value; }
    public setValue(int value) { this.value = value; }
}

Then:
void KillOver21(MutableInt m) {
    if(m.getValue() > 21) { m.setValue(0); }
}

However, be aware the mutable types that represent concepts that are defined by their value rather than their identity are generally an extremely bad idea. But, this is the only way to achieve what you're trying to achieve. Again, I caution you with the strongest words: what you're doing is a bad idea. You should find another way.
Doc, it hurts when I do this.
Then don't do that!

A: The simpliest way (quick&dirty) is to put value within an array
int holder[] = new int[]{ a};

KillOver21(holder)

System.out.printf( "value=[%d]", holder[0]  );

void KillOver21(int holder[] ) {
    holder[0] = 0;
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: On scroll div colour change Trying to change the colour of btns within a menu dependant on scroll according to the div.. but not working right.. Added a pic to help understand what im trying to do.
html menu btns:













html div:

Name

My new tattoo

Style

Heading

Position on body

Black & White

Side

Right

Brief

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Budget

$200-$400

Photos

javascript:

A: Is this what you are looking for -
JS code:
$(".right").scroll(function(){
var st = $(this).scrollTop();
if(st <= 50){
    $(".A").css("color", "red")
}
else if(st <= 100){
    $(".B").css("color", "red")
}
else if(st <= 150){
    $(".C").css("color", "red")
}
});

https://jsfiddle.net/ashwyn/qudnauvq/

A: This is a modification to @MotaBOS's solution
$(".right").scroll(function(){
var st = $(this).scrollTop();
  $(".left span").css("color", "black")
if(st <= 50){

    $(".A").css("color", "red")
}
else if(st <= 100){
    $(".B").css("color", "red")
}
else {
    $(".C").css("color", "red")
}


text:
Q: MySQL LIMIT X, Y slows down as I increase X I have a db with around 600 000 listings, while browsing these on a page with pagination, I use this query to limit records:
SELECT file_id, file_category FROM files ORDER BY file_edit_date DESC LIMIT 290580, 30

On first pages LIMIT 0, 30 it loads in few ms, same for LIMIT 30,30, LIMIT 60,30, LIMIT 90,30, etc. But as I move forward to the end of the pages, the query takes around 1 second to execute.
Indexes are probably not related, it also happens if I run this:
SELECT * FROM `files` LIMIT 400000,30

Not sure why.
Is there a way to improve this ?
Unless there is a better solution, would it be a bad practice to just load all records and loop over them in the PHP page to see if the record is inside the pagination range and print it ?

Server is an i7 with 16GB ram;
  MySQL Community Server 5.7.28;
  files table is around 200 MB

here is the my.cnf if it matters
query_cache_type = 1

query_cache_size = 1G

sort_buffer_size = 1G

thread_cache_size = 256

table_open_cache = 2500

query_cache_limit = 256M

innodb_buffer_pool_size = 2G

innodb_log_buffer_size = 8M

tmp_table_size=2G

max_heap_table_size=2G

A: You may find that adding the following index will help performance:
CREATE INDEX idx ON files (file_edit_date DESC, file_id, file_category);

If used, MySQL would only need a single index scan to retrieve the number of records at some offset.  Note that we include the columns in the select clause so that the index may cover the entire query.

A: LIMIT was invented to reduce the size of the result set, it can be used by the optimizer if you order the result set using an index.
When using LIMIT x,n the server needs to process x+n rows to deliver a result. The higher the value for x, the more rows have to be processed.
Here is the explain output from a simple table, having an unique index on column a:
MariaDB [test]> explain select a,b from t1 order by a limit 0, 2;
+------+-------------+-------+-------+---------------+---------+---------+------+------+-------+
| id   | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra |
+------+-------------+-------+-------+---------------+---------+---------+------+------+-------+
|    1 | SIMPLE      | t1    | index | NULL          | PRIMARY | 4       | NULL | 2    |       |
+------+-------------+-------+-------+---------------+---------+---------+------+------+-------+
1 row in set (0.00 sec)

MariaDB [test]> explain select a,b from t1 order by a limit 400000, 2;
+------+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
| id   | select_type | table | type  | possible_keys | key     | key_len | ref  | rows   | Extra |
+------+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
|    1 | SIMPLE      | t1    | index | NULL          | PRIMARY | 4       | NULL | 400002 |       |
+------+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
1 row in set (0.00 sec)

When running the statements above (without EXPLAIN) the execution time for LIMIT 0 is 0.01 secs, for LIMIT 400000 0.6 secs.
Since MariaDB doesn't support LIMIT in a subquery, you could split your SQL statements in to two statements:
The first statement retrieves the id's (and needs to read the index file only), the second statement uses the id's retrieved from first statement:
MariaDB [test]> select a  from t1 order by a limit 400000, 2;
+--------+
| a      |
+--------+
| 595312 |
| 595313 |
+--------+
2 rows in set (0.08 sec)

MariaDB [test]> select a,b from t1 where a in (595312,595313);
+--------+------+
| a      | b    |
+--------+------+
| 595312 | foo  |
| 595313 | foo  |
+--------+------+
2 rows in set (0.00 sec)

A: Caution:  I am about to use some strong language.  Computers are big and fast, and they can handle bigger stuff than they could even a decade ago.  But, as you are finding out, there are limits.  I'm going to point out multiple limits that you have threatened; I will try to explain why the limits may be a problem.
Settings
query_cache_size = 1G

is terrible.  Whenever a table is written to, the QC scans the 1GB looking for any references to that table in order to purge entries in the QC.  Decrease that to 50M.  This, alone, will speed up the entire system.
sort_buffer_size = 1G
tmp_table_size=2G
max_heap_table_size=2G

are bad for a different reason.  If you have multiple connections performing complex queries, lots of RAM could be allocated for each, thereby chewing up RAM, leading to swapping, and possibly crashing.  Don't set them higher than about 1% of RAM.
In general, do not blindly change values in my.cnf.  The most important setting is innodb_buffer_pool_size, which should be bigger than your dataset, but no bigger than 70% of available RAM.
load all records
Ouch!  The cost of shoveling all that data from MySQL to PHP is non-trivial.  Once it gets to PHP, it will be stored in structures that are not designed for huge amounts of data -- 400030 (or 600000) rows might take 1GB inside PHP; this would probably blow out its "memory_limit", leading PHP crashing.  (OK, just dying with an error message.)  It is possible to raise that limit, but then PHP might push MySQL out of memory, leading to swapping, or maybe running out of swap space.  What a mess!
OFFSET
As for the large OFFSET, why?  Do you have a user paging through the data?  And he is almost to page 10,000?  Are there cobwebs covering him?
OFFSET must read and step over 290580 rows in your example.  That is costly.
For a way to paginate without that overhead, see http://mysql.rjweb.org/doc.php/pagination .
If you have a program 'crawling' through all 600K rows, 30 at a time, then the tip about "remember where you left off" in that link will work very nicely for such use.  It does not "slow down".
If you are doing something different; what is it?
Pagination and gaps
Not a problem.  See also:  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks which is more aimed at walking through an entire table.  It focuses on an efficient way to find the 30th row going forward.  (This is not necessarily any better than remembering the last id.)
That link is aimed at DELETEing, but can easily be revised toSELECT`.
Some math for scanning a 600K-row table 30 rows at a time:
My links:  600K rows are touched.  Or twice that, if you peek forward with  LIMIT 30,1 as suggested in the second link.
OFFSET ..., 30 must touch (600K/30)*600K/2 rows -- about 6 billion rows.
(Corollary:  changing 30 to 100 would speed up your query, though it would still be painfully slow.  It would not speed up my approach, but it is already quite fast.)


text:
Q: Prioritizing message in Akka I've been attempting to follow the example from Akka's docs on Dispatchers, which I found from this post originally.
After running a sample, I'm not convinced I have it setup correctly. I'm deviating from the example slightly. Instead of creating a new dispatcher entry in the application.conf, like the tutorial:
prio-dispatcher {
  mailbox-type = "akka.docs.dispatcher.DispatcherDocSpec$MyPrioMailbox"
}

I want to overwrite the default dispatcher for ALL actors in my application. Therefore, I've done this:
default-dispatcher
{
  mailbox-type = "LoggingPriorityMailbox"
}

And in Scala:
class LoggingPriorityMailbox
extends UnboundedPriorityMailbox(
  PriorityGenerator {
     case Debug(ts: Timestamp, s: String) => 10 // Lowest
     ...
     case otherwise                       =>  0 // Highest
  }) {}

I've turned on log-config-on-start setting and verified the mailbox-type is set properly for the default-dispatcher. So I suppose it's at least being configured properly... Am I missing something? As I've read elsewhere for priority mailboxes, it might just be the case that my testing hasn't overloaded the mailboxes and actors enough to allow them to prioritize.


text:
Q: Exclude file types expect txt files in C Hello and Happy new Year ,
I have to accept juste txt files in my C programme ,
I don't have any idea to how to made it .. any ideas?
And I don't know if text file contain Header or something which characterize it..
PS: I'm using Ubuntu so file extension is not seen.
Thank you

A: In a Linux environment, I would personally go with libmagic, which is the core of the utility program file. The purpose of this library is to do exactly what you are trying to accomplish: identify the type of a file based on it content.
Example usage would look like this.
/* identify.c */

#define _POSIX_SOURCE /* required for fileno() */

#include <magic.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    const char *description;
    magic_t cookie;
    FILE *fp;

    fp = fopen("example.txt", "r");

    if(fp == NULL) {
        fprintf(stderr, "error: cannot open file\n");
        exit(EXIT_FAILURE);
    }

    cookie = magic_open(MAGIC_NONE);

    if(cookie == NULL) {
        fprintf(stderr, "error: cannot initialize library\n");
        fclose(fp);
        exit(EXIT_FAILURE);
    }

    if( magic_load(cookie, NULL) != 0 ) {
        fprintf(stderr, "error: cannot load database : %s\n",
                                            magic_error(cookie));
        magic_close(cookie);
        fclose(fp);
        exit(EXIT_FAILURE);
    }

    description = magic_descriptor(cookie, fileno(fp));
    printf("%s\n", description);

    magic_close(cookie);
    fclose(fp);

    return EXIT_SUCCESS;
}

Name this source file identify.c, create a text file name example.txt with some content in the same directory, and compile with:
gcc -Wall -std=c99 -pedantic -lmagic -o identify identify.c
Then run it.
./identify
And you get something like this printed:
UTF-8 Unicode text

This library can be used in a few different ways, so you should probably have a look at the man page. For example, you can get a MIME type instead of a description like the one above.
The file package of which libmagic is a part is probably already installed on your machine. However, if you are using a distribution such as RHEL of CentOS that splits development headers into a separate package, make sure you have file-devel installed.


text:
Q: sending mail error python i get the following error when trying a script thaat sends mail
    import urllib.request
    import re
    import smtplib
    from email.mime.text import MIMEText
    from bs4 import BeautifulSoup
    page=urllib.request.urlopen("http://www.crummy.com/")
    soup=BeautifulSoup(page)
    v=soup.findAll('a',href=re.compile('http://www.crummy.com/2012/07/24/0'))
    for link in v:

      w=link.get('href')

    server = smtplib.SMTP( "smtp.gmail.com", 587 )
    server.starttls()
    server.login( 'xxxxxxxxxxx', 'xxxxxxx' )
    server.sendmail( 'xxxxxxxxx', 'xxxxxxxxx', "bonus question is up" )

Traceback (most recent call last):  File "C:\Python32\bonus", line 14,
  in   server = smtplib.SMTP( "smtp.gmail.com", 587 )  File
  "C:\Python32\lib\smtplib.py", line 259, in init   File
  "C:\Python32\lib\smtplib.py", line 319, in connect
      self.sock = self._get_socket(host, port, self.timeout)   File "C:\Python32 \lib\smtplib.py", line 294, in _get_socket
      return socket.create_connection((host, port), timeout)   File "C:\Python32\lib\socket.py", line 386, in create_connection
      for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno 11004] getaddrinfo failed plse advice on the
  best way to go round it

A: The getaddrinfo function has this purpose:

The getaddrinfo function provides protocol-independent translation from an ANSI host name to an address.

If it fails it means that it cannot translate your given hostname to it's respective address. It's essentially doing a DNS query.
Your error number returned "11004" by getaddrinfo has this message associated with it:

Valid name, no data record of requested type. The requested name is
  valid and was found in the database, but it does not have the correct
  associated data being resolved for. The usual example for this is a
  host name-to-address translation attempt (using gethostbyname or
  WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX
  record is returned but no A record—indicating the host itself exists,
  but is not directly reachable.

It seems the name you're looking up has no correct data associated with it.
Are you sure your URL's are correct?
Links:
getaddrinfo: http://msdn.microsoft.com/en-us/library/windows/desktop/ms738520(v=vs.85).aspx
WinSock Error Codes: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx


text:
Q: Using select_related and extra clause I'm trying to achieve some extra select on a queryset and wants to add the needed table to the pool of tables in the query using the select_related method in order to benefit for the '__' syntax.
Here is an example with simple models :
from django.db import models

# Create your models here.

class testA(models.Model):
    code = models.TextField(unique = True)
    date = models.DateTimeField(auto_now_add = True)

class testB(models.Model):
    text = models.TextField()
    a = models.ForeignKey(testA)

And here is the query I want to build :
SELECT (extract(hour from testa.date)) AS hour, testb.text FROM testb INNER JOIN testa ON (testb.a_id = testa.id)

So here is how i build it in python :
testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour','text')

but django removes the select_related when he sees that I'm not using the "testa" table (because of the 'values' statement). So the resulting SQL query fails :
SELECT (extract(hour from testa.date)) AS "hour", "testb"."text" FROM "testb"

If I remove the "values" statement it works fine :
SELECT (extract(hour from testa.date)) AS "hour", "testb"."id", "testb"."text", "testb"."a_id", "testa"."id", "testa"."code", "testa"."date" FROM "testb" INNER JOIN "testa" ON ("testb"."a_id" = "testa"."id")

but I must put the values statement as I want to make aggregates as in "count the b objects grouped by the hour of the date in the a object" :
testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour').annotate(count = Count('pk'))

So what is the good way to achive this ? "Count objects grouped by something in another object" ? Or is there a way to "force" django to keep the "select_related" tables even if he thinks they are useless ?
PS : I know I could use the "tables" argument of the extra statement but in that case I would have to rewrite the join by myself and I want to benefit from the django ORM

A: I have developped a Django app to solve this kind of problems : django-cube. The base idea is to emulate a multi-dimensional DB, in order to easily calculate aggregations.
The functionnality you require ('__hour' : a field-lookup for 'hour') is not implemented, but implementing it would take probably 15 minutes. So read what's next, how it works, etc ... and if it fits your need, write to me, and I'll implement it.
The examples on the main page and the api doc are not up-to-date (they will be in a few days), but these snippets are. If you want to give it a try, here is how you would solve this problem with django-cube :
#install the app first ...
from cube.models import Dimension, Cube

class MyCube(Cube):
    #declare a dimension called 'hour_a',
    #that is related to the field 'a__date__hour'.
    hour_a = Dimension(field='a__date__hour')

    #declare how to calculate the aggregation on a queryset
    @staticmethod
    def aggregation(queryset):
        return queryset.count()

And then, there are various methods to calculate the results, check in the snippets... You can for example use :
cube(testB.objects.all()).measure_dict('hour_a', full=False)

Which would return something like :
{
    12: {measure: 889},
    13: {measure: 6654},
    14: {measure: 77},
    #<hour>: <count>
}

Also, don't take the featured download, rather check-out from source (branch 0.3).
I don't know what are your real needs, it might be a little heavy for the use you will have (it was initially made for data visualization purposes).

A: I can't answer your main query, but it's worth noting that select_related has nothing to do with the __ syntax. select_related is simply an optimisation that will return extra related objects, adding joins to the query if necessary. But the double-underscore syntax for querying related tables works with or without select_related.

A: I get the same error locally:  everything works until "values" is appended and then django fails to place the appropriate FROM clause.  I would post this example to the django-users group and see if someone in the know can verify if this is a bug or if there's a quick was to fix it.


text:
Q: Jump y axis values when highest value is to far away from the other points Basically I'm building an area graph with Chart.js, the data that I'm using in order to build the graph usually contains a peak that is much higher than the rest of the points and the y-axis range of values will be to high, to notice the diference between the lower points and it wil seem almost as a parallel line to the x-axis as we can see in this image:
Graph with problems
The solution I want to try is to skip the values from the y-axis between the lower points and the peak of the graph, and accomplish a graph presentation similar to this one:
Solution graph sketch
As we can see at this sketch the y-axis has a normal scale until 300 but then as the next point is to far away from the other ones the y-axis values are skiped.
So what I want to know is if this jump on the values of the y-axis is possible to achieve with this library (Chart.js) and if so where can I find documentation about it, because I already looked everywhere and couldn't find a thing. If not I would ask you for recommendations of any other librarys where I could achieve this.


text:
Q: Unable to upload large vector file to Postgis error:Geometry type (MultiSurface) does not match column type (MultiPolygon) I am unable to upload this large vector file of 30GB(Multipart polygon in ArcGIS FGDB). ogr2ogr throws the following error

Warning 1: Geometry to be inserted is of type Multi Surface, whereas the layer geometry type is Multi Polygon.
  Insertion is likely to fail
  ERROR 1: COPY statement failed.
  ERROR:  Geometry type (MultiSurface) does not match column type (MultiPolygon)
  CONTEXT:  COPY fuzzy_2016, line 17643, column wkb_geometry: "010C000020110F000002000000010A0000000100000001020000001500000

Note: The same dataset works fine in ArcGIS environment.

A: The first thing to take a look at, is the specific feature being referenced in the error string.  Something about it is making PostGIS think it is a MultiSurface feature.  I know you have imported these datasets successfully before, so please provide some information about them.  What is the source?  How were they created?
PostGIS is pretty strict about data types matching up.  If you don't specify the target layer type, PostGIS will guess what type to use, basically by assigning the type of the first features that it imports in the layer.  If it then runs across a feature that it thinks is a different type, it will throw an error.
I would try specifying the layer type using -nlt as part of your import command.
Example:
ogr2ogr -overwrite -f "PostgreSQL" PG:"host=xxx user=xxxxx dbname=xxxx password=xxxx port=5432" "X:\postgresData\Fuzzy_2016.gdb" "fuzzy_2016" -nlt MULTIPOLYGON
Please note that I also added the -overwrite command to your string as this will ensure any existing table matching that name, and thus formatting, is dropped so it doesn't interfere.  If you want to append to an existing table, or some such, then do this testing into a temp table, and change the table name to a permanent table once you have the kinks worked out.
Use the New Layer Name command -nln to do this.
Example:
ogr2ogr -overwrite -f "PostgreSQL" PG:"host=xxx user=xxxxx dbname=xxxx password=xxxx port=5432" "X:\postgresData\Fuzzy_2016.gdb" "fuzzy_2016" -nln fuzzy_2016_temp -nlt MULTIPOLYGON
If it continues to give you fits, you could write an sql query to filter out this particular feature during the import and see if it is able to process the rest.

A: This happens to me when the data I'm importing contains CURVEPOLYGONs inside of MULTIPOLYGONs. A MULTIPOLYGON isn't allowed to contain a CURVEPOLYGON, but a MULTISURFACE can contain both POLYGONs and CURVEPOLYGONs.
I fix this by specifying -nlt CONVERT_TO_CURVE as an option to ogr2ogr. The result is that it will import the features as MULTISURFACEs. Each of these collections will contain the curved and regular polygons from the original data. Only the container is converted to the curve type; the non-curved polygons inside are not.
I've run into issues in the past with limited support for curved polygons in certain software, but they seem to load fine in recent versions of QGIS.


text:
Q: if condition in haml view I want to set a :data attr if a condition is met. In this case a user should have a role. So it's a boolean statement. Let me give an example.
 - @data = 'contract-confirm'

 .create_button= link_to 'Something', new_some_path(@customer), :class => 'btn btn-success', :'data' => @data ? 'contract' : nil
 .clearer

So I know this might look strange but I want to set a data attribute if customer is labeled and then hook js to that data attr. That part works. What does not work is that now I'm setting the attribute always. So even in the case that customer does not have the role the js gets hooked. I know that I am not explicitly indicating at all the role here. I have a @customer.role? but I cant seem to incorporate it properply. I managed it before with an if else statement but then with a lot of duplication which I'm not so fund of. Any tips?

A: Try to replace :'data' => @data ? 'contract' : nil with :'data' => 'contract' if @data.
I checked it and next code:
- @data_present = true
= link_to 'Something', root_path, :class => 'btn', :'data' => ('test' if @data_present)

renders to:
Something

And code without - @data_present = true renders to:
Something

A: You can try this piece of code:
link_to 'Something', ... , :data => @customer.role? ? 'contract' : nil

haml won't include nil attributes, so it should work as you expect.


text:
Q: Dynamically resize images linked to JLabels in a GridLayout layoutmanager Current implementation layout:

((EDIT: added
Code: ))
private JPanel panelCenter;
private List<BufferedImage> listCreatedImages;
public ChooseCircuitPanel(List<BufferedImage> listCreatedImages) {
        this.listCreatedImages = listCreatedImages;
        initiate();
}
private void initiate() {
        setLayout(new BorderLayout(50, 50));
        panelCenter = new JPanel();
        LayoutManager theLayout = new GridLayout(0, 3, 0, 0);
        panelCenter.setLayout(theLayout);
        panelCenter.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        for (BufferedImage bufferedImage : listCreatedImages) {
            ImageIcon theImage = new ImageIcon(bufferedImage);
            JLabel lblForImage = new JLabel(theImage);
            lblForImage.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            panelCenter.add(lblForImage);
        }
        this.add(panelCenter, BorderLayout.CENTER);
}

Situation:
We want to display a race circuit here. A circuit should be displayed by placing standards tiles next to each other. It should be possible to resize the window, and with that, the circuit tiles should also resize.
((EDIT: bit more info: The race circuit data is stored on a server and the desktop application has to translate the data to a visual thing, by placing some standard tiles in the right order. ))
((EDIT: we are not allowed to use any external library. It should be doable by only using Java Swing code.))
I thought about placing the images in a JLabel and placing these JLabels in a panel with GridLayout as layout manager.
Using a GridLayout - I thought - it should be rather easy to get to a solution:
the components in the GridLayout (= JLabels) already scale and do exactly what I want.
Now, it would only be a matter of finding a way to resize the images so they fill the JLabels.
As you can see: right now, the images have a fixed size and don't scale at all.
I browsed a bit and saw lots of solutions that boil down to using Graphics2D and super.paintComponent, etc.
But most of these solutions had nothing to do with a GridLayout.
So conclusive question:
Is there an easier solution aside from using Graphics2D, etc. knowing that I use a GridLayout?
If not, I will of course use Graphics2D, etc. but I'm now just exploring my options. :)
((EDIT: SOLVED The tiles now neatly fit on each other. Don't mind the misalignments, that's our fault.))

A: There are no Swing components that do what you want so you will need to write your own code.
The easiest approach would be to use Darryl's Stretch Icon on your JLabel.
Or another approach is to create your own custom component that dynamically scales the image as it is painted. Something like the Background Panel which has code that allows you to scale or tile an image.

A: Given the nature of the view, I would recommend abandoning images altogether and instead implement the rendering in an Icon.  Presuming you can make an icon scale with the label.


text:
Q: Querying for Objects that contains some object in a one to many relationship So I have two models
class User
  has_many :roles
end

class Role
   belongs_to :user
end

how would I query for "who has xxx-role?"
thank you,

A: Start off my making a roles query
roles = Role.where(some_key: some_val).includes(:user)
You tack on the includes here to preload the associated user records. This way, you can get the users like so:
roles.map(&:user) which is equivalent to roles.map { |role| role.user }.
It would work without the includes but it would be slower. This is because of the N+1 sequel issue.


text:
Q: Chat menu design If you go to any Stack Exchange chatroom site (e.g. Stack Exchange Chat) the top bar is different than the regular pages. This should be changed to the 'modern' design; if not possible, could you provide a specific reason?

A: Chat literally hasn't changed at all from early on, and SE doesn't/hasn't had any developers working on major improvements to it in years.
So the specific reason is it's not a priority, and if there's engineering and development resources put towards chat, it'll probably be in line with the rest of the network, but there aren't.


text:
Q: how to get touches began, moved, and ended actions in a scroll view i have a uiscrollview with a list of images. if i touches an image it should get the location touched on scrollview and likewise for touches moved and ended.
I did the same process for UIView. but it wont works for scrollview. Guide me


text:
Q: Pass GET and read mySQL using GET I am currently stuck on a bug where I need to pass a parameter value from the url to a PHPfile on the back-end.
What the URL looks like ?p=tasks&t=view_task&id=1. I need to pass the idwith the value 1to my page which is located at i.e url: '/core/views/task_comments.php'.
var seconds = 1000; // time in milliseconds
var tc_reload = function() {
   $.ajax({
     type: 'GET',
     url: '/core/views/task_comments.php',
     data: {id: id},
     cache: false,
     success: function(data) {
       $('#task-comments').html(data);
       setTimeout(function() {
         tc_reload();
       }, seconds);
     }
   });
 };
 tc_reload();

And on the PHP page I got the following code.
// Fetch task data
$task_fetch = $conn->prepare("SELECT * FROM system_tasks WHERE task_id = :task_id");
$task_fetch->bindValue(":task_id", $_GET['id'], PDO::PARAM_INT);
$task_fetch->execute();

What I receive is the following error.

Notice: Undefined index: id in C:\xampp\htdocs\core\views\task_comments.php on line 19`

I would love to know what went wrong.

A: Solved the issue.
Apparently the config.php file was adding ?p=login after the id parameter.
url: '/core/views/task_comments.php?id='+id+'&p=login' fixed the problem, it now works like it should.


text:
Q: where does zxing check for Luminance, finder pattern and error correction level Anyone knows where does zxing library (in Java) check for Luminance and other factors that would affect the readability of a QR code?
For example, if the luminance is lower than some number, it will show a massage saying "Luminance is low". Where exactly is this number checked in the zxing library? And also where are the other factors that have been checked for scannability?
I have looked into LuminanceSource and Detector libraries, but didn't found that specific number or function checking for these.
Also what are the all factors that I need to check to make sure the QR code is scannable?

A: Did you look at the source? It's pretty clear. LuminanceSource is not the place; look at HybridBinarizer for luminance. There is no such thing as a "check for scannability". qrcode.Detector calls FinderPatternFinder to locate finder patterns. I don't know what you mean by error correction level but the common.reedsolomon package performs correction, as you can probably guess just by the name.


text:
Q: What is the spelling of `~`? I searched ~ spelling and ~ symbol spelling on Google but found nothing. My dictionary doesn't contain ~ either.
P.S.: is there any online dictionary that can translate symbols? I find I know almost nothing about the symbols. Even in my native language, I say /\ or something else tilted stick. I don't know which is slash, and which is backslash.

A: The formal name for ~ is tilde.
Many programmers call it twiddle.
A slash or forward slash is /.  If north is at the top of the page, it points southwest-to-northeast.  It is tilted the same way that most right-handed people slant their writing, so it has a "forward" slant.  Standard American keyboards have ? as Shift-/.
A whack or backslash is \.  If north is at the top of the page, it points northwest-to-southeast.  Standard American keyboards have | as Shift-\.
See also "What do programmers call these punctuation marks? (Parentheses, brackets, ticks, etc.)"
The ASCII entry in The New Hacker's Dictionary, as edited by Eric S. Raymond, includes English-language computer programming names for many common symbols.

A: I believe the symbol is known as a tilde
https://en.wikipedia.org/wiki/Tilde
The Punctuation Guide is a good source of information for English punctuation and its usage, including what each symbol is called (though in this case it doesn't mention the tilde).
Typing the actual symbol into Google or Wikipedia also yields an accurate result.
[edit]
If you type a punctuation symbol into Wikipedia (such as tilde, above) it also returns a comprehensive list of other punctuation symbols, spellings, plus links to more detailed information on the right hand side of the page.


text:
Q: start flask server @ startup with supervisor: FATAL Exited too quickly I am trying to start my flaskserver at startup with the help of supervisor. But i get this error message:
python_auutostart                FATAL      Exited too quickly (process log may have details)

This is the entry in my logfile:
Traceback (most recent call last):
  File "run.py", line 2, in <module>
    from app import app
  File "/home/flaskserver/app/__init__.py", line 1, in <module>
    from flask import Flask
ImportError: No module named flask

This is my .conf:
[program:python_auutostart]
user=nobody
command = python run.py
directory = /home/flaskserver/
autostart = true
autorestart = true
stderr_logfile=/etc/supervisor/long.err.log
stdout_logfile=/etc/supervisor/long.out.log

I can start my flaskserver without problems if I run ./run.py but I don´t get it to run with supervisor. I don´t see why i get the ImportError i posted. Maybe some1 can point me to my probleme here.

A: The python you use is the default system python (you can check that wich which python which should display something like /usr/bin/python or wherever your system python is). This does not have access (by default) to libraries that are installed in a virtual environment. Instead you should use the python that is specific to the virtualenv. You can do that by explicitly calling the python which should be located in /path/to/virtualenv/env/bin/python. You can check that by activating the virtualenv and which python which should output the path to the python of the virtualenv.


text:
Q: Keeps getting NaN as result for jQuery AJAX copmuted value I have this HTML:

Insert New URL:

    <input type="text" id="NEW" value="" />

Inserted URLs:

    <textarea id="direct_URLs" rows="0"></textarea>

  <input id="run" type="submit" value="Insert" />

And, I have this jQuery:
  $("#run").click(function () {
  if ($("#NEW").val() !== "") {
    $("#direct_URLs").append(($("#direct_URLs").val() == '' ? '' : "\n") + $("#NEW").val());
    $("#direct_URLs").attr('rows', function (i, val) {
      var cnt = parseInt(val, 10) || 0;
      return isNaN(cnt) ? 1 : cnt + 1;
    });
  }
  });

I keep getting NaN on the rows=NaN.
I've tried the and did setup the mentioned code in here: http://jsfiddle.net/s3GDr/1/ , and it's working just fine.
But, on my page.. it's NOT..!! This drives me crazy, I've tried every thing I got my eyes on (Googled, other questions etc).
Please, some body shed some light on this..!! :(


text:
Q: How to get rid of laravel_session cookie from Laravel application? I'm trying to get rid of laravel_session.
I've tried to create a middleware for it
https://laracasts.com/discuss/channels/laravel/laravel-51-disable-session-and-cookies-for-some-routes
Change the driver to use : array file, database
None of that works. Every time I refresh, I always see this:

How can I achieve this? Is it even possible to do ?

A: If you don't want to start a session at all, in Laravel 5.1 go to app/Http/Kernel.php and comment out the session-related parts:
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    // \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    // \App\Http\Middleware\VerifyCsrfToken::class,
];

Note that it's not sufficient to only rip out the StartSession middleware, you'll also have to disable ShareErrorsFromSession and VerifyCsrfToken since they rely on a session being present. If you want more logic like excluding it for certain routes, you could override the StartSession middelware. I don't know of any other side effects though because I haven't tested it.
If you don't need sessions or all the website related functions because, for instance, you're only building an API, you might want to have a look at Laravel Lumen that is streamlined for this purpose.
And by the way: The session driver only defines where/how to store the session server-side. From the client side it's still just an encrypted cookie.

A: If I have specific routes that I don't want Laravel to use laravel_session.
You can apply that to any routes you want.
Ex. For example, if you want to apply to only these 2 routes :
url1 or url2
Route::get('/url1', 'SampleController@fnName');
Route::get('/url2', 'SampleController@fnName2');

Create /app/Http/Middleware/StartSessionMiddleware.php
<?php
namespace App\Http\Middleware;

use Closure;
use Config;

use Illuminate\Session\Middleware\StartSession as BaseStartSession;

class StartSessionMiddleware extends BaseStartSession
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        if($request->is('url1') || $request->is('url2')) {
            Config::set('session.driver', 'array');
        }

        return parent::handle($request, $next);
    }
}

Register that by appending a line into /app/Http/Kernel.php
\App\Http\Middleware\StartSessionMiddleware::class,
and now, that laravel_session should not be there anymore for those 2 routes.
I hope this can help someone.

A: For anyone searching, in Laravel 5.5+ you can change the env variable SESSION_COOKIE=. If you have a little older app, you might need to set this in config/session.php directly.

A: Use
if($request->path('url1') || $request->path('url2')) {

to look for a url path. For EU Cookie tracking I used:
<?php
  namespace App\Http\Middleware;

  use Closure;
  use Config;

  use Illuminate\Session\Middleware\StartSession as BaseStartSession;

  class StartSessionMiddleware extends BaseStartSession
  {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next) {

    if(!isset($_COOKIE['my-cookie'])) {
        Config::set('session.driver', 'array');
    }

    return parent::handle($request, $next);
  }
}

with my-cookie as the name of the cookie you are setting when user accepts.


text:
Q: Is it possible to catch ViewExpriedException in PhaseListener? For logging purposes, I am interested in detecting when a session timeout occurs in my JSF application.
I have implemented a PhaseListener that checks if users are logged in and have their session already active. My implementation of afterPhase method is:

*

*var url_accepted (used in the code) contains a list of public pages that users should have access in order to provide a login form.
public void afterPhase(PhaseEvent event) {
    FacesContext context = event.getFacesContext();
    HttpSession session = (HttpSession) context.getExternalContext().getSession(true);

    AuthenticationBean sessionBean = (AuthenticationBean) session.getAttribute("sessionBean");

    String url_req = context.getViewRoot().getViewId();

    //1. Check if user has a session and is logged in:
    if(((sessionBean == null) || (sessionBean != null && !sessionBean.isLoggedIn())) && !url_accepted.contains(url_req)){
        context.getApplication().getNavigationHandler().handleNavigation(context,null,"auth_error");
        return;
    }

//2. Code continues in order to check if a logged user has permissions to access the requested page(not relevant):
}

When an user has been disconnected due to a session timeout, the PhaseListener cannot retrieve my sessionBean from the ExternalContext and assigns null to the sessionBean attribute. At this point I cannot distinguish whether the user hasn't been logged-in before or has been disconnected by timeout.
I've read that one can use errorPages in order to detect a ViewExpiredException exception and redirect the view to a specific page. But i don't know if it's possible to manage this exception in my source code.
My question is: Can I catch this ViewExpiredException inside my PhaseListener implementation in order to handle a session timeout?
Thanks in advance.

A: I've faced the same scenario in a JSF project. The solution was to use a Filter to catch the session expired. BalusC (JSF Expert) explains this matter and shows a good example:

*

*User session filter
Additional, don't forget to add session.invalidate() in your logout method and in your session timeout handler.


text:
Q: Problems getting clean sunrise, sunset, civil, nautical and astronomical twilight data If in a notebook you enter:
WolframAlphaResult["Sunrise june 25, 2013", {{"DaylightInformation", 1}, "ComputableData"},
                   PodStates -> {"DaylightInformation__More"}]

you get:
{{"begin astronomical twilight","3:16 am EDT"},
{"begin nautical twilight","4:07 am EDT"},
{"begin civil twilight", "4:50 am EDT"},
{"sunrise","5:24 am EDT"},
{"sunset", "8:31 pm EDT"},
{"end civil twilight","9:05 pm EDT"},
{"end nautical twilight","9:48 pm EDT"},
{"end astronomical twilight","10:39 pm EDT"},
{"duration of daylight", {15, 8}}}

as a result (I didn't know there was something called "nautical twilight," but now that I do, I want it).  Unfortunately, the result is returned not as a nice list, but instead embedded in a complicated WolframAlphaResult format. Despite trying many different approaches, I have been unable to discover a way to get just a list of this data returned. It is possible?

A: WolframAlpha["Sunrise june 25, 2013", {{"DaylightInformation", 1},
   "ComputableData"}, PodStates -> {"DaylightInformation__More"}]

gives

{{"begin astronomical twilight",
    "3:56 am PDT"}, {"begin nautical twilight",
    "4:40 am PDT"}, {"begin civil twilight", "5:18 am PDT"}, {"sunrise",
     "5:49 am PDT"}, {"sunset", "8:33 pm PDT"}, {"end civil twilight",
    "9:04 pm PDT"}, {"end nautical twilight",
    "9:43 pm PDT"}, {"end astronomical twilight",
    "10:26 pm PDT"}, {"duration of daylight", {14, 44}}}

A: Oh, I was going to say the same thing. Here's a picture instead of me clicking in the little screw icon...

This pastes the query into your document (and runs it too):
WolframAlpha["Sunrise june 25, 2013", {{"DaylightInformation", 1},
  "ComputableData"}]

Then I assigned the results to a symbol for further processing.


text:
Q: Relative system path to miktex and pandoc - Shiny Application packaged as Windows desktop app I have packaged a Shiny application as a Windows desktop App by following the following tutorial: http://www.r-bloggers.com/deploying-desktop-apps-with-r/
In my Shiny application I provide the user to generate a PDF Report using pandoc and MikTex.
In order for this to work in my Desktop application, I have added the following code in my runShinyApp.R script.
Sys.setenv(PATH=paste("C:/Users/WoBa/Documents/dist/pandoc",sep=";",
"C:/Users/WoBa/Documents/dist/miktex/miktex/bin/"))

Although this works correctly, I would like this path to be relative so the application can be distributed to other users without them having to change the path.
I've tried the following - but this didn't work:
Sys.setenv(PATH=paste("./pandoc",sep=";",
"./miktex/miktex/bin/"))

Folder structure is the following:
dist/
 + GoogleChromePortable
 + miktex
 + pandoc
 + R-Portable
 + runShinyApp.R
 + run.bat

Anybody maybe nows how to make this path relative? (on Windows) It would help me a lot!

A: I managed to provide a relative path with the following code in my runShinyApp.R script:
miktex = file.path(getwd(), 'miktex/miktex/bin/')
pandoc = file.path(getwd(), 'pandoc')

Sys.setenv(PATH=paste(pandoc, sep=";", miktex))

Just providing the answer as this could be useful for other people in the future.

A: I have made a similar application using the same tutorial.
I have added the following to my runShinyApp.R-script based on a solution provided ny Yihui Xie, jst before the runApp command.
pandoc <- paste(getwd(), "pandoc-2.4", sep = "/")
TinyTex <- paste(getwd(), "TinyTeX/bin/win32", sep = "/")

add_path = function(path) {
  s = .Platform$path.sep
  paths = c(path, unlist(strsplit(Sys.getenv('PATH'), s)))
  Sys.setenv(PATH = paste(paths, collapse = s))
}

add_path(pandoc)
add_path(TinyTex)


text:
Q: How to programmatically turn off/on monitor on Raspberry Pi2 with Windows 10 IoT Core How to programmatically turn off/on monitor connected to Raspberry Pi 2 via the HDMI cable. The Raspberry Pi is used operating system Windows 10 IoT Core (10586).
I try user32.dll and SendMessage, but it does not work.
"Unable to load DLL 'user32.dll'. The specified module could not be found."

A: you can't send messages on current version of Windows IoT Core. There's actually no way to programmatically change power management options or interact with a monitor.


text:
Q: Do Android Message 'what' codes need to be unique in the scope of a Handler or a thread? Is the Message 'what' field unique to a Handler instance or to the MessageQueue of the thread that one or more Handler instances may be associated with?  The docs read "A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue" which seems to suggest that Message 'what' codes must be unique to a MessageQueue and therefore within the scope of a single thread rather than a single instance of Handler.
I have several Handler objects associated with my UI thread throughout my project, so do I have to ensure that all Message 'what' codes that are sent to any of these Handlers are unique, or do they only have to be unique for each Handler instance?
For example, what would the logs say after the following code is executed and both messages have been received:
class MainActivity extends Activity{
  public static final String TAG = "MainActivity";
  public static final int FIRST_PURPOSE_MESSAGE_CODE = 1;
  public static final int SECOND_PURPOSE_MESSAGE_CODE = 1;
  ...
  private static class FirstUIThreadHandler extends Handler{
    ...
    @Override
    public void handleMessage(Message msg){
      switch(msg.what){
        case FIRST_PURPOSE_MESSAGE_CODE:
          Log.v(TAG,"handling the first message");
          break;
      }
    }
  }
  ...
  private static class SecondUIThreadHandler extends Handler{
    ...
    @Override
    public void handleMessage(Message msg){
      switch(msg.what){
        case SECOND_PURPOSE_MESSAGE_CODE:
          Log.v(TAG,"handling the second message");
          break;
      }
    }
  }

  ...
  FirstUIThreadHandler firstUIThreadHandler = new FirstUIThreadHandler(...);
  SecondUIThreadHandler secondUIThreadHandler = new SecondUIThreadHandler(...);
  Message firstMsg = firstUIThreadHandler.obtainMessage();
  firstMsg.what = FIRST_PURPOSE_MESSAGE_CODE;
  firstUIThreadHandler.sendMessage(firstMsg);
  Message secondMsg = secondUIThreadHandler.obtainMessage();
  secondMsg.what = SECOND_PURPOSE_MESSAGE_CODE;
  secondUIThreadHandler.sendMessage(secondMsg);
  ...

}

A: The messages will be delivered only to the handler you use to send the message, two different handlers will not share any info about the messages sent to a different handler, hence, if you have the same "what" attribute in different messages, it will be passed to the "handleMessage(Message msg)" of the handler that called "sendMessage(yourMessage)", for example:
secondUIThreadHandler.sendMessage(secondMsg);

In the code above it means that the message will be received by the second handler only and it will be able to use the "what" attribute no matter if that attribute is the same for another message other than the current one used in secondUIThreadHandler.
Hope it helps!
Regards!


text:
Q: Exception thrown while executing UI block: [NSNull doubleValue]: unrecognized selector sent to instance 0x204329c00 I am trying to display icon relative to specific coordinates on a map, but I keep getting this error thrown, followed by:
removedChildren count(0) was not what we expected (1)

This won't allow the pin to show up on the map. Below is my code:
const [restaurant_Latitude, setRestaurantLatitude] = useState(0)
const [restaurant_Longitude, setRestaurantLongitude] = useState(0)
const [restaurantPositionError, setRestaurantPositionError] = useState(null)

Using react-native-svg to create an icon
const restaurantIcon = () =>{
      return(
        <Svg
          height = {30}
          width = {30}
        >
          <Ellipse
            cx="10"
            cy="10"
            rx="10"
            ry="10"
            fill="red"
            stroke="#fff"
            strokeWidth="2"
          />

        </Svg>
        )
    }

//useEffect to get restaurant's coordinates
useEffect(() =>{

...

displayRestaurantInfo = async () =>{
 let restaurantInfo = client_instance.getFoodInfo()

   setRestaurantLatitude(restaurantInfo.latitude)
   setRestaurantLongitude(restaurantInfo.longitude)
   setRestaurantPositionError(null)
}

displayRestaurantInfo()

)
}

...
//How it renders in the MapView
return(

        <MapView>

            <Marker
                coordinate={
                    {latitude: restaurantLatitude,
                     longitude: restaurantLongitude,
                     error: position_error,
                    }}
              >
                <View>
                  {(restaurantIcon())}
                </View>
              </Marker>
</MapView>


text:
Q: R optim function - N parameters I am working on SIR model. I try to estimate the parameters according to datas.
Here is a code similar to what I am working with.
library(pomp)

niamey <- read.csv("http://kingaa.github.io/clim-dis/parest/niamey.csv")

pomp(
  data=subset(niamey,community=="A",select=-community),
  times="biweek",t0=0,
  skeleton=vectorfield(
    Csnippet("
      DS = -Beta*S*I/N;
      DI = Beta*S*I/N-gamma*I;
      DR = gamma*I;")),
  rinit=Csnippet("
      S = S_0;
      I = I_0;
      R = N-S_0-I_0;"),
  statenames=c("S","I","R"),
  paramnames=c("Beta","gamma","N","S_0","I_0")) -> niameyA

sse <- function (params) {
  x <- trajectory(niameyA,params=params)
  discrep <- x["I",,]-obs(niameyA)
  sum(discrep^2)
}

f2 <- function (par) {
  params <- c(Beta=par[3],gamma=1,N=50000,S_0=par[1],I_0=par[2])
  sse(params)
}

for (m in c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN")){
  optim(fn=f2,par=c(10000,10,8),lower = -Inf, upper = Inf,method=m) -> fit2
  print(paste("for method",m,"we have-----------------------------:"))
  print(fit2)
}

*

*What is the general idea behind multiple parameters estimation ? ie, I understant the global idea for 1 parameter but how does it works for N parameters

*I am getting errors with some methods due to number size (<e-16), is there a way to avoid it ?


text:
Q: Convert digits into letters I am trying to make a javascript project in its basic stage in which the script should prompt the user, ask a digit as input, convert the digit into letters and display it to the user. However the script it not working as it should.

A: Particularly, I really don't like switch structure. I prefer JavaScript literal object notation.
Check this below:
html
<input type="button" id="getMyNumber" value="Get my Number"/>
JavaScript + jQuery
$(function() {
  $('#getMyNumber').on('click', function() {
      var numbers = {
          "1": "One",
          "2": "Two",
          "3": "Three",
          "4": "Four",
          "5": "Five",
          "6": "Six",
          "7": "Seven",
          "8": "Eight",
          "9": "Nine",
          "10": "Ten",
          "default": "No number typed!"
      };
      var input = prompt("Type a number: ");
      alert(numbers[input] || numbers["default"]);
   });
});

If you prefer, here goes jsFiddle. No conversion or tricks needed, just simple JavaScript.
Some references:
Mozilla - Working with Objects
The Case against Switch
-- EDIT --
Here is the solution with JavaScript only, to avoid the critics (jQuery loading, heavy loading, etc):
html
<input type="button" id="getMyNumber" value="Get my Number" onclick="getNumberRepresentation()" />
JavaScript Only
function getNumberRepresentation() {
  var numbers = {
      "1": "One",
      "2": "Two",
      "3": "Three",
      "4": "Four",
      "5": "Five",
      "6": "Six",
      "7": "Seven",
      "8": "Eight",
      "9": "Nine",
      "10": "Ten",
      "default": "No number typed!"
  };
  var input = prompt("Type a number: ");
  alert(numbers[input]);
}

Another jsFiddle version.

A: Check out this Fiddle I made for you.
EDIT: Source:
Html:

Click

Javascript:
function ask(){

    var inputAsString;
    var userInput = prompt("Pick a number");

    switch( parseInt(userInput) ){

        case 1:
            inputAsString = "One";
        break;
        case 2:
            inputAsString = "Two";
        break;
        default:
            inputAsString = "I don't know...";
    }

    alert( "\"" + userInput + "\" as a string is: " + inputAsString );
}


text:
Q: How to use Invoke for avoiding Cross Thread operation? I am developing a small software for retrieving data from device and send it to server.As it is a desktop software so i have to add current available message to GUI.It works fine until i have joined those Thread. When i try to stop this thread by setting flag(currently IsRunning  is my flag) value to false and then try to add a message to Gui it freeze whole application.probably deadlock issue but i am not entirely sure about that.
Please help
stop point of thread
try
        {
            IsRunning = false;
           _bgThread.Join(); //this makes a deadlock probably

           //_bgThread.Join(7000); //this works fine
        }
        catch (ThreadStartException ese)
        {
            throw ese;
        }

//Thread method
private void DeviceSync()
    {
        while (IsRunning)
        {
            // ...statement
        }
    //now what actually happen in my case is
    //when i try to stop the thread by setting the value of "IsRunning" false
    //it comes to this line and pass a message to UI by throwing OnThrowingMessage event

        var info = "Service Stopped at: " + DateTime.Now.ToString(BusinessRules.DateTimeFormat);
        OnThrowingMessage(info, MessageType.Important);// this event fails to bind message to UI thread causes freeze UI
    }

//delegate method
 private void OnGuiMessaging(string message, MessageType messageType)
    {
        try
        {
    //for avoiding Invalid Cross-thread Operations as sometimes it is calling from background thread
            if (this.currentStatedataGridView.InvokeRequired)
            {
                Console.WriteLine("Here it is for the first time ");
               //Application freeze here
                this.currentStatedataGridView.Invoke(new SomeDelgate(OnGuiMessaging), new object[] { message, messageType });
            }
            else
            {
               //add row
                string[] rowData = new string[] { DateTime.Now.ToString(BusinessRules.DateTimeFormat), message };
                currentStatedataGridView.Rows.Insert(0, rowData);
                currentStatedataGridView.Rows[0].DefaultCellStyle.BackColor = rowColor;
             }
       }
        catch (Exception ex)
        {
            Log.Error(ex);
        }
    }

A: fixed this issue :)
Replace Delegate.Invoke with Delegate.BeginInvoke solve my issue because it executes asynchronously as it Executes on the UI thread, and calling thread doesn't wait for completion. on the other side Control.Invoke Executes on the UI thread, but calling thread waits for completion before continuing.
can see more from What's the difference between Invoke() and BeginInvoke()


text:
Q: Wget works, Ping doesn't There are some anomalies on a Virtuozzo virtualized Debian 4 (I know, I'm gonna upgrade this one asap, but there dependences). We run some Websites on this one. And a view Days ago exmi4 wasnt able to send mails to SOME people. I'll use live.com as exampledomain!
So some of this people got mails and some didn't.
Some of the mails got stuck in the queue, and after 2 days they went out!!
My Nagios never showed problems with the internet connection or disk space
Now i wanted to install "dig" to look how he's solving the dns request. And this Debian tells me he doesn't know dig..
Long story made short, Debian is able to download sites with exact IP or even with wget live.com, but it is not able to ping live.com.
I'm 99% sure that the networking is right and the routing too!
Some examples of my tring below:
wget live.com

downloads the site
ping live.com
ping http://www.live.com
ping http://live.com

returns:

ping: unknown host live.com

EDIT:
i now use heise.de not live.com any more.
and i found out i can ping the heise.de server by using it's IP-address.
myserver:~# ping 193.99.144.85
PING 193.99.144.85 (193.99.144.85) 56(84) bytes of data.
64 bytes from 193.99.144.85: icmp_seq=1 ttl=248 time=12.7 ms
64 bytes from 193.99.144.85: icmp_seq=2 ttl=248 time=12.6 ms
64 bytes from 193.99.144.85: icmp_seq=3 ttl=248 time=12.9 ms
64 bytes from 193.99.144.85: icmp_seq=4 ttl=248 time=13.1 ms
64 bytes from 193.99.144.85: icmp_seq=5 ttl=248 time=13.1 ms

--- 193.99.144.85 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4001ms
rtt min/avg/max/mdev = 12.671/12.924/13.163/0.238 ms

EDIT 2:
myserver:/etc/apt# dig heise.de

; <<>> DiG 9.3.4-P1.2 <<>> heise.de
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40551
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 5, ADDITIONAL: 3

;; QUESTION SECTION:
;heise.de.                      IN      A

;; ANSWER SECTION:
heise.de.               2266    IN      A       193.99.144.80

;; AUTHORITY SECTION:
heise.de.               1622    IN      NS      ns.pop-hannover.de.
heise.de.               1622    IN      NS      ns.s.plusline.de.
heise.de.               1622    IN      NS      ns.plusline.de.
heise.de.               1622    IN      NS      ns2.pop-hannover.net.
heise.de.               1622    IN      NS      ns.heise.de.

;; ADDITIONAL SECTION:
ns.plusline.de.         265     IN      A       212.19.48.14
ns.pop-hannover.de.     5113    IN      A       193.98.1.200
ns2.pop-hannover.net.   15150   IN      A       62.48.67.66

;; Query time: 2 msec
;; SERVER: 193.200.112.80#53(193.200.112.80)
;; WHEN: Tue Oct  9 13:03:50 2012
;; MSG SIZE  rcvd: 216

A:
ping: unknown host live.com

An unknown host error refers to problems with name to ip address resolution.  AFAICT, you're not having that problem as long as you use 192.200.113.30 and 192.200.112.80 in /etc/resolv.conf...
[mpenning@tsunami tests]$ dig +short @193.200.113.30 live.com
65.55.206.154
[mpenning@tsunami tests]$ dig +short @193.200.112.80 live.com
65.55.206.154
[mpenning@tsunami tests]$

That said, what you're seeing could be related to trying to use ping http://live.com.  Do not use the http:// prefix on your pings... that is only meaningful to a web browser.
FYI, live.com does not return pings, so you should not expect any to be returned... they should all time-out...
[mpenning@tsunami tests]$ ping -w 1 live.com
PING live.com (65.55.206.154) 56(84) bytes of data.

--- live.com ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

[mpenning@tsunami tests]$

EDIT
I get this when I ping heise.de...
[mpenning@tsunami tests]$ ping heise.de
PING heise.de (193.99.144.80) 56(84) bytes of data.
64 bytes from redirector.heise.de (193.99.144.80): icmp_req=1 ttl=241 time=144 ms
64 bytes from redirector.heise.de (193.99.144.80): icmp_req=2 ttl=241 time=144 ms
64 bytes from redirector.heise.de (193.99.144.80): icmp_req=3 ttl=241 time=144 ms
64 bytes from redirector.heise.de (193.99.144.80): icmp_req=4 ttl=241 time=143 ms
^C
--- heise.de ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3002ms
rtt min/avg/max/mdev = 143.734/144.344/144.730/0.598 ms
[mpenning@tsunami tests]$


text:
Q: PWM LED using TIM1 on STM32 I need to PWM my LED on STM32F3 Discovery which is on PE8. I have found code which is using PWM on PA8 and PC8 (one using TIM1) but unfortunately I can't change it to PE8.
How to do it? Or maybe you have better code to enable PWM using TIM1?
Original code:
#include "main.h"                                                                                //main library to include for device drivers, peripheral drivers, etc.
void RCC_Configuration(void);
void GPIO_Configuration(void);

// Unused global variables that have to be included to ensure correct compiling */
// ###### DO NOT CHANGE ######
// ===============================================================================
__IO uint32_t TimingDelay = 0;                                                                  //used with the Delay function
__IO uint8_t DataReady = 0;
__IO uint32_t USBConnectTimeOut = 100;
__IO uint32_t UserButtonPressed = 0;
__IO uint8_t PrevXferComplete = 1;
// ===============================================================================

int main(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

    RCC_Configuration();
    GPIO_Configuration();

    TIM_TimeBaseStructure.TIM_Period = 600;
    TIM_TimeBaseStructure.TIM_Prescaler = 6000-1;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = 600/1.2;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

    TIM_OC3Init(TIM3, &TIM_OCInitStructure);
    TIM_OC1Init(TIM1, &TIM_OCInitStructure);

    TIM_Cmd(TIM3, ENABLE);
    TIM_Cmd(TIM1, ENABLE);

    TIM_CtrlPWMOutputs(TIM1, ENABLE);

    while (1);

}

void RCC_Configuration(void)
{
   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);
   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC,ENABLE);
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
   RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
}

void GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

   GPIOA->AFR[1] |= 6; // AF6
   GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_8 ;
   GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
   GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;

   GPIO_Init(GPIOA, &GPIO_InitStructure);

   GPIOC->AFR[1] |= 2; // AF2
   GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_8;
   GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
   GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
   GPIOC->AFR[1] |= 2;

   GPIO_Init(GPIOC, &GPIO_InitStructure);
}

// Function to insert a timing delay of nTime
// ###### DO NOT CHANGE ######
void Delay(__IO uint32_t nTime)
{
  TimingDelay = nTime;

  while(TimingDelay != 0);
}

// Function to Decrement the TimingDelay variable.
// ###### DO NOT CHANGE ######
void TimingDelay_Decrement(void)
{
  if (TimingDelay != 0x00)
  {
    TimingDelay--;
  }
}

// Unused functions that have to be included to ensure correct compiling
// ###### DO NOT CHANGE ######
// =======================================================================
uint32_t L3GD20_TIMEOUT_UserCallback(void)
{
  return 0;
}

uint32_t LSM303DLHC_TIMEOUT_UserCallback(void)
{
  return 0;
}
// =======================================================================

Edited part:
void RCC_Configuration(void)
{
   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);
   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOE,ENABLE);
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
   RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
}

void GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

   GPIOA->AFR[1] |= 6; // AF6
   GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_8 ;
   GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
   GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;

   GPIO_Init(GPIOA, &GPIO_InitStructure);

   GPIOE->AFR[1] |= 2; // AF2
   GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_8;
   GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
   GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
   GPIOE->AFR[1] |= 2;

   GPIO_Init(GPIOE, &GPIO_InitStructure);
}

A: The problem was with alternating function. I had to find a table and change it to proper one for port E :)


text:
Q: Classification vs clustering I am beginner to data mining.
This is my understanding, regression is used to predict continuous values. It is a type of classification.
Classification is Supervised and Clustering is unsupervised.
In classification we have predefined classes, whereas in clustering there are no classes defined.
What does this exactly mean? But in both of them we do have training data, which tells which output the set of features should belong to. Then how can we say that clustering does not have per-defined classes?
Please explain when to use classification and clustering.
Can clustering also predict continuous values?
Thanks. Please help.
This post has been edited.

A: Clustering: In clustering you group(cluster) the data based on some variables into some number of groups (cluster).
Classification: In classification, you have certain groups & you want to know how different variables are related to the groups.

A: As @chl says, there are good threads on this site regarding supervised versus unsupervised learning. In regards to your bolded question: you're misunderstanding what data is supplied to supervised versus unsupervised methods. Supervised methods will always include an additional piece of information for each sample: the correct answer.

A: These video lecture's are really a good if you bring some time to listen to them. Particularly your questions about supervised vs. unsupervised should all be covered.


text:
Q: Динамический прогресс бар с датой и наложением цвета на дату Задача сделать динамический progress bar.
Во первых должно изменяться время, которое осталось до определённой даты. С этим проблем нет.
Основной вопрос - как сделать так, чтобы цифры заливались по контуру? (этот контур тоже считается динамически от остaвшегося).
Нужен совет в какую сторону вообще смотреть, ибо у меня в голове не совсем понятно как это реализовать. В теории должно быть какое-то перекрытие между 2 текстурами - текстом и белым прямоугольником. Но ничего похожего я не нашёл.
Интересует подход к решению на чистом canvas или three.js или pixi.js. Спасибо!

A: Голый canvas с отрисовкой:

var text = "6D:20:50:17";
var ctx = c.getContext("2d");
ctx.font = "bold 96px Times New Roman";
ctx.textAlign = 'center';

function drawText() {
  ctx.clearRect(0, 0, 512, 128);
  ctx.fillStyle = "gray";
  ctx.fillRect(0, 0, Math.floor(Math.random() * 512), 128);
  ctx.globalCompositeOperation = "destination-in";
  ctx.fillText(text, 256, 96);

  ctx.globalCompositeOperation = "source-over";

  ctx.strokeStyle = "maroon";
  ctx.lineWidth = 3;
  ctx.strokeText(text, 256, 96);
}

drawText();

setInterval(drawText, 1000);
canvas {
  border: 1px solid red;
  background-color: pink;
}
<canvas id="c" width="512" height="128"></canvas>

A: Вариант на чистом css:

body{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 100%;
  text-align: center;
  min-height: 100vh;
  font-size: 16px;
  background: black;
}

h1 {
  background: linear-gradient(to right, tomato 17%,  transparent 17%);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  -webkit-text-stroke: 1px #ffffff
}

Text Transparent

A: Регулируется с помощью background-position от 0% до -100%... Но к сожалению работает только в webkit-браузерах. Для остальных браузеров можно сделать fallback.

div {
  height: 200px;
  background-image: linear-gradient(0deg, yellow 0%, green 100%);
}

h1 {
  display: inline-block;
  font-variant: small-caps;
  font-size: 70px;
  font-weight: 800;
  text-align: center;
  background-image: linear-gradient(90deg, transparent 50%, red 50%);
  background-size: 200% 200%;
  background-position: -43% center;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke: 1px rgb(0, 0, 0);
}

Character


text:
Q: How do I check if a sound is playing in the background? I'm using My.Computer.Audio.Play(My.Resources.Sound1, AudioPlayMode.Background)
to play my sound, but I need to check if it's already playing before executing this code because otherwise it just keeps looping to the start of the audio file, is there any way to do this in vb.net?

A: It's impossible without external library.
You can use a OpenSource DLL like NAudio or LibZPlay to play and give all control over the player.
It's simple and very efficient.
http://naudio.codeplex.com
http://libzplay.sourceforge.net/
Att.
Anderson


text:
Q: pandas: sorting observations within groupby groups According to the answer to pandas groupby sort within groups, in order to sort observations within each group one needs to do a second groupby on the results of the first groupby.  Why a second groupby is needed?  I would've assumed that observations are already arranged into groups after running the first groupby and all that would be needed is a way to enumerate those groups (and run apply with order).

A: They need a second group by in that case, because on top of sorting, they want to keep only the top 3 rows of each group.
If you just need to sort after a group by you can do :
df_res = df.groupby(['job','source']).agg({'count':sum}).sort_values(['job','count'],ascending=False)

One group by is enough.
And if you want to keep the 3 rows with the highest count for each group, then you can group again and use the head() function :
df_res.groupby('job').head(3)

A: Because once you apply a function after a groupby the results are combined back into a normal ungrouped data frame. Using groupby and a groupby method like sort should be thought of like a Split-Apply-Combine operation
The groupby splits the original data frame and the method is applied to each group, but then the results are combined again implicitly.
In that other question, they could have reversed the operation (sorted first) and then not have to use two groupbys. They could do:
df.sort(['job','count'],ascending=False).groupby('job').head(3)


text:
Q: Java operands different consistency Do you know if there is any rule statement to follow regarding the feasible arithmetic operations among different representations?
For instance:7
int a = 0342342;
int b = 0x1abcdef;
int c = a +b;
System.out.println("It prints out : "+c);

It prints out : 28152529
.
The results (c) is a decimal representation of the addition of the 2 operands a and b.
What if I wanted the result in a particular representation format different from the decimal format?

A: The numbers 0342342 and 0x1abcdef are literal representations of integers that Java supports for the convenience of developers. Within Java, there really is only one representation of that integer and it is stored in the int type with no reference to a number base (like octal or hexadecimal).
By default, when you print an int, it is displayed in the decimal format.
If you want some other format, you should use System.out.printf:
System.out.printf("Decimal: %d",c);
System.out.printf("Octal: %o",c);
System.out.printf("Hexadecimal: %x",c);

A: to print in hex do like this
System.out.printf("It prints out %x\n", c);

A: You can use System.out.format in order to represent in different format.
You can find more detailed answer in here:
http://docs.oracle.com/javase/tutorial/essential/io/formatting.html


text:
Q: redirect to requested page after login using PHP function i have a function that echo $_SESSION value in login page and store $_SERVER['REQUEST_URI'] as $_SESSION value on other page and it works fine.
But i need to call redirect_after_login function in all product page so i just added line after redirect_after_login
So my function.php file will look link this
<?php

session_start();
$key = '';

function redirect_after_login($value) {
if (!empty($value)) {
    echo $_SESSION['url'];
  } else {
      echo $_SESSION['url'] = $_SERVER['REQUEST_URI'];
  }
}

$activate_finction = $key == true ? 'Yes' : '';
$url = redirect_after_login($activate_finction);

And in login.php i added
$key .= 'login';//calling redirect function with value so it should send session value

if (isset($_POST['submit'])) {
        // login function skipped it....
            header('location:' . $url);
            exit;
        } else {
            $error[] = 'Wrong username or password or your account has not been activated.';
        }
    }

Since $key .= 'login'; has value
$activate_finction = $key == true ? 'Yes' : '';
$url = redirect_after_login($activate_finction);

Function is now called with ==true so i should receive stored value but still i get requested_url
My problem is
in all page i get $_SESSION['url'] = $_SERVER['REQUEST_URI']; this value.
How do i get session value login.php and in all product pages function should store requested_url as session value.

A: I refactor the code, so here you are a complete example:
function.php:
<?php
    session_start();

    if (isset($_SERVER['HTTP_REFERER']) && basename($_SERVER['HTTP_REFERER']) != basename($_SERVER['PHP_SELF'])) {
        $_SESSION['url'] = $_SERVER['HTTP_REFERER'];
    }

    function redirect_after_login() {
        header('Location:' . $_SESSION['url']);
    }
?>

product.php:
<?php
    include "function.php";
?>

        This is <?php echo $_SERVER['PHP_SELF']; ?> file.

        <input type="button" name="login" value="Login" onclick="location.href='login.php'">

login.php
<?php
    include "function.php";

    if(isset($_POST['submit'])){
        if($_POST['username'] == 1 && $_POST['password'] == 1){
            //success
            $_SESSION['logged'] = 1;
            redirect_after_login();
        }else{
            //error
            $_SESSION['logged'] = 0;
            $error = 'Wrong username or password';
        }
    }else{
        unset($error);
    }
?>

        This is <?php echo $_SERVER['PHP_SELF']; ?> file.

        <form method="post" action="login.php">
            User: <input type="text" name="username">

            Pass: <input type="password" name="password">

            <input type="submit" name="submit" value="Login">
        </form>
        <?php
            if(isset($error)) echo "ERROR:" .$error;
        ?>

Some short explanations:

*

*to test the redirect logic, you can load product.php?id=258 initially;

*$_SESSION['url'] is keeping HTTP_REFERER - the page you are coming from;

*login.php is calling redirect_after_login() function on successful login (currently with user:1/pass:1, just for the example)

*on successful login, there is an addition SESSION variable logged which you can use further (like to hide LOGIN button onto product.php page)

*on bad login, there is an error displayed, but you the user stays on login screen.

*$_SESSION['url'] is overwritten every time when you are visiting a different page and only then. This prevents losing HTTP_REFERER in case of bad login (when you have an actual refresh and HTTP_REFERER becomes the page itself)

Hope this helps.


text:
Q: Overwriting a variable I'm still in the early days with Perl, so apologies if this is obvious.
I'm declaring a variable in Perl as shown below:
my $new_filename = 'nope';

Now if a certain condition is met (lets assume it is here), I'm attempting to reassign the value of $new_filename like so:
my $new_filename = "$common::conf{'html_dir'}/images/banners/$lc_prodid.$filetype";

I'm them assigning the valuu to a table:
my $sql_query = qq(INSERT INTO banner_image (link, title, active, imageloc, rank) VALUES ('$link_text','$banner_text','$active','$new_filename','$new_rank'));

The issue I have is $new_filename always appears as 'nope' in the database. Could anyone suggest why this might be?
Thanks

A: The keyword my is used to declare a variable. That means it will tell Perl about a new variable in a given scope. You only have to do that once. After you have declared the variable, you can assign to it as often as you want.
my $foo = 'foo';
$foo = 'bar';

But that is not the only issue here.

Now if a certain condition is met (lets assume it is here), I'm attempting to reassign

This probably looks like the following:
my $foo = 'foo';
if ( $bar ) {
  my $foo = 'bar';
}

Now you have declared a new lexical version of $foo in the smaller scope of those braces after the if. You are not overwriting the existing $foo in the outer scope. That's why the value does not change.
Here are some tips/a summary about this:

*

*declare variables in the smallest scope necessary

*declare variables as late as possible

*don't declare variables twice

A: if you are assigning :
my $new_filename ="$common::conf{'html_dir'}/images/banners/$lc_prodid.$filetype";

inside the if clause then it is local to the scope of the if statement and will not override the variable declared outside, you need to omit the my in the second assingment


text:
Q: Finding a linear transformation given the null space
Find a linear transformation $T\colon \mathbb{R^5} \to \mathbb{R^3}$ such that $$\operatorname{null}(T) =\operatorname{span}\left\{\begin{pmatrix} 1 \\ 1 \\ 0 \\ 0 \\ 1 \end{pmatrix}, \begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \\ 1 \end{pmatrix}\right\}.$$

I tried to construct a matrix with columns corresponding to transformations of the basis vectors of $\mathbb{R^5}$ which are
$$e_1=\begin{pmatrix} 1 \\ 1 \\ 0 \\ 0 \\ 1 \end{pmatrix},\quad e_2=\begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \\ 1 \end{pmatrix},\quad e_3=\begin{pmatrix} 0 \\ 0 \\ 1 \\ 0 \\ 0 \end{pmatrix},\quad e_4=\begin{pmatrix} 0 \\ 0 \\ 0 \\ 1 \\ 0 \end{pmatrix},\quad e_5=\begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 1 \end{pmatrix}.$$
The matrix I made was $$\begin{pmatrix} 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 1 \end{pmatrix}.$$
I made this thinking that $e_1$ gets sent to $\begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}$, $e_2$ gets sent to $\begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}$, $e_3$ gets sent to $\begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}$, $e_4$ gets sent to $\begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}$ and $e_5$ gets sent to $\begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}$. Because we need $T(e_3), T(e_4), T(e_5)$ to be linearly independent. But this transformation I found out is just $T(x_1,x_2,x_3,x_4,x_5) = (x_3,x_4,x_5)$ and then it doesn't send $e_1$ or $e_2$ to $\begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}$. I'm kind of confused. I want  to find the linear transformation by constructing a matrix but it seems my work is wrong. How should I do this?
I also have another question. We have $$\operatorname{null}(T)=\operatorname{span}\left\{\begin{pmatrix} 1 \\ 1 \\ 0 \\ 0 \\ 1 \end{pmatrix},\begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \\ 1 \end{pmatrix}\right\}.$$ How can I make an equation of the null space using these two basis vectors? I am asking this because I saw another question where we had to construct a linear transformation using the null space but the answer used the equation of the null space instead of the basis vectors of the null space. I, however, wish to do it both ways.
Thank you.

A: Yes, that matrix that you got corresponds to the linear map $T(x_1,x_2,x_3,x_4,x_5)=(x_3,x_4,x_5)$, but only if you consider $\{e_1,e_2,e_3,e_4,e_5\}$ as a basis of $\Bbb R^5$ (and the standard basis as a basis of $\Bbb R^3$). However, if you consider the standard basis as a basis of $\Bbb R^5$, then, since:

*

*the first vector of the standard basis is $e_2-e_5$,

*$T(e_2-e_5)=(0,0,-1)^T$;

*the second vector of the standard basis is $e_1-e_2$;

*$T(e_1-e_2)=(0,0,0)^T$,

the matrix of $T$ with respect to both standard bases is$$\begin{bmatrix}0&0&1&0&0\\0&0&0&1&0\\-1&0&0&0&1\end{bmatrix},$$and therefore $T(x_1,x_2,x_3,x_4,x_5)=(x_3,x_4,-x_1+x_5)$, and so indeed $T(e_1)=T(e_2)=0$.


text:
Q: Creating a dataframe from dictionary with arbitrary length values (using recycled keys as column value) I am struggling with converting a dictionary into a dataframe.
There are already a lot of answers showing how to do it in the "wide format" like https://stackoverflow.com/a/52819186/6912069 but I would like to do something different, preferably not using loops.
Consider the following example:
I have a dictionary like this one
d_test = {'A': [1, 2], 'B': [3]}

and I'd like to get a dataframe like
index id    values
0     A     1
1     A     2
2     B     3

The index can be a normal consecutive integer column. By recycling I mean turning 'A'=[1, 2] into two rows having A in the id column and the values in the values column. This way I would have a "long format" dataframe of the dictionary items.
It seems to be a very basic thing to do, but I was wondering if there is an elegant pythonic way to achieve this. Many thanks for your help.

A: I would create 2 lists. One from the keys, and other one from the values of the dictionary. As you defined the lists you can pass the lists into the DataFrame.
import pandas as pd
dic = {'A': [1, 2], 'B': [3], 'D': [4, 5, 6]}

keys = []
values = []

for key, value in dic.items():
    for v in value:
        keys.append(key)
        values.append(v)

df = pd.DataFrame(
    {'id': keys,
     'values': values,
    })
print(df)


text:
Q: Does WaitOnAddress return when values match or when values differ? I am trying to use the WaitOnAddress() function to achieve read-write synchronization.
According to MSDN, WaitOnAddress() has the following declaration:
BOOL WaitOnAddress(
  volatile VOID *Address,
  PVOID         CompareAddress,
  SIZE_T        AddressSize,
  DWORD         dwMilliseconds
);

and the following parameter definition:

CompareAddress
A pointer to the location of the previously observed value at Address. The function returns when the value at Address differs from the value at CompareAddress.

According to the definition, I should store and pass the current value of the watched address, so when the watch value changes, WaitOnAddress() will return. But this function does not work as I expected, so I wrote the following test code for WaitOnAddress() in Visual Studio (and also included linker library Synchronization.lib):
#include <stdio.h>
#include <stdlib.h>  // atoi
#include <string.h>

// include these two files after including winsock2.h
#include <process.h>
#include <Windows.h>
#include <synchapi.h>

void* threads(void* num) {
    int* number = (int*)num;
    for (int i = 0; i < 10; i++) {
        printf("number = %d\n", *number);
    }
    int catch = *number; // will be passed as CompareAddress
    WaitOnAddress((int*)num, &catch, sizeof(int), INFINITE);
    for (int i = 0; i < 10; i++) {
        printf("number2 = %d, %d\n", catch, *(int*)num);
    }
    return NULL;
}

int main() {
    int int_list[10];
    for (int i = 0; i < 10; i++) {
        int_list[i] = i;
        _beginthread(threads, 0, (void*)&int_list[i]);
    }
    printf("hello\n");
    Sleep(1000);
    for (int i = 0; i < 10; i++) {
        int_list[i] = 10 - i;
    }
    printf("changed\n");
    Sleep(1000);
    return 0;
}

In above code, WaitOnAddress() never returns even though the value it watches changes. But, if I change
int catch = *number;

to:
int catch = 10 - *number;

then WaitOnAddress() returns and the rest of the output is printed, as if it returns ONLY when the watched value matches the compared value.
But, I want to used the described behavior so my thread is released whenever the watched variable is changed.

A: According to the documentation:

Parameters
Address
The address on which to wait. If the value at Address differs from the
value at CompareAddress, the function returns immediately. If the
values are the same, the function does not return until another thread
in the same process signals that the value at Address has changed by
calling WakeByAddressSingle or WakeByAddressAll or the timeout
elapses, whichever comes first.

Although you modify the value of the original array in the second loop, the catch and num are always the same when calling WaitOnAddress in the thread, so the WaitOnAddress function will not return.
You can try to modify it to:
#include <stdio.h>
#include <stdlib.h>  // atoi
#include <string.h>

// include these two files after including winsock2.h
#include <process.h>
#include <Windows.h>

void* threads(void* num) {
    int* number = (int*)num;
    printf("number = %d\n", *number);
    int catch = *number; // will be passed as CompareAddress
    WaitOnAddress((int*)num, &catch, sizeof(int), INFINITE);
    printf("number2 = %d, %d\n", catch, *(int*)num);
    return NULL;
}

int main() {
    int int_list[10];
    for (int i = 0; i < 10; i++) {
        int_list[i] = i;
        _beginthread(threads, 0, (void*)&int_list[i]);
    }
    printf("hello\n");
    Sleep(1000);
    printf("changed\n");
    for (int i = 0; i < 10; i++) {
        int_list[i] = 10 - i;
        WakeByAddressSingle(&int_list[i]);
    }
    Sleep(1000);
    return 0;
}

And it works for me:


text:
Q: Combinatorial proof of sum of numbers Does anyone have any insight on showing that $\sum_{i=1}^n i = {n+1\choose 2}$, through a combinatorial argument (i.e., not an algebraic argument)?

A: *

*We will make two choices.  First we will chose a number $i$ from $\{1,\ldots, n\}$ and  put down a row of $i$ identical objects.  Then we will split the row into at most two parts.
Clearly, for each $i$ the row can be split in exactly $i$ ways.  So the number of possible ways of doing this is $\sum_{i=1}^n i$.

*But this is the same as taking a row of $n$ objects, inserting two dividers, say to the right of objects $k_1$ and $k_2$, discarding all the objects to the right of the rightmost divider, and considering the remaining row of objects as being divided in two by the left divider.  And there are $n+1\choose 2$ ways to insert the two dividers.

A: See the top-voted proof without words at MathOverflow.  This proof was discovered by Loren Larson, professor emeritus at St. Olaf College. He included it along with a number of other, more standard, proofs, in "A Discrete Look at $1+2+...+n$," published in 1985 in The College Mathematics Journal (vol. 16, no. 5, pp. 369-382).

A: Here is a very simple combinatorial proof which uses the fact:
$$\sum_{k=r}^{n} {k \choose r} = {n+1 \choose r+1}$$
Proof:
Consider the numbers $1,2,3,...,n,(n+1)$.
Note that we can select $(r+1)$ numbers from these $(n+1)$ numbers in ${n+1\choose r+1}$ ways.
But note that every choice of $(r+1)$ elements must have a largest element, so we can as well pick this largest element $t$ and pick the remaining $r$ numbers from the the set of all numbers less than $t$. But $t$ can range from $(r+1)$ to $(n+1)$, and for each choice of $t$ we have to select the remaining $r$ elements in ${t-1 \choose r}$ ways, so we have
$$\sum_{t=r+1}^{n+1} {t-1 \choose r} = \sum_{k=r}^{n} {k \choose r} = {n+1 \choose r+1}$$
Now our original problem simply becomes
$$\sum_{k=1}^{n} {k \choose 1} = \sum_{k=1}^{n} k = {n+1 \choose 2}$$
And we are done.

A: There is a way to see this inductively. Suppose you knew this formula up till $n-1$. Then, $n + 1$ choose $2$ is equal to $n$ choose $2$ plus the number of ways to choose a pair of distinct elements from $\{1,\cdots, n + 1\}$ such that one of them is the 'new' element $n+1$. This is equal to $n$ choose $1$, i.e. $n$, and so the difference between $n+1$ choose $2$ and $n$ choose $2$ must be $n$.


text:
Q: Proper use of Virtual Scrolling with Angular Material and mat-tables? Alright, so recently I've been trying to migrate some of my table functionality over to using virtual scrolling, simply because the DOM is being bogged down with hundreds of nodes all at once with large data sets.
That being said, I was just going to use the Angular Material CDK virtual table scrolling directive on my tables, since they are mat-tables anyways. I found some examples and all, though I can't seem to get things to properly work.
These are the sources I was using for info:

*

*https://material.angular.io/cdk/scrolling/examples

*https://diprokon.github.io/ng-table-virtual-scroll/#/examples
Below is the template I'm using here for the table
<cdk-virtual-scroll-viewport tvsItemSize>

 0" [dataSource]="yuleLogs">

    <ng-container matColumnDef="logID">
       Log ID
      {{ yuleLog.logID }}
    </ng-container>

    <ng-container matColumnDef="logCategory">
       Log Category
      {{ yuleLog.category.categoryName }}
    </ng-container>

    <ng-container matColumnDef="logText">
       Log Information
      {{ yuleLog.logText }}
    </ng-container>

    <ng-container matColumnDef="logDate">
       Log Date
      {{yuleLog.logDate.toLocaleDateString()}} {{ yuleLog.logDate.toLocaleTimeString() }} (Eastern Standard Time)
    </ng-container>

</cdk-virtual-scroll-viewport>

And the actual Typescript
import { Component, Input, OnInit } from '@angular/core';
import { YuleLog } from 'src/classes/yuleLogTypes';

@Component({
  selector: 'app-log-table',
  templateUrl: './log-table.component.html',
  styleUrls: ['./log-table.component.css']
})
export class LogTableComponent implements OnInit {

  constructor() { }

  @Input() yuleLogs: Array<YuleLog> = [];

  columns: string[] = ["logID", "logCategory", "logText", "logDate"];

  ngOnInit(): void {
  }

}

So I'm aware that the data source for the table needs to be a TableVirtualScrollDataSource object and all, though the problem here is that this is a child table that should be variable and usually is based on the data in the input. Many of the Angular Material examples make constants outside of the class, which wouldn't exactly help out in the realm of using Input binding and all, so my question is, what is the best way in this situation to make the @Input() array as it is, but pass its data to a  TableVirtualScrollDataSource variable, keeping in mind that the actual array might change because of the parent?


text:
Q: django settings variables get lost in while being passed to templates i have a weird problem.
Basically, in my settings.py file i have 4 variables
URL_MAIN = 'http://www.mysite'
URL_JOBS = 'http://jobs.mysite'
URL_CARS = 'http://cars.mysite'
URL_HOMES = 'http://homes.mysite'

In my views.py i have the usual:
from settings import *

I have 6 views calling them and just returning them to templates inside the context:
class CarsHp(TemplateView):
     ...

class JobsHp(TemplateView):
     ...

class HomesHp(TemplateView):
     ...

class CarsList(TemplateView):
     ...

class JobsList(TemplateView):
     ...

class HomesList(TemplateView):
     ...

which are being called in urls by
CarsList.as_view()
...

All of those views have the same statement:
context['URL_MAIN'] = URL_MAIN
...

for all 4 variables.
In templates i'm correctly getting all 4 of them, except for URL_MAIN, which "gets lost" in 2 of those 6 views. I'm accessing them with classical {{ URL_MAIN }} and i've been trying everything, from moving to renaming, but still that URL_MAIN doesn't show up (i get empty string, no errors of sort) after being served from 2 of those views. All the functions basically share the same code (except for the querying and data processing part) and those settings' variables are just being assigned and returned off. Not any sort of check nor modification. I've been trying with django's shell, and i could always retrieve them.
We're being served by apache, with some proxypassing configurations for the robots.txt file and static files. Nothing "serious".
I'm not posting all the 6 views source codes just because they're long and the relevant parts are all described above. But i can post them if you want,i just don't know if it is actually useful since i've been triple checking all the sources for clashing on names or double declarations or incorrect use.
Thanks all in advance, this is really stunning my brain

A: Ideally, you should use template context processors for this. It will cut down your code and allow you to see exactly where the problem is.
Make a file in your projects called urls_context_processor.py (or similar) and put your variables in there:
def common_urls(request):
    return {
        'URL_MAIN': "http://...",
        'URL_JOBS': "http://...",
        'URL_CARS': "http://...",
        'URL_HOME': "http://...",
    }

and in your settings.py
TEMPLATE_CONTEXT_PROCESSORS = = (
      ....
      'my_project.urls_context_processor.common_urls',)

now the urls variables will be automatically available in all your template, and you won't need to hard code them into every view.


text:
Q: How to pass an integer as a command line argument in c? I have the following code below:
int main(int argc, char *argv[]) {

  int n = argv[1];
  function1(n);

}

Naturally, my code gives an error because argv[] is a pointer to a char. I want to run the program with an integer that gets passed and used by a function called "function1."
For example:
./program 5

How do I do this with any input, so that the n is equal to that input?