text:
Q: How to compile Corkscrew using Cygwin I want to compile Corkscrew. However I am not very familiar with Unix environments.
Here are the things I have tried and how I failed.

Step 1 : I installed Cygwin and from the Cygwin Terminal (mintty.exe), I tried to invoke ./configure in the Corkscrew source directory, as instructed in the README file.
This action produced the following error message:
checking whether the C compiler (gcc  ) works... no

On further investigation, typing gcc in Cygwin Terminal produced :
-bash: gcc: command not found

Step 2 : I therefore downloaded Mingw32. There is now on my PC this file
C:\MinGW\bin\mingw32-gcc

I want Cygwin to be able to use this file as a gcc version.

Step 3 : I created a link under Cygwin (inspired by a different this article where a similar action is done for make).
cd /bin
ln -s /cygdrive/c/mingw/bin/mingw32-gcc.exe gcc.exe

However the instruction ./configure still produce the same error. The config.log teaches me that :
configure:912: gcc -o conftest    conftest.c  1>&5
configure: failed program was:

#line 907 "configure"
#include "confdefs.h"

main(){return(0);}

Step 4 : I momentarily give up trying to use Cygwin Terminal and switches to MinGW Shell. This time the ./configure command seems to be successful !
Step 5 : In MinGW Shell, I enter the make command. It returns the following error message :
gcc -DHAVE_CONFIG_H -I. -I. -I. -I.    -g -O2 -c corkscrew.c
corkscrew.c:2:23: fatal error: arpa/inet.h: No such file or directory
compilation terminated.
make: *** [corkscrew.o] Error 1

After a few searches I find more information in this stackoverflow question, where the first answer suggest to "go with Cygwin, which provides a POSIX compatibility wrapper on Windows."
Therefore it seems I have to stick to Cygwin. Thus my question : how do I get Cygwin to compile this program ?
Note : I think I need to give access to Cygwin to all the programs included in MinGW32, however adding the "C:\MinGW\bin\mingw32-gcc" string to my computer's PATH environment variable did not produce positive results.

A: You need to install the Cygwin gcc compiler. Run Cygwin's setup.exe again, which is used both for the initial Cygwin install and subsequent updates and additions. Click your way through to the package selection screen, select the gcc4 package from the 'Devel' category, and click Next once more to start the install.
Chances are that the program you want to build depends on some libraries, in which case you'll need to go through setup.exe again and install the relevant libSOME-devel packages.


text:
Q: como puedo enviar la factura de la orden de compra por correo electronico quiero que cuando una compra tenga un estado 'aprobado' en el modelo order se envie un pdf al correo del cliente. alguien me puede sugerir algo con respecto a eso?
estos son los modelos de la orden
class Order(models.Model):
usuario = models.ForeignKey(User, on_delete=models.CASCADE)
estado = models.CharField(max_length=50)
precio_total = models.IntegerField()
invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
fecha = models.DateTimeField(verbose_name="Fecha", default=now)

class Meta:
    verbose_name="Order"
    verbose_name_plural = "Orders"
    ordering = ['-id']

def __str__(self):
    return 'Order {}'.format(self.invoice_no)

class OrderItem(models.Model):
producto = models.ForeignKey(Caracteristica, on_delete=models.CASCADE)
orden = models.ForeignKey(Order, on_delete=models.CASCADE)
precio = models.DecimalField(max_digits=10, decimal_places=0)
cantidad = models.PositiveIntegerField(default=1)

def __str__(self):
    return '{}'.format(self.id)

def get_cost(self):
    return self.price * self.cantidad

gracias por su colaboracion.

A: Podrías hacerlo de esta forma:
from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

Pero en settings.py tienes que escribir el siguiente código:
#SMPT CONFIGURATION

EMAIL_BACKEND = 'django.core.mail.backends.smpt.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com' #si usas gmail
EMAIL PORT = 587 # puerto de gmail
EMAIL_USE_TLS = True
EMAIL_HOST_USER = example@gmail.com #tu correo
EMAIL_HOST_PASSWORD = password #contrasena del correo

Además, en gmail tienes que ir a este link: https://myaccount.google.com/lesssecureapps
y pones en permitir el acceso de aplicaciones poco seguras.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Joomla DB Customizing I'm new to Joomla (3). I've researched a bit but could not find an exact match for what I need to know.
I need to create other categories (not referring to Joomla "categories") in the mysql DB so I can assign them to each article (not Tags). These would control how each article is formatted in the layout.
So let's say Article->Type1 = .classType1 in the layout and Article->Type2 = .classType2 in the layout.
So my basic question is: how would you go about adding data to the Joomla db outside of the basic table that's created - is it a simple process, can it be done withing the framework or do I have to code extra stuff??
I hope I'm clear in my question...
Thanks

A: I think what you want is to "control the article layout" on an individual basis. You don't need to do anything specific for this as Joomla supports this already. Here is a parallel StackOverflow question: JOOMLA, Best way to make alternate layouts for articles?
It also has additional links to get you started.
A quick and "dirty" way would be to simply wrap all the text in the article content in a div with a specific class and then you can override the default layout/styles accordingly.
My personal opinion is try and learn how to create alternate layouts - which is really what you want and once you know how to do it will also be fun to work with.


text:
Q: Breakpoint in console App visual studio I work on a project, where a process starts a console app on another thread and then it continues to its previous flow. I have attached the original process to the debugger, but I can't do that with the console app process, as that process doesn't get listed in the 'Attach to process' list. How can I debug the console app?

A: Not sure why it's not showing in the processes (have you made sure that All processes are showing?).
Anyway, try this:
using System.Diagnostics;

and in your code:
System.Diagnostics.Debugger.Break();

You should then get a dialog when the code hits that line, allowing you to attach Visual Studio to the process.

A: Make sure you check Show processes from all users and Show processes in all sessions


text:
Q: Array value not incrementing properly I have mainList of type Qlist<QStringList> to which a set 5 of QStringLists named newList is being added. The 7th index of a QStringList named List has an integer value( price). For each of the 5 iterations I want to increase the price value by 10.
i.e the 1st newList has a value of 110 in the 7th index, 2nd newList has a value of 120 in the 7th index, and the the last(5th) newList should have a value 150.
void MainWindow::on_pushButton_clicked()
{
    int Price;

    Price=100;

    for(int i=0;i<5;i++){
        for(int j=0;j<List.size();j++){
            if(j==7){
              Price+=10;
             QString priceString=QString::number(Price);
             newList<<priceString;
           }
            else{
               newList<<List[j];
            }
        }

        mainList<<newList;
    }
    ui->label->setText(mainBuyList[0][7]);
    ui->label_2->setText(mainBuyList[1][7]);
    ui->label_3->setText(mainBuyList[2][7]);
    ui->label_4->setText(mainBuyList[3][7]);
    ui->label_5->setText(mainBuyList[4][7]);
}

But when I click the button all the labels print only 110! How can I correct this issue?

A: You must clear newList after mainList<<newList;


text:
Q: MetalKit's drawInMTKView function not called if app is built using cmake/make? I ran into a strange issue testing Metal cpp. The following project is almost the same as Apple's official Metal Cpp example project.
https://github.com/shi-yan/testmetal
The apple official example contains an Xcode project, whereas my modified version tries to use cmake.
My cmake project builds and runs, but the window is empty. I debugged it, the root cause is that the drawInMTKView function never gets called.
If I generate an Xcode project using cmake, then build and run my code in Xcode, the resulting app can render to its window just fine.
However, if I run the same app binary through the terminal, it will show an empty window again.
Any idea what might cause this? Thanks.

A: Thanks to an Apple engineer, the issue is resolved.
My CMakeLists.txt doesn't load MetalKit. XCode can load MetalKit automatically, hence there was no issue running it via xcode.
Adding MetalKit to my CMakeList.txt solved the issue.


text:
Q: Sqlalchemy using ~ with and_, or_ I have an expression:
recent_oa = db_session.query(exists().where(
    and_(
        and_(Jobs.candidate_id == candidate_id, Jobs.interview_type == 'EVALUATION', Jobs.disposition_date < datetime.now()-timedelta(days=1)),
        ## I want this to evaluate to be True
        and_(~Jobs.candidate_id == candidate_id, Jobs.interview_type == 'IN_HOUSE', Jobs.disposition_date > '2017-01-01'),
        ## and I want this to evaluate to False
    )
)).scalar()

recent_oa
>> True

so that recent_oa will evaluate to be True
I want to create multiple conditions that if the first line evaluates to be True and then the rest of the lines evaluate to be False, recent_oa will evaluate as True
How would I write that expression? the way I have it doesn't seem to work.

A: You need to prefix the expression you need to invert with ~, so ~ and_(...).
Note that there are operators and functions for all boolean logic operators. ~ is also available as the not_() function, and similarly, and_() can be expressed with &, and or_() can be expressed with |. I'd stick with one style or the other, not both.
So your requirements can be expressed as
and_(
    and_(
        Jobs.candidate_id == candidate_id,
        Jobs.interview_type == 'EVALUATION',
        Jobs.disposition_date < datetime.now()-timedelta(days=1)
    ),

    not_(
        and_(
            not_(Jobs.candidate_id == candidate_id),
            Jobs.interview_type == 'IN_HOUSE',
            Jobs.disposition_date > '2017-01-01'
        )
    )
)

or as
(
    (
        (Jobs.candidate_id == candidate_id)
        & (Jobs.interview_type == 'EVALUATION')
        & (Jobs.disposition_date < datetime.now()-timedelta(days=1))
    )

    & (
        ~ (
            ~ (Jobs.candidate_id == candidate_id)
            & (Jobs.interview_type == 'IN_HOUSE')
            & (Jobs.disposition_date > '2017-01-01')
        )
    )
)

Because the ~, & and | operators have a lower precedence than comparison operators you do have to use (...) parentheses around each of the tests above to make sure the operators apply to the whole column == value and column < value tests.
I'm not 100% certain you meant to use not_(Jobs.candidate_id == candidate_id), but if you did, then I'd just use != there, so Jobs.candidate_id != candidate_id and drop the not_() condition on that test.
Next, the query is probably not going to give the right results anyway. It'll tell you if there are 1 or more rows that match your criteria, so rows where the candidate id matches, and there are specific conditions on the interview type and disposition date. What it will not do is tell you if there are only such rows that match. So if there are rows like this:
 candidate_id  |  disposition_date |  interview_type
---------------|-------------------|-----------------
 42            | 2018-01-01        | EVALUATION
 42            | 2018-01-02        | IN_HOUSE

then you get True because there is 1 row that matches your criteria. The IN_HOUSE row is filtered out. You won't get False here because it doesn't matter that the other row exists to the filter.
In that case you want to use the NOT expression boolean logic on separate EXISTS clauses, not the conditions, so the existence of the second row results in a False result countering the True for the other row:
SELECT id
FROM jobs
WHERE
    EXISTS(candidate_id = ? AND interview_type = ? AND disposition_date < ?)
    AND NOT EXISTS(candidate_id = ? AND interview_type = ? AND disposition_date > ?)

so create two separate exists queries:
candidate = db_session.query(Jobs).filter(Jobs.candidate_id == candidate_id)
has_evaluation = (
    candidate
    .filter(Jobs.interview_type == 'EVALUATION')
    .filter(Jobs.disposition_date < datetime.now() - timedelta(days=1))
)
has_inhouse = (
    candidate
    .filter(Jobs.interview_type == 'IN_HOUSE')
    .filter(Jobs.disposition_date > '2017-01-01')
)
recent_oa = (
    db_session.query(Jobs.id)
    .filter(has_evaluation.exists())
    .filter(not_(has_inhouse.exists())) # or .filter(~has_inhouse.exists())
    .scalar()
)

This uses the Query.exists() method to produce the separate EXISTS conditions.


text:
Q: Acumatica add Virtual field to Data Grid from different table I would like to add a virtual data field containing a custom db field UsrSubID in DB Table RQRequest.
I am trying to add the virtual field into a column in data grid on EPApproval screen. Below is my code on attend to use PXDBScalar to get the value for UsrSubID.
The relation between the two DAC is RQRequest.noteID = EPApproval.refNoteID
I get error:

error: The type name 'usrSubID' does not exist in the type
  'PX.Objects.RQ.RQRequest' in file: Code#EPOwned(22)

Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PX.Data;
using PX.Objects.CM;
using PX.TM;
using PX.Objects.CR;
using PX.Objects;
using PX.Objects.EP;

namespace PX.Objects.EP{
public class EPApprovalExt: PXCacheExtension<PX.Objects.EP.EPApproval>{

      #region UsrCustomField

      [PXString]
      [PXUIField(DisplayName="Sub Account")]
      [PXDBScalar(typeof(Search<RQ.RQRequest.usrSubID,Where<RQ.RQRequest.noteID,Equal<Current<EP.EPApproval.refNoteID>>>>))]

      public virtual string UsrCustomField{get;set;}
      public abstract class usrCustomField : IBqlField{}

      #endregion

}

}

A: I will delete this answer after I help Fillip because I can't comment in his questions.
Fillip if it doesn't exists in DAC you can not get it. So why not declare it in DAC?
If that is default DAC of Acumatica, you can use your package and choose Add Field in your package, or you can create you own.
I think key work Graph Extension can help you with this.

Remeber, your DAC must have UsrSubID Field before you use it to another DAC or Graph. See HB_Acumatica comment


text:
Q: Setting up a server using Boost-ASIO for Wireshark to connect to and receive packets? I am trying to create a simple server using ASIO in order to send packets to Wireshark to view them using the remote interfaces feature.
This is the code that sets up the server and waits for a connection.
void server(boost::asio::io_service& io_service, unsigned short port)
{

    tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));

    for (;;)
    {
        auto pSock = std::make_shared<tcp::socket>(io_service);

        auto handler = [pSock](const boost::system::error_code& err) -> void
        {
            if (err)
            {
                pSock->close();
                return;
            }
            auto buf = connectToNamedPipe();
            streamOut(pSock, buf);
            pSock->close();
        };
        std::cout << "Awaiting connection" << std::endl;
        a.async_accept(*pSock, handler);
        io_service.run();
    }
}

This is the code that sends a packet once a client connects
void streamOut(std::shared_ptr<tcp::socket> pSock, const std::pair<std::unique_ptr<char[]>, std::size_t>& b)
{
    ::boost::system::error_code ec;

    write(*pSock, ::boost::asio::buffer(b.first.get(), b.second));

    for (;;)
    {
        char a;
        std::cin >> a;
        if (a == 'e')
            return;
    }
}

However when Wireshark does connect (using the remote interfaces tab in the manage interfaces dialog), it hangs and stops respond until the close this application. Is there some other data I need to send to Wireshark before it starts sending data? Am I just sending data incorrectly? Is the server not set up correctly?

A: Wireshark is a "wire-tap".
You don't "send packets to it for viewing" and it doesn't "connect" to your application.
Instead, Wireshark just taps into the NIC and sees all the packets that get transmitted. So, instead connect to your server with a regular client (like netcat) and have Wireshark monitor the NIC(s) involved.
You can, for simplicity, capture the traffic on all network adaptors at once, I believe.


text:
Q: Correct Field Name For "Album Artist" ID3 Tag In SoX With LAME I've got SoX compiled with LAME, and it works fine, I can make an .mp3 file with common ID3 tags.
But I can't figure out what to call the "Album Artist" field so that I can specify a value.
For example:
sox -n --comment "Title=Sweep" --comment "album_artist=ALBUM ARTIST TEST" input.mp3 synth 3 sine 20-20000

Will properly make a file that sounds like a sweeping sine wave, and the ID3 title will be "Sweep".
But the Album artist field is still blank.  I've tried several variations, to no avail:
band
bandname
albumartist
album_artist
group
orchestra
accompaniment
soloist
performer
leadperformer
TPE2, which is the technical name in ID3 for the field I'm trying to give a value.
But none of them seem to work.  Does anybody know the right "name" to use for this value?

A: The following works for me:
 sox --add-comment "Artist=Anonymous" ...

And while we're here, I also set other ID3v2 tags with sox:
--add-comment "Title=Le Tourdion Alto Learning" \
--add-comment "Album=Le Tourdion" \
--add-comment "Artist=Anonymous" \
--add-comment "Year=2019" \
--add-comment "Comment=2019-11-20T13:28:14+00:00"

Looking at the results using id3info:

$ id3info AltoLearning.mp3

*** Tag information for AltoLearning.mp3
=== TSSE (Software/Hardware and settings used for encoding): LAME 64bits version 3.100 (http://lame.sf.net)
=== TIT2 (Title/songname/content description): Le Tourdion Alto Learning
=== TPE1 (Lead performer(s)/Soloist(s)): Anonymous
=== TALB (Album/Movie/Show title): Le Tourdion
=== TYER (Year): 2019
=== COMM (Comments): ()[eng]: 2019-11-20T13:28:14+00:00
=== TLEN (Length): 56003
=== COMM (Comments): (ID3v1 Comment)[XXX]: 2019-11-20T13:28:14+00:00


text: Q: If 2 or more functions are parallel,do their primitives always intersect in only one point? So if we had $f(x)=3x+2 $ and $ g(x)=3x+4$,we know these functions are parallel because they have the same slope,but if we integrate we get that they intersect in one point,do all functions that are parallel have the same propriety?


text:
Q: The MADDPG action prints a specific value     p = p_func(p_input, int(act_pdtype_n[p_index].param_shape()[0]), scope="p_func", num_units=num_units)
    p_func_vars = U.scope_vars(U.absolute_scope_name("p_func"))

    # wrap parameters in distribution
    act_pd = act_pdtype_n[p_index].pdfromflat(p)

    act_sample = act_pd.sample()

How do I get the concrete value of act_simple


text:
Q: How to get the styling of a directive's element in AngularJS I am trying to create a directive that uses the dimensions of its element. I've noticed that if the styling is done inline on the element then the related style attributes become available in the link function. However if the styling is done in an external css file (which is what I would like to do) the styling doesn't get applied before compilation. Is there some way around this?
Plunkr example

A: Angular's jqLite css function isn't equivalent to the jQuery implementation. Unfortunately the documentation doesn't emphasize this difference, unlike their emphasis on limitations in other functions. jQuery will do what you're expecting and grab the width whether it's defined in an external stylesheet or in an inline style. Angular's jqLite will only grab it from an inline style. There's an open issue about this: jqLite .css() retrieves only inline styles.
Some possible work-arounds:

*

*Use the offsetWidth property instead:
elem.prop('offsetWidth')

*If you decide to include jQuery then it will take precedence and css will work as expected


text:
Q: Amqp client not connecting to activemq server. I'm trying connect from a amqp client to a aqtivemq server with default settings. It always gives the error message saying connection refused. Then I tried it with a rabbitmq server instead of a activemq server and it works fine. I wonder whether activemq needs a linux library to communicate.
Activemq server versions used which does not connects: 5.4.2 / 5.10.0
Rabitmq version used: 3.3.5
rabitmq sample client code
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

public class Cache {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv)
            throws java.io.IOException {

        //creating the connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        //Creating a connection to the server
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //declaring a queuw
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World!";

        //publishing the queue the queue
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        //closing the connection
        channel.close();
        connection.close();
    }
}

Fails in the following line of code
//Creating a connection to the server
    Connection connection = factory.newConnection();

How can I solve this issue ?

A: I found a similar issue and I fixed checking the exchange declared was equals to the channel used to publish, in this way:
@Test
public void test() throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("10.211.55.20");
    factory.setPort(5672);
    factory.setVirtualHost("/");
    factory.setUsername("guest");
    factory.setPassword("guest");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare("KipcastDirect", "direct",
           true,    /* durable */
           true,    /* autodelete */
           null);   /* */

    byte[] messageBodyBytes = "Hello, world!".getBytes();

    AMQP.BasicProperties.Builder basic = new AMQP.BasicProperties.Builder();
    AMQP.BasicProperties minBasic = basic.build();

    minBasic = basic.priority(0).deliveryMode(1).build();

    channel.basicPublish("KipcastDirect", "KipcastRouting", minBasic, messageBodyBytes);
    System.out.println(" [x] Sent ");

    channel.close();
}

Please be carefoul: the URI (from and to) on Camel Spring DSL context and JUnit class must refer to same Exchange and Queue to prevent a reply-text=PRECONDITION_FAILED – parameters for queue 'QUEUE' in vhost '/' not equivalen error or similar. To check the queues / exchanges configuration parameter use:
rabbitmqadmin -V / list queue
rabbitmqadmin -V test list exchanges

Take a look to this: http://www.andreagirardi.it/blog/camel-and-rabbitmq-finally-how-to/


text:
Q: How to select SQL Server row values as columns (Dynamic Pivot) I have one table where we are collecting status data from different sensors. For reporting purposes I would need to group information for each sensor (SGUID) to one row. Each sensor is sending reader (RGUID) and value for reader (VAL).
Source table:

Goal result:

I have heard about pivot's but don't know how to use those in this kind of case.

A: You need a dynamic pivot using some dynamic T-SQL:
CREATE TABLE #VALS (
    VALS NVARCHAR(4000)
)

INSERT INTO #VALS
SELECT DISTINCT RGUID
FROM [TABLE]

DECLARE @SQL NVARCHAR(MAX)
DECLARE @VALS NVARCHAR(4000)

SELECT @VALS = COALESCE(@VALS+', ','') + '[' + VALS + ']' FROM #VALS

SET @SQL = '
SELECT SGUID, '+@VALS+'
FROM [TABLE]
PIVOT(MAX(VAL) FOR RGUID IN ('+@VALS+')) PIV'
PRINT @SQL
EXEC (@SQL)

The PRINT will show you the constructed query. From there you can debug any issues quite simply. The idea is fairly simple, I've created a working fiddle here.


text:
Q: Tracking buttons on facebook messenger bot I am trying to track the buttons clicks on facebook messenger bot. Does any one have any experience or tips on doing it.
Here is a portion of my JSON
buttons:[
{
type:'web_url',
url:'<link to my url>',
title:'Click me'
},
{
type:'phone_number',
title:'Call',
payload:'+1' + phoneNumber
}
]

I am primarily unable to track the phone_number, I can get away with few workarounds with the web_url on the target side.

A: Change the call me one to be a URL then on your website note that they clicked the button and redirect them to tel:+123456789012345


text:
Q: Highlight ^M(CR) in vim I'm looking for a way to highlight ^M(CR) in vim.

A: Make sure fileformat is set=unix or mac mine is:
set fileformats=unix,mac

If it is DOS you will not see it
I have a mapping in my .vimrc that will remove them, but this response here explains it best.
https://stackoverflow.com/a/3852892/2869058
You can view all terminal line endings and characters by enabling
:set list

one way you can highlight them is like this in your .vimrc:
syntax on

set list listchars=trail:_
set listchars=tab:·\ ,trail:·,extends:»,precedes:«
:highlight SpecialKey ctermfg=darkgrey ctermbg=yellow


text:
Q: Javascript Fails After Another Script Initiates I'm making a website that uses a Javascript sorter. In addition to the sorter, I also   put in some custom javascript, to make certain div's clickable. My reasoning was that using the  property just couldn't do all that we wanted it to do, so I stuck with divs, and used javascript to make them function.
Take a look here --
http://www.opohills.com/taipei-rentals.php
You can scroll down to where you see the search bar, and click on one of the apartments. When you go back click (1 bedroom), you'll see that clicking on the apartments doesn't work anymore.
I'm not quite sure what to make of this at all. The javascript for the clickability is at the bottom of the page.
What are your thoughts on this?
Here's my javasscript
    <script type='text/javascript'>
    $(".box_1").click(function(){
         window.location=$(this).find("a").attr("href");
         return false;
    });
     $(".box_2").click(function(){
         window.location=$(this).find("a").attr("href");
         return false;
    });
         $(".box_3").click(function(){
         window.location=$(this).find("a").attr("href");
         return false;
    });
    $(".apt2").click(function(){
         window.location=$(this).find("a").attr("href");
         return false;
    });
  </script>

Thoughts?
UPDATE
In accordance to the suggestions, I've updated the code by moving the javascript for clickability above jquery.quicksand, and initiated it only after the document was ready.
Even with these changes, I'm still having trouble getting it to work.
The latest version of the site can be seen here---
http://www.opohills.com/taipei-rentals.php
Your thoughts greatly appreciated

A: the script basically works for me (and should for you). your problem is probably that sometimes your dom is not ready:
$(document).ready(function() {
  // your code here
});

2 more things.
1.) add "cursor: pointer;" to your css for the clickable boxes (usability)
2.) just trigger the click of your link:
$(".apt2").click(function(){
  $(this).find("a").trigger('click');
  return false;
});

A: When I'm using the chorme built in debuger on your website, if I create custome fields like ID on you "li" tags, they are deleted after a filter. I think quicksand is creating a cache during the page loading. You are creating you .click() event only after the initialisation of the quicksand library and it is possible that theses click events are deleted because quicksand replaces your li tags.
Try to initialize your click like
$(function() {
  $("#ourHolder li").click(function() { window.location.href=$(this).find('a').attr('href')});
});

You should add an id="ourHolder" to your ul tag to optimize the script speed.
And only after this initialisation start your quicksand object initialisation. Move your
<script src="js/jquery.quicksand.js"></script>
<script src="js/sorter-settings.js"></script>

after the previous click functions.

A: So you can try to edit our file sorter-settings.js and replace by this code (based on the documentation available here (http://razorjack.net/quicksand/docs-and-demos.html) :
  $(document).ready(function() {

  // get the action filter option item on page load
  var $filterType = $('#filterOptions li.active a').attr('class');

  // get and assign the ourHolder element to the
    // $holder varible for use later
  var $holder = $('ul#ourHolder');

  // clone all items within the pre-assigned $holder element
  var $data = $holder.clone();

  // attempt to call Quicksand when a filter option
    // item is clicked
    $('#filterOptions li a').click(function(e) {
        // reset the active class on all the buttons
        $('#filterOptions li').removeClass('active');

        // assign the class of the clicked filter option
        // element to our $filterType variable
        var $filterType = $(this).attr('class');
        $(this).parent().addClass('active');

        if ($filterType == 'all') {
            // assign all li items to the $filteredData var when
            // the 'All' filter option is clicked
            var $filteredData = $data.find('li');
        }
        else {
            // find all li elements that have our required $filterType
            // values for the data-type element
            var $filteredData = $data.find('li[data-type=' + $filterType + ']');
        }

        // call quicksand and assign transition parameters
        $holder.quicksand($filteredData, {
            duration: 800,
            easing: 'easeInOutQuad',
                    enhancement: function() {
                        $("#ourHolder li").click(function() { window.location.href=$(this).find('a').attr('href')});
                        }
        }
            );
        return false;
    });
});

Additinaly, I think that this code is useless on your html content.
  <!--Begin Sorter-->
    <script type='text/javascript'>
    $(document).ready(function() {
          $('#source').quicksand( $('#destination li') );
     });
  </script>


text:
Q: how to know when the user is in specific part of the website and when he leaves that part and display the data in the admin dashboard I want to display for the admin when a user visits a page and when he leaves that page
the page is for example test.test/my-dashboard. and it's only available for the logged in users.
the admin knows to know the time when the user is in that page and the time the user leaves that page.
thanks in advance and excuse my language.


text:
Q: get record with at least one associated object I have the following schema in mongoid:

User has many tasks - has_many :tasks
Task belongs to user - belongs_to :user

How can I get only 10 first users with at least one task?
Something like this:
User.where(:tasks.ne => [] ).limit(10)

A: Your problem is that Mongoid's has_many doesn't leave anything in the parent document so there are no queries on the parent document that will do anything useful for you. However, the belongs_to :user in your Task will add a :user_id field to the tasks collection. That leaves you with horrific things like this:
user_ids = Task.all.distinct(:user_id)
users    = User.where(:id => user_ids).limit(10)

Of course, if you had embeds_many :tasks instead of has_many :tasks then you could query the :tasks inside the users collection as you want to. OTOH, this would probably break other things.
If you need to keep the tasks separate (i.e. not embedded) then you could set up a counter in User to keep track of the number of tasks and then you could say things like:
User.where(:num_tasks.gt => 0).limit(10)

A: You can do
User.where(:tasks.exists => true).limit(10)

Update:
Worked for me when doing:
u = User.new
t = u.tasks.build
t.save
u.save

u = User.new
u.save

User.where(:tasks.exists => true).limit(10).count
=> 1


text:
Q: basic_timed_mutex.hpp(159): fatal error C1001: An internal error has occurred in the compiler I have problem when I am building project in Visual Studio 2010 for 64bit. I couldn't able to build for 64bit with boost library, I am getting below error. I can build for 32bit but not for 64bit.
    \boost_1_49_0\boost\thread\win32\basic_timed_mutex.hpp(159): fatal error C1001: An internal error has occurred in the compiler
(compiler file 'f:\dd\vctools\compiler\utc\src\p2\wvm\mdmiscw.c', line 2704)
5  To work around this problem, try simplifying or changing the program near the locations listed above.
5>  Please choose the Technical Support command on the Visual C++
5>   Help menu, or open the Technical Support help file for more information
5>  The command exited with code 2.

It is pointing error to the below code and ofcourse I can't change the boost library. I am confused with this error
void unlock()
            {
                long const offset=lock_flag_value;
                long const old_count=BOOST_INTERLOCKED_EXCHANGE_ADD(&active_count,lock_flag_value);
                if(!(old_count&event_set_flag_value) && (old_count>offset))
                {
                    if(!win32::interlocked_bit_test_and_set(&active_count,event_set_flag_bit))
                    {
                        win32::SetEvent(get_event());
                    }
                }
            }

Can you please help me,
Thank you
Edited :
I am not sure where the error but I think its in the boost libraries, there is a cpp file like
Class a::a(, point, )
{
}

and the "point" is a namespace  which is defined in a header file which is using boost libraries and it has following code
#include <boost/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>

    namespace point
    {
// some work1
    void fun()
    {
    boost::unique_lock< boost::recursive_mutex > lck(*m_RedrawMutex);
// some work2
    }
// some work3
    }

Answer :
It finally worked !! After two days of search, I found another way.I just changed the order of include path in the project header where it was using boost basic_timed_mutex.hpp. I placed boost include path at the top and it worked. It's strange!!!

A: I've had this same issue myself - and it seems to be related to certain code-blocks in boost itself. It appears to be caused by a bug in the MSVC compiler toolchain.
Disabling optimisation appears to solve the issue for many users As per this MSDN article - Source from MSDN suggesting this fix Souce on stack-overflow
I wish I could present a logical cause, or bug report on the issue, but for myself the problem was solved by upgrading to Boost 1.60.
That said, other uses have reported that trailing-slashes are the cause!
update:
After some browsing it appears this issue can be caused by everything from infinite-loops, though to templates types holding function pointers. and doesn't always list the actual-source of the error correctly (eg: it's not where the error message says it is). That said, disabling optimisation appears to solve the issue near universally - at the cost that your software may run slower.


text:
Q: Python Vertica Insert I've been trying to load data into a Vertica DB using Python.
def test():
    try:
        connection = psycopg2.connect(db_connect_string)
        cursor = connection.cursor()
    except psycopg2.DatabaseError, e:
        print 'Error %s' % e
        sys.exit(1)
    cursor.execute("INSERT INTO <table_name> (cusip, ticker) VALUES (%s, %s)"% (1234, "'tkr'"))
    connection.commit()

That returns without an error but subsequent SELECTS don't return anything. (NOTE: the SELECT code as been independently tested and works).

A: You are using psycopg2 which is targeted to postgres, maybe using pyodbc instead (suggested by the vertica doc) would solve your issue?
There is open source library we developed at $work to help using vertica with python and more specifically to insert data the proper Vertica way (single INSERTs are veeerryyy slow). Maybe it could help you: http://pypi.python.org/pypi/pyvertica

A: You should use the following syntax:
cursor.execute("INSERT INTO <table_name> (cusip, ticker) VALUES (%s, %s)"% (1234, "'tkr'");commit;)

or
change
connection.commit()

by
cursor.execute("commit")


text:
Q: Why is Textarea component displaying it's text value in a white or transparent color? I have a Textarea component used from ChakraUI that's displaying text inserted in my container component called BookReview as a text prop called "bookReview".
It's supposedly picking up the bookReview prop and displaying it in a textarea on an edit button click for the user to edit the text. It has worked the first time I implemented it, however, when I tried to test it today, I got the strange bug mentioned in the title.
import { AccordionItem, Box, AccordionIcon, AccordionPanel, PopoverTrigger, PopoverContent, PopoverArrow, PopoverCloseButton } from "@chakra-ui/react";
import * as React from "react";
import { Accordion, AccordionButton, Popover, Button, PopoverHeader, PopoverBody,Textarea } from "@chakra-ui/react";

const BookReview = ({ bookReview }: { bookReview: string }) => {

  const [isClicked,SetIsClicked] = React.useState(false);
  let [areaReview,setAreaReview] = React.useState(bookReview);
  let [review,setReview] = React.useState(bookReview);

  const editClickHandler = () => {
    SetIsClicked(current => !current);
  }

  const saveClickHandler = () => {
    setReview(areaReview);
  }

  return (
    <>
     <Accordion allowToggle w={"100%"}>
     <AccordionItem>
     <h2>
   <AccordionButton>
     <Box flex="1" textAlign="left">
       Review
     </Box>
     <AccordionIcon />
   </AccordionButton>
   </h2>
   <AccordionPanel pb={4}>
     {review}
       <Popover>
         <PopoverTrigger>
           <Button float={"right"} size="sm" onClick={editClickHandler} p={3}>
             Edit
           </Button>
         </PopoverTrigger>
         <PopoverContent>
           <PopoverArrow />
           <PopoverCloseButton />
           <PopoverHeader>Edit review</PopoverHeader>
           <PopoverBody zIndex={"base"}>
           <Textarea placeholder='your review' resize="vertical" value={areaReview} onChange={(e) => setAreaReview(e.target.value) } variant={"md"} />
           <Button variant={"ghost"} bg="red.500" float={"right"} marginTop={3} onClick={saveClickHandler}>
             Save
           </Button>
           </PopoverBody>
         </PopoverContent>
       </Popover>
    </AccordionPanel>
     </AccordionItem>
     </Accordion>
    </>
  );

}

A: Check if your "bookReview" prop received in BookReview is undefined ? also check by adding debug point what value you are passing to TextArea


text:
Q: Add Folders to Root of Zip Using Ionic Zip Library what I'm trying to do is add a list of folders and files all to the root of my Zip file, using the Ionic Zip library (c#).
Here's what I have so far
string k = "B:/My Documents/Workspace";
private void button1_Click(object sender, EventArgs e)
{
   using (ZipFile zip = new ZipFile())
   {
       //add directory, give it a name
       zip.AddDirectory(k);
       zip.Save("t.zip");
   }
}

Now, I want my zip to be looking like this.

*

*t.zip

*

*Random Files and Folder

But it's looking like this.

*

*t.zip

*

*t (folder)

*

*Random files and folders

Any help would be appreciated, Thank you.

A: Try this
using (ZipFile zip = new ZipFile())
    {
        zip.AddFiles(sourcefiles, ""); //For saving things at root of your zip
        foreach (DirectoryInfo objFile in objDir.GetDirectories())
        {
            zip.AddDirectory(objFile.FullName, objFile.Name); ///For saving subdirectories within zip
        }
        zip.Save(pathzipfile + ".zip");
    }

A: The default behavior of AddDirectory should add the contents of the directory to the root path in the zipfile, without creating a subdirectory.
There is a second overload of AddDirectory, which adds a parameter to specify what the path of the added files should be within the zipfile.  But since you want the files to go into the root directory, this would just be an empty string.
zip.AddDirectory(k, "");

See this documentation for more info.
None of this explains where your subfolder is coming from.  I suspect the problem is from something else in the code.  It might be useful to run this in debug and see what 'k' equals when you call AddDirectory, or to print out all the "entries" in the zip.Entries collection.

A: Why not try something like this:
foreach (var file in System.IO.Directory.GetFiles(k))
{
    zip.AddFile(file);
}

To get the directories and files to an unlimited depth, combine that with a recursion method based on System.IO.Directory.GetDirectories("path") - should be pretty straightforward methinks.


text:
Q: how get item from list which is in Array of Object in c# This is my code, I can`t get elements from the list which is situated Object array. How I can get "info" from data?
Object[] data = {
new List<string>() {"name", "name2", "name3", "name4",},
new List<string>() { "info", "info2", "info3", "info4",},
new List<int>() { 2002, 1999, 2005, 1980 },
new List<int>() { 12000, 1000000, 2500, 900000 },
new List<int>() { 1337, 2828, 1890, 4210 },
};

I tried to get elements with the help:
var i = data[1][1]
var i = data[1,1]

A: You're treating an Object array as if it were a List array. In order to use an indexing operator on an element retrieved from the array, you'll need to denote that it's a List.
This is most commonly done with the as, is, typeof, and/or casting operators.
Here's an example using as and is:
object[] data = {
new List<string>() {"name", "name2", "name3", "name4",},
new List<string>() { "info", "info2", "info3", "info4",},
new List<int>() { 2002, 1999, 2005, 1980 },
new List<int>() { 12000, 1000000, 2500, 900000 },
new List<int>() { 1337, 2828, 1890, 4210 },
};

foreach (var item in data)
{
    if (item is List<string>)
        Console.WriteLine((item as List<string>)[0]); // Use the string however you want
}

For more information, I'd take a look at Microsoft's Type-testing documentation.

A: data[1] is not a list, it's an object, technically it is object?. so you cant use the index on it.
you can get the value like this.
var ls = data[1] as List<string>;

var item = ls[1];

or var item = ((List<string>)data[1])[1];
Edit:
both cases are compiling for me.


text:
Q: .htaccess apache 2.2 to 2.4 update Our host has recently updated their apache server from 2.2 to 2.4 and now we keep getting a 500 Internal Server Error, our error log reads "RewriteCond: bad flag delimiters".
Our .htAccess file looks like this.
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/views/.*$ #allows to access views folder and everything in it.
RewriteCond %{REQUEST_URI} !^test.php$ #allows to access views folder and everything in it.
RewriteCond %{REQUEST_URI} !^phonegapFunction.php$ #allows to access views folder and everything in it.
RewriteRule ^([a-zA-Z0-9æøå]*)\/?(\w*)\/?(.*)$ /app.php?team=$1&page=$2&value=$3 [L]

Our host said we need to update the .htaccess file to apache 2.4 specification, but we are having problems doing that, so hopefully someone here can help.
Thanks in advance

A: This is what I get in both Apache 2.2 and 2.4
With .htaccess file like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/views/.*$ #allows to access views folder and everything in it.
RewriteCond %{REQUEST_URI} !^test.php$ #allows to access views folder and everything in it.
RewriteCond %{REQUEST_URI} !^phonegapFunction.php$ #allows to access views folder and everything in it.
RewriteRule ^([a-zA-Z0-9æøå]*)\/?(\w*)\/?(.*)$ /app.php?team=$1&page=$2&value=$3 [L]

This is the error I get in the error logs, for both versions:
/var/www/localhost/htdocs/.htaccess: RewriteCond: bad flag delimiters

But if I remove the comments:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/views/.*$
RewriteCond %{REQUEST_URI} !^test.php$
RewriteCond %{REQUEST_URI} !^phonegapFunction.php$
RewriteRule ^([a-zA-Z0-9???]*)\/?(\w*)\/?(.*)$ /app.php?team=$1&page=$2&value=$3 [L]

No errors and I can get routed to app.php just fine.


text:
Q: Asynctask used by multiple Java Fragments I am currently working on a project, where I fetch data from a JSON dump, on Android. So far, have I set up a customised Asynctask in every fragment, where I need to fetch data from the JSON dump. What I am curious about is whether I can have one public Java class, which the fragments can just "use" whenever they need to fetch data.
This is an example of how i have attempted to do this. First the fragment who calls the Asynctask from a public java class:
public class DataTabelFragment extends Fragment {

private TextView sensor1;
private Button jsonButton;

jsonAsynctask jsonasynctask = new jsonAsynctask();

public DataTabelFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate( R.layout.fragment_data_tabel, container, false );

    sensor1 = (TextView) view.findViewById( R.id.sensor1Box );
    //jsonButton = (Button) view.findViewById( R.id.buttonjson );

    new jsonAsynctask().execute();

    for (int i = 0; i < jsonasynctask.allId.size(); i++) {
        sensor1.append( jsonasynctask.allId.get( i ) + " | " + jsonasynctask.allDevice.get( i ) + " | " + jsonasynctask.allTemp.get( i ) + " | " + jsonasynctask.allHum.get( i ) + " | " + jsonasynctask.allBat.get( i ) + " | " + jsonasynctask.allMode.get( i ) + " | " + jsonasynctask.allLux.get( i ) + " | " + jsonasynctask.allDate_time.get( i ) + "\n\n" );

    }

    //new jsonConnection().execute();

    /*

    jsonButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new jsonConnection().execute();
        }
    } );*/

    return view;

}

}

Here's the java class with the Asynctask:
public class jsonAsynctask extends MainActivity {

private TextView sensor1;
private Button jsonButton;

JSONObject deviceArray;
JSONObject tempArray;
JSONObject humArray;
JSONObject batArray;
JSONObject modeArray;
JSONObject date_timeArray;
JSONObject luxArray;

JSONArray json2;

List<String> allId = new ArrayList<String>();
List<String> allDevice = new ArrayList<String>();
List<String> allTemp = new ArrayList<String>();
List<String> allHum = new ArrayList<String>();
List<String> allBat = new ArrayList<String>();
List<String> allMode = new ArrayList<String>();
List<String> allDate_time = new ArrayList<String>();
List<String> allLux = new ArrayList<String>();

String basicAuth;
String line;
String json_string;
String json;
String cxwebURL;
String credentials;
String password;
String username;

Gson gson;
ProgressDialog pd;
String data = "";
HttpURLConnection connection;
BufferedReader bufferedReader;

String id = "";
JSONObject idArray;

URL url;

private static String encodeBase64URLSafeString(byte[] binaryData) {

    return android.util.Base64.encodeToString( binaryData, android.util.Base64.URL_SAFE );

}

public class jsonConnection extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {

        username = "xxx";

        password = "xxx";

        credentials = username + ":" + password;

        cxwebURL = "https://" + credentials + "@xxx.com/fetch.php?device=xxx";

        try {

            url = new URL( cxwebURL );

            connection = (HttpsURLConnection) url.openConnection();

            basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );

            connection.setRequestProperty( "Authorization", basicAuth );
            connection.setRequestMethod( "GET" );
            connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
            connection.setRequestProperty( "Content-Language", "en-US" );
            connection.setUseCaches( false );
            connection.setDoInput( true );
            connection.setDoOutput( true );
            connection.connect();

            InputStream stream = connection.getInputStream();

            bufferedReader = new BufferedReader( new InputStreamReader( stream ) );

            line = "";

            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }

            json2 = new JSONArray( data );

            for (int i = 0; i < json2.length(); i++) {
                idArray = json2.getJSONObject( i );
                deviceArray = json2.getJSONObject( i );
                tempArray = json2.getJSONObject( i );
                humArray = json2.getJSONObject( i );
                batArray = json2.getJSONObject( i );
                modeArray = json2.getJSONObject( i );
                date_timeArray = json2.getJSONObject( i );
                luxArray = json2.getJSONObject( i );
                id = idArray.getString( "id" );

                String temp = tempArray.getString( "temp" );
                String device = deviceArray.getString( "device" );

                String hum = humArray.getString( "hum" );

                String bat = batArray.getString( "bat" );

                String mode = modeArray.getString( "mode" );

                String date_time = date_timeArray.getString( "time" );

                String lux = luxArray.getString( "light" );

                allId.add( id );
                allDevice.add( device );
                allTemp.add( temp );
                allHum.add( hum );
                allBat.add( bat );
                allMode.add( mode );
                allDate_time.add( date_time );
                allLux.add( lux );

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog( new MainActivity() );
        pd.setMessage( "Være sød at vente" );
        //pd.setCancelable( false );
        pd.show();
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute( result );
        if (pd.isShowing()) {
            pd.dismiss();
        }

        System.out.println( data );

        gson = new Gson();

        json = gson.toJson( data );

        System.out.println( "String json: " + json );

        json_string = data;

        System.out.println( "json_string: " + json_string );

//            System.out.println( "DET HER ER ID!!: " + allId.get( 1 ) );

        //textView2.setMovementMethod( new ScrollingMovementMethod() );

        System.out.println("Size of Array: " + allId.size());

    }
        }

}

Am I able to do program it like this, or should I continue to have an Asynctask in each fragment? By the way, "new jsonAsynctask().execute();" in the fragment does not work and i receive this error:

error: cannot find symbol class execute

* Update *
Here's the update in the Java Class, where the Asynctask is.
public class jsonAsynctask extends AsyncTask<Void, Void, Void> {

private TextView sensor1;
private Button jsonButton;

JSONObject deviceArray;
JSONObject tempArray;
JSONObject humArray;
JSONObject batArray;
JSONObject modeArray;
JSONObject date_timeArray;
JSONObject luxArray;

JSONArray json2;

List<String> allId = new ArrayList<String>();
List<String> allDevice = new ArrayList<String>();
List<String> allTemp = new ArrayList<String>();
List<String> allHum = new ArrayList<String>();
List<String> allBat = new ArrayList<String>();
List<String> allMode = new ArrayList<String>();
List<String> allDate_time = new ArrayList<String>();
List<String> allLux = new ArrayList<String>();

String basicAuth;
String line;
String json_string;
String json;
String cxwebURL;
String credentials;
String password;
String username;

Gson gson;
ProgressDialog pd;
String data = "";
HttpURLConnection connection;
BufferedReader bufferedReader;

String id = "";
JSONObject idArray;

URL url;

private static String encodeBase64URLSafeString(byte[] binaryData) {

    return android.util.Base64.encodeToString( binaryData, android.util.Base64.URL_SAFE );

}

    @Override
    protected Void doInBackground(Void... voids) {

        username = "xxx";

        password = "xxx";

        credentials = username + ":" + password;

        cxwebURL = "https://" + credentials + "@xxx.com/fetch.php?device=xxx";

        try {

            url = new URL( cxwebURL );

            connection = (HttpsURLConnection) url.openConnection();

            basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );

            connection.setRequestProperty( "Authorization", basicAuth );
            connection.setRequestMethod( "GET" );
            connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
            connection.setRequestProperty( "Content-Language", "en-US" );
            connection.setUseCaches( false );
            connection.setDoInput( true );
            connection.setDoOutput( true );
            connection.connect();

            InputStream stream = connection.getInputStream();

            bufferedReader = new BufferedReader( new InputStreamReader( stream ) );

            line = "";

            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }

            json2 = new JSONArray( data );

            for (int i = 0; i < json2.length(); i++) {
                idArray = json2.getJSONObject( i );
                deviceArray = json2.getJSONObject( i );
                tempArray = json2.getJSONObject( i );
                humArray = json2.getJSONObject( i );
                batArray = json2.getJSONObject( i );
                modeArray = json2.getJSONObject( i );
                date_timeArray = json2.getJSONObject( i );
                luxArray = json2.getJSONObject( i );
                id = idArray.getString( "id" );

                String temp = tempArray.getString( "temp" );

                String device = deviceArray.getString( "device" );

                String hum = humArray.getString( "hum" );

                String bat = batArray.getString( "bat" );

                String mode = modeArray.getString( "mode" );

                String date_time = date_timeArray.getString( "time" );

                String lux = luxArray.getString( "light" );

                allId.add( id );
                allDevice.add( device );
                allTemp.add( temp );
                allHum.add( hum );
                allBat.add( bat );
                allMode.add( mode );
                allDate_time.add( date_time );
                allLux.add( lux );

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog( new MainActivity() );
        pd.setMessage( "Være sød at vente" );
        pd.show();
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute( result );
        if (pd.isShowing()) {
            pd.dismiss();
        }

        gson = new Gson();

        json = gson.toJson( data );

        json_string = data;

      }
        }

}

The error I receive:

error: class, interface, or enum expected

I appreciate the help! Thanks in advance.

A: Creating the separate class for AsynctTask is better, rather than creating AsyncTask in every fragment.
You are getting error because in
   new jsonAsynctask().execute() // jsonAsyncTask extends from MainActivity, So its not a AsyncTask
Replace above line with  new jsonConnection .execute()


text:
Q: TypeError: res.send is not a function when trying to load site I recently converted my build process over to using typescript and webpack.  Now after resolving most the TS errors, I'm trying to run my site finally.
When I load the site, I'm getting TypeError: res.send is not a function from my expressjs static server.  This code hasn't changed, it's always been the same even when I used gulp and worked fine but for some reason now after using webpack and TS, it's giving me this error now.
The server does indeed start on port 8080 and listens for requests.  I start it with "start": "node --trace-warnings dist/server/server.js",
I don't know if it's because I typed the res param with any or what it is..
Full Error:
TypeError: res.send is not a function
    at dist/server/api.js:58:9
    at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/node_modules/express/lib/router/index.js:317:13)

dist (output from TS and webpack)

*

*TS is outputting my server folder code

*webpack is outputting the rest via copy and bundling

webpack.config.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

const isProduction = process.env.NODE_ENV === 'production';

const html = () => {
  return new HtmlWebPackPlugin({
    template: path.resolve(__dirname, 'src/client', 'index.html'),
    filename: 'index.html',
    hash: true,
  });
};

const copyAllOtherDistFiles = () => {
  return new CopyPlugin({
    patterns: [
      { from: 'src/client/assets', to: 'lib/assets' },
      { from: 'package.json', to: './' },
      { from: 'ext/ink-3.1.10/js/ink-all.min.js', to: 'lib/js' },
      { from: 'ext/ink-3.1.10/js/autoload.min.js', to: 'lib/js' },
      { from: 'ext/js/jquery-2.2.3.min.js', to: 'lib/js' },
      { from: 'ext/ink-3.1.10/css/ink.min.css', to: 'lib/css/ink.min.css' },
      { from: 'feed.xml', to: './' },
      {
        from: 'src/shared',
        to: './shared',
        globOptions: {
          ignore: ['**/*suppressed.json'],
        },
      },
    ],
  });
};

module.exports = {
  entry: './src/client/index.tsx',
  output: {
    filename: 'scripts/app.[hash].bundle.js',
    publicPath: '/',
    path: path.resolve(__dirname, 'dist'),
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  devtool: isProduction ? '' : 'inline-source-map',
  devServer: {
    writeToDisk: true,
    port: 8080,
  },
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true,
        },
      },
    },
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.(tsx|ts)?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
          },
        ],
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        loader: 'file-loader',
        options: {
          outputPath: 'lib/assets/fonts',
        },
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ['url-loader'],
      },
    ],
  },
  plugins: isProduction
    ? [
        new CleanWebpackPlugin(),
        new MiniCssExtractPlugin({
          filename: isProduction ? 'lib/css/main.[hash].css' : 'main.css',
        }),
        html(),
        copyAllOtherDistFiles(),
      ]
    : [new CleanWebpackPlugin(), html(), copyAllOtherDistFiles()],
};

./tsconfig.json
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    "target": "ES2015",                     /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "es2020",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "lib": ["es6", "dom"],                      /* Specify library files to be included in the compilation. */
        "moduleResolution": "node",
        "allowJs": true,                     /* Allow javascript files to be compiled. */
        "checkJs": true,                     /* Report errors in .js files. */
    "jsx": "react",
    "noImplicitAny": true,
        "sourceMap": false,                   /* Generates corresponding '.map' file. */
    "rootDir": "./",                     /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        "removeComments": true,              /* Do not emit comments to output. */
    "strict": true,                      /* Enable all strict type-checking options. */
        "noUnusedLocals": true,                /* Report errors on unused locals. */
        "noUnusedParameters": true,            /* Report errors on unused parameters. */
//    "rootDirs": ["."],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    "typeRoots": [
      "node_modules/@types"
    ],                      /* List of folders to include type definitions from. */
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
//      "resolveJsonModule": true,
        "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true
    },
    "include": [
        "src"
    ],
    "exclude": [
        "/node_modules",
        "/src/server",
        "/src/client/js/ink-config.js",
        "**/test"
  ]
}

./client/server/tsconfig.js (where server.ts and api.ts live)
{
    "extends": "../../tsconfig",
    "compilerOptions": {
        "outDir": "../../dist/server",
        "rootDir": "."
    },
    "include": ["./*.ts"]
}

./src/server/api.ts
(api.js is outputted to dist/server)
const compression = require('compression'),
  express = require('express'),
  historyApi = require('connect-history-api-fallback'),
  oneYear = 31536000;

module.exports = express()
  .use(compression())
  .on('error', function (err: string) {
    console.log(err);
  })
  .use(historyApi())
  .use(
    express.static('dist', {
      maxage: oneYear,
    })
  )
  .use((res: any) => {
    res.send('Sorry, Page Not Found');
  });

A: As @num8er writes in the comment, you need to correct the signature of the handler you passed to express.use(). Your code fails because the first parameter in that function is the request object, not the response object. The request object doesn't have a send() method, so you need to add at least two parameters if you're trying to send a response:
import express from 'express'

const app = express();

app.use((req, res) => {
    res.send()
})

The reason Typescript didn't catch this error is because you're using the any type. To actually get type checking, make sure you don't specify the type of either of those parameters as any. Instead, either:

*

*Allow Typescript to correctly infer the type by removing the any; or

*Specify the type explicitly:

import express from 'express'

const app = express();

app.use((req: express.Request, res: express.Response) => {

})

Finally, make sure @types/express is installed.
You can check it out here:
https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=11&pc=3#code/JYWwDg9gTgLgBAUwB5iggzuuAzKERwDkyqG6hAUBQMYQB268AhmGHALyIpqYAUAlAG4qLMADoArugS9eaAI4AaOD34cAfHADecKgF9+I1pOmyFALi6lMYgEoJ5EjDGU9LJHujsZIDBGvZNHX1+IA


text:
Q: What is the purpose of the 'self' parameter in Python's builtins.print()? Being new to Python, I was looking for the implementation of the built-in print() function. Following the "Go to implementation" feature of my IDE, I landed in a builtins.py file containing function prototypes - and the print() function particularly stood out:
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print

It was the only function of the whole section that made use of the self parameter. Why? It's never called as a member of an object and you never assign to that attribute either. What purpose does it serve?

A: __init__ and in this init function we use SELF and this allows the class to initialize the attributes of the class. __init__ is also a reserved method in classes it is a constructor in OOP (Object Oriented/Object Oriented Programming) concept:
class Test():
  HELLO = "Hello World!"
  def __init__(self,HELLO):
    self.HELLO = "Hello World? I guess.."

x = Test()
print(x.HELLO) // prints Hello World? I guess..
print(Test.HELLO) // prints Hello World!

Usually it is our practice to write the __init__ method for setting the default state of an(the) attribute with SELF


text:
Q: Getting error while publishing data to GCP IoT core and Pub/Sub using C SDK I am running an example code from Google IoT C SDK which is iot-device-sdk-embedded-c.
iot-device-sdk-embedded-c/examples/iot_core_mqtt_client

I am running the code using the following commands
./iot_core_mqtt_client --project_id=project-aura-249003 --device_path=projects/project-aura-249003/locations/asia-east1/registries/Linux_PC/devices/linux_pc --publish_topic=projects/project-aura-249003/topics/Example --publish_message=Hello_world --private_key_filename=./ec_private.pem

I am getting error, below
IoTC Embedded C Client Version: 1.0.2
connected to mqtt.2030.ltsapis.goog:8883
publishing msg "H" to topic: "projects/project-aura-249003/topics/Example"
connection closed - reason 17 : !
The error means IOTC_CONNECTION_RESET_BY_PEER_ERROR
I found a solution from git where they told to try to change the topic to events or states so i tried with that as well by the same error is coming.
You can find the SDK here
What am i missing here?
Please help me with this
Thank you
Harsha

A: The issue here is that we need to provide the topic name properly. In this we are suppose to provide the MQTT topic which in this case is
--publish_topic=/devices/linux_pc/events
(OR)
--publish_topic=/devices/linux_pc/state
should work fine.
The topic which was provided projects/project-aura-249003/topics/Example" is wrong.
Format Topic = /devices/<Device-ID>/events or /devices/<Device-ID>/state


text:
Q: Inject factory into directive's link function defined OUTSIDE of the directive's scope I saw the following question (among other similar questions) and it solves the problem of trying to inject a factory into a directive's link function:
Injecting service to Directive
The solutions I've seen keep the link function within the scope of the directive:
angular.module('myapp')
    .directive('myDir', function(myService){
        return {
            restrict: 'E',
            scope: {
                frame: '='
            },
            link: function postLinkFn(scope, elem, attr) {
                myService.doSomething();
            }
        };
    });

However, I want to be able to separate the postLinkFn outside of the .directive scope for organization, just like I can do with controllers.
Is it possible to separate this function while also injecting a service into it?

A: .directive('myDir', function(myService){
    var deps = { myService: myService };

    return {
        ...
        // myService is available as this.myService inside postLinkFn
        link: angular.bind(deps, postLinkFn)
    };
});

link function doesn't make use of dependency injection and doesn't have lexical this, binding injected dependencies to this is a reasonable move.

A: Sure you can put your code in a factory and then refer it globally across the app.
angular.module('myapp').factory('myfactory', myService, function(){
return{
var myfac;
my fac = function (myService){
  var myItem = myService.doSomething;
  return myItem;
};

};
}).
.directive('myDir', function(myService){
    return {
        restrict: 'E',
        scope: {
            frame: '='
        },
        link: myfactory.myItem;
    };
});'

Just a little care you need to take is binding your factory with an angular promise $q if your service deals with asynchronous calls.


text:
Q: how to get user's last login with OneToOneField and display it on admin panel? Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'portal_users.admin.ProfileAdmin'>: (admin.E108) The value of 'list_display[10]' refers to 'user__last_login', which is not a callable, an attribute of 'ProfileAdmin', or an attribute or method on 'portal_users.Profile'.
System check identified 1 issue (0 silenced).
There is my code
models.py:
class Profile(models.Model):
user = models.OneToOneField(
User,
null=True,
related_name='profile',
on_delete=CUSTOM_SET_NULL,
)
student_id = models.IntegerField(
blank=True,
null=True,
verbose_name='ID студента/преподавателя',
help_text='Из 1С',
)
first_name = models.CharField(
    max_length=200,
    verbose_name='Имя',
    blank=True,
)
last_name = models.CharField(
    max_length=200,
    verbose_name='Фамилия',
    blank=True,
)

admin.py:
@admin.register(models.Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = [
    'user',
    'first_name',
    'last_name',
    'user__last_login',
]

A: You would need to add a custom method that would display the last login on admin:
class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user','first_name', 'last_name', 'get_last_login']

    def get_last_login(self,instance):
        return instance.user.last_login
    get_last_login.short_description = "Last login"

More on this: Documentation on list_display


text:
Q: Error while trying to add external local fonts in nextJS I'm trying to add local font to my NextJS + TailwindCSS project.
I have added the font inside public/fonts folder and I'm following the docs:
This is my code
import localFont from '@next/font/local'
const inter = Inter({
    subsets: ['latin'],
})

const recoleta = localFont({
    src: 'fonts/Recoleta-Regular.ttf',
    fontFamily: 'Recoleta',
})

And I'm getting this error from the terminal.
I need help on which folder to add it or how to configure it perfectly.
Module not found: Can't resolve './fonts/Recoleta-Regular.ttf'

A: Had this error and fixed the issue by setting it up as such. Used https://nextjs.org/docs/api-reference/next/font#src for assistance.
Using app folder.
page.tsx:
import CustomFont from '@next/font/local'

const cfont = CustomFont({
  src: '../public/fonts/cfont.ttf',
  variable: '--font-cfont',
})

export default function Home() {
  return (
    <div className={`${cfont.variable}`}>

        Test

  )
}

tailwind.config.js:

const { fontFamily } = require('tailwindcss/defaultTheme')

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        cfont: ['var(--font-cfont)', ...fontFamily.sans],
      },
    },
  },
  plugins: [],
}


text:
Q: Maximal "distance" of two probability measures? Consider the two coins (i.e., probability measures on the discrete set ${0,1}$) $C_{0.9}$ and $C_{0.99}$, where $C_{x}$ is the coin having probability of turning head equal to $x$.
Let $\mu_{0.9}$ and $\mu_{0.99}$ be the probability measures on $2^{\omega}$ (Markov chains) obtained by flipping infinitely often the two coin $C_{0.9}$ and $C_{0.99}$ respectively. So that, for instance, the probability assigned by $\mu_{0.9}$ to the (open) set of sequences starting with two zeros is $0.81$.
Question: I would like to calculate $D(\mu_{0.9}, \mu_{0.99})$ defined as:
$D(\mu_{0.9}, \mu_{0.99})$ = $\displaystyle \bigsqcup_{B} \{ |\mu_{0.9}(B) - \mu_{0.99}(B)| \ \ $ ;  $B$ a Borel subset of $2^{\omega}  \}$.
I don't know how to approach this problem. I have the feeling that the above supremum should be strictly less than $1$ and that the maximizing event should be the set of sequences starting with about 25 ones. The number 25 comes from the function $f : \mathbb{R}\rightarrow \mathbb{R}$ defined as $f(x)= {0.99}^x - {0.9}^x$ which attains its maximum around 25.
Question 2: More generally, is the function $D$ (mapping pairs of probability measures to the unit interval) as defined above well known?
Thank you in advance for any comment!

A: Call $B$ the event that the asymptotic proportion of heads exists and is 0.9, then the law of large numbers shows that $\mu_{0.9}(B)=1$ and $\mu_{0.99}(B)=0$. Hence $D(\mu_{0.9},\mu_{0.99})=1$. One sees that in fact the measures $\mu_{0.9}$ and $\mu_{0.99}$ are mutually singular.


text:
Q: Adding Multiple Favorites of User in MySQL I'm generally work on android development but decided to build my own REST API for a medium-large project. I need to-do idea for this application.
I have 2 tables:
User
user_id, user_name, password
Favourite List
list_id,
list_name
Let's assume we have 1000 lists about news. Every user can add one or many of these list items as their favourite.
I learned about foreign key, but I should relate many lists to user not only one.
I should make like:
id_1 --->  user's lists: id 1,3,12,33
id_2 ---> user's lists: id 1,12,55,77 etc.

A: You'll need to use a junction table to associate the users with the lists. Each row in that table will contain a user_id and the list_id that they want to follow.


text:
Q: Calling Javascript - Window.open in PHP I'm trying to call a window.open() javascript code inside a php file, but unfortunately it is not responding.
Here's my code:

<?php .....

$printHeader .= "

User: " . $username . " | Access: " . $level ." | Logout
";
$printHeader .= "
Refresh List

";
$printHeader .= "

";

.... ?>

Unfortunately, when I run it, it doesn't work at all. Can we not call javascript in php? Please advise!
Thanks!

A: I think the issue is related to the quotes, Your inner single quotes are ending the onClick string, so replacing the outter single quotes to double quotes(will keeping the inner quotes single) will solve your issue. try changing this:
onClick='window.open(this.href,'mywin','width=400,height=200)'

To this:
onClick=\"window.open(this.href,'mywin','width=400,height=200)\"

Here's an example:
On JSFiddle
Another solution is to simply escape your inner quotes by prefixing them with a backslash (\).

A: One thing that catches my eye right away is that you did not escape your single quotes withing the onclick event. Modify it like so:
onclick=\"window.open(this.href, 'mywin', width=400, height=200);\"

See if this helps you out.


text:
Q: Plotly Dash - TypeError: Object of type Polygon is not JSON serializable I am attempting to plot choropleth map using dash and mapbox. At runtime, I am getting an error "TypeError: Object of type Polygon is not JSON serializable".
sample data and code:
url = "https://drive.google.com/file/d/1bP_SdwrU7pMtCPnOd5XfA3oQYKWYlNjn/view?usp=sharing"

import geopandas as gpd
from shapely.geometry import Point
from shapely.geometry import Polygon
import fiona
from shapely import wkt
import dash
from dash import html
import geojson
import json

MAPBOX_KEY="pk.xxx...."
token = MAPBOX_KEY

with urlopen(url) as response:
    geo_json = json.load(response)

df_geo = gpd.read_file(url)

layout = html.Div([

                    dcc.Graph(id="map"),
                    html.Div(id="dummy")

         ])

@app.callback(
              [

                Output("map", "figure")

              ],
              [

                Input("dummy", "value")

              ],
             )
def update_map(d):

    s = df_geo['avg_price'].astype(float)

    datad = []

    datad.append({

                    "type": "choroplethmapbox",
                    "geojson": geo_json,
                    "locations": df_geo['tract'],
                    "z": s,
                    "featureidkey": "properties.tract",
                    "autocolorscale":False,
                    "colorscale":"YlOrRd",
                    "colorbar":dict(
                                    title = label,
                                    orientation = 'h',
                                    x= -0.15,
                                    xanchor= "left",
                                    y= 0,
                                    yanchor= "bottom",
                                    showticklabels=True,
                                    thickness= 20,
                                    tickformatstops=dict(dtickrange=[0,10]),
                                    titleside= 'top',
                                    ticks= 'outside'
                                   ),
                    "zmin": s.min(),
                    "zmax": s.max(),
                    "marker_line_width": 0,
                    "opacity": 0.2,
                    "labels": label,
                    "title": "Choropleth - Census Tract Level"

                 }
    )

    layout = {

              "autosize": True,
              "datarevision": 0,
              "hovermode": "closest",
              "mapbox": {

                 "accesstoken": MAPBOX_KEY,
                 "bearing": 0,
                 "center": {
                     "lat": 33.6050991,
                     "lon": -112.4052438
                 },
                 "pitch": 0,
                 "opacity": 0.2,
                 "zoom": zoom,
                 "style": "streets",

             },

             "margin": {
                "r": 0,
                "t": 0,
                "l": 0,
                "b": 0,
                "pad": 0
            }

       }

return ({"data": datad, "layout": layout})

Full Traceback:
Exception on /_dash-update-component [POST]
Traceback (most recent call last):
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/_callback.py", line 191, in add_context
    jsonResponse = to_json(response)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/_utils.py", line 21, in to_json
    return to_json_plotly(value)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/plotly/io/_json.py", line 124, in to_json_plotly
    return json.dumps(plotly_object, cls=PlotlyJSONEncoder, **opts)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/json/__init__.py", line 234, in dumps
    return cls(
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/_plotly_utils/utils.py", line 59, in encode
    encoded_o = super(PlotlyJSONEncoder, self).encode(o)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/_plotly_utils/utils.py", line 136, in default
    return _json.JSONEncoder.default(self, obj)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Polygon is not JSON serializable

    During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/dash.py", line 1336, in dispatch
    response.set_data(func(*args, outputs_list=outputs_list))
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/_callback.py", line 193, in add_context
    _validate.fail_callback_output(output_value, output)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/_validate.py", line 297, in fail_callback_output
    _validate_value(val, index=i)
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/_validate.py", line 287, in _validate_value
    _raise_invalid(
  File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/dash/_validate.py", line 226, in _raise_invalid
    raise exceptions.InvalidCallbackReturnValue(
dash.exceptions.InvalidCallbackReturnValue: The callback for `[<Output `map.figure`>]`
returned a value having type `list` which is not JSON serializable.

A: Have used data provided on google drive

*

*have simplified geometry to make it more performant.  Plus removed spurious column tract_geom. This column was probably causing your error on JSON serialisation, but data provided for this question is WKT not objects.

*made GeoDataFrame compatible with callback code and defined referenced variables

*fixes

*

*used geo_interface to pass geojson

*opacity is not valid as a mapbox parameter

*callback was using arrays as parameters.  This was causing errors, so switched to

@app.callback(
    Output("map", "figure"),
    Input("dummy", "value"),
)
def update_map(d):

full working code
import pandas as pd
import geopandas as gpd
from dash import dcc, html, Input, Output
import pandas as pd
from jupyter_dash import JupyterDash

url = (
    "https://drive.google.com/file/d/1bP_SdwrU7pMtCPnOd5XfA3oQYKWYlNjn/view?usp=sharing"
)
df = pd.read_csv("https://drive.google.com/uc?id=" + url.split("/")[-2], index_col=0)

# construct geodataframe from provided data
df_geo = gpd.GeoDataFrame(
    df, geometry=gpd.GeoSeries.from_wkt(df["geometry"]), crs="epsg:4386"
)

# reduce size of dataframe geometry....
df_geo["geometry"] = (
    df_geo.to_crs(df_geo.estimate_utm_crs()).simplify(5000).to_crs(df_geo.crs).drop(columns=["tract_geom"])
)
# make compatible with code in call back
df_geo["tract"] = df_geo["tract_ce"]
zoom = 5
label = "Average Price"

app = JupyterDash(__name__)
app.layout = html.Div([dcc.Graph(id="map"), html.Div(id="dummy")])

@app.callback(
    Output("map", "figure"),
    Input("dummy", "value"),
)
def update_map(d):
    s = df_geo["avg_price"].astype(float)

    datad = []

    datad.append(
        {
            "type": "choroplethmapbox",
            "geojson": df_geo.__geo_interface__,
            "locations": df_geo["tract"],
            "z": s,
            "featureidkey": "properties.tract",
            "autocolorscale": False,
            "colorscale": "YlOrRd",
            "colorbar": dict(
                title=label,
                orientation="h",
                x=-0.15,
                xanchor="left",
                y=0,
                yanchor="bottom",
                showticklabels=True,
                thickness=20,
                tickformatstops=dict(dtickrange=[0, 10]),
                titleside="top",
                ticks="outside",
            ),
            "zmin": s.min(),
            "zmax": s.max(),
            "marker_line_width": 0,
            "opacity": 0.2,
            "labels": label,
            "title": "Choropleth - Census Tract Level",
        }
    )

    layout = {
        "autosize": True,
        "datarevision": 0,
        "hovermode": "closest",
        "mapbox": {
            "accesstoken": MAPBOX_KEY,
            "bearing": 0,
            "center": {"lat": 33.6050991, "lon": -112.4052438},
            "pitch": 0,
            # "opacity": 0.2,
            "zoom": zoom,
            "style": "streets",
        },
        "margin": {"r": 0, "t": 0, "l": 0, "b": 0, "pad": 0},
    }

    return {"data": datad, "layout": layout}

if __name__ == "__main__":
    app.run_server(mode="inline")

A: I just had the same error coming up in a similar context.- I solved by: (A) Making sure all columns in the geodataframe had allowed values for geoJson standards (no lists or arrays, only one geometry column) and by setting index and geometry column with
df = df.set_geometry("geometry").set_index("id")
After that mapbox would display correctly.


text:
Q: In my Fourier text book, there are the following exercises to prove. why do some of them have the same left side but have different right sides?
In my Fourier text book, there are the following exercises to prove.why do some of them have the same left side but  have different right sides? The demand of these question is to prove these equations by Parseval theorem. It is best that you can give a detailed answer.

A: I believe these formulas were accompanied by text that explains the nature of $f$ and its relation to $a_b,b_n,c_n$. For example:

*

*(a) concerns the exponential form of Fourier series, $\sum_{n=-\infty}^\infty c_n e^{inx}$

*(b) concerns the trigonometric Fourier series, $\frac{a_0}{2}+\sum_{n=1}^\infty (a_n \cos nx+b_n\sin nx)$

*(c) is about the  trigonometric Fourier series of an odd function $f$. Such a function has only sines in its expansion, no cosines: $\sum_{n=1}^\infty b_n\sin nx$

*Similarly, (d) is about the  trigonometric Fourier series of an even function $f$. Such a function has only cosines in its expansion: $\frac{a_0}{2}+\sum_{n=1}^\infty a_n \cos nx$

*Finally, (e) and the last item named "(d)" concern a function defined on an interval $[0,L]$. Such a function can be extended to $[-L,L]$ either as odd or an even function. Then one uses (c) or (d), as appropriate.

You will find a detailed explanation of sine and cosine series here.


text:
Q: Disable transfer-encoding chunked in jax-ws I made a web service using jax-ws, but I need to disble the transfer-encoding chunked.
I used a handler, similar to this one:
public class MyHandler<SOAPMessageContext> implements Handler {

    public boolean handleMessage(SOAPMessageContext c) {
        if((Boolean)c.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
            c.put(SOAPMessageContext.HTTP_RESPONSE_HEADERS,"your header stuff here");
            return true;
        }
    }
 }

But I don't know which header is the correct one to disable the chunked encoding.


text:
Q: GAE - Serving Images I have a finite set of images (> 1000) that will be used on a site hosted on the Google App Engine. In reading the documentation, I noticed there's the Images library that provides various image manipulation capabilities. The one method that caught my attention is
get_serving_url(blob_key, size=None, crop=False, secure_url=None)

This returns a URL that serves the image. The documentation then goes on to say:

This URL format allows dynamic resizing and cropping, so you don't
  need to store different image sizes on the server. Images are served
  with low latency from a highly optimized, cookieless infrastructure.

I would like to know if there is an advantage, speed wise, between serving the images from a static folder or using the Image service.

A: Dynamically resizing images and reading out of the blob store as the other answer here mentions is never going to be that fast. You need to store static copies of your images if you want performance. If for no other reason than caching. Prefer the static version if you can, and prefer a CDN above the static version.
The choice between blob store and static can also revolve around if your content is from you, or submitted by users. If submitted by users, then the blob store is usually the way to go if you're stuck with storing the images on app engine.
In practice, we found the internals of GAE and pricing to be less than adequate for serving images. Instead, consider a CDN if you're especially worried about serving images fast. For example, you could go with Amazon Cloudfront/S3 combo or Rackspace Cloudfiles. In both cases, there was absolutely no comparison speed-wise between using the serving url vs. a CDN.
Simply push your content either directly to the CDN on creation, or keep a fallback copy in the blobstore. What we do in our app is we keep uploaded images by users in the blobstore first, and queue up a background task to submit the content to the CDN. The various sizes such as thumbnails are generated using our CDN's API that we call via REST from App Engine. If somehow the user hits our site before all of this happens and we need these images, we simply serve them the dynamic version you referenced in your question. It's much slower, but it ensures we always have a fall-back while the system is refreshing or generating the CDN content. 99% of the time though, the user hits the fast version in the CDN.
EDIT: I want to point out that certainly the app engine static content is cached, just not with the efficiency of a decent CDN provider in my real world experience running a very image heavy app engine site with lots of unique hits per day.

A: Images service does not store or serve images. Images are served either from a BlobStore, or from Google Cloud Storage, depending on which option you use. Both options offer very fast response times. I believe that serving files from a static folder will offer very similar performance.
UPDATE:
I noticed that with the new pricing on GAE they will charge the same price for static files as they do for Google Cloud Storage or BlobStore, but the free quota is larger (5GB) for GCS and BlobStore than for code and static files (1GB).


text:
Q: How to make multi column List Box in ASP.Net? I want to make multi column list box in asp.net. At beginning it should be an empty. At runtime when user add some thing, it has to add in list box in client side, not in server side.

Now I made this . Now I just want to make that filter list box with multi columns.


text:
Q: reverse triangle inequality Given the reverse triangle inequality, mod(a+b+c) is greater than or equal to mod(a)- mod(b) - mod(c).
Suppose a, b, c are complex numbers such that mod(a)=4, mod(b)=10 and mod(c)=1. What is the smallest possible value that mod(a+b+c) can attain? Justify your answer.
I know the answer is 5, and that it relates to b's dominance over the over numbers but am struggling to explain how this is the case?
Could someone please shine some light on this for me please?
Thank you

A: Step 1: $|a+b+c|\geq|b|-|a+c|$ by the reverse triangle inequality.
Step 2: $|a+c|\leq |a|+|c|$ by the triangle inequality.
Step 3: $|a+b+c|\geq|b|-|a+c|\geq|b|-|a|-|c|=10-4-1=5$.
Step 4: Find an instance where the equality is attained.


text:
Q: Is this a valid approach to sharing a function between Python classes? My goal is to use the same function from multiple classes in Python.
I've seen discussion about mixins and inheritance etc but they all seem to come with caveats and cautions about doing things just right.
So I wondered if I could just call another plain old function that lives outsides the classes.  It seems to work, but maybe I'm failing to understand something important?
So my question is - is this a valid approach to sharing a function between Python classes?
def clean_reference_url(self):
    if not self.cleaned_data['reference_url']:
        return ''
    try:
        if 'illegaltext' in self.cleaned_data['reference_url']:
            raise Exception
    except:
        raise forms.ValidationError('You cannot put illegaltext in this field.')
    return self.cleaned_data['reference_url']

class ContactForm(forms.ModelForm):

    def clean_reference_url(self):
        return clean_reference_url(self)

class TripForm(forms.ModelForm):

    def clean_reference_url(self):
        return clean_reference_url(self)

A: It's valid, but it's unnecessary to have the extra layer of wrapping. The mix-in approach is the simplest, but yes, it has some caveats (largely related to metaclasses), so if you want to avoid that, you can still set a method in multiple classes by just setting during the definition of each class. Keep the function definition the same, and change the classes to:
class ContactForm(forms.ModelForm):
    clean_reference_url = clean_reference_url

class TripForm(forms.ModelForm):
    clean_reference_url = clean_reference_url

Again, a mixin is even cleaner, e.g.:
class CleanableUrl:  # Change name as appropriate
    def clean_reference_url(self):
        # ...

class ContactForm(CleanableUrl, forms.ModelForm):
    # No need to talk about clean_reference_url at all

class TripForm(CleanableUrl, forms.ModelForm):
    # No need to talk about clean_reference_url at all

and it's usually the most Pythonic approach, assuming it works for your scenario (no conflicting metaclasses on the base types).


text:
Q: Solve $2x^{3}ydy+(1-y^{2})((xy)^{2}+y^{2}-1)dx=0$ The question is to solve this
$$2x^{3}ydy+(1-y^{2})(x^2y^{2}+y^{2}-1)dx=0$$
What I tried was to bring this equation in linear differential equation form but failed. I have also tried out rewriting the given in such a way so that each term can be integrated easily but to no avail it isnt exact either since $\frac{dm}{dy}$ is $4y-4y^{3}$ and  $\frac{dn}{dx}$ is $6x^2y$
Please help me to solve this.
Thanks in advance.

A: I can't seem to get the Mathematica solution. Just chipping away at it,
$$2y\frac{dy}{dx}=\frac{(y^2-1)}{x^3}(x^2y^2+y^2-1)$$
Let $s=y^2$. Then
$$\frac{ds}{dx}=\frac{(s-1)}{x^3}(x^2s+s-1)$$
Let $s-1=t$. Then
$$\frac{dt}{dx}=\frac t{x^3}(x^2(t+1)+t)$$
Let $t=\frac1u$. Then
$$-\frac1{u^2}\frac{du}{dx}=\frac1{ux^3}\left(x^2\left(\frac1u+1\right)+\frac1u\right)$$
$$\frac{du}{dx}+\frac1xu=-\frac1x-\frac1{x^3}$$
The integrating factor is
$$\mu=e^{\int\frac1xdx}=e^{\ln x}=x$$
So
$$\frac d{dx}\left(xu\right)=x\frac{du}{dx}+u=x\left(-\frac1x-\frac1{x^3}\right)=-1-\frac1{x^2}$$
$$xu=-x+\frac1x+C=\frac xt$$
$$t=\frac x{-x+\frac1x+C}=\frac{x^2}{-x^2+1+Cx}=s-1$$
$$s=\frac{1+Cx}{-x^2+1+Cx}=y^2$$
$$y=\pm\sqrt{\frac{1+Cx}{-x^2+1+Cx}}$$
OK, I take it back. That is the Mathematica solution. I found my mistake while typing this up.

A: Mathematica gives the solution as
$$ y(x) = - \sqrt {\frac{ 2 c x -1 } { 2 c x + x^2 -1 } } $$
If you use the sub $z = y^2$,you'll find the equation transform  to
$$ x^3 d z + ( 1-z) ( x^2 z + z -1) dx =0 $$
Then it looks like you should be able to find an integrating factor in $z$.


text:
Q: Difference between BigDecimal.ONE and new BigDecimal("1") what is the difference between below two lines of code?
BigDecimal one = new BigDecimal("1");
BigDecimal two = BigDecimal.ONE;

Are both the lines same?
Thanks!

A: BigDecimal.ONE is a pre scanned object and its efficient in terms of memory utilization as compared to
BigDecimal one = new BigDecimal("1");

because in this line it first creates an instance and then parses string "1" and then assigns.
whereas BigDecimal.ONE is like a constant and will give you direct value.
Hope this helps!

A: No, they're not quite the same - new BigDecimal("1") allocates a new object each time it's executed (and have to parse the value, too); BigDecimal.ONE will use a reference to the same existing object each time.
As BigDecimal is immutable, you can reuse an existing instance freely - so it makes sense to refer to a "pre-canned" object where you know what the value will be.