text:
Q: How to get distance in few meters between 2 pair of latitude longitude I would like to calculate distance between 2 points of latitude and longitude in PHP (NOT IN ANDROID)**i have read about **Haversine Formula and Spherical Law of Cosines for calculate distance between two points but my main motive is get best location difference between 2 points in Meters.
For Example Two devices place at next to each other and that android devices is sending location to server,So we need to take that location of each device and calculate minimum distance between these 2 device in meter.Result from Server after calculation should be like in 2-3 meters when device is placed next to each others
So what are the possible ways to calculate minimum distance between two device in meters when device next to each other on server side
Note : I need to calculate distance which i got in kms or miles which is big difference when device is next to each other. Haversine Formula and Spherical Law of Cosines is i found best way to calculate but i need to do more in these formulas to get minimum difference between 2 device.Not on Android Device. This question is not related to This Question

A: I have used the Haversine formula in PHP to calculate distance in kms between two geocoordinates:
// Haversine formula
function geoDistance($lon1, $lat1, $lon2, $lat2) {
    $R = 6371; // Radius of the earth in km
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $d = $R * $c; // Distance in km

    return $d;
}

I guess, having enough precision in lon and lat would yield a result that multiplied by 1,000 migth be useful as a measure of distance in meters, right?
According to https://gis.stackexchange.com/questions/8650/measuring-accuracy-of-latitude-and-longitude the fifth decimal place is worth up to 1.1 m: it distinguish trees from each other.


text:
Q: Group and Join Linq statement wont pass to my view from controller My View:
@model IEnumerable<TestingMainPage.Models.SummaryModel>

@if (Model.Count() > 1 )
{//Do something}
else
{//Do something else}

The error involved:
The model item passed into the dictionary is of type  'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType11`4[System.Int32,System.Nullable`1[System.DateTime],System.String,System.Nullable`1[System.Int32]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[TestingMainPage.Models.SummaryModel]'.

Which is caused by the linq statement...
Can anybody tell me what is wrong with this linq statement? I am still new to linq and trying to figure it out..
For some reason I can run it in Linqer but it wont actually pass the model to my view in my project? Which I am assuming because there is something wrong with the Linq statement, because if I switch it up to a very simple select then it will pass the model..
        var BeginDate = DateTime.Now.AddDays(-5).ToString("d") + " 2:00:00";
        var EndDate = DateTime.Now.ToString("d") + " 2:00:00";
        DateTime Start = Convert.ToDateTime(BeginDate);
        DateTime End = Convert.ToDateTime(EndDate);

      var TestLinq = (from a in db.seqexp_master
                      join b in db.seqexp_detail on a.recid equals b.recid into b_join
                      from b in b_join.DefaultIfEmpty()
                      where
                        a.shipto == "1020" &&
                        (new string[] { "a", "c" }).Contains(a.status) &&
                        a.active == 1 &&
                        b.active == 1 &&
                        a.datetimestamp >= Start &&
                        a.datetimestamp <= End
                      group new { a, b } by new
                      {
                          a.recid,
                          a.datetimestamp,
                          a.status
                      } into g
                      orderby
                        g.Key.recid descending
                      select new
                      {
                          Recid = g.Key.recid,
                          datetimestamp = g.Key.datetimestamp,
                          status = g.Key.status,
                          Qty = g.Sum(p => p.b.qty)
                      });
return View(TestLinq);

Any help is appreciated :D
Thanks
I dont think you would need to see my Model either, but just incase:
   public class SummaryModel
{
    public DateTime datetimestamp { get; set; }
    public char status { get; set; }
    public int? Recid { get; set; }
    public int? Qty { get; set; }
    public int? test { get; set; }
}

A: This is the problem, at the end of your query:
select new
{
    Recid = g.Key.recid,
    datetimestamp = g.Key.datetimestamp,
    status = g.Key.status,
    Qty = g.Sum(p => p.b.qty)
}

That's an anonymous type, but your view wants an IEnumerable<SummaryModel>. It's not clear what SummaryModel is, but perhaps you want:
select new SummaryModel
{
    Recid = g.Key.recid,
    datetimestamp = g.Key.datetimestamp,
    status = g.Key.status,
    Qty = g.Sum(p => p.b.qty)
}

(If so, I strongly recommend that you fix your property names to follow normal .NET conventions...)

redpajama_set_name: RedPajamaStackExchange


text:
Q: pthread with php 7.0.8 (ZTS) I would like use pthreads with php 7.0.8 (ZTS) (Manually compiled and configured)
I have add the followinG configuration during compiling of php :
--enable-maintainer-zts \
--enable-pthreads=shared \
--with-tsrm-pthreads \

NOTICE: fpm is running, pid 25546
NOTICE: ready to handle connections

I add pthread extension with pecl : pecl install pthreads-3.1.6 and I add extension=pthreads.so into my php.ini. But after restarting php7-fpm, php-fpm not running :

NOTICE: Finishing ...
NOTICE: exiting, bye-bye!

I have a 502 nginx error.
How I can add this extension in my php.ini without exit php-fpm ?

A: You should use php-cli for use pthreads. You can create a second php.ini configuration for CLI :

*

*First, copy if not exist your php.ini to php-cli.ini :
cp /PATH_OF_YOUR_PHP_INSTALLATION/php.ini /PATH_OF_PHP_INSTALLATION/php-cli.ini

*Then, install pthreads with PECL (if php is compiled with
--enable-maintainer-zts \ --enable-pthreads=shared \ --with-tsrm-pthreads )
pecl install pthreads

*Then, add the configuration of the extension into your php-cli.ini :
echo "extension=/PATH_OF_EXTENSION/pthreads.so" >>/PATH_OF_PHP_INSTALLATION/php-cli.ini

*Finnaly, restart your php7-fpm service :
service php7-fpm restart

You can test the pthread installation is working to create a test class and execute it with php :
Create file : ImportWorker.php
<?php
class ImportWorker extends Worker {
    private $data;

    public function __construct($_data) {
        $this->data = $_data;//
    }

    public function run(){
        var_dump("Worker test");
    }
}

Execute that : php ImportWorker.php -> If you have any errors, that is pthreads is not working.


text:
Q: Create a single-server replica set only for watching on change streams I have a MongoDB database which is of relatively low importance. I shovel data from home automation stuff into it (mostly sensor data, sunlight, switch states and so on) and don't need any replication.
I want to subscribe to change streams on that DB, and for that they must be members of a replica set. Is it OK to just add the --replSet [name] flag to the already existing server and then call rs.initiate() in it without rs.add()-ing any secondary members?
What drawbacks will this have (database size, performance, ...)?
Basically I want devices/software to insert data directly into the database, and then have some middleware watching on change streams to then publish the data via RabbitMQ.
Currently I'm inserting into RabbitMQ and MongoDB in parallel. Inserting into RabbitMQ and having a middleware insert the data into MongoDB is also an option, but I want to check both ways of doing it.
I'm not that much of a friend of replica sets as I have an important Database which holds about 80-90MB of documents (total size when exporting all collections to disc), but each member consumes around 1.5 GB of space (--logpath data excluded).

A:
Is it OK to just add the --replSet [name] flag to the already existing server and then call rs.initiate() in it without rs.add()-ing any secondary members?

Yes, a single node replica set is fine if you don't require data redundancy or fault tolerance.

What drawbacks will this have (database size, performance, ...)?

A replica set node maintains an operation log (oplog) which has some additional storage overhead. You can change the size of the oplog to suit your use case. Since you only need the oplog for change streams, it can perhaps be smaller than the default to save on disk space.
In MongoDB 3.6+ you can also adjust the size at runtime using the replSetResizeOplog  command. In earlier server versions the resize procedure is manual: Change the size of the oplog (MongoDB 3.4).

I'm not that much of a friend of replica sets as I have an important Database which holds about 80-90MB of documents (total size when exporting all collections to disc), but each member consumes around 1.5 GB of space (--logpath data excluded).

Clarifying excessive storage usage is really a separate question, but this definitely seems an anomalous ratio.
Some likely causes:

*

*Storage usage in the dbPath includes the replication oplog. The default oplog size is determined based on free disk space and O/S (for example, 5% of free disk space on Linux/Windows with a lower bound of 990MB and upper bound of 50GB).

*You were using an older version of MongoDB (likely 3.2 or earlier) with the MMAPv1 storage engine. MMAP does not compress data on disk and some use cases will lead to storage fragmentation over time. Modern versions of MongoDB default to the WiredTiger storage engine which includes data & index compression and significant improvements over MMAPv1.


text:
Q: QAbstractItemModel - inserting rows - how to specify the columns The doc shows a table

But the API does not allow you to specify the column under which to insert the rows.
void QAbstractItemModel::beginInsertRows(const QModelIndex &parent, int first, int last)

Under which column does the row get inserted?

A: You always insert a complete row, not a single cell so when adding a row into a table model the parent is the root index (= invalid QModelIndex), if you insert into a tree then the parent is the parent node.


text:
Q: Does Visual Studio 2010 come with sql server express Hi
I installed VS 2010 and sql server management studio 2008 express. I full installed VS but I can't find a sql server. Do I need to download and install sql server express on my PC? I have Windows 7 64 bit and I installed server management studio 2008 express x86

A: It turns out that VS2010 installs sql server 2008 express
It does install sql server express but you need to enable sql browsing. You need to go to sql server configuration manager->sql server services->sql server browsing and enable it
Visual studio 2010 and Sql Server

A: SQL Management Studio is the tool used to connect to a SQL Server instance.  It does not necessarily install a SQL Server instance on your machine.
If you have the DVD you will need to install the full instance.  If you don't have the full SQL Server DVD, then you'll need to buy it or download SQL Server Express free from http://www.microsoft.com/express/Database/


text:
Q: Bose-Einstein statistics in de Sitter spacetime The metric in de Sitter spacetime with $(+,-,-,-)$ as metric signature is, in cartesian coordinates:
\begin{equation}
ds^2=dt^2-a^2(t)(dx^2+dy^2+dz^2).
\end{equation}
Where $a(t)=e^{Ht}$. How do I calculate the mean energy in the case of the Bose-Einstein distribution in such space-time? I suspect, for photons, something of the following form:
\begin{equation}
\langle E \rangle_o = 2 V \int_{\mathbb{R}^3} \frac{d^3k}{(2\pi)^3} \frac{|\vec{k}|}{a(t)} \frac{1}{e^{|\vec{k}|/(a(t)T)}-1},
\end{equation}
where $V$ is the volume defined by the cosmological event horizon for the observer $o$, but I am not sure about my equation.


text:
Q: MATLAB, interpolation of 3D curve crossing xy plane In Matlab, I have a 3D-curve (array with 3 coordinates) that crosses the xy-plane in a 3 dimensional coordinate system.  The "curve" is just a bunch of x,y,z points and its shape is elliptical that spans across the 3D space and spirals towards the origin. It crosses the xy plane several times and I would like to interpolate the x and y coordinates when the curve intersects the xy plane (i.e. when z=0). How do I do so?

A: Assuming you have 3 vectors x, y, and z with coordinates,
crossidx = find(diff(sign(z)) ~= 0); % z(zcross) and z(zcross+1) have different signs
z1 = z(crossidx);
z2 = z(crossidx+1);
dz = z2 - z1;
alpha = -z1;
beta = z2;
xcross = (beta*x(crossidx) + alpha*x(crossidx+1))./dz;
ycross = (beta*y(crossidx) + alpha*y(crossidx+1))./dz;
zcross = 0;
hold on; plot3(xcross, ycross, zcross, '*');

It should work for either positive to negative or negative to positive crossing. I wrote the code assuming only 1 zero crossing, but I think it would also work for any number of crossings.


text:
Q: Facing Issues in WinForm Integration with my Existing Azure Bot Using Directline API I have created a bot using Bot Framework SDK (C#, .Net). I have published it in Azure. It is working fine in WebChat as well as in Teams channel. Now I want to create one Winform and trying to connect the Winform UI to my bot using Directline Api.
This is my code :
public partial class Form1 : Form
{
    private static string directLineSecret = ConfigurationSettings.AppSettings["DirectLineSecret"];

    private static string botId = ConfigurationSettings.AppSettings["BotId"];

    private static string fromUser = "User";
    private static string id = "default-user";

    private Conversation conversation;
    DirectLineClient directLineClient = null;

    public Form1()
    {
        InitializeComponent();
        InitClientAsync();

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    private async Task InitClientAsync()
    {
        directLineClient = new DirectLineClient($"{directLineSecret}");
        directLineClient.BaseUri = new Uri($"https://directline.botframework.com/");

        //directLineClient = new DirectLineClient(directLineSecret);
        conversation = await directLineClient.Conversations.StartConversationAsync().ConfigureAwait(false);

            new System.Threading.Thread(async () => await ReadBotMessageAsync(directLineClient, conversation.ConversationId)).Start();

    }

    private async Task ReadBotMessageAsync(DirectLineClient client, string conversationId)
    {
        string watermark = null;

        while(true)
        {
            var activitySet = await client.Conversations.GetActivitiesAsync(conversationId, watermark);
            watermark = activitySet?.Watermark;

            var activities = from x in activitySet.Activities where x.From.Id == botId select x;

            foreach(Activity activity in activities)
            {
                if(activity.Text != null)
                {
                    string message = activity.Text;
                    if(InvokeRequired)
                    {
                        BeginInvoke(new MethodInvoker(delegate
                        {
                            textBox.AppendText("Bot : " + message + "\r\n");
                        }));
                    }

                }
            }
        }
    }

    private async void btn_Send_Click(object sender, EventArgs e)
    {
        string input = txt_Send.Text;
        txt_Send.Clear();
        if(input.Length>0)
        {
            Activity userMessage = new Activity
            {
                From = new ChannelAccount(id, fromUser),
                Text = input,
                Type = ActivityTypes.Message,
                TextFormat = "plain"
            };
            textBox.AppendText("You : " + input + "\r\n");
            await directLineClient.Conversations.PostActivityAsync(this.conversation.ConversationId, userMessage);
        }
    }
}

But when I execute the program it is stopping due to Null reference exception when it is trying to get conversation as well as conversation Id.
you can check the error image here.
Can anyone please tell me what I'm missing here?
Any help will be appreciated.....

A: The problem was with the directline secret key. I regenerate a new key and used it. Now that is starting the conversation and I am able to see conversation Id.
But after that I was getting status code 429 error. That is basically Multiple thread issue. It is trying to create multiple threads at the same time.
Then I recreate the whole project with .Net Framework version 4.6.2 (Previously using 4.7). Now that issue also got resolved. Project is working fine.


text:
Q: How to launch another application by passing c drive path in react web application? I am working on react web application.I want to launch application which is already into the system on c drive.So for eg, I will click on some button at that moment it should read c drive path (say C:\Program Files\VLC\VLC.exe) and launch/open VLC player. Also, I have another drive (say, \d:\test.mpg) path where playable file is located which I wanted to play with that player at the same moment when its launch. So I want to pass path "C:\Program Files\VLC\VLC.exe \d:\test.mpg" and open file. Here, not sure how I can pass outside application path to access file.
I have not tried anything as I have no idea how to do so any help would be really appreciate. TIA!

A: You cannot access a visitor's file system from a web application. This would be a tremendously dangerous security vulnerability if any web browser allowed this.
Resources about this are listed in other Stack Overflow answers
If you want a React application to have access to this kind of information you need to create a desktop application that the intended user can then use.
For instance Electron can load and render a web application with a Node.js instace available which can then access a user's system, but again, there are extremely serious security concerns that should (one might argue must) be considered thoroughly before proceeding down that path.


text:
Q: Import Opportunities using Data Loader in NPSP I need to import opportunity data to NPSP cloud.
Contact lookup to Account. And Opportunities lookup to both Account and Contact.
I first imported Contact data using data loader. And then imported Account data via data loader. And then mapped their ID's in the Opportunity excel sheet using VLookup.
(This is how I imported data while working in other clouds)
What I didn't realize was that while importing Contact data, it would automatically create a household account.
I now have duplicate account records in NPSP - the household account related to contact, and the account records imported(related to opportunity). The names of both account records are different - ContactLastName Household and OpportunityOrganization Name.
How should I proceed?

A: I managed to resolve this issue by following the following steps:

*

*Delete OpportunityOrganization Name Accounts

*

*Export the ID's of all Accounts.

*Map the OpportunityOrganization Name Accounts with their corresponding ID using VLookup in excel.

*Delete all OpportunityOrganization Name Accounts using data loader.

*Keep the OpportunityOrganization Name Accounts names in the main table - they are mapped with contacts.(to be used later)

*Map Account ID to Contact ID

*

*Export the ID's of all Contacts

*Map each contact with it's corresponding ID using VLookup in excel.

*Map each contact ID with the corresponding Account ID it is looking up to.

*This gives the ID's of all the ContactLastName Household accounts.

*Upsert OpportunityOrganization Name Accounts

*

*Each Account ID is a ContactLastName Household account.

*Each Contact ID/Account ID has a corresponding OpportunityOrganization Name Accounts name.

*Upsert the Account ID(of ContactLastName Household account) with the OpportunityOrganization Name Accounts name.

*Now all the contacts are looking up to the correct account.


text:
Q: AWS API Gateway Overwriting Integration Request Mapping Template with the same parameters I need to overwrite template by adding one new parameter.
But if I am adding something like this:
{
    "custom" : "param"
}

In my Lambda, I am getting just this parameter.
How I can overwrite template to pass existing parameters as is and add my sustom?


text:
Q: Biasedness of Gini Impurity estimator I am trying to show that whether the Gini Impurity of a discrete probability distribution can be estimated by using an iid sample from the distribution. We have a distribution $p(c)$ and its Gini Impurity is given as:
$$G = \sum_{c=1}^{L}p(c)(1-p(c)) = 1 - \sum_{c=1}^{L}p(c)^2$$
We have and iid sample $(x_1,\dots,x_n)$ and the impurity of this sample is:
$$\hat{G} = 1 - \sum_{c=1}^{L}\left(\sum_{i=1}^{n}\dfrac{[x_i - c]}{n}\right)^2 = 1 - \dfrac{1}{n^2}\sum_{c=1}^{L}\left(\sum_{i=1}^{n}[x_i - c]\right)^2$$. $[.]$ is the indicator function giving $[0]=1$ and $0$ else.
Then I want to calculate the expectation of this sample impurity. I read somewhere else that when we multiply $\hat{G}$ by $\dfrac{n}{n-1}$, it becomes the unbiased estimator for $G$:
$$\mathbb{E}[\hat{G}]=1 - \dfrac{1}{n^2}\sum_{c=1}^{L}\mathbb{E}\left[\left(\sum_{i=1}^{n}[x_i - c]\right)^2\right]$$
$$\mathbb{E}[\hat{G}]=1 - \dfrac{1}{n^2}\sum_{c=1}^{L}\mathbb{E}\left[\left(\sum_{i=1}^{n}[x_i - c]^2 + \sum_{i=1}^{n}\sum_{j=1, j\neq i}^{n}[x_i-c][x_j-c]\right)\right]$$
$$\mathbb{E}[\hat{G}]=1 - \dfrac{1}{n^2}\sum_{c=1}^{L}\left(\sum_{i=1}^{n}\mathbb{E}\left[[x_i - c]^2\right] + \sum_{i=1}^{n}\sum_{j=1, j\neq i}^{n}\mathbb{E}\left[[x_i-c][x_j-c]\right]\right)$$
$$\mathbb{E}[\hat{G}]=1 - \dfrac{1}{n^2}\sum_{c=1}^{L}\left(\sum_{i=1}^{n}\mathbb{E}\left[[x_i - c]^2\right] + (n^2 - n)p(c)^2\right)$$
Now, I am stuck here. $\mathbb{E}\left[[x_i - c]^2\right]$ is not equal to $\mathbb{E}\left[[x_i - c]\right]^2$ and it does not lead to a straightforward simplification as far as I can see. Am I missing something here? I was expecting that the above evaluation would lead to $\mathbb{E}[\hat{G}]=\dfrac{n-1}{n}$G but this is incorrect it seems.


text:
Q: CHCSVParser returns nil Array for valid filePath & valid csv file I am trying to parse a .csv file with approximately 30K lines. The following was mycode:
NSString *pathToGameLibrary = [[NSBundle mainBundle] pathForResource:@"GameLibrarySample" ofType:@"csv"];
NSArray *gameLibraryData = [NSArray arrayWithContentsOfCSVFile:pathToGameLibrary];

At the end of this execution, gameLibraryData is nil.
I can confirm that both the path and the csv file are valid because the following code spits out 30,000 lines of data to the console:
NSString *pathToGameLibrary = [[NSBundle mainBundle] pathForResource:@"GameLibrarySample" ofType:@"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToGameLibrary encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", fileString);

Because this code does not work, I assume that the failure has to do with the length of the csv file.  In an earlier question, CHCSV's author Dave DeLong suggests that:

"If this is a very big file, then you'll want to alloc/init a
  CHCSVParser with the path to the local copy of the CSV file."

So...I've tried to follow what the original poster attempted with this code:
NSString *pathToGameLibrary = [[NSBundle mainBundle] pathForResource:@"GameLibrarySample" ofType:@"csv"];
CHCSVParser *file = [[CHCSVParser alloc] initWithContentsOfCSVFile:pathToGameLibrary];
[file setDelegate:self];

At which point the method callbacks which enable retrieval of data are:
- (void)parserDidBeginDocument:(CHCSVParser *)parser;
- (void)parserDidEndDocument:(CHCSVParser *)parser;
- (void)parser:(CHCSVParser *)parser didBeginLine:(NSUInteger)recordNumber;
- (void)parser:(CHCSVParser *)parser didEndLine:(NSUInteger)recordNumber;
- (void)parser:(CHCSVParser *)parser didReadField:(NSString *)field atIndex:(NSInteger)fieldIndex;
- (void)parser:(CHCSVParser *)parser didReadComment:(NSString *)comment;
- (void)parser:(CHCSVParser *)parser didFailWithError:(NSError *)error;

Thanks to yonosoytu for le assistance.
On Topic Post-Edit Question: So what counts as a "very big file" anyway?  At which point is it prudent to use delegation over the simple 'arrayWithContentsofCSVFile'?

A:
So what counts as a "very big file" anyway? At which point is it prudent to use delegation over the simple 'arrayWithContentsofCSVFile'?

The way that CHCSVParser reads and parses your CSV file is identical regardless of whether you're using the NSArray category method or directly interfacing with the delegate itself (you can see this for yourself here). So "a very big file" is really a CSV file which would be too large to hold in memory as an NSArray in its entirety. The memory consumption will depend both on the number of columns and the number of rows, so it's hard to give a definite limit.
What this means is that the problems you get from using the -arrayWithContentsOfCSV with large files shouldn't manifest themselves as returning nil, but as low memory warnings and the like. The fact you're getting nil returned suggests something else is going on.
Firstly, you say you've tried logging the file, so you know it exists - have you tried parsing a much smaller subset of that file? The problem might be that your CSV is badly formed. Or alternatively - and this is something I've had problems with myself when working with CSV on iOS - is your CSV encoded correctly? Sometimes if you're outputting directly from Excel you can end up with strange and weird text encodings that occasionally seem to break things.
You can always breakpoint and step-through the parsing methods in CHCSVParser for yourself and see what's going on. I hope this is of some use to you. As you've discovered, Dave DeLong actually posts here quite a bit - if you're lucky he'll probably come along and share more wisdom than I can.


text:
Q: Why isn't this reassigning working I have an arraylist called election(). Why isn't code this reassigning the name variable like it should.
private static void replaceName(String oldName, String newName){
    Candidate c;
    for(int i = 0;i<election().size();i++){
        c = election().get(i);
        if(c.name == oldName){
            election().get(0).name = newName;
            System.out.println(election().get(0).getName());
        }
    }
}

A: You are incorrectly comparing strings in your if statement. Instead of c.name == oldName, it should be c.name.equals(oldName).
Also, you're assigning the new name to the wrong object.
Instead of elections.get(0).name = newName, it should be c.name = newName since c is a reference to the object stored in your ArrayList. Changes made to c will be reflected in your list. Your current code changes the name of the first candidate in your ArrayList, since you always call get() with 0 rather than i.


text:
Q: Auto Layout proportionally Scaling Views I have already found several questions and answers about this topic but I simply cannot get this to work for me.

The blue rectangle is a UIView which contains the Test Label and Gear image button. The red one is a second UIView.
What I'd like to do is to get the blue bar (which is a UIView) increase in size for larger sized screens, which will result in the scaling of the Label and settings button, while the Red UIView shrink in height so the blue UIView can become larger. So basically the question is, how to proportionally scale the UIViews for different screen sizes.
I have tried using aspect ratio constraints, height constraints (greater than/less than) but I just can't get the desired effect.
Thanks.

A: You have two ways for do that:
1. Proportional constraints:
but if you set a proportional height for one view means that the view change for every little change in screen size. For example, your view can be a little bigger switching from 4" to 4,7", but does not mean that it is a bad idea.
For use that feature just check the answer by Asadullah Ali :)
2. Use size-classes:
if you using Xcode 6 you can use the size classes and add a constraints just for a screen size; it's not difficult to use, check the Apple Documentation.
For this feature you need to able size classes for your Storyboard:

after that you can set up your view controller like you want and add a rule just for one of the classes:

you can tell to Xcode "ok, if the screen size is an 5,5 at least use this rule".
Remember that for add a constraint for a specific size classes you need first select the size class then add normally your constraint: when a size class is selected (you can check in the size classes control) Xcode add the constraints just for that class.
EDIT 1: If you have some trouble with scaling font & similar you can also use size-classes feature just for scaling a font size in a label for example; you find this option by clicking on this after activated the size classes feature:

I prefer tell you everything I know about your problem but in your case personally I would use the first solution: your view can dynamically change whatever is the screen size.
You need just find the best proportional percentage: you can set maybe around 10%, so the 0.1 multiplier with first item your blue view and for second item the red view.

A: Try proportional height and width. You need to make constraints for Equal Heights and/or equal Widths and then you double click on the constraint and change the multiplier for example 0.2 if you wish to make First Item to be 20% of second item in width and 2.0 for 200% (means double) in width. to make it increase or decrease proportionally according to your requirement


text:
Q: How to Find the Browser Tab is Focused or Not using HostListener in Angular 2+ I want the Browser Tab Focus and Blur Event using HostListener.

A: First Import HostListener in your Component
import { HostListener } from '@angular/core';

Then put this code to get Tab Focus and Blur Event
export class AppComponent {

   @HostListener('window:focus', ['$event'])
   onFocus(event: FocusEvent): void {

       // Do something

   }

   @HostListener('window:blur', ['$event'])
   onBlur(event: FocusEvent): void {

      // Do something

   }

  ........
  .....
}


text:
Q: How do I get a list of YouTube channels, and associated channel URLs (user or channel), owned by an authenticated user We use the following call to get ChannelID's for an authenticated user and it works well for most cases. Some YouTube user connect their channels to a Google+ page and this fails for one of our users in that situation. In that case, the call only returns the channelID associated the user's email account used for authentication, not all channels owned by the user.
System.IO.Stream resultStream = service.Query(new Uri("https://www.googleapis.com/youtube/v3/channels?part=id%2Csnippet%2CcontentDetails%2Cstatistics%2CtopicDetails&mine=true&key=" + GlobalSettings.developerKey));

Also, we construct the channel URL by appending the channelID to the following URL.
http://www.youtube.com/channel/

However, some channels us a user name and path instead of channelID. How can I detect that the type is user instead of channel? In that case the user name is appending to the following path. The Google+ user's main channel uses this path with a user name.
http://www.youtube.com/user/

A: A few things:

*

*In v3 of the YouTube Data API, you're forced to work with channel ids everywhere. This is a good thing. Channel ids are the only universal way of identifying channels! Legacy usernames used to serve that purpose as well, but the number of channels without legacy usernames is increasing by the day, so writing new v2 code that relies on legacy usernames is not recommended (and isn't possible in v3).

*When making a channels.list(..., mine=true) call, you're always going to get back exactly one channel. The channel you get back will depend on which channel was chosen when you went through the OAuth 2 flow—there's a picker within that flow that lets you choose whichever channel you'd like if your Google Account happens to have access to more than one channel. If you want to operate on a different channel, you need to explicitly obtain an OAuth 2 token for that channel.

*channel.list(..., managedByMe=true) can return multiple channels, but that API call is only relevant to YouTube content partners, and is used hand-in-hand with the onBehalfOfContentOwner parameter. Most developers can safely ignore this unless you know you're explicitly working with YouTube content partners' accounts.

*The URL to visit a channel's page isn't returned anywhere in the v3 API response—that's true, and maybe it should be (feel free to file a feature request). If you want to manually construct the URL, you can use http://www.youtube.com/channel/CHANNEL_ID, where CHANNEL_ID is the standard UC... value that is used everywhere else in v3. That should produce a valid URL regardless of whether there's also a legacy username for the channel.

A: The only way that I have been able to do this is to use the v2 API, instead of v3. Specifically, you can use the same OAuth token, but access this API endpoint:
https://gdata.youtube.com/feeds/api/users/default?v=2

It will return an XML doc that contains both a URL to the user's channel (using the channel id), as well as the YouTube username.
See https://developers.google.com/youtube/2.0/reference#User_profile_entry for more info.


text:
Q: ¿Cómo muestro una etiqueta nueva () al dar click en "submit" en mi formulario en php? ¡Hola amigos! Una consulta, tengo mi código en HTML y en PHP, pero no logro hacer que al momento de dar click en "SUBMIT", al usuario le salga una alerta o un "div" nuevo que diga "MENSAJE ENVIADO CORRECTAMENTE", no quiero dirigirlo a una página diferente, quisiera que en la misma página salga ese mensaje, ya que al momento de dar en "submit", sólamente se recarga la página y causa confusión al usuario si se mandó el mensaje o no.
Este es mi código HTML:
<form action="contact.php" id="form1" name="form1" method="post" class="rd-mailform text-left offset-top-30">

                                    Nombre Completo*

                                    <input id="name" type="text" name="name" data-constraints="@Required" placeholder="Nombre Completo" class="form-control" required>

                                    Email*

                                    <input id="email" type="email" name="email" placeholder="Email" data-constraints="@Required @Email" class="form-control" required>

                                    Teléfono
                                    <input id="phone" type="text" name="phone" placeholder="Teléfono" class="form-control">

                            Mensaje*

                            <textarea id="message" name="message" placeholder="Mensaje" data-constraints="@Required" class="form-control"></textarea>

                            <button type="submit" name="Submit" value="ENVIAR" class="btn btn-primary">Enviar Ahora</button>

                    </form>

Este es mi código PHP, pueden notar que el div de "¡Mensaje enviado correctamente" está como un comentario, ya que obviamente no quiero que salga en la página por default sin que el usuario haya hecho algo, me estuvieron diciendo que lo puedo hacer en "AJAX" para que no lo redirija a otra página, pero sinceramente no sé nada sobre AJAX, si existe la forma de hacerlo en php, les agradecería mucho su ayuda, igual me comentaron que hiciera un "if-else" para pasarlo a otras páginas, pero no creo que sea la mejor opción.
<?php

    $para = "luiz_naiper@hotmail.com, luan.ortodoncia@gmail.com";

    $asunto = "Mensaje desde la pag web";

    $mailheader = "From: ".$_POST["email"]."\r\n";
    $mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
    $mailheader .= "Content-type: text/html; charset=utf-8\r\n";
    $MESSAGEBODY = "Nombre: ".$_POST["name"]."\n";
    $MESSAGEBODY .= "\n
Email: ".$_POST["email"]."\n";
    $MESSAGEBODY .= "\n
Teléfono: ".$_POST["phone"]."\n";
    $MESSAGEBODY .= "\n
Mensaje: ".($_POST["message"])."\n";

    mail($para, $asunto, $MESSAGEBODY, $mailheader) or die ("Error al enviar email");

    header("Location: http://www.luanclinicadental.com/contacto.html");

?>

A: Tienes que usar ajax
<form onsubmit="return false;" id="form1" name="form1" method="post" class="rd-mailform text-left offset-top-30">

                Nombre Completo*
                <input id="name" type="text" name="name" data-constraints="@Required" placeholder="Nombre Completo" class="form-control" required/>

                Email*
                <input id="email" type="email" name="email" placeholder="Email" data-constraints="@Required @Email" class="form-control" required>

                Teléfono
                <input id="phone" type="text" name="phone" placeholder="Teléfono" class="form-control">

        Mensaje*
        <textarea id="message" name="message" placeholder="Mensaje" data-constraints="@Required" class="form-control"></textarea>

        <button type="submit" name="Submit" value="ENVIAR" class="btn btn-primary" onclick="submitForm()">Enviar Ahora</button>

</form>

Agrega jquery

Y este script

A: No entiendo muy bien lo que quieres en si ? Tienes dos opciones mandar el form mediante ajax luego limpiar el formulario y mostrar el div con el mensaje que quieres o puedes enviar con php mandarlo a otra pagina o la misma y mostrar el mensaje

*

*php-flash-messages

*https://getbootstrap.com/docs/4.1/components/alerts/


text:
Q: Ajax image upload submit conflict with form ajax - make .submit() function work for that form only In the middle of a multi-page form, i have a section where the user can upload an image, and that image is previews straight away using ajax. However, when the user uploads the image, the actual form itself also tries to submit, and i think there is an ajax conflict. This is the code i am using for the ajax image upload:
$(document).ready(function() {
    $('#logo').live('change', function()            {
        $("#prlogo").html('');
        $("#prlogo").html('<img src="../preview/loader.gif" alt="Uploading...."/>');
        $("#logoform").ajaxForm({
            target: '#prlogo'
        }).submit();
    });
});

And this is the form:
<form id="logoform" method="post" enctype="multipart/form-data" action='../preview/logo.php'>
    <input type="file" name="logo" id="logo" />
</form>

Is it possible to link that .submit() to the form with id logoform? Is there any other way i can limit the submit to work only for the image upload and not the form?

A: You could try overriding the submit function of the form, so before you call submit, you would need to set something like the below
$('form').submit(function () {
    $.ajax({
        url: this.action, type: this.method,
        data: $(this).serialize(), cache: false,
        success: function () {
            //Do upload of Image
           }
        }

        //Or upload image here
    });


text:
Q: A curious property of Ramanujan's function $\tau(n)$ As it is well known, Ramanujan's $\tau(n)$ function can be defined through the   power series expansion of the modular discriminant:
$$\Delta(q)=q\prod\limits_{n=1}^\infty (1-q^n)^{24}=\sum \limits_{n=1}^\infty
\tau(n)q^n=q-24q^2+252q^3-1472q^4+4830q^5+\ldots.$$
In the short paper http://arxiv.org/abs/1408.2083 (Moonshine and the Meaning of Life, by Yang-Hui He and John McKay) a curious observation was made that
$$\sum \limits_{n=1}^{24}\tau(n)^2\equiv 42 \;\; (\mathrm{mod} \;70).$$
Another observation of the same paper is that
$$\sum \limits_{n=1}^{24}c(n)^2\equiv 42 \;\; (\mathrm{mod} \;70),$$
where $c(n)$ are defined through the power series expansion of the $SL_2(\mathbb{Z})$ elliptic modular function $j(q)$: $$j(q)=\sum \limits_{n=-1}^\infty
c(n)q^n=q^{-1}+744 + 196884q + 21493760q^2+\ldots.$$
In the abstract, the authors write that "The observation is purely for the sake of entertainment and could be of some diversion to a mathematical audience". Nevertheless, is there any deep mathematics behind these curious observations?

A: (Too long for a comment.)
Since the authors point out their two observations in a "jocund" air, we can match their observations with another pair.

I. The Baby monster

Just like the j-function $j(\tau)$ above and the Monster, the modular function $j_{2A}(\tau)$ that can be related to the Baby monster,
$$\begin{aligned}j_{2A}(\tau) &=\Big(\big(\tfrac{\eta(\tau)}{\eta(2\tau)}\big)^{12}+2^6 \big(\tfrac{\eta(2\tau)}{\eta(\tau)}\big)^{12}\Big)^2 \\
&=\sum\limits_{n=-1}^{\infty}a(n)q^n\\&= q^{-1} + \color{blue}{104} + 4372q + 96256q^2 + 1240002q^3+\cdots
\end{aligned}$$
also has,
$$\sum \limits_{n=1}^{24}a(n)^2\equiv 42 \;\; (\mathrm{mod} \;70),$$
Recall that $e^{\pi\sqrt{58}} =396^4-\color{blue}{104}.00000017\dots$.

II. Modular lambda function

Given the modular lambda function $\lambda(\tau)=\lambda$ such that,
$$j(\tau) =  \frac{256(1-\lambda+\lambda^2)^3}{\lambda^2 (1-\lambda)^2}$$
and,
$$\begin{aligned}\lambda(\tau) &= \Big(\tfrac{\sqrt{2}\,\eta\big(\tfrac{\tau}{2}\big)\eta^2(2\tau)}{\eta^3(\tau)}\Big)^8\\
&=\sum\limits_{n=1}^{\infty}b(n)q^n\\
&=16q - 128q^2 + 704 q^3 - 3072q^4 + 11488q^5 - 38400q^6 + \dots
\end{aligned}$$
then,
$$\sum \limits_{n=1}^{24}b(n)^2\equiv 42 \;\; (\mathrm{mod} \;70),$$
Of course, it is well-known that,
$$1^2+2^2+3^2+\dots+24^2 = 70^2$$
It should be interesting if, for these four related functions, there is a reason for the congruences other than whimsy.

$\color{red}{Update}$

P.S. By a really serendipitous error almost straight from the pages of the Hitchhiker's Guide, it turns out the same $24$ coefficients $s(n)$ of all four sequences also obey,
$$\sum_{n=1}^{24} \frac{s(n)^2+42}{70} = \,\text{Integer}$$
The discussion below should illustrate how the error was found.


text:
Q: I want to filter by id the firebase realtime-database in my asp.net web api application, but I do not know how to build up the query I am developing a asp.net web api project with firebase real-timedatabase. I use firebaseclient libraries. But I want to know how to develop queries using firebase client.
I have already created query get all the suppliers. It is working.
And another to get suppliers by id. It gives syntax errors. This is not working.
//method to get all suppliers. Working properly
[Route("getAll")]
public async Task<HttpResponseMessage> GetSuppliers()
{
    var firebaseClient = new FirebaseClient(<firebase url>);

    //Retrieve data from Firebase
    var suppliers = await firebaseClient
    .Child("suppliers")
    .OnceAsync<SupplierModel>();

     List<SupplierModel> supplierList = new List<SupplierModel>();

     foreach (var sup in suppliers)
     {
         supplierList.Add(sup.Object);
     }
     HttpResponseMessage response;
     response = Request.CreateResponse(HttpStatusCode.OK, supplierList);
     return response;
}

//method to filter by id. Have syntax errors

[Route("addSuppllier/{supplierId}")]
public async Task<HttpResponseMessage> GetSupplierById([FromUri] string supplierId)
{
    var firebaseClient = new FirebaseClient(<firebase url>);

    //Retrieve data from Firebase
    var suppliers = await firebaseClient
    .Child("suppliers")
    .OrderBy("supplierId")
    .EqualTo(supplierId);
    List<SupplierModel> supplierList = new List<SupplierModel>();
    foreach (var sup in suppliers)
    {
        supplierList.Add(sup.Object);
    }
    HttpResponseMessage response;
    response = Request.CreateResponse(HttpStatusCode.OK, supplierList);
    return response;
}

First query retrieves all suppliers properly.
Second query has syntax errors.

A: You can try with this approach.
FirebaseResponse response = await firebaseClient.GetAsync("suppliers");
JObject jsonResponse = response.ResultAs<JObject>();

var query = new List<SupplierModel>();
if (jsonResponse != null)
{
foreach (var item in jsonResponse)
        {
         var value = item.Value.ToString();
         var supplierModel = JsonConvert.DeserializeObject<SupplierModel>(value);

         //note: supplier model should have id attribute
         supplierModel.Id = item.Key;
         query.Add(supplierModel);
        };
 }

Then filter the query by Id if it is not null.


text:
Q: Fill the missing quarter values from annual values using R In the data.table below, column value shows the sales growth at each quarterly and annual event of groups A and B for the years 2017 and 2018.
Sometimes, groups A or B don't hold the quarterly event and just hold the annual event. In such a scenario, I want to create a new row in test_dt and copy the annual growth value to the quarter's growth value.
test_dt = structure(list(group = c("A", "A", "A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B"), yq = structure(c(17167,
17257, 17348, 17440, 17532, 17622, 17713, 17805, 17167, 17257,
17257, 17348, 17440, 17532, 17622, 17713, 17805), fiscal_start = 1, class = c("yearquarter",
"vctrs_vctr")), event_type = c("quarterly", "annual", "quarterly",
"quarterly", "quarterly", "quarterly", "quarterly", "quarterly",
"quarterly", "annual", "quarterly", "quarterly", "quarterly",
"quarterly", "annual", "quarterly", "quarterly"), value = c(4.39958592132506,
-10.9243697478992, 3.8793103448276, -6.7936507936508, -3.44322344322345,
4.41176470588236, -4.99153976311336, -1.98321891685735, -18.2953077916487,
0.918273645546375, -4.99770747363595, 3.1849912739965, -10.7555555555556,
-12.2950819672131, -1.15257958287595, -17.8796046720575, -6.99300699300699
)), row.names = c(NA, -17L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x5642ee9663a0>)

> test_dt
    group      yq event_type       value
 1:     A 2017 Q1  quarterly   4.3995859
 2:     A 2017 Q2     annual -10.9243697
 3:     A 2017 Q3  quarterly   3.8793103
 4:     A 2017 Q4  quarterly  -6.7936508
 5:     A 2018 Q1  quarterly  -3.4432234
 6:     A 2018 Q2  quarterly   4.4117647
 7:     A 2018 Q3  quarterly  -4.9915398
 8:     A 2018 Q4  quarterly  -1.9832189
 9:     B 2017 Q1  quarterly -18.2953078
10:     B 2017 Q2     annual   0.9182736
11:     B 2017 Q2  quarterly  -4.9977075
12:     B 2017 Q3  quarterly   3.1849913
13:     B 2017 Q4  quarterly -10.7555556
14:     B 2018 Q1  quarterly -12.2950820
15:     B 2018 Q2     annual  -1.1525796
16:     B 2018 Q3  quarterly -17.8796047
17:     B 2018 Q4  quarterly  -6.9930070

Here is the expected output
> test_dt
    group      yq event_type       value
 1:     A 2017 Q1  quarterly   4.3995859
 2:     A 2017 Q2     annual -10.9243697
 2:     A 2017 Q2  quarterly -10.9243697 <---- New row added
 3:     A 2017 Q3  quarterly   3.8793103
 4:     A 2017 Q4  quarterly  -6.7936508
 5:     A 2018 Q1  quarterly  -3.4432234
 6:     A 2018 Q2  quarterly   4.4117647
 7:     A 2018 Q3  quarterly  -4.9915398
 8:     A 2018 Q4  quarterly  -1.9832189
 9:     B 2017 Q1  quarterly -18.2953078
10:     B 2017 Q2     annual   0.9182736
11:     B 2017 Q2  quarterly  -4.9977075
12:     B 2017 Q3  quarterly   3.1849913
13:     B 2017 Q4  quarterly -10.7555556
14:     B 2018 Q1  quarterly -12.2950820
15:     B 2018 Q2     annual  -1.1525796
15:     B 2018 Q2  quarterly  -1.1525796 <---- New row added
16:     B 2018 Q3  quarterly -17.8796047
17:     B 2018 Q4  quarterly  -6.9930070

Please suggest a solution only using data.table

A: I solved it as follows. Please suggest if efficiency can be improved any further.
setkey(test_dt, group, yq, event_type)
dt_1 = test_dt[CJ(group, yq, event_type, unique=TRUE)]
dt_1[, value := ifelse(event_type == "quarterly" & is.na(value), value[event_type == "annual"], value), by = .(group, yq)]
na.omit(dt_1[])

> dt_1
    group      yq event_type       value
 1:     A 2017 Q1  quarterly   4.3995859
 2:     A 2017 Q2     annual -10.9243697
 3:     A 2017 Q2  quarterly -10.9243697
 4:     A 2017 Q3  quarterly   3.8793103
 5:     A 2017 Q4  quarterly  -6.7936508
 6:     A 2018 Q1  quarterly  -3.4432234
 7:     A 2018 Q2  quarterly   4.4117647
 8:     A 2018 Q3  quarterly  -4.9915398
 9:     A 2018 Q4  quarterly  -1.9832189
10:     B 2017 Q1  quarterly -18.2953078
11:     B 2017 Q2     annual   0.9182736
12:     B 2017 Q2  quarterly  -4.9977075
13:     B 2017 Q3  quarterly   3.1849913
14:     B 2017 Q4  quarterly -10.7555556
15:     B 2018 Q1  quarterly -12.2950820
16:     B 2018 Q2     annual  -1.1525796
17:     B 2018 Q2  quarterly  -1.1525796
18:     B 2018 Q3  quarterly -17.8796047
19:     B 2018 Q4  quarterly  -6.9930070

A: Good to see a fellow efficiency fanatic. Here is my attempt
library(data.table)

# group
x <- c("A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B")

# dummy data
df <- structure(list(group = x
                     , yq = structure(c(17167,17257, 17348, 17440, 17532, 17622, 17713, 17805, 17167, 17257, 17257, 17348, 17440, 17532, 17622, 17713, 17805)
                                      , fiscal_start = 1
                                      , class = c("yearquarter","vctrs_vctr")
                                      )
                     , event_type = c("quarterly", "annual", "quarterly","quarterly", "quarterly", "quarterly", "quarterly", "quarterly", "quarterly", "annual", "quarterly", "quarterly", "quarterly", "quarterly", "annual", "quarterly", "quarterly")
                     , value = c(4.39958592132506,-10.9243697478992, 3.8793103448276, -6.7936507936508, -3.44322344322345, 4.41176470588236, -4.99153976311336, -1.98321891685735, -18.2953077916487, 0.918273645546375, -4.99770747363595, 3.1849912739965, -10.7555555555556, -12.2950819672131, -1.15257958287595, -17.8796046720575, -6.99300699300699))
                , row.names = c(NA, -17L)
                , class = c("data.table", "data.frame")
                )
y <- 1e4
z <- vector('list', y)
for (i in 1:y)
{
  z[[i]] <- df
}
df <- rbindlist(z)

# create distinct group across batches (of dfs)
df[, group := paste0(df$group, rep(1:y, each=length(x)))]

# benchmark
a <-
  microbenchmark(Saurabh = { setkey(df, group, yq, event_type)
                              dt_1 = df[CJ(group, yq, event_type, unique=TRUE)]
                              dt_1[, value := ifelse(event_type == "quarterly" & is.na(value), value[event_type == "annual"], value), by = .(group, yq)]
                              na.omit(dt_1[])
                              }
                 , akrun = {df[df[,  .(yq = if('annual' %in% event_type) yq else first(yq) + 0:3), .(group, yr = year(yq), event_type)
                                  ][, yr := NULL
                                    ], on = .(group, yq, event_type)
                               ][order(group, yq, event_type == 'quarterly')
                                 ][, value := nafill(value, type = 'locf')
                                   ]
                              }
                 , sweepydodo = {df[, `:=` (yq = tsibble::yearquarter(yq)
                                             , year = year(yq)
                                             , quarter = quarter(yq)
                                             )
                                     ][, dummy := sum(chmatch(event_type, 'quarterly'), na.rm=T)
                                       , .(group, year)
                                       ]

                                  x <- df[event_type == 'annual'
                                          & dummy < 4
                                          ][, event_type := 'quarterly'
                                            ]

                                  df <- rbind(df, x)[, c('dummy', 'year', 'quarter') := NULL
                                                     ][order(group, yq, event_type)
                                                     ]
                                  }
                 , times = 20
                 )

# plot
autoplot(a)

Let me know any comments you may have


text:
Q: How to load a html file to memory? I want to load a html file to memory (in fact a wchar_t string). And this is the code:
size_t myGetFileSize(const wchar_t *wcPath)
{
    struct _stat fileinfo;
    _wstat(wcPath, &fileinfo);
    return (fileinfo.st_size);
}
int LoadUtf8FileToString(const wchar_t *wcFilename, wchar_t **wcBuffer)
{
    FILE* file = _wfopen(wcFilename, L"rtS, ccs=UTF-8");
    if (file == NULL)
        return (0);
    size_t filesize = myGetFileSize(wcFilename);
    if (filesize > 0)
    {
        *wcBuffer = (wchar_t*) malloc(filesize * sizeof(wchar_t));
        size_t nRead = fread(*wcBuffer, sizeof(wchar_t), filesize, file);
        realloc(*wcBuffer, nRead * sizeof(wchar_t));
    }
    fclose(file);
    return(1);
}

And when I navigate it to a iwebbrowser2, it show all page and 4 empty square at the end of page!
I googled and find a string class called wstring, and using it like this way:
std::wstring wString;
/////////////////////
wString->resize(filesize);
size_t wchars_read = fread(&(wString->front()), sizeof(wchar_t), filesize, file);
wString->resize(wchars_read);
wString->shrink_to_fit();

and navigate it to iwebbrower2, everythings will be OK! But I don't like to use any class in my program!
So, What is wrong with my code, please?

A: You seem to forget two things: One is that that UTF-8 is a variable-length encoding, a character may be one byte, or it may be six bytes. You can't read it as a fixed-width encoding. The other thing you forget is that the size of the file you get is not the number of characters in the file, it's the number of bytes in the file.
In fact, if you're reading a HTML-file, odds are quite a lot of the text are single bytes, namely all the markup.
In short, the file doesn't contain filesize characters, it contains filesize bytes. And you try to read sizeof(wchar_t) * filesize bytes, which is why the fread call will return the "wrong" size.

A: *

*The realloc is totally obsolete. You initialize the correct amount of memory (not really, see next) and the number of bytes read can only differ if fread somehow fails and reads less characters. Then again, even if it does and you shrink (!) your allocated buffer, you forget to update the pointer, so it will still point to the original memory block. Which actually gets freed by the realloc. You may be getting away with this Undefined Behavior because (apparently) either the memory block is resized in-place, or because realloc determines resizing is not necessary.

*You are getting random characters at the end of your string because it is a string, and you do not allocate enough space for a terminating Zero, nor are you writing it.

*filesize is in bytes. Thus allocate and read in bytes, not in wchar_t units.


text:
Q: How to select a component on jframe? How to select a JTextArea on JButton click?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    jTextArea1.setEditable(true);
    jTextArea1.setForeground(Color.BLACK);

    //*******************************************************
    jframe.setselected(jTextArea1); // I need such function!
    //*******************************************************

}

A: By select I assume you mean transfer focus to the JTextArea. If so you can request focus of you text area with the following.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

jTextArea1.setEditable(true);
jTextArea1.setForeground(Color.BLACK);

/*******************************************************
jTextArea1.requestFocusInWindow();
/*******************************************************
}


text:
Q: Probability of failure of a system made of n identical SPOF components A fuel pump is correctly functionning $a \%$ of the time.
So it has probability of failure of $(1 - \frac{a}{100})$ (I'm not already sure that I can say that).
The system is made of $n$ independant fuel pumps. If any of the pumps fails, the whole system fails.
What's the probability of the whole system to fail ?
Getting all the pumps to function at the same time would be $(\frac{a}{100})^{n}$. So is the probability for the whole system to fail $(1 - (\frac{a}{100})^{n})$ ?
Then, considering 2 systems for high-availability: if a pump fails in systemA with probability $(1 - (\frac{a}{100})^{n})$, what is the probability of systemB to also fail, that is to say, for the 2 systems to fail at the same time ?
Is it simply $(1 - (\frac{a}{100})^{2n})$ ?
Or is it something linked with the birthday paradox ? Assuming that a pump AFR is $\frac{1}{365}$ and that when it fails, it fails the whole system for a whole day, given than 1 pump has failed in systemA, the probability of any other pump in systemB to also fail would be $(1 - \frac{365!}{(365 - (n + 1))!} \cdot \frac{1}{365^{n+1}})$, wouldn't it ?
($n + 1$ is the one failed pump form system A and the $n$ pumps for systemB).


text:
Q: Equation Calculating what Day it is Consider this word problem:
If the first day of the year is a Monday, what is the 260th day? Answer: Monday
Why does this equation work to calculate what day of the week it is:
260 = (7w + 1) [w stands for week]
How does it work and how would you even develop this equation to get the answer?
I understand that if you divide 260 by 7 you get 37.1 . Meaning all the days fit into weeks excluding one day; the first day of the week.. Monday.
But what if the first day of the year is Wednesday. What would you do then ?
Thanks!!

A: Use modular arithmetic. Let's say the first day of the year is day $x$, which takes a value from $0$ to $6$, with and $0 \equiv \text{ Monday}$, so that $x$ is the number of days after the start of the first week that the transition to the new year occurs.
Now, to find what day of the week the $y$th day of the year will be, note that $y-1$ days have passed between the $1$st an $y$th day, so add on an extra $y-1$ days to whatever the first day was ($x$).
$$(y-1)+x \mod 7$$
where $... \mod 7$ is the remainder left over when you take away $7$ the maximum number of times from $...$ (that still leaves a positive integer).
In the first case, $x= \text{ Monday }=0$ and $y=260$, so
$$(260-1)+0 \mod 7 \equiv 259-7-7-7-... \mod 7 $$$$259-7(w) \mod 7$$$$\equiv 0 \mod 7$$
Which is Monday
If Wednesday is the first day, then let $x=2$, so the $260$th day is
$$(260-1)+2 \mod 7 \equiv 2 \mod 7$$
Edit: the answer with less modular arithmetic.
If the $1$st day is Monday, then the $8$th, $15$th, $22$nd... days will also be Monday. These numbers have the general form $7w+1$.
If the $1$st day is Monday, then the $2$nd, $9$th, $16$th, $23$rd... days will be Tuesday. These numbers have the general form $7w+2$.
The $3$rd, $10$th, $17$th, $24$th... days will be Wednesday. These numbers have the general form $7w+3$.
In general, why do Mondays have the form $7w+1$? Day $1$ is a Monday, and any day a multiple of $7$ up from that will also be a Monday (or, will $\equiv 1 \mod 7$). So you can add $7$ to $1$ as many times as you want without affecting the resulting number's Mondayness.
If the first day is a Wednesday, all days that year will be shifted down $2$ from the Monday situation. Thus Monday has the form $(7w+1)-2=7w-1=7w+6$, Tuesday $7w$, W. $7w+1$, Th. $7w+2$, F. $7w+3$, Sa. $7w+4$, and Sunday $7w+5$.

A: Consider the following table:
 Monday-1, 8, 15, 22, ...
 Tuesday-2, 9, 16, 23, ...
 Wednesday-3, 10, 17, 24, ...
 Thursday-4, 11, 18, 25, ...
 Friday-5, 12, 19, 26, ...
 Saturday-6, 13, 20, 27, ...
 Sunday-7, 14, 21, 28, ...

Since there exist only seven days in a week, and they always happen in the same sequence, it follows that Mondays only happen on the (1+(7n))th of the year, Tuesdays on the (2+(7n))th day, ..., Sundays on the (7+(7n))th day of the year, where n is a natural number.  Thus, all Mondays fall into the equivalence class [1], Tuesdays into the equivalence class [2], ..., Sundays into the equivalence class [7].  Thus, for the yth day of the year there exists some number (y-x) which is divisible by 7, where x is the number within the brackets and belongs to {1, 2, 3, 4, 5, 6, 7}.  For example, for the 39th day of the year (39-4)=35 which is divisible by 7.  So, the 39th day falls into the [4] equivalence class.  Consequently, the 39th day of the year is a Thursday.  Similarly, 39=((7*5)+4).
If you divide 260 by 7, you get 37 and (1/7)th (NOT 37.1... which means 37.1000... and NO approximation is NOT appropriate here).  Another way of looking at this comes as to try and divide the nth day by 7 and see what you get for the remainder.  You either have a remainder of 0, (1/7), (2/7), (3/7), (4/7), (5/7), or (6/7).  If you have a remainder of 0, then that day is a Sunday, since 0 is in the [7] equivalence class.  If you have a remainder of (x/7), then that day corresponds to the [x] equivalence class.  In your case you have a remainder of (1/7), so the day corresponds to the [1] equivalence class, which is the equivalence class for Mondays.
If the first day of the year is a Wednesday, then you can write the following table:
 Wednesday-1, 8, 15, ...
 Thursday-2, 9, 16, ...
 Friday-3, 10, 17, ...
 Saturday-4, 11, 18, ...
 Sunday-5, 12, 19, ...
 Monday-6, 13, 20, ...
 Tuesday-7, 14, 21, ...

Thus, Wednesday now belong to the [1] class, Thursdays to the [2] class, ..., and Tuesdays to the [7] (or [0]) class.  So, if you want to know the 260th day of the year, you can divide by 7 and check the remainder.  You get a remainder of (1/7) placing the 260th day in the [1] equivalence class.  Thus, if the first day of the year is "day x", where "day x" belongs to {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sundary}, then the 260th day of the year is also "day x".


text:
Q: URL Parse NodeJS Deprecated How to transform this below deprecated URL parse on Node v14 and express v4.  I tried few changes but still failed.
url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
base_grant_url = query.base_grant_url;

The code originally from github rafael-carvalho/meraki-azure-ad

A: Express gives access to the query part of the request through req.query. It's not entirely clear what you are hoping to accomplish, but if you want to parse the following url:

hostname.com/path?base_grant_url=urlValue

The following will be true in your request handler:
req.query.base_grant_url === "urlValue"

And so instead of the code
url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
base_grant_url = query.base_grant_url;

You could just write
base_grant_url = req.query.base_grant_url


text:
Q: SQL InitCap that Uppercase some special words How can i modify this InitCap function so that it always will uppercase AB when its in the end of the string and has a space before it.

*

*test Ab <-- should display AB

*testab <-- should display ab

*abtest <-- should displat ab
DELIMITER $$
DROP FUNCTION IF EXISTS `CapitializeFirstCharInEveryWord`$$

CREATE FUNCTION `CapitializeFirstCharInEveryWord`(x char(100)) RETURNS char(100) CHARSET utf8
BEGIN
SET @str='';
SET @l_str='';
WHILE x REGEXP ' ' DO
SELECT SUBSTRING_INDEX(x, ' ', 1) INTO @l_str;
SELECT SUBSTRING(x, LOCATE(' ', x)+1) INTO x;
SELECT CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(@l_str,1,1)),LOWER(SUBSTRING(@l_str,2)))) INTO @str;
END WHILE;
RETURN LTRIM(CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2)))));
END$$

A: You want to capitalize last word in string? You can do it in simple way. Description in comments.
CREATE FUNCTION `CapitalizeLastWord`(x char(100)) RETURNS char(100) CHARSET utf8
BEGIN
-- detect has x space
SET @space_pos_reverse = LOCATE(' ', REVERSE(x));

-- if not return unchanged x
IF @space_pos_reverse = 0 THEN RETURN x;
END IF;

-- getting last space position
SET @last_space_pos = LENGTH(x)-@space_pos_reverse+1;

-- split x to 2 parts, 2nd part gettin UPPER
RETURN CONCAT(SUBSTRING(x, 1, @last_space_pos), UPPER(SUBSTRING(x, @last_space_pos+1)) );

END$$


text:
Q: Fitting imageButtons into different screen sizes i am new to android programming.
I have a problem scaling ImageButtons to different screen-resolutions.
I made different image sizes based on the dpi and put them into hdpi(120px*72px,160dpi), mdpi(80px*48px,160dpi) and xhdpi(160px*96px,160dpi)
But on screen-resolutions like 1280x720 there is a little bit of space on the right side.
I tried things like:
android:scaleType="fitXY"
android:scaleType="centerInside"
android:adjustViewBounds="true"

but nothing worked. Also, i am not quite sure what these do.
Like i said, i am new to android.
https://www.dropbox.com/sh/dmtcn4lxyxxh5wt/vpq9pBMOSl
<ImageButton
    android:id="@+id/imageButtonsearch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/imageButtonshare"
    android:background="@null"
    android:scaleType="centerInside"
    android:src="@drawable/selector_search"
    android:adjustViewBounds="true" />

Thanks in advance

A: You should use linearlayout and than set all imagebutton's layout_weight attr to 0.25
Linearlayout must be in the parent bottom.
Like this;

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <ImageButton
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:src="@drawable/ic_launcher"/>

    <ImageButton
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:src="@drawable/ic_launcher"/>

    <ImageButton
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:src="@drawable/ic_launcher"/>

    <ImageButton
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:src="@drawable/ic_launcher"/>

</LinearLayout>

A: Set your layout_width attribute to "fill_parent" and make sure that the scaleType is fitXY

A: Use equal weight attribute in our ImageButtons. It will occupy the space as compare to Screen Sizes, and use dp not dip.


text:
Q: Why is the output of these 2 programs not same I am trying to find the numbers that are not divisible by 3,5,7 and counting them
And printing the ones that are divisible
The two approaches are
#include <stdio.h>
int main()
{
   int count=0;

   for(int i = 1; i<=500;i++)
   {
       if(i%3==0 && i%5==0 && i%7==0) {
            printf("%d \n", i);
       }
       else {
           count++;
       }
   }
    printf(" the count is : %d \n", count);
}

/*
WAP to count the numbers from (1-500) which are not divisible by 3, 4 and
*/
#include <stdio.h>
int main()
{
    int count=0;

    for(int i = 1; i<=500;i++)
    {
        if(i%3!=0 && i%5!=0 && i%7!=0) {
            count++;
        }
        else {
            printf("%d \n", i);
        }
    }
     printf(" the count is %d \n", count);
}

The problem is that the output should be same but it is not

A: Because these two if statements are not opposite from each other. The negation from
if(i%3==0 && i%5==0 && i%7==0)

would be
 if(!(i%3==0 && i%5==0 && i%7==0))

which changes equals to not equals, but also changes ANDs to ORs. So the second code should have something like this
if(i%3!=0 || i%5!=0 || i%7!=0)


text:
Q: Why is the search box shortened by half? What's up with the width: 50% for the search box?

A: Looks like some CSS changes to an unrelated area in the site slipped in to the shared CSS file.
I have removed this specific rule and the search box is back to normal.
This will be deployed in the next build.


text:
Q: How to invoke " def imperativeBubbleSort[T <% Ordered[T]](source: Array[T]): Array[T] = { " The method imperativeBubbleSort has signature :
  def imperativeBubbleSort[T <% Ordered[T]](source: Array[T]): Array[T] = {
    for (i <- 0 until source.length - 1; j <- 0 until source.length - 1 - i) {
      if (source(j) > source(j + 1)) {
        val temp = source(j)
        source(j) = source(j + 1)
        source(j + 1) = temp
      }
    }
    source
  }

To call it I use :
 imperativeBubbleSort(3,2,1)

But receive error :
Multiple markers at this line - too many arguments for method imperativeBubbleSort: (source: Array[T])(implicit
 evidence$1: T => Ordered[T])Array[T] - too many arguments for method imperativeBubbleSort: (source:
 Array[T])(implicit evidence$1: T => Ordered[T])Array[T]

But does this function just takes one parameter ?
Does [T <% Ordered[T]] mean I need to add a type parameter which is subclass of Ordered ?

A: It looks like you actually want a varargs method. Instead of Array[T], use T* to specify a vararg type. Here's an updated version:
def imperativeBubbleSort[T <% Ordered[T] : ClassTag](inputs: T*): Array[T] = {
  val source = inputs.toArray
  for (i <- 0 until source.length - 1; j <- 0 until source.length - 1 - i) {
    if (source(j) > source(j + 1)) {
      val temp = source(j)
      source(j) = source(j + 1)
      source(j + 1) = temp
    }
  }
  source
}

Note that I had to add the ClassTag restriction on the T type. This is because the toArray method in Seq requires it in order to create a new array. This is because in Scala the varargs are passed in as a Scala sequence object rather than as an array.


text:
Q: Acessar JLabels sem utilizar switch...case Estou desenvolvendo um jogo com JLabel de 1 a 50, consigo acessa-las em linha de código sem ter que usar um switch.
Vocês podem verificar que o que muda no código e só o lblBoard1 ou lblBoard2 e assim por diante, quem vai determinar o JLabel eh a variável points.
Não existe problema no código abaixo, somente gostaria de usar algo como (vou inventar pois eh exatamente isto que quero) lblBoard[points].setIcon. Mais um detalhe como criei estes JLabel em tempo de desenho não vi como criar um array deles na interface do netBeans. O que tenho realmente são JLabel's terminando com números lblBoard1, lblBoard2 e assim por diante.
 switch (points){
        case 1:{
            if (samePlace){
                lblBoard1.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay12) ) ));
            } else {
                if (player == "Player 1"){
                    lblBoard1.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay1) ) ));
                } else {
                    lblBoard1.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay2) ) ));
                }
            }
            break;
        }
        case 2:{
            if (samePlace){
                lblBoard2.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay12) ) ));
            } else {
                if (player == "Player 1"){
                    lblBoard2.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay1) ) ));
                } else {
                    lblBoard2.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay2) ) ));
                }
            }
            break;
        }
        case 3:{
            if (samePlace){
                lblBoard3.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay12) ) ));
            } else {
                if (player == "Player 1"){
                    lblBoard3.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay1) ) ));
                } else {
                    lblBoard3.setIcon(new ImageIcon(ImageIO.read( new File(imagePlay2) ) ));
                }
            }
            break;
        }

Caso elucide mais a questao esta eh a tela do meu jogo. queria ir movimentando os players casa por casa. esta funcionado fazendo o swicth porem eh codigo que nao acaba mais. 51 Labels.

A: A solução mais simples que vejo é trabalhar com um array de JLabels e depois acessar apenas o índice do JLabel desejado, usando a variável points. Mas pra isso, você precisará mexer direto no código, e não no construtor de telas do netbeans.
Instancie um array de labels no começo do seu código:
JLabel[] labelBoards = new JLabel[51];

Você pode usar um loop para iniciar, configurar e preencher cada um deles na sua tela:
for(int i = 0; i < labelBoards.lenght; i++) {
    JLabel label = new JLabel();
    // aqui voce configura o label do jeito que precisar
    labelBoards[i] = label;

}

E depois pra acessar, basta ter em mente que a variável points representará a posição do JLabel desejado no array:
if (samePlace){
    labelBoards[points].setIcon(new ImageIcon(ImageIO.read(new File(imagePlay12))));
} else {
    if (player == "Player 1"){
        labelBoards[points].setIcon(new ImageIcon(ImageIO.read(new File(imagePlay1))));
    } else {
        labelBoards[points].setIcon(new ImageIcon(ImageIO.read(new File(imagePlay2))));
    }
}

Lembrando que, se points é incrementada em outro lugar, não precisaria de laço neste caso, apenas este trecho ser chamado cada vez que ela mudar de valor.
Atente-se apenas de que, apesar de ter 51 JLabels no array, os índices vão de 0 a 50, portanto, a variável points só poderá ter valores apenas dentro desse range, senão vai estourar exceção ArrayIndexOfBoundException.

Há uma outra forma, aplicando a dica desta resposta, que consiste em pegar os componentes e filtrar quando for uma instancia de JLabel e colocá-los num ArrayList ou num array mesmo, com sua tela já criada do jeito que está agora, mas no seu caso, fazer isso seria um workaround bem ridículo, pois seria o mesmo que criar um remendo de código para arrumar outro código mal planejado. O recomendado seria a solução com array mesmo, daria mais trabalho mas ao menos seu código fica melhor com a lógica melhor organizada.
Sem mais detalhes fica dificil sugerir outra solução que não seja com array, se não conseguir implementá-la, edite a pergunta e forneça um exemplo Mínimo, Completo e Verificável para que seja possível ver o código funcionando e sugerir algo alternativo.


text:
Q: Touch and Drag in Flash CC AS3 I'm only learning AS3 this year, I need to be able to turn my key events into touch and drag events to export my game to iOS everything in my app works fine except for the paddle which I need to be able to touch and drag horizontally. Any help is appreciated here is my code for the paddle key events.
    private function keyDownHandler(evt:KeyboardEvent)
    {
        if (evt.keyCode == Keyboard.A)
        {
            //1st Player Left Key
            p1speed = -1;
        }
        else if (evt.keyCode == Keyboard.D)
        {
            //1st Player Right Key
            p1speed = 1;
        }

        if (evt.keyCode == Keyboard.SPACE)
        {
            spacePressed = true;
        }
    }

    private function keyUpHandler(evt:KeyboardEvent)
    {
        if ((evt.keyCode == Keyboard.A) || (evt.keyCode == Keyboard.D))
        {
            p1speed = 0;
        }
    }

A: If you are wanting to use Touch and Drag Events you are going to have to implement the following code:
import flash.ui.Multitouch;
import flash.events.TouchEvent;
import flash.ui.MultitouchInputMode;

then in your MainFunction where you declare your variables you would add this piece of code:
    //MultiTouch added for touch gestures
    Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

In your constructor Function:
            //setup Listeners when btn's touch begin and end
        btnUp.addEventListener(TouchEvent.TOUCH_BEGIN, btnUpMouseOver, false, 0, true);
        btnUp.addEventListener(TouchEvent.TOUCH_END, btnUpMouseOver, false, 0, true);

the functions that control the Events:
private function btnUpMouseOver(e:TouchEvent):void
    {
        //trace("btnUpRollOver");
          if (e.type == TouchEvent.)
          {
              //Mouse was pressed on this button
              btnPressedUp = true;

          }
          else if(e.type == TouchEvent.TOUCH_END)
          {
              //Mouse was released
              btnPressedUp = false;
          }
    }

You can also refer to this:  Adobe Touch EVents


text:
Q: How to use useEffect with if statement React I want to add in the dependencies of a useEffect an if statement if a variable is certain value. For example:
let counter = 5;

    useEffect(() => {
        socket.on("counter", counter => {
            setCounter(counter);
        });
        return () => socket.off('counter', counter);
    }, [socket])

useEffect(() => {
//do something
}, counter = 0)

This "counter = 0" in the end is obviously wrong. So how can I run the second useEffect anytime the counter is 0?

A: You cannot do what you're describing (or at the very least shouldn't), so you just need to move your logic. Instead of only running the useEffect when a variable equals another value, you need to run the useEffect anytime that variable changes and check the value inside the callback.
let counter = 5;

useEffect(() => {
  if (counter == 0) {
    //do something
  }
}, [counter])

Also note that = is always an assignment. To check equality you need == or ===.


text:
Q: Kafka AVRO Consumer: MySQL Decimal to Java Decimal I'm trying to consume records from a MySQL table which contains 3 columns (Axis, Price, lastname) with their datatypes (int, decimal(14,4), varchar(50)) respectively.
I inserted one record which has the following data (1, 5.0000, John).
The following Java code (which consumes the AVRO records from a topic created by a MySQL Connector in Confluent platform) reads the decimal column: Price, as java.nio.HeapByteBuffer type so i can't reach the value of the column when i receive it.
Is there a way to extract or convert the received data to a Java decimal or double data type?
Here is the MySQL Connector properties file:-
{
  "name": "mysql-source",
  "config": {
  "connector.class": "io.confluent.connect.jdbc.JdbcSourceConnector",
   "key.converter": "io.confluent.connect.avro.AvroConverter",
   "key.converter.schema.registry.url": "http://localhost:8081",
   "value.converter": "io.confluent.connect.avro.AvroConverter",
   "value.converter.schema.registry.url": "http://localhost:8081",
   "incrementing.column.name": "Axis",
   "tasks.max": "1",
   "table.whitelist": "ticket",
   "mode": "incrementing",
   "topic.prefix": "mysql-",
   "name": "mysql-source",
   "validate.non.null": "false",
   "connection.url": "jdbc:mysql://localhost:3306/ticket?
   user=user&password=password"
   }
}

Here is the code:-
    public static void main(String[] args) throws InterruptedException,
     IOException {

        Properties props = new Properties();

        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");

        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
        "org.apache.kafka.common.serialization.StringDeserializer");
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
        "io.confluent.kafka.serializers.KafkaAvroDeserializer");
        props.put("schema.registry.url", "http://localhost:8081");

        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        String topic = "sql-ticket";
final Consumer<String, GenericRecord> consumer = new KafkaConsumer<String, GenericRecord>(props);
consumer.subscribe(Arrays.asList(topic));

try {
  while (true) {
    ConsumerRecords<String, GenericRecord> records = consumer.poll(100);
    for (ConsumerRecord<String, GenericRecord> record : records) {
      System.out.printf("value = %s \n", record.value().get("Price"));
    }
  }
} finally {
  consumer.close();
}

}

A: Alright so i finally found the solution.
The Heapbytebuffer needs to be converted to a byte[] array, then i used BigInteger which constructs the value from the created byte array, then i created a BigDecimal variable that takes the value of the BigInteger and i set the decimal point with movePointLeft(4) which is the Scale (in my case : 4) and everything worked as expected.
    ByteBuffer buf = (ByteBuffer) record.value().get(("Price"));
    byte[] arr = new byte[buf.remaining()];
    buf.get(arr);
    BigInteger bi =new BigInteger(1,arr);
    BigDecimal bd = new BigDecimal(bi).movePointLeft(4);
    System.out.println(bd);

Here are the results ( Left is the output, Right is MySQL) :-


text:
Q: Users have open files on BackupSharedFolder. Continuing the operation will force the files closed I am using below sql statement to create shared folder with permission
EXEC xp_cmdshell 'net share BackupSharedFolder=D:\testshared /REMARK:"test shared"'
It is working fine with create shed folder.
then i will use below sql command to remove shared
EXEC xp_cmdshell ' net share BackupSharedFolder  /delete"'
Above is also working fine if shared folder is not opened.
if shared folder is opened.It giving error like following
 "Users have open files on BackupSharedFolder.  Continuing the operation will force the files closed.
Do you want to continue this operation? (Y/N) [N]:
No valid response was provided."
and ask for prompt for Yes or NO.
So, how can i force sql command to yes and remove share by this XEC xp_cmdshell ' net share BackupSharedFolder  /delete".

A: So, I am bending the SO rules a little: instead of answering your question, I have to advise that doing this seems like a really bad idea. Please don't control the OS through SQL Server's xp_cmdshell. It's just wrong on so many levels... architecture, security, design ...


text:
Q: RelativeLayout is taking fullscreen for wrap_content Why does FOOBARZ get layed out all the way at the bottom when no elements are layout_height="fill_parent" in other words, all elements are wrap_content for height?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/feed_u"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:layout_marginLeft="5dip"
        android:scaleType="centerCrop"
        android:drawableTop="@android:drawable/presence_online"
        android:text="U" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/feed_u">
        <ImageView
            android:id="@+id/feed_h"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/btn_minus" />
        <ImageView
            android:id="@+id/feed_ha"
            android:layout_toLeftOf="@id/feed_h"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/btn_plus" />
        <TextView
            android:id="@+id/feed_t"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Title">
        </TextView>
        <TextView
            android:id="@+id/feed_a"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Band"
            android:layout_below="@id/feed_t">
        </TextView>
        <TextView
            android:id="@+id/feed_s"
            android:layout_below="@id/feed_a"
            android:text="S"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content">
        </TextView>
        <TextView
            android:id="@+id/feed_tm"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:text="FOOBARZ"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content">
        </TextView>

    </RelativeLayout>
</RelativeLayout>

A: For those looking for a solution to this, like I did, you can use FrameLayout instead of RelativeLayout.
Then you can set the gravity the intended object to bottom right as below
<TextView
    android:layout_gravity="bottom|right"
    android:text="FOOBARZ"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
</TextView>

A: From the RelativeLayout doc:

Class Overview
A Layout where the positions of the children can be described in relation to each other or to the parent.
Note that you cannot have a circular dependency between the size of the RelativeLayout and the position of its children. For example, you cannot have a RelativeLayout whose height is set to WRAP_CONTENT and a child set to ALIGN_PARENT_BOTTOM

Class documentation
Which is exactly your case. RelativeLayout can not do that.

A: You have set the RelativeLayout to "wrap_content"
and the TextView to android:layout_alignParentBottom="true", so it automatically tries to stretch the RelativeLayout to the bottom. Don't use such dependencies with Relative Layout, as it can count as "circular dependencies".
From the docs for RelativeLayout:

Note that you cannot have a circular dependency between the size of the RelativeLayout and the position of its children. For example, you cannot have a
  RelativeLayout whose height is set to WRAP_CONTENT and a child set to ALIGN_PARENT_BOTTOM.

Try to align your TextView to something other than the parent RelativeLayout, but watch out for this problem as well:
Circular dependencies, need some help with exact code
Alternatively, try to add more sophisticated inner layouts.

A: Dont use alight_Parent type properties with the child views
You can use frame layout instead of RelativeLayout with respective gravity
    <FrameLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
     <TextView
        android:layout_gravity="bottom|right"
        android:text="Hello "
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">

    </TextView>

</FrameLayout>

A: FrameLayout is usually good for placing different views one on top of each other (where the most recent child is on top of the previous child). In your case, you'd like to place views one next to each other (above, below, start, end), so I think ConstrainLayout fits better because it's exactly what it does.
Unlike RelativeLayout, you'd be able to set the ConstrainLayout width to wrap_content and still arrange its children views as you wish, for example instead of
android:layout_alignParentTop="true"

you can use
grid:layout_constraintTop_toTopOf="parent"

and instead of
android:layout_alignParentBottom="true"

you can use
grid:layout_constraintBottom_toBottomOf="parent"

A: Good answers. Now if you don't have layout_alignParentBottom="true" and still getting this issue watch out for android:background="@drawable/bkgnd" where bkgnd is a biggie.

A: I'm not sure why the clean and obvious way of accomplishing this hasn't been posted yet. This performant solution works for any View MyView with a known height.
Wrap your RelativeLayout with height wrap_content in a FrameLayout:
<!-- width here should constrain RelativeLayout -->
<FrameLayout
     android:layout_width="@dimen/my_layout_width"
     android:layout_height="wrap_content">

     <RelativeLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />

     <MyView
        ...
        android:layout_gravity="bottom" />
</FrameLayout>

Just note that the view at the bottom of the FrameLayout will be on top of your RelativeLayout content, so you'll need to add padding to the bottom of that layout to accomodate it. If you want that view to be variable height, you can either Subclass FrameLayout to add padding in code based on the measured view height, or just change the FrameLayout to vertical LinearLayout if you're not worried about the performance, i.e. it's not a listview item, or the views are relatively lightweight.

A: Not sure why all the answers here suggest FrameLayout, which is designed to render a single view or views layered in the z axis. OP's problem is a sequence of views stacked vertically, which should be in a LinearLayout.


text:
Q: Evaluate $ \mathop{\sum^{n}\sum^{n}}_{i=0\ i < j\ j=0} i \binom{n}{j}$ Evaluate $$S=\mathop{\sum^{n}\sum^{n}}_{i=0,\:  i <  j,\: j=0} i \binom{n}{j}$$
My try:
I considered:
$$P=\mathop{\sum^{n}\sum^{n}}_{i=0,\:  i <  j,\: j=0} i \binom{n}{j}+j \binom{n}{i} \tag{1}$$
By Symmetry we have:
$$P=\mathop{\sum^{n}\sum^{n}}_{i=0,\:  i >  j,\: j=0} i \binom{n}{j}+j \binom{n}{i} \tag{2}$$
Letting $$Q=\mathop{\sum^{n}\sum^{n}}_{i=0,\:  i =  j,\: j=0} i \binom{n}{j}+j \binom{n}{i}$$
Hence:
$$Q=2\sum_{i=0}^{n}i \binom{n}{i}=2n 2^{n-1}=n2^n \tag{3}$$
Adding $(1)$,$(2)$ and $(3)$ we get:
$$2P+Q=\sum_{i=0}^{n}\sum_{j=0}^{n}\left(i\binom{n}{j}+j \binom{n}{i}\right)$$
We get:
$$2P+Q=2\left(\sum_{i=0}^{n}\sum_{j=0}^{n}\left(i\binom{n}{j}\right)\right)$$
$$2P+Q=2\left(\frac{n(n+1)}{2}\right)2^n=n^22^n+n2^n$$
$\implies$
$$P=n^22^{n-1}$$
With $P$ can we calculate $S$?

A: $S=\sum^n\sum^n_{i=0,j=0,i<j}i{n\choose j}=\sum_{j=1}^n{n\choose j}\sum_{i=0}^{j-1}i=\sum_{j=1}^n{n\choose j}\frac{j(j-1)}2=\sum_{j=2}^n\frac{n!}{j!(n-j)!}\frac{j(j-1)}2\\=
\frac12\sum_{j=2}^n\frac{n!}{(j-2)!(n-j)!}=\frac{n(n-1)}2\sum_{j=2}^n\frac{(n-2)!}{(j-2)!(n-j)!}=\frac{n(n-1)}2\sum_{j=2}^n{n-2\choose j-2}=\frac{n(n-1)}2\sum_{k=0}^{n-2}{n-2\choose k}=\frac{n(n-1)}2 2^{n-2}=n(n-1)2^{n-3}.$


text:
Q: Latitude Longitude is null outside LocationCallback I am using google play services api to get location. I got the location in LocationCallback and I can update the UI also from inside the callback method. But when I want to store the lat, lng in another variable to it becomes 0. here is my code, what i am missing here?
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
LocationRequest request = new LocationRequest();
request.setInterval(5000);
request.setFastestInterval(2500);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

LocationCallback callback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        for (Location location : locationResult.getLocations()) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();

            lattitude = lat;
            longitude = lng;

            ((TextView) findViewById(R.id.tvLat)).setText(String.valueOf(lat));
            ((TextView) findViewById(R.id.tvLng)).setText(String.valueOf(lng));
        }
    }
};

client.requestLocationUpdates(request, callback, null);


text:
Q: Does MonetDBLite support auto-commit mode? I am trying to optimize data upload in an R package using MonetDBLite. As per the MonetDB website, using LOCKED mode can speed up upload:

LOCKED mode
In many bulk loading situations, the original file can be saved as a
  backup or recreated for disaster handling. This reliefs the database
  system from having to prepare for recovery as well and to safe
  significant storage space. The LOCKED qualifier can be used in this
  situation (and in single user mode!) to skip the logging operation
  normally performed.

However, when I try to run my COPY INTO statement with LOCKED mode I get the error:
Server says 'ParseException:SQLparser:COPY INTO .. LOCKED: only allowed in auto commit mode'.

Reading the CRAN MonetDBlite documentation would have me believe that the standard mode is auto-commit, eg. the documentation for dbTransaction():

dbTransaction is used to switch the data from the normal
  auto-commiting mode into transactional mode. Here, changes to the
  database will not be permanent until dbCommit is called. If the
  changes are not to be kept around, you can use dbRollback to undo all
  the changes since dbTransaction was called.

but perhaps this isn't true since I'm getting the above error.
Does anyone have any insight?


text:
Q: OpenSSL on Windows and Visual Studio 2010 I want port an OpenSSL based project over to Windows that uses OpenSSL. I have Visual Studio 2010, and I downloaded OpenSSL from their download page.
I am trying to follow the directions from How to use OpenSSL with Visual Studio, but I am unable to find any library folders (lib) or dlls.
I am also getting the error Cannot open include file: 'openssl/openssl.conf.h': No such file or directory the file that is attempting to use that is the 'e_os2.h' file.

*

*Why are there no lib folders or dll files?

*Why is it trying to include a file that doesn't exist in the original package?

A:
Why are there no lib folders or dll files?

OpenSSL is distributed in source form. You have to build it yourself.
An alternative to building it yourself is to use Thomas Hruska's Win32 OpenSSL.

Why is it trying to include a file that doesn't exist in the original package?

OpenSSL's Configure script creates two header files that are tailored for your platform. The first is <openssl/opensslconf.h>, and the second is <openssl/bn.h>. If you have not run configure, then they will not be present.


text:
Q: Determine complexity class or big-o What is the big O for the following problem?
public static void mystery(int[] list)
{
   for (int i = 0; i < list.length/2; i++)
   {
      int j = list.length-1-i;
      int temp = list[i];
      list[i] = list[j];
      list[j] = temp;
    }
}

A: It's O(n), since it loops the array only once.


text:
Q: How to find IP of WiFi Powerline adapter While connected to the wifi of a powerline adapter, the ip my mac network settings and ifconfig show is 192.168.0.10, however when browsing to this ip I get an ERR_CONNECTION_REFUSED
The actual ip is 192.168.0.90
I'm just curious to understand why there is a difference

Context
Installed some powerline wifi adapters the other day ( something like this )
Needed to change the network settings to match my existing wifi name and password. Thought I could use the small bit of networking knowledge to hit the adapter's ip directly for the settings instead of installing vendor software to do so.
ipconfig didn't point to the right place so in the end had to get the software and that located the adapters and listed the correct ip to change the settings.
How was the vendor software able to find the true ip?

A: Presuming these devices work as simply a 'dumb hub' - in which case there won't be an ip address displayed in the ipconfig output at all. What you likely thought you needed was the gateway address, but this will be the ip of a completely different system.
How the software was able to find the true IP is something that you can only really guess at, until you do some more research such as using wireshark to see what packets it actually sends out in the discovery phrase. It's most likely that the device is listening on a port and just responds with the IP address it's using. All the software has to do is a scan of all IP's in your subnet, using this port to see which devices respond in the manner it expects.
Other such ways of identifying the devices is using multicast or broadcasts configured in such a way that only the power-line adaptors reply.

A: Mine didn't show up in the DHCP clients list on the router. You can find it on your subnet using nmap:
nmap -p80 192.168.0.0/24

The vendor software could do the same thing and check the http response if it finds one.
If you find the IP you can check all ports:
nmap -p- 192.168.0.108

Mine has telnet open, so the scanning software can use that too if it has a secret knock.


text:
Q: Convert from JSon to Object Collection Below is my json string, which i am trying to parse to list of my class
i am using NewtonsJson.net.3.5
[
    {
        "message": {
            "$": "@12:55 Big Rally on South Bound of Dr. B.A. Road. Motorists may use RAK Road, P. D'Melow Road & A.B. Road for CST.\n -visit icicilombard.com"
        },
        "picture": {
            "$": ""
        },
        "medium": {
            "$": "API"
        },
        "timestamp": {
            "$": "03\/15\/2011 12:55:42 IST"
        }
    }
]

This is my class of which i want my json to be parsed to
public class GupShupTrafficAlerts
    {
        private string _message = string.Empty;

        private string _picture = string.Empty;

        private string _medium = string.Empty;

        private string _timeStamp = string.Empty;

        public String message
        {
            get;
            set;
        }

        public string timestamp
        {
            get;
            set;
        }

        public string medium
        {
            get;
            set;
        }

        public string picture
        {
            get;
            set;
        }
    }

this is the way i m trying to parse to List
List<GupShupTrafficAlerts> lstTrafficAlert =
JsonConvert.DeserializeObject<List<GupShupTrafficAlerts>>(@JSonString);

but to no avail
Please help me...

A: Your JSON should look like that:
[
    {
        "message": "@12:55 Big Rally on South Bound of Dr. B.A. Road. Motorists may use RAK Road, P. D'Melow Road & A.B. Road for CST.\n -visit icicilombard.com",
        "picture": "",
        "medium": "API",
        "timestamp":"03\/15\/2011 12:55:42 IST"
    }
]


text:
Q: Connection timeout error for vagrant up I have Installed virtualbox-dkms
$ sudo apt-get install virtualbox-dkms
DKMS: install completed.
 * Stopping VirtualBox kernel modules                                                                                [ OK ]
 * Starting VirtualBox kernel modules                                                                                [ OK ]
Setting up virtualbox (4.3.34-dfsg-1+deb8u1ubuntu1.14.04.1) ...
 * Stopping VirtualBox kernel modules                                                                                [ OK ]
 * Starting VirtualBox kernel modules                                                                                [ OK ]
Setting up virtualbox-qt (4.3.34-dfsg-1+deb8u1ubuntu1.14.04.1) ...

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'lucid32'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: chef-repo_default_1449661717604_69994
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...