text:
Q: Copy one CPT to another one in Wordpress I'm building a site with two separate CPTs nominees and winners
The idea is that we have a user submit a nomination in one of 7 categories ( taxonomy ) on the front end, and editors go in and approve nominations for display on the website.
Once every quarter, a selection of 7 nominees ( one from each category ) are chosen as winners.
Is there a way to copy the fields from a nominee CPT ( name, department, taxonomy, content ) to a winner CPT? Ideally, this would be done by a call in the Admin.

A: You can update a posts type using wp_update_post:
$my_post = array(
    'ID'        => $post_id,
    'post_type' => 'winner',
);
$result = wp_update_post( $my_post, true );

// check if it failed and tell the user why
if ( is_wp_error( $result ) ) {
    $errors = $result->get_error_messages();
    foreach ( $errors as $error ) {
        echo 'error: '.esc_html( $error );
    }
}

Where $post_id is the ID of the post you're switching to, and $result is either a post ID or an error object

A: Someone else posted a link to this plug-in, but the answer disappeared. I'm not sure why ( is it against the rules to post a link to a plug-in or something? ).
Anyway, I have the link open, so I'm posting it. I think it may solve my issue. I don't know if it will handle Custom Fields yet, but it looks promising.


text:
Q: Linux stdin buffering With the following program and the sample run, I expected to see "stdin contains 9 bytes", but as you can see in the sample run, I got "stdin contains 0 bytes". Why is that? How can I fix this program to get the actual number of unread bytes in stdin?
Program:
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>

void main() {
    if ( (setvbuf(stdin, NULL, _IONBF, 0) |
            setvbuf(stdout, NULL, _IONBF, 0)) != 0) {

        printf("setting stdin/stdout to unbuffered failed");
        return;
    }

    printf("type some keys\n");
    sleep(3);
    printf("\n");

    unsigned long bytesUnread=0;
    if (ioctl(0, FIONREAD, &bytesUnread) != 0) {
        printf("ioctl error");
        return;
    }
    printf("stdin contains %ld bytes\n", bytesUnread);
}

Sample run:
$ ./a.out
type some keys
some keys
stdin contains 0 bytes

Here is another sample run where I hit enter, and you can see it worked as expected.
$ ./a.out
type some keys
asd

stdin contains 4 bytes

A: Redirect stdin from a file or press enter after pressing a few keys and you will see that your code works as expected, independent of whether you call setvbuf or not, because your problem is not the FILE stream being buffered. The FILE stream isn't even involved in your ioctl. Rather, your problem is that the bytes have not been transmitted yet. They're in the kernel's line editing buffer for the canonical-mode tty, allowing you to backspace, CtrlW, etc. them before sending them.
If you want the tty layer to transmit bytes as they're generated on the terminal, rather than only in aggregate after line editing, you need to take the tty out of canonical mode. The termios.h interfaces are how you do this (see man 3 termios). Generally the easiest way is to tcgetattr, cfmakeraw, then tcsetattr, but cfmakeraw is not entirely portable so it can be preferable to just do the equivalent changes yourself.

A: setvbuf sets the output buffering of a FILE stream.  You can't change the input buffering, because it makes no sense to do so -- you generally don't know what is available to be read from the underlying file descriptor until you actually read it.  Even in cases where you could know (eg, by checking with an ioctl), that might change, due to later events and other threads and processes accessing the file descriptor.  So you can never actually know for certain what you are going to read until you read it.
Looking at you sample run, it looks like you are using a terminal and not hitting enter?  In which case, the input will be held in the terminal buffer (in case you will later hit backspace), and your ioctl call (which checks the file descriptor's buffer) will not see it.
In any case, getting the amount of data in the input buffer is not useful, as trying to do anything with that knowledge before you actually read it is a race condition -- you have no way of knowing if some other process or driver is in the middle of modifying the buffer.  So for any real use, you just want to read the input data and react based on what the (atomic) read system call returns.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What causes a MOSFET to short? I'm building a Royer Oscillator, and I'm not sure why my initial MOSFET (U2) is shorting? My LT Spice simulation works somewhat, however I get a lot of current coming out of the drain (6A+), and likewise the 2 inductors drawing massive currents. Why would this be the case?
Is it because of the MOSFETs M1 and M2? Are they what's causing this massive surge in current? And hence the short in the initial MOSFET.
The power supply I'm using is rated to 6A, and it actually goes up to 6A when I turn it on, but the voltage reduces drastically.
Anyone have any ideas? (Ground is the bottom rail).

A: As HandyHowie told you, you put the Mosfet across the battery.
Look on Fig 1 and 2.
http://www.irf.com/product-info/datasheets/data/irfr4105.pdf
11 V as Vds and 10V as Vgs and the Mosfet will allow ~ 100A,
assuming you battery is capable, a nice 1kW.
The devices will blow up in ~ 100 us. (Zth ~ 0.2 C/W)


text:
Q: How to apply css to php 'echo $tube->error;'? The CSS that I'm attempted to attach to 'echo $tube->error;' is not showing.. It just shows as default black text as if it had no css... How would I fix this?
Thanks (:
Below is what I need to fix..
The html/php part:

        <?php } else {

        echo $tube->error;

        }
    }
        ?>

The html/php part in context:
<?php

if(isset($_POST['url']))
{
  include('curl.php');
  include('youtube.php');

  $tube = new youtube();

  $links = $tube->get($_POST['url']);

  if($links) { ?>

  Download Links  ( Same IP Downloading only ) :
        <?php
        $format = '
Download video.%s - %s
Right-click download link and choose etc...
';
        while($link = array_shift($links))
{
    echo vsprintf($format,$link);
}
        ?>

        <?php } else {

        echo $tube->error;

        }
    }
        ?>

The CSS:
#error {
    width:404px;
    margin-left: auto;
    margin-right: auto;
    font-size:12;
    font-family: 'Dosis', sans-serif;
    color:white;
    padding-top:20px;
}

The part of youtube.php(additional info.. not sure if you guys need this):
function get($url)
{
    $this->conn = new Curl('youtube');

    $html = $this->conn->get($url);

    if(strstr($html,'verify-age-thumb'))
    {
        $this->error = "Adult Video Detected";
        return false;
    }

    if(strstr($html,'das_captcha'))
    {
        $this->error = "Captcah Found please run on diffrent server";
        return false;
    }

    if(!preg_match('/stream_map=(.[^&]*?)&/i',$html,$match))
    {
        $this->error = "Error Locating Downlod URL's";
        return false;
    }

Thanks again for any help!!

A: EDIT: I was wrong, it wasn't a CSS error, but a construct error, as others have noticed. I just rewrote the "The html/php part in context" to make it more clear and hopefully working:
<?php

if(isset($_POST['url']))
{
  include('curl.php');
  include('youtube.php');

  $tube = new youtube();

  $links = $tube->get($_POST['url']);

  if($links)
  {
    ?>

      Download Links  ( Same IP Downloading only ) :
      <?php
      $format = '
Download video.%s - %s
Right-click download link and choose etc...
';
      while($link = array_shift($links))
      {
        echo vsprintf($format,$link);
      }
      ?>

    <?php
  }
  else
  {
    ?>

      <?php echo $tube->error; ?>

    <?php
  }
}
?>

Hope everything is ok now :)

A: Your
 is never rendered if there is an error, because your else statement only includes the error text itself. Move the div and pre inside the else to get it working.
<?php } else { ?>

       <?php echo $tube->error; ?>

<?php } ?>

A: Try this code:
<?php
if (isset($_POST['url'])) {
    include('curl.php');
    include('youtube.php');

    $tube = new youtube();

    $links = $tube->get($_POST['url']);

    if ($links) {
?>

Download Links  ( Same IP Downloading only ) :
<?php
    $format = '
Download video.%s - %s
Right-click download link and choose etc...
';
    while($link = array_shift($links)) {
        echo vsprintf($format,$link);
    }
?>

<?php } else { ?>

    <?php echo $tube->error; ?>

<?php } } ?>

Don't forget to include the CSS... and please, please write more readable in the future.

A: Try this css:
#error pre {
    width:404px;
    margin-left: auto;
    margin-right: auto;
    font-size:12;
    font-family: 'Dosis', sans-serif;
    color:white;
    padding-top:20px;
}

A: Try to define your CSS also for #error pre and not only #error:
div#error {
    width:404px;
    margin-left: auto;
    margin-right: auto;
    padding-top:20px;
}

div#error pre
{
    font-size:12;
    font-family: 'Dosis', sans-serif;
    color:white;
}

Use also an inspector (like Chrome's one, that you call with CTRL+I) to make sure:
- there are not overrides that undo there lines
- CSS is properly loaded (if in an external file)


text:
Q: Sending an ArrayList over a socket in Java Basically what I have is a Packet class which implements Serializable. Within this Packet class I have two ArrayList of type byte[]. I have no trouble sending over a Packet containing two ArrayList of type String.
The main reason I need to send it over as an ArrayList of type byte[] is because I first have to encrypt the data. Here is a snippet of the code:
public class Packet implements Serializable
{

        private ArrayList<byte[]> data;             // String data to be sent
        private ArrayList<byte[]> data2;            // Numeric data to be sent
        private Encryption encryption;              // Encrypts data using RSA

        public void insertString(String input)
        {
            byte[] dataToBeSent = encryption.encrypt(input, encryption.getPublicKey());
            data.add(dataToBeSent);
        }
}

I am now wondering how I can send the byte arrays through a socket from within the Packet class?


text:
Q: Arel Table with PostgreSQL OVERLAPS method Let me preface this by acknowledging that there are a couple of different ways to accomplish overlapping, but with regard to this question, I'm specifically trying to figure out how to use the actual PostgreSQL OVERLAPS method with Arel. To that end, this question has more to do with gaining a better understanding of Arel rather than implementing some version of overlapping functionality.
I'm using Rails 5.1
This is the SQL statement that I am trying to duplicate in Arel:
SELECT DISTINCT
  venues.id
FROM
  venues
LEFT OUTER JOIN
  reservations
ON
  venues.id = reservations.venue_id
WHERE (
  (reservations.venue_id IS NULL)
  OR NOT (
    (reservations.start, reservations.end)
    OVERLAPS
    (DATE '2018-09-02', DATE '2018-09-03')
  )
)

I currently have the following which does generate the above:
Venue.arel_table.project(
  Venue.arel_table[:id]
).from(
  Venue.arel_table
).join(
  Reservation.arel_table, Arel::Nodes::OuterJoin
).on(
  Venue.arel_table[:id].eq(Reservation.arel_table[:venue_id])
).where(
 Arel::Nodes::Grouping.new(
    Reservation.arel_table[:venue_id].eq(nil)
  ).or(
    Arel.sql("NOT ((reservations.start, reservations.end) OVERLAPS (DATE '2018-09-02', DATE '2018-09-03'))")
  )
)

However, I feel like there is probably a better way to do this; I had been trying to implement Arel::Nodes::NamedFunction for OVERLAPS however, when I replace the above Arel.sql statement with the following, it doesn't execute the SQL properly:
Arel::Nodes::NamedFunction.new(
  'OVERLAPS',
  [
    Arel::Nodes::SqlLiteral.new('(reservations.start, reservations.end)'),
    Arel::Nodes::SqlLiteral.new("(DATE '2018-09-02', DATE '2018-09-03')")
  ]
)

results in
...OVERLAPS ((reservations.start, reservations.end), (DATE '2018-09-02', DATE '2018-09-03'))

What is the proper method for implementing OVERLAPS with Arel?

A: Since OVERLAPS is a SQL operator, I believe the following expression should work:
Arel::Nodes::InfixOperation.new(
  'OVERLAPS',
  Arel::Nodes::SqlLiteral.new('(reservations.start, reservations.end)'),
  Arel::Nodes::SqlLiteral.new("(DATE '2018-09-02', DATE '2018-09-03')"
)

A: Since rails7 you can use
Arel::Nodes::Overlaps.new(left, right)
Shorter version of answer:
Arel::Nodes::Overlaps.new(
  Arel.sql('(reservations.start, reservations.end)'),
  Arel.sql("(DATE '2018-09-02', DATE '2018-09-03')"
)

But saying A, why dont u say B? Here is clearly Arel soultion.
Arel::Nodes::Overlaps.new(
  Arel::Nodes::NamedFunction.new('', [Reservation.arel_table[:start], Reservation.arel_table[:end]]),
  Arel::Nodes::NamedFunction.new('', [
    Arel::Nodes::InfixOperation.new('::', Arel::Nodes.build_quoted('2018-09-02'), Arel.sql('DATE')),
    Arel::Nodes::InfixOperation.new('::', Arel::Nodes.build_quoted('2018-09-03'), Arel.sql('DATE'))
  ])
)

Result of #to_sql is so damn good
("reservations"."start", "reservations"."end") && ('2018-09-02' :: DATE, '2018-09-03' :: DATE)

We can shorten it by using #overlaps method of Arel::Predications
Arel::Nodes::NamedFunction.new('', [Reservation.arel_table[:start], Reservation.arel_table[:end]]).overlaps(
  Arel::Nodes::NamedFunction.new('', [
    Arel::Nodes::InfixOperation.new('::', Arel::Nodes.build_quoted('2018-09-02'), Arel.sql('DATE')),
    Arel::Nodes::InfixOperation.new('::', Arel::Nodes.build_quoted('2018-09-03'), Arel.sql('DATE'))
  ])
)


text:
Q: Setting the name of an object in Powerpoint as a String I have a powerpoint slide with about 3000 slides. On each slide I have a one picture and a text box. In powerpoint the picture has a specific name attached to it in the selection pane while the text box is named "TextBox 3". Each text box contains the text "2013-09-27 16.27.54". My job is to go through each text box and replace that text with name of the picture in the selection pane. I have written the following code to do this however I am having trouble setting the name of the picture as a string. When I run this code I get "Compile error: Invalid qualifier" on line 10, and Name is highlighted in line 10
How do I get rid of this error? I am assuming it is because the name of the object is not being recognized as a string.
My code is as follows:
Sub Hello()

For Each sld In Application.ActivePresentation.Slides
    For Each shp In sld.Shapes
        If shp.HasTextFrame Then
            Set txtRng = shp.TextFrame.TextRange
            Set foundText = txtRng.Find(FindWhat:="2013-09-27 16.27.54")
            Do While Not (foundText Is Nothing)
                With foundText
                .Replace(FindWhat:=foundText, _
          Replacewhat:=Application.ActivePresentation.Slides(i).Shapes(1).Name.TextRange.TextFrame, WholeWords:=True) = True

                End With
            Loop
        End If
End If
Next
Next
End Sub

A: Find and Replace is unnecessarily complex. Find the picture, get its name, find the text box, replace the text:
Sub Hello()
Dim sld As Slide
Dim shp As Shape
Dim PicName As String

    For Each sld In Application.ActivePresentation.Slides
        For Each shp In sld.Shapes
            If shp.Type = msoPicture Then
                PicName = shp.Name
            End If
        Next
        For Each shp In sld.Shapes
            If shp.HasTextFrame Then
                shp.TextFrame.TextRange.Text = PicName
            End If
        Next
    Next
End Sub


text:
Q: Sending/Receiving/Interpreting Dynamic Email I wanted to write a program that can receives an email, interprets what the message is, then performs a calculation, then responds based on the email received.
For example:
The mail server receives an email that has "option 1" in the body...then somehow the mail server asks the program what it should do in the event of option 1. The program performs some calculations, then asks a SQL server to relay some data related to option 1. The mail server then returns a dynamically created message "option 1 means xxx".
I really have no idea where to start on this one. A friend recommended PostFix but I'm not exactly sure where any program logic can be performed. Any ideas or suggestions are welcome.

A: The procmail mail processor is very good at this. Examples should be in the documentation.  It essentially allows you strip mail bodies from headers given conditions (e.g. 'security' tokens, 'passwords', 'addresses', ...) and to then pipe the mail body through other arbitrary programs.

A: You can do this using a regular POP3/IMAP and SMTP setup.

*

*Monitor the Mailbox for incoming messages

*Download the message and parse the contents

*Process your events as needed

*Generate a SMTP response to the sender and respond.

Some helpful links:

*

*System.Net.Mail

*Processing POP3 messages in C#
P.S. We have done this at several jobs I have worked at, its actually very straight forward.

A: Chris,
I started here: codeproject - NetPopMimeClient.  Using this I wrote a program to check for a new inventory email based on subject text (inventory attached.)   When I found a new one I would save the attachment and then upload it to my sql server and kick off a stored proc to process it.  Then saved the email DateTime stamp for the next run and to display to the user on the front-end.
I created a Console Application that is scheduled in SQL Server Agent.  I did this so I can have a log of activity, it is close to the database, it is easy to kick off manually, and it emails out when there is a problem.
Jim

A: If your mailserver can be connected via IMAP4, I recommend taking a look at IMAPFilter. You can implement a LUA script to take certain actions based on the content of the emails. I found a blog post that might give you some hints on how to get started.


text:
Q: Putting UITabbarController inside UINavigationController. What problem may occur? I have a stack like below hierarchy (I'm using programatic way, so I done it)
UINavigationController -> UITabbarController -> UInavigationController -> UIViewController
                                             -> UInavigationController -> UIViewController

As Apple Docs say for pushViewController:

The view controller to push onto the stack. This object cannot be a tab bar controller

I need to know If this has a known bug or will CERTAINLY causes a bug.
I really searched a lot for similar posts but none of them give me an acceptable answer.
Using UITabBarController with UINavigationController - Swift 3
Can you push a UITabBarController inside an UINavigationController

A:
From Apple:

Before creating a tab bar interface, you need to decide how you intend
  to use a tab bar interface. Because it imposes an overarching
  organization on your data,you should use one only in these specific
  ways:

*

*Install it directly as a window's root view controller.

*Install it as
  one of the two view controllers in a split view interface. (iPad only)

*Present it modally from another view controller.

*Display it from a
  popover. (iPad only)

  Installing a tab bar interface in your app's main
  window is by far the most common way to use it.
  In such a scenario,
  the tab bar interface provides the fundamental organizing principle
  for your app's data, with each tab leading the user to a distinct part
  of the app. You can use tab bar controllers by themselves or in
  conjunction with other view controllers to create even more
  sophisticated interfaces. For more information, see Combined View
  Controller Interfaces.
It is also possible to present a tab bar controller modally if a very
  specific need makes doing so worthwhile. For example, you could
  present a tab bar controller modally in order to edit some complex
  data set that had several distinct sets of options. Because a modal
  view fills all or most of the screen (depending on the device), the
  presence of the tab bar would simply reflect the choices available for
  viewing or editing the modally presented data. Avoid using a tab bar
  in this way if a simpler design approach is available.


text:
Q: Given A,B and n find the minimum value of Ax-By where x+y = n Given $A$, $B$, $n$ we're interested in non negative values $Ax-By$, where $A,B,n$ $\in$ $\mathbb Z$, n $\le$ $10^5$, $A+B=n$
and the value of the equation is minimized in case of multiple possible values of $x,y$
My idea is nothing but plain bruteforce, checking each values from $i$ to $n$ and $n-i$,thus finding minimum value.
For example:
$A=5,B=6$
$6*5 - 4*6 = 6$
Need some efficient ideas. Thanks in advance.

A: $y=n-x$ and you minimize $$Ax-B(n-x)=(A+B)x-Bn.$$
All values taken by this expression differ in multiples of $A+B$, and the smallest positive value is
$$(-Bn)\bmod(A+B),$$ which is in $[0,A+B)$.

UPDATE:
The conditions in the title and in the body define completely different problems !


text:
Q: passing an image for an opacity effect I have this code that will change the pictures every 3 seconds (slider) and I want to add a fade in effect but I can't seem to do it.
Most of the tuts I see are using libraries like Jquery and I want to use pure js.
This is the code:
var slide = document.getElementsByClassName("slide");
var i = 0;
var op = 0;

function fadeIn(obj) {
    if(op < 1) {
        op += .1;
        op = Math.round(op*10)/10; // this is because the op+=.1 gives me results .899999999...
        obj.style.opacity = op;
    }
    setTimeout( fadeIn , 300);
}

function callbackSlider() {

    if( typeof(slide[i-1]) === "object") {
        slide[i-1].style.display = "none";
    }

    slide[i].style.display = "inline";
    fadeIn();

    if( typeof(slide[i+1]) === "object") {
        slide[i+1].style.display = "none";
        i++;
    }
    else {
        i=0;
    }
    setTimeout( callbackSlider , 3000);
}

callbackSlider();

My logic is that every picture I add - just put a class="slide" in the img tag
my problem is that when the current image comes to get its turn to get some opacity effects added or removed I don't know how to change the opacity inside the fadeIn function since I'm just passing it. Any ideas ?

A: I write a demo to solve this problem, but it may run better to use the CSS3 "transition".
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

a

b

c


text:
Q: Running a Hadoop job from a Java Program I am writing a distributed system and am facing problem with connecting it to Hadoop. Here's my situation:
1) I have a distributed system running on 3 computers (sys1, sys2, sys3)
2) Sys2 and Sys3 are MasterNodes of two different Hadoop Clusters. These two Hadoop clusters are not connected to each other and each runs independently.
3) My distributed system has three parts (p1, p2, p3).
P1 sits on sys1 and receives the source code of Mappers/Reducers from the client (client is another system). P1 will then contact P2 or P3 and send them the code for mappers/reducers.
4)Now the problemis that P2 or P3 needs to run the job on Hadoop and send back the result to P1.
I have worked with hadoop for a while and know how to write a simple mapReduce program, convert it to a JAR file and execute it on Hadoop. The problem is that in my case the source code of mapReduce job is sent during the execution and I can't make a JAR file out of it. I need to make a hadoop job out of the received code and run it in hadoop. I would appreciate any advice/suggestion on how to solve this problem?
PS. I know one solution is to write the received map/Reduce code to a file on disk, execute all the required commands to make the JAR file and running the job in a shell from within my Java code (using a Runtime instance) and ... but I prefer to be able to directly run the job from my Java code and not go through all the possible troubles of the above solution.

A: What about using the JavaCompiler API ? You could then easily create a jar file on the fly with  JarOuptputStream
Here is a nice blog post explaining the API :
JavaBeat


text:
Q: Don't rewrite link generator with dinamic route In my code I created a route with a prefix, this prefix is a slug of courses.
Route::prefix('{course_slug}')->middleware('courses')->group(function () { ...

The URL is like this.
http://127.0.0.1/class/php/exams

It's all right, but now I need to rewrite my views, with a parameter of course.
route('class.exams.index', ['course' => 'php'])

My question is, it's possible don't rewrite my views? There are the possibility to inject the parameter of course on generate link and don't change the code on the view?
Then keep the code so.
route('class.exams.index')

A: I found a solution to my problem. The solution is described on this post: https://laracasts.com/discuss/channels/laravel/default-route-parameters?page=1#reply=426656
The solution, on my case, was in the Middleware set a default param
namespace App\Http\Middleware;

use Illuminate\Contracts\Routing\UrlGenerator;

class SetRouteDomain
{
    private $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }

    public function handle($request, Closure $next)
    {
        $course_default = Course::getDefault();

        $this->url->defaults([
            'course_slug' => isset($request->course_slug) ? $request->course_slug : $course_default->slug,
        ]);

        return $next($request);
    }
}

Then I don't needed to change the views.


text:
Q: android opengl skip faces I'm drawing a simple triangle on a screen. This is my object class:
public class GLObj
{
private FloatBuffer     vertBuff;
private ShortBuffer     pBuff;

private float           vertices[] =
{
     0f,  1f, 0, // point 0
     1f, -1f, 0, // point 1
    -1f, -1f, 0  // point 3
};

private short[]         pIndex = { 0, 1, 2 };

public GLObj()
{
    ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4); // each point uses 4 bytes
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff = bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);

    // #### WHY IS THIS NEEDED?! I JUST WANT TO DRAW VERTEXES/DOTS ####
    ByteBuffer pbBuff = ByteBuffer.allocateDirect(pIndex.length * 2); // 2 bytes per short
    pbBuff.order(ByteOrder.nativeOrder());
    pBuff = pbBuff.asShortBuffer();
    pBuff.put(pIndex);
    pBuff.position(0);
    // ################################################################
}

public void Draw(GL10 gl)
{
    gl.glFrontFace(GL10.GL_CW);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);

    // ### HOW TO PASS VERTEXT ARRAY DIRECTLY WITHOUT FACES?? ###
    gl.glDrawElements(GL10.GL_POINTS, pIndex.length, GL10.GL_UNSIGNED_SHORT, pBuff);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}

}
My problem is this: to understand OpenGL I want to skip the faces and just display vertices on the screen. The problem is I don't understand how to pass vertices only to glDrawElements function.
Do I 'must' have 'faces' defined (pIndex variable) in order to display vertices even if they're dots?

A: No, you do not need an index array to just draw points. Use glDrawArrays() instead of glDrawElements(). glDrawElements() is for indexed geometry, while glDrawArrays() simply draws a sequence of vertices.
In your example, replace the glDrawElements() call by:
gl.glDrawArrays(GL10.GL_POINTS, 0, vertices.length / 3);

Note that the last argument is the vertex count. Since the vertices array contains 3 coordinates for each vertex, the length of the array needs to be divided by 3 to obtain the vertex count.


text:
Q: SQL server extension in PHP manual I need in my website to add php to the server side for IIS , I installed the PHP form the :
http://windows.php.net/download#php-7.0
the last version and unziped to the C:\PHP also I added the Wincache extension. Beside that i add the Environment variable and the PHP to IIS Manager. so PHP site loads perfect, so my problem is my database is MS SQL SERVER so I need to add the extension to the php . ALTHOUGHT I dont have a php.ini File instead there are 2 files  php.ini-production and php.ini-development . I installed the driver form : https://www.microsoft.com/en-us/download/details.aspx?id=20098
 I dont know how to go further .!! i tried to connect to my database but I got this error

Fatal error: Uncaught Error: Call to undefined function mssql_connect()

i edited the 2 ini files and removed the ; but there are no lines related to the sqlsrv , i tried to add them manually but also did not work .
ANY IDEAS , PLEASE !!

A: Indeed, you can't use mssql_connect() anymore, sqlsrv_connect() is the prefered method since PHP 5.3.2, if I'm not mistaken.
I've created a "How to install Microsoft's SQL Server Driver for PHP" that you can find at https://www.saotn.org/install-microsoft-sql-server-driver-php/.


text:
Q: Citations with biblatex-apa: Same lead author, yet actually different group of authors I have run into a problem in biblatex-apa that has previously been discussed here: citing -- within the same parentheses -- multiple author groups that abbreviate to the same (Smith et al.), yet actually refer to different groups and different years. Here's my demonstration of this issue:

But: When I use the workaround proposed by moewe in 2013, I get the following, which might be correct:

Question 1: Is this fix actually correct (as per APA style)? Unfortunately, I cannot find any other reference to this problem online. I believe that moewe's fix nails it. But does it?
Question 2: Has anyone used this fix in large documents (without running into any other errors that such an interference with the package might cause)?
Question 3: I am wondering whether Philip Kime (plk) has ever implemented an official (APA compliant) solution to this problem!?
I know this is a somewhat bulky and complicated issue, but any help would be greatly appreciated!

A: Regarding Question 1: Correct as per APA style?
I believe that the examples and rules described under 6.16 in the APA Manual (6th ed.) indeed suggest that moewe's solution gives us what the APA wants in such cases. The manual says that we must sort multiple citations within the same parentheses, "including citations that would otherwise shorten to et al." (p. 177), in the same order as in the reference list. And that is, of course, alphabetically. An exception from this rule is the case of "works by the same authors (in the same order)" (p. 178). These are migrated and sorted by year ("Bauer et al., 2001, 2016"). If, however, two works shorten to the same term ("Smith et al." in my above example), yet do not represent the same authors (let alone the same authors in the same order), the criteria of the exception are not met. Therefore, the special rule of combining citations and sorting them by year cannot be applied here. As a consequence, the superordinate rule (sort multiple citations within the same parentheses alphabetically) should be used. And that would indeed give us "Smith et al., 2016; Smith et al., 2001".
Regarding Question 2: Use fix in a large document?
I have implemented moewe's fix in a large document - and it works perfectly and does not interfere with any other procedure in biblatex-apa.
Regarding Qustion 3: Official solution in the package?
Philip Kime has told me that this correction has indeed been implemented in a more recent version of biblatex-apa (probably 6.8).


text:
Q: Lock multiple files in MKS Can someone help me with the command to lock multiple files in MKS.
To lock a single file, the command is si lock --gui "filepath". I have tried some combinations like si lock --gui "filepath1;filepath2" and si lock --gui "filepath1";"filepath2" but ended up in getting an errormessage.

A: Answering my question:
Use spaces to specify more than one member.
si lock --gui "filepath1" "filepath2"


text:
Q: awk print lines where the values of any of 5 fields are different, ignoring missing data I'm trying to figure out if there are any pairwise differences in the values of 5 fields (fields 4-8) in my tabular file. Missing data are represented by the string "na". I'd like to print any lines with more than one value in these fields ignoring missing data (for instance, T and G in the first line of the example below), or more than two values if including "na".
Here are a few lines from the data file I'm working with:
2       1150    T       na      na      na      T       G
2       1151    C       na      na      na      T       C
2       1156    A       na      na      na      A       T
2       10742   C       T       na      T       na      na
2       10769   G       A       na      A       na      na
2       10781   T       G       na      G       na      na
2       58959   C       na      na      G       G       na
2       66907   G       na      na      A       G       na
2       66911   A       na      na      T       A       na
2       73087   C       C       na      C       C       T
2       92844   G       na      na      na      T       T
2       92846   T       na      na      na      T       G
2       99932   G       G       G       na      GT      na

The output I'm aiming for would be:
2       1150    T       na      na      na      T       G
2       1151    C       na      na      na      T       C
2       1156    A       na      na      na      A       T
2       66907   G       na      na      A       G       na
2       66911   A       na      na      T       A       na
2       73087   C       C       na      C       C       T
2       92846   T       na      na      na      T       G
2       99932   G       G       G       na      GT      na

This seems to be a bit beyond my skill level so I'd appreciate any help or advice!

A: With GNU awk for delete array and length(array):
$ awk '{delete unq; for (i=4;i<=NF;i++) unq[$i]} length(unq)>2' file
2       1150    T       na      na      na      T       G
2       1151    C       na      na      na      T       C
2       1156    A       na      na      na      A       T
2       66907   G       na      na      A       G       na
2       66911   A       na      na      T       A       na
2       73087   C       C       na      C       C       T
2       92846   T       na      na      na      T       G
2       99932   G       G       G       na      GT      na

delete array has actually been part of POSIX since 2012 (see http://austingroupbugs.net/view.php?id=544) and length(array) isn't only available in gawk, but also in other awks, so you could try the above on your awk and it might work even if it's not gawk.

A: For completeness, a version that doesn't rely on GNU-specific features:
awk '{ c=0; split("",a); for(i=4;i<=NF;++i) if(!a[$i]++) c++ } c>2' file

The variable c keeps a count of all unique entries in the fields from the 4th to the last. !a[$i]++ identifies unique entries by only being true the first time it is evaluated for a given value $i. If more than two unique entries have been found, the record is printed. split("", a) achieves the effect of delete a, as splitting the empty string results in an array with no elements.


text:
Q: multiple AJAX calls requesting JSONP GeoServer I have a code which I request data from a geoserver and display geoJSON on a map. To this request I'm using three AJAX calls like the following:
$(document).ready(function(){

//BASEMAP
var center = new L.LatLng(-0.8936,119.8638);
var map = new L.Map('map', { center: center, zoom: 14, attributionControl:true, zoomControl:false});

osmTile = "http://tile.openstreetmap.org/{z}/{x}/{y}.png";
osmCopyright = "Map data © 2016 OpenStreetMap contributors";
osmLayer = new L.TileLayer(osmTile, { maxZoom: 18, attribution: osmCopyright } );
map.addLayer(osmLayer);

//URL SERVICE
var owsrootUrl = 'http://sample.com/geoserver/ows';

//different color in layers
function getColor(d) {
    return d > 10000 ? '#FF0000' :
       d > 5000 ? '#FF9900' :
       d > 2000 ? '#E31A1C' :
       d > 1000 ? '#00FF00' :
       d > 500  ? '#FD8D3C' :
       d > 200  ? '#0000CC' :
       d > 100  ? '#FED976' :
                  '#FFEDA0';
}
function style(feature) {
    return {
        weight: 1,
        opacity: 3,
        color: 'white',
        dashArray: '3',
        fillOpacity: 3,
        fillColor: getColor(feature.properties.luas_tanah)
    };
}

var lyr_1 = new L.LayerGroup();
var lyr_2 = new L.LayerGroup();
var lyr_3 = new L.LayerGroup();
var lyr_4 = new L.LayerGroup();

var defaultParameters = {
    service : 'WFS',
    version : '1.0.0',
    request : 'GetFeature',
    typeName : 'pbb:view_map',
    maxFeatures: 1000,
    outputFormat : 'text/javascript',
    format_options : 'callback:getJson',
    SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);

var lyr_1 = new L.LayerGroup();
var ajax1 = $.ajax({
    type: 'GET',
    url : URL,
    dataType : 'jsonp',
    async: false,
    jsonpCallback : 'getJson',
    success : function (response) {
        console.log("Layer 1");
        L.geoJson(response, {
            style: function (feature) {
                return {
                    stroke: true,
                    color: getColor(feature.properties.luas_tanah),
                    opacity: 1,
                    weight: 1
                };
            },
            onEachFeature: function (feature, layer) {
                popupOptions = {maxWidth: 200};
                layer.bindPopup("D NOP :  " + feature.properties.d_nop
                    ,popupOptions);
            }
        }).addTo(lyr_1);
    },
    error: function (xhr, status) {
        alert("Failed call Layer A");
    }
});

var defaultParameters1 = {
    service : 'WFS',
    version : '1.0.0',
    request : 'GetFeature',
    typeName : 'pbb:view_map',
    maxFeatures: 1000,
    outputFormat : 'text/javascript',
    format_options : 'callback:getJson',
    SrsName : 'EPSG:4326'
};
var parameters1 = L.Util.extend(defaultParameters1);
var URL1 = owsrootUrl + L.Util.getParamString(parameters1);

var lyr_2 = new L.LayerGroup();
var ajax2 = $.ajax({
    type: 'GET',
    url : URL1,
    dataType : 'jsonp',
    async: false,
    jsonpCallback : 'getJson',
    success : function (response) {
        console.log("Layer 2");
        L.geoJson(response, {
            style: function (feature) {
                return {
                    stroke: true,
                    color: getColor(feature.properties.luas_tanah),
                    opacity: 0.8,
                    weight: 1
                };
            },
            onEachFeature: function (feature, layer) {
                popupOptions = {maxWidth: 200};
                layer.bindPopup("D NOP :  " + feature.properties.d_nop
                    ,popupOptions);
            }
        }).addTo(lyr_2);
    },
    error: function (xhr, status) {
        alert("Failed call Layer B");
    }
});

var defaultParameters2 = {
        service : 'WFS',
        version : '1.0.0',
        request : 'GetFeature',
        typeName : 'pbb:view_map',
        maxFeatures: 1000,
        outputFormat : 'text/javascript',
        format_options : 'callback:getJson',
        SrsName : 'EPSG:4326'
    };
var parameters2 = L.Util.extend(defaultParameters2);
var URL2 = owsrootUrl + L.Util.getParamString(parameters2);

var lyr_3 = new L.LayerGroup();
var ajax3 = $.ajax({
    type: 'GET',
    url : URL2,
    dataType : 'jsonp',
    async: false,
    jsonpCallback : 'getJson',
    success : function (response) {
        console.log("Layer 3");
        L.geoJson(response, {
            style: function (feature) {
                return {
                    stroke: true,
                    color: getColor(feature.properties.luas_tanah),
                    opacity: 0.8,
                    weight: 1
                };
            },
            onEachFeature: function (feature, layer) {
                popupOptions = {maxWidth: 200};
                layer.bindPopup("D NOP :  " + feature.properties.d_nop
                    ,popupOptions);
            }
        }).addTo(lyr_3);
    },
    error: function (xhr, status) {
        alert("Failed call Layer C");
    }
});

var defaultParameters3 = {
        service : 'WFS',
        version : '1.0.0',
        request : 'GetFeature',
        typeName : 'pbb:view_map',
        maxFeatures: 1000,
        outputFormat : 'text/javascript',
        format_options : 'callback:getJson',
        SrsName : 'EPSG:4326'
    };
var parameters3 = L.Util.extend(defaultParameters3);
var URL3 = owsrootUrl + L.Util.getParamString(parameters3);

var lyr_4 = new L.LayerGroup();
var ajax4 = $.ajax({
    url : URL3,
    dataType : 'jsonp',
    async: false,
    jsonpCallback : 'getJson',
    success : function (response) {
        console.log("Layer 4");
        L.geoJson(response, {
            style: function (feature) {
                return {
                    stroke: true,
                    color: getColor(feature.properties.luas_tanah),
                    opacity: 0.8,
                    weight: 1
                };
            },
            onEachFeature: function (feature, layer) {
                popupOptions = {maxWidth: 200};
                layer.bindPopup("D NOP :  " + feature.properties.d_nop
                    ,popupOptions);
            }
        }).addTo(lyr_4);
    },
    error: function (xhr, status) {
        alert("Failed call Layer D");
    }
});

var baseMaps = [
                {
                    groupName : "OSM Base Maps",
                    layers    : {
                        "OpenStreetMaps" : osmLayer
                    }
                }
        ];

var overlays = [
                {
                    groupName   : "Kecamatan",
                    expanded    : true,
                    layers      : {
                        "Layer A"     : lyr_1,
                        "Layer B"     : lyr_2,
                        "Layer C"     : lyr_3,
                        "Layer D"     : lyr_4
                    }
                }
        ];

var options = {
            container_width     : "300px",
            group_maxHeight     : "800px",
            exclusive           : true
        };

var control = L.Control.styledLayerControl(baseMaps, overlays, options);
map.addControl(control);

var legend = L.control({position: 'bottomright'});
    legend.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'info legend'),
            grades = [0, 100, 200, 500, 1000, 2000, 5000, 10000],
            labels = [],
            from, to;
        for (var i = 0; i < grades.length; i++) {
            from = grades[i];
            to = grades[i + 1];
            labels.push(
                ' ' +
                from + (to ? '–' + to : '+'));
        }
        div.innerHTML = labels.join('
');
        return div;
};
legend.addTo(map);

});
Now my problem is every time I open the page everything work just fine, but sometimes when I refresh the page everything breaks apart. For example some times "Layer A" data is displayed, some times data ends up on the wrong dataset. When I get this bug I get the following message in the console:
ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pbb%3Aview_map&maxFeatures=1000&outputFor…:1 Uncaught TypeError: getJson is not a function

On my research it seems that this type of error is quite common when running multiple AJAX calls. What I don't understand is why this error does not occur 100% of the time. What type of techniques can be used to fix it? I heard of Deffered Objects but could not apply it on my code, my expertise level on this is far from great. Although this may tend towards a GIS question I believe that this type of issue is more related to ordinary jQuery and Asynchronous calls.

A:
jsonpCallback Type: String or Function()  Specify the callback function
  name for a JSONP request. This value will be used instead of the
  random name automatically generated by jQuery. It is preferable to let
  jQuery generate a unique name as it'll make it easier to manage the
  requests and provide callbacks and error handling.

Don't use it.
Remove this line:

jsonpCallback : 'getJson',

When you have multiple requests in flight at once, their callback functions (since you are forcing them to use the same name) overwrite each other.

async: false

Making a synchronous request would resolve the problem (since you can't have multiple synchronous requests in flight at once (they queue)) … but they are:

*

*Horrible (they are deprecated in XHR on the main browser thread with good reason)

*Completely incompatible with JSONP (so your instruction is ignored).

You should remove the attempt to make the request synchronous too.


text:
Q: Python file with dot is getting run without my updates I am trying to run a file.py program. But when i run it through cmd with python3 file.py, I see in my text editor a new file called ".file.py" gets made and run instead. This file has none of my changes, so whatever I change to file.py is not run.
What is causing this?

A: first make sure you are in the directory where you have your file (use dir and it will show you all the files in the folder you are in) once you have done that just run python file.py and your program should run.
to make sure cmd is in the folder you want, put cmd in the bar above where the path to your current folder is shown.


text:
Q: Objective-C Database connection I have to realise a sort of Library in objective-C which help to store any object in a Database, with introspection. But I'm having some trouble with the database connection.
I found some tutorials to do this with SQLite on an iphone with Obj-C, but not on OSX in an application.
I would like to provide a Sqlite connection and a MySql connection (to meet the user's preference).  Is it possible to do this in an Objective-C command line tool ? If so, how?
Thank you!

A: Whoah.   That is a mighty big request;   there are entire companies devoted to nothing but object relational mapping layers.
There is no way that you can do this through introspection only with arbitrary objects.   First, there isn't enough metadata available at runtime to effectively serialize all types, much less map them to a database.   Secondly, even if there was, you still have to deal with exactly how much of the object graph to persist.
You really need some kind of modeling information that describes specifically the objects to be persisted, how they will be persisted, and how much of the object graph you need to persist.
I.e. you are effectively asking to re-invent EOF, the predecessor to CoreData, that provided a much more generic Object to Relational mapping layer.
To gain perspective on what you are asking, I'd suggest reading the first few chapters of the Enterprise Objects Framework Development Guide.
Core Data does provide an incremental storage API that would greatly simplify your implementation goals, but will require that you model your data layer properly as a Core Data model.

A: I dont know about MySql but about sqlite, you should use FMDB:
FMDatabase
FMDB can use for iOS, MAC OSX (arc and non-arc)
It's great framework.
Good luck


text:
Q: Nodejs variable route I have and variable nodejs route, I'm trying to use those values in the aggrerate function of mongodb using mongoose:
apiRoutes.get('/val6/:_level/:location', function(req, res) {

val6.aggregate([
    {
        $match:
            {
                [req.params.location]:true

            }
    },
    {
        $sample:{size:1}
    }
],
    function(err, val6) {
        res.json(val6);
    })
});

When I send a postman request, i get an random item with val2 set to true

When I add another condition to my match clause, like this:
$match:
{
  [req.params.location]:true,
  level:1
}

I get absolutely no matches, but in the same screenshot as above, the level is one. What am I doing wrong?
Edit one
$match:
{
   level:1,
   [req.params.location]:true

}

Switching the values seems to fix the problem (So i think it's a bug in general with computed javascript values) but leads me to the next problem that I was actually facing.
console.log(req.params.location);
console.log(req.params.level)

//logs 'val6' (location) and '1' (level)
using them inside the code like this, doesnt work:
$match:
{
   level:req.params.level,
   [req.params.location]:true

}

So hardcoded values work, but variable values don't. Anyone got a clue?


text:
Q: Active Record connect to SQL Server 2008 says no known event listeners I try to connet to SQL SERVER 2008 using active record and I get:
Failed to initialize ActiveRecords! ---> System.ArgumentException: The Listener of type .... does not implement any known NHibernate event listener interfaces.
Is this some problem in my business object declaration? It works well with other databases, Oracle, SQLite, etc...
<activerecord isWeb="false" isDebug="false">
      <config>
        <add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
        <add key="dialect" value="NHibernate.Dialect.MsSql2008Dialect" />
        <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
        <add key="connection.connection_string" value="Data Source=SQLSERVER;Initial Catalog=HFPMDB;User ID=db_owner;Password=HFPMAdmin;" />
        <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
      </config>
    </activerecord>

A: Looks like I added an extra assembly to the "ActiveRecordAssemblies".
The assembly did not contain any Active Record attributes and etc, so that was the reason.


text:
Q: Force SpingBoot to use Gson over Jackson I am trying to force SpringBoot to use Gson instead of Jackson. I've read most of the articles I've found online and I am still seeing Jackson being used.  Here's what I've done

*

*Added

spring:
  http: { converters: { preferred-json-mapper: gson } }
  mvc: { converters: {preferred-json-mapper: gson } }

in application.yaml

*Updated POM

*

*Added gson dependency

*Added jackson-databind to exclusion list in spring-boot-starter-web depedency.

*Added @EnableAutoConfiguration(exclude = JacksonAutoConfiguration.class) to main class.

*Written below @Configuration class:

@Configuration
@Slf4j
public class MyConfig implements WebMvcConfigurer {

  @Override
  public void extendMessageConverters (List<HttpMessageConverters<?>> converters) {
    log.debug("Setting gson converter");
    converters.add(new GsonHttpMessageConverter(myCustomGsonInstance()));
  }

  public Gson myCustomGsonInstance() {
    return new Gson();
  }
}

When running tests in debug, I can see that Jackson is still listed in the HttpMessageConverters list and Gson is not.

Update:
This behavior is seen while running live and in the below test class.
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = MOCK)
@ExtendWith(MockitoExtension.class)
public class MyTestClass {

  @Autowired
  private MyController controller;

  private MockMvc mockMvc;

  @BeforeEach
  public void setUp(){
    mockMvc = MockMvcBuilders.standaloneSetup(controller)
    // .setMessageConverters(new GsonHttpMessageConverter(myCustomGsonInstance())) // if I add this, the test passes.
    .build();
  }

  @Test
  public void happyFlow(){
    // given
    URI uri = "/test/uri";
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    // when
    String responseBody = mockMvc.perform(get(uri).headers(headers)).andReturn().getResponse().getContentAsString();

    // then
    assertThat(responseBody, wasSerializedByGson());
  }
}

A: It looks like you're using the wrong property for configuring the preferred JSON mapper. You are using spring.http.converters.preferred-json-mapper but the correct property is spring.mvc.converters.preferred-json-mapper. In application.yaml, that would be the following:
spring:
  mvc:
    converters:
      preferred-json-mapper: gson

A: Spring Boot comes with Gson Auto Configuration support: Source Code
So you have to Autowire the Gson singleton instance to be used by your WebMvcConfigurer in addition to enabling the yaml property:
@Configuration
@Slf4j
public class MyConfig implements WebMvcConfigurer {

  @Autowired
  private Gson gson;

  @Override
  public void extendMessageConverters (List<HttpMessageConverters<?>> converters) {
    log.debug("Setting gson converter");
    converters.add(new GsonHttpMessageConverter(gson));
  }

}

And the yaml properties borrowed from Andy Wilkinson:
spring:
  mvc:
    converters:
      preferred-json-mapper: gson

With this setup Spring MVC is using the same Gson instance as the one Autowired in your configuration.
And in your test, it should look like this:
@WebMvcTest(MyController.class)
public class MyTestClass {

  @Autowired
  private MockMvc mockMvc;
  @Autowired
  private MyController controller;

  @Test
  public void happyFlow(){
    // given
    URI uri = "/test/uri";
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    // when
    String responseBody = mockMvc.perform(get(uri).headers(headers)).andReturn().getResponse().getContentAsString();

    // then
    assertThat(responseBody, wasSerializedByGson());
  }
}


text:
Q: Display Prompt with universal app when using NavigationHelper hangs? I'm using the NavigationHelper class in my Universal App and I've enabled the BackPressed event at the application level
#if WINDOWS_PHONE_APP
    private async void HardwareButtons_BackPressed(object sender,
    Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
     ...
    }
#endif

In my HardwareButtons_BackPressed event, I want to prompt the user as to whether or not they are sure they want to quit the application by calling the following code:
UICommand ans = await this.GetLocatorViewModel.
DialogService.ShowMessagePrompt("Are you sure you want to quit?");

//NOTE: The validation below is not the complete code as I've removed
//the usage of my Enum for testing purpose but I would check the
//ans.Id
if (!object.ReferenceEquals(ans, null))
{
  e.Handled = true;
}

I'm using the standard async method to display the prompt and it's defined as follows:
    public async Task<Object> ShowMessagePrompt(string content)
    {
        MessageDialog msgbox = new MessageDialog(content);

        msgbox.Commands.Clear();
        msgbox.Commands.Add(new UICommand { Label = "Yes", Id = 0 });
        msgbox.Commands.Add(new UICommand { Label = "No", Id = 1 });

        return await msgbox.ShowAsync();
    }

If I use with the above code, as it is called from the NavigationHelper class asynchronously, it continues on with the code and still closes the app.
If I use the msgbox.ShowAsync().Result:
object ans = this.GetLocatorViewModel.DialogService.ShowMessagePrompt("Are you sure you want to quit?").Result;
it displays the prompt ok, but once I tap Yes or No, it closes the prompt but it causes my app to hang and any code after it doesn't get executed i.e. checking for the prompt's result, etc...
Any idea how I can resolve this?
Thanks.

A: Set the e.Handle to true before you show the message dialog.


text:
Q: Oracle data insertion strange behavior. Data is truncating while inserting I am using oracle database as back end of one of my projects.
I have a table which has a ADDRESS_TYPE column nvarchar(3)
In some scenarios the system trying to insert a text  'Business' into the column ADDRESS_TYPE. When I try it from the local it is showing an error like the value is too large for the column, this one is an expected result. But the same code I have deployed in QA and Production but in both cases the data got inserted as 'Bus' so the text 'Business' got truncated and it only inserts 'Bus'. My local instance and the QA instance pointing to the same Database.
var data= new MYTABLE();
 data.ADDRESS_TYPE= 'Business';
 context.MYTABLE.AddObject(data);
 context.SaveChanges();

Note : I am using Entity framework.
I have tried to insert/update the data directly into the database and I am getting the error value is too large for column. This behavior only happen in the hosted sites. I am planning to put a log on the code for getting more idea , but before that I thought of asking here , so if anyone faced the same situation then they might can help me I guess.
I have tried to do the same operation locally using release mode there also getting the exception
Anyone have any idea/suggestions so that I can investigate on that way.


text:
Q: Fix dns on ubuntu 16.04 I did something to mess up my DNS on my virtual ubuntu 16.04 box.  Can you help me diagnose what the problem is and get DNS working again.  I am able to connect to servers using an ip address.  However, when I use hostnames, my box can't resolve them.  This used to work - I did something to mess it up, but don't remember what file I edited.
ubuntu version:
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.7 LTS
Release:    16.04
Codename:   xenial

Here's the problem using a hostname:
  root@ubuntu:/etc/dhcp# curl -vvv http://example.com
  * Rebuilt URL to: http://example.com/
  * Could not resolve host: example.com
  * Closing connection 0
  curl: (6) Could not resolve host: example.com

I can connect to example.com using an ip address.  I truncated the response because it's not relevant.  The point is that I am definitely connected to the internet.  My problem is that DNS is messed up.
curl -H "Host: example.com" "http://93.184.216.34"
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;

Here's my dns server:
nmcli dev show | grep DNS
IP4.DNS[1]:                             172.16.217.2

Which seems to work:
dig @172.16.217.2 example.com

; <<>> DiG 9.10.3-P4-Ubuntu <<>> @172.16.217.2 example.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42927
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 2

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; MBZ: 0005 , udp: 1220
;; QUESTION SECTION:
;example.com.           IN  A

;; ANSWER SECTION:
example.com.        5   IN  A   93.184.216.34

;; ADDITIONAL SECTION:
example.com.        5   IN  TXT "ETPA"

;; Query time: 184 msec
;; SERVER: 172.16.217.2#53(172.16.217.2)
;; WHEN: Tue Mar 09 14:45:02 EST 2021
;; MSG SIZE  rcvd: 84

My resolve.conf file might have a problem:
root@ubuntu:/etc/dhcp# ls -latr /etc/resolv.conf
lrwxrwxrwx 1 root root 37 Jan  5 12:21 /etc/resolv.conf -> /run/systemd/resolve/stub-resolv.conf
root@ubuntu:/etc/dhcp# ls -latr /run/systemd/resolve/stub-resolv.conf
ls: cannot access '/run/systemd/resolve/stub-resolv.conf': No such file or directory

The "host" command fails
root@ubuntu:/etc/dhcp# host -v -d example.com
Trying "example.com"
;; connection timed out; no servers could be reached

So, why won't curl or my browser or anything work with hostnames?  What should I do to diagnose and fix?

A: This was the key problem; resolv.conf pointed to a non-existent file.
root@ubuntu:/etc/dhcp# ls -latr /etc/resolv.conf
lrwxrwxrwx 1 root root 37 Jan  5 12:21 /etc/resolv.conf ->   /run/systemd/resolve/stub-resolv.conf
root@ubuntu:/etc/dhcp# ls -latr /run/systemd/resolve/stub-resolv.conf
ls: cannot access '/run/systemd/resolve/stub-resolv.conf': No such file or  directory

The fix was to point it to an existing file:
ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf

A: From your posted results follows that name server @ 172.16.217.2 works correctly, but it was not clear if it was used for address resolution.That's why I asked about /etc/resolve.conf that is the place where system looks for name server(s) to be used.
It looks like some systemd services broke this file (I have /etc/resolv,conf -> /var/run/resove.conf on Kubuntu 20.04).
Packages resolveconf and  resolveconf-admin may help do deal with such problems.


text:
Q: Parallel compilation for projects with dependencies on each other in Visual studio In my company we are using Visual Studio 2013 and we would like to reduce the build times of our C++ solution. It is about 55 projects and it takes roughly 20 minutes for a debug build and a lot more for a release build. I am wondering if there is a way to make projects with dependencies on each other compile in parallel. I am already aware and make use of multiprocess compilation (/MP flag). Indeed, each project in the solution is built using multiple cores. Aslo when two projects, let's say A and B, don't depend on each other they build in parallel. However with our current settings, if A depends on B, the build of B has to complete before A starts. As far as I understand, compilation of files in A can start even before B finishes, and only linking of A has to really wait until B finishes (let's assume that A generates either a .dll or an .exe). Is there a way to achieve this? If not possible in VS2013, we soon plan to upgrade to VS2017, so suggestions about VS2017 are also useful.

A: The C++ compiler switch /MP is for compiling cpp files in parallel. This is on a per project basis. This will not however get all the projects to build in parallel. To do that you have to pass in -M[:num] or -maxcpucount (max cpu count) to msbuild.exe. (see https://msdn.microsoft.com/en-us/library/ms164311.aspx for details)
In answer to your first question: "if there is a way to make projects with dependencies on each other compile in parallel".
The answer is kinda.
If the two projects that depend on each other, are in a solution and the dependencies between each other are clearly marked, then the cpp files can compile simultaneously, but not link simultaneously. The linking must occur in order of how they depend on one another.
So in general you want as few dependencies as possible between your projects if you want to make things compile faster. But there are other ways to make C++ compile faster.
As for VS 2017, Run don't Walk to upgrade.


text:
Q: Angular nesting same controller Hi is it a good practice to have controller within a controller in angular?
For Example:
The body tag of my html has a controller called "CommonCtrl" within the html tag i'm loading a template using includes and inside the template i reuse the same controller.
Code:
Index.html

show this div

header.html

 Already registered? Sign In
     Need an account? Create account

A: You don't need to use ngController in header.html, Just remove the following line from header.html


text:
Q: Make parallel concurrent calls to external apis from django I have a django app (django+python+apache mod_wsgi) which act as a middleware between two systems, app gets requests from one system and it makes multiple requests to other apis to fetch and prepare the desired response, and then it passes the response to the requesting system.
So it's basically acting as a one-to-many middleware, problem is making calls sequentially is taking too much time, I tried to use threading for IO concurrency. However this is not working (I've read django works on single thread; correct me if I'm wrong), I've not worked with making requests in parallel on a webserver and have no idea how to do it.
Following is the current implementation :
   with futures.ThreadPoolExecutor(max_workers=MAX_BATCH_SIZE) as executor:
        future_to_url = {}
        for pnode in plist_node:
            config = {'url':rurl}
            futur = executor.submit(self.get_result_from_url, config)

Can someone please suggest the right way to do this ?


text:
Q: C++ constant reference in compare method on different platforms I have this piece of c++ code for sorting a struct,
const bool operator<(P& p) const {
  //...
}

It compiles without any problem on a linux device with "gcc 4.9.2".
But if try it on a windows machine with "gcc 4.7.1" (the one that comes with Code::Blocks 13.12), it gives nasty errors that you can see here http://pastebin.com/S28tD9kc
For compiling in both cases I've used: "g++ -std=c++11"
If I change "operator<(P& p)" to "operator<(const P& p)" it magically works. OK no problem I've made some mistake, but why does the first one not work on a windows machine if it works on a linux machine without any sign of problem?
An example.

A: This is probably because in those gcc versions sort is implemented differently. I have checked under VS2005 and it also produces such errors, but from looking into my stl implementation - I see lots of const T& parameters used when sorting. This will cause the same error you see if operator< is used with no const& parameter. I was able to compile such code using custom comparator and const_cast:
struct my_comp {
 bool operator() (const P& a, const P& b) const {
   return const_cast<P&>(a).operator<(const_cast<P&>(b));
 }
};
std::vector<P> pp(10);
std::sort(pp.begin(), pp.end(), my_comp());

I am not sure if this is correct code,just wrote it for compile experiment.
On the other hand, under Visual Studio 2015 it all compiles fine with non const parameter in operator<. In VS2015 sort uses move semantics, and this is what I suppose makes it compile.


text:
Q: How to make a horizontal scrolling area for left-floating element? I want this outer
 to scroll in the x-axis only, but it's not working.

.wrapper {
  width: 98%;
  height: 320px;
  padding-left:1%;
  padding-right:1%;
  white-space: nowrap;
  overflow-y: hidden;
  overflow-x: scroll;
  -webkit-overflow-scrolling: touch;
  background-color: #fff;
  float:left;
  position:absolute;
}

.internal {
  width:250px;
  height:320px;
  display: inline;
  background-color: wheat;
  float:left;
  position:static;
}

item 1

item 2

item 3

item 4

item 5

item 6

item 7

On my screen, it renders as:

What is wrong?

A: First, your code is a bit of a mess.  You have a bunch of overriding rules in the same selector.
You need to wrap your items in an inner container thats set to a larger size than the wrapper.  Here is your code, cleaned up:
http://jsfiddle.net/aLysdueo/
HTML:

item 1

item 2

item 3

item 4

item 5

item 6

item 7

CSS:
.wrapper {
    width: 98%;
    height: 320px;
    overflow-y: hidden;
    overflow-x: scroll;
}
.container {
    width: 1500px;
    height: 320px;
}

.internal {
    float:left;
    width:250px;
    height:320px;
    background-color: wheat;
}


text:
Q: Change a folder's icon with a custom right click menu I try to make a custom right click menu that allows me to set a folder's custom icon using whatever folder.ico I put in that folder.
My way so far:
Have a right click menu on folders that runs a batch file (done thanks to this topic):
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\set_folder_icon]
@="Set folder icon"

[HKEY_CLASSES_ROOT\Directory\shell\set_folder_icon\command]
@="\"C:\\path\\set_folder_icon.bat\" \"%1\""

For the bat file, I fail to make it work. I fear this is because I can't get it to pickup the folder I right click on.
I based my work from this topic:
rem @echo off
set O=desktop.old
set F=desktop.ini
FOR /R %%I IN (*.ico) DO @(
cd%%~pI
if exist %%~dpnfolder.ico (
echo %%~dpnfolder.ico
attrib -h -s %F%
copy /Y %F% %O%
echo [.ShellClassInfo] > %F%
echo IconResource=folder.ico,0 >> %F%
echo [ViewState] >> %F%
echo Mode= >> %F%
echo Vid= >> %F%
echo FolderType=Generic >> %F%
attrib +h +s %F%
)
)
pause

I'd like to just check if folder.ico exists, edit desktop.ini or create it entirely if it doesn't exist (I don't know if the current bat can do that), and ideally (but not mandatory) not edit the other options that might be there already.

A: @echo off

setlocal EnableExtensions
title <nul && title ..\\%~nx0
%__AppDir__%chcp.com 1252 >nul

set "_bat=%~dpnx0" & %__AppDir__%mode.com 40,02
set "_key=HKCR\Directory\shell\Set_Folder_Icon"

set "_reg_qry=%__AppDir__%reg.exe query "%_key%""
set "_ico_reg=%SystemRoot%\System32\shell32.dll,71"
set "_bat=%_bat:\=\\%" & set "_ico_reg=%_ico_reg:\=\\%"

>nul 2>&1 ( %__AppDir__%net.exe "session" && set "_adm=y" || set "_adm=n"
      %_reg_qry%|%__AppDir__%find.exe "_" && set "_reg=y" || set "_reg=n")

if /i "%_adm%|%_reg%" == "y|n" >nul 2>&1 (
    ( %__AppDir__%reg.exe add "%_key%" /ve /d "Set Folder Icon" /f
      %__AppDir__%reg.exe add "%_key%\command" /ve /d "\"%_bat%\" \"%%V\"" /f
      %__AppDir__%reg.exe add "%_key%" /v Icon /t reg_sz /d "\"%_ico_reg%\"" /f
    )&& goto %:^))else if /i "%_adm%|%_reg%" == "n|n" (set "_er=y" && goto %:^|
    )else if "%_adm%%_reg%" == "yy" (set "_er=n" && goto %:^|)else ;set "_er=n"

%:^)
2>nul cd/d "%~dpnx1\\." && %__AppDir__%Attrib.exe -r -a .\. || goto %:^|

if exist .\\Folder.ico (%__AppDir__%Attrib.exe -s -r -h +a .\\Folder.ico
    )else if exist .\\*.ico (for %%i in (.\\*.ico)do ren "%%~fi" Folder.ico & goto %:^/
    )else goto %:^| )

%:^/
if exist .\\Desktop.ini >.\\Desktop.old (
     %__AppDir__%Attrib.exe -s -r -h +a .\\Desktop.ini
     echo;[.ShellClassInfo] && echo;IconResource=Folder.ico,0
     %__AppDir__%Findstr.exe /bliv "\[\.Shell IconR IconF IconI" <.\\Desktop.ini
    )else >nul 2>&1 %__AppDir__%CertUtil.exe -decode -f "%~dpnx0" .\\Desktop.ini

if exist .\\Desktop.old >nul 2>&1 move/y .\\Desktop.old .\\Desktop.ini

%:^|
if "%_er%" == "y" (%__AppDir__%timeout.exe 5|echo\Admin rights required!
    )else if "%_er%" == "n" (%__AppDir__%Attrib.exe +s +r +h -a .\\Desktop.ini
     <con: %__AppDir__%Attrib.exe -r +a .\. && %__AppDir__%Attrib.exe +r -a .\.
     <con: cd../ && %comSpec% /e:off/v:off/s/q/r "ren "%~dpnx1" "%~nx1" >nul 2>&1"
    )>nul 2>&1 else rem :: batch continue.

2>nul del/q /f /a "%~f1\Desktop.old" & endlocal & <con: move nul 2>&0 ||goto :eOf
::-----BEGIN -----Wy5TaGVsbENsYXNzSW5mb10gDQpJY29uUmVzb3VyY2U9LlxGb2xkZXIuaWNvLDA
NCltWaWV3U3RhdGVdDQpNb2RlPQ0KVmlkPQ0KRm9sZGVyVHlwZT1HZW5lcmljDQo=-----END -----::

This code considers:

*

*That you are going to put the bat in the folder where it should be, where it will always be called.

*Will run a first time (as an administrator) so that the necessary entries in the Windows registry are added, (by the bat itself) and pointed to the location of to your File.bat.

*The following executions will be right click menu, in the target folder

*If a Folder.ico file is in the target folder, it will be used, in the absence, another icon file will be used, and renamed to Folder.ico

*When a Desktop.ini file exists in the target folder, the necessary edits will be made to replace the .ico file, if not, a new one will be created.

1. Run a first time as admin, and it will add all the entries to the Windows registry.
2. Execute (click/prompt), without informing a valid folder as parameter, and it will abort.
3. Informing a valid folder, and it will check if a Folder.ico icon is present and will use it, if it does not exist, it will use another one that is in the same folder.
4. If the informed folder does not contain an icon, it will abort without warnings.
5. If the folder has a \Desktop.ini, it will use all the settings, except those related to icon options.
6. If the folder does not contain >\Desktop.ini, it will create one using decoding a standard file saved in itself in base64 strings.

*

*The .\Desktop.ini defaults to folders that do not contain configuration.

[.ShellClassInfo]
IconResource=.\Folder.ico,0
[ViewState]
Mode=
Vid=
FolderType=Generic

*

*Base64 encoded .\Desktop.ini:

-----BEGIN CERTIFICATE-----
Wy5TaGVsbENsYXNzSW5mb10gDQpJY29uUmVzb3VyY2U9LlxGb2xkZXIuaWNvLDAN
CltWaWV3U3RhdGVdDQpNb2RlPQ0KVmlkPQ0KRm9sZGVyVHlwZT1HZW5lcmljDQo=
-----END CERTIFICATE-----

*

*Base64 encoded .\Desktop.ini strings in the bat/code:

::-----BEGIN -----Wy5TaGVsbENsYXNzSW5mb10gDQpJY29uUmVzb3VyY2U9LlxGb2xkZXIuaWNvLDA
NCltWaWV3U3RhdGVdDQpNb2RlPQ0KVmlkPQ0KRm9sZGVyVHlwZT1HZW5lcmljDQo=-----END -----::
Note: Assign the icon to the folder, some displays immediately, others after a few seconds, the same seems to happen also when we change the wallpaper via the Windows registry/command line...
Obs.: CertUtil.exe already comes with Windows

A short answer, where the presence of registry entries are ignored, would be...
@echo off

setlocal EnableExtensions
%__AppDir__%mode.com 40,02
%__AppDir__%chcp.com 1252 >nul

2>nul cd/d "%~f1\\." || goto %:^|
if not exist ".\\Folder.ico" goto %:^|
<con: %__AppDir__%Attrib.exe -r -a .\.

if exist .\\Desktop.ini >.\\Desktop.old (
     %__AppDir__%Attrib.exe -s -r -h +a .\\Desktop.ini
     echo;[.ShellClassInfo] && echo;IconResource=.\Folder.ico,0
     %__AppDir__%Findstr.exe /bliv "\[\.Shell IconR IconF IconI" <.\\Desktop.ini
    ) else >nul 2>&1 %__AppDir__%CertUtil.exe -decode -f "%~dpnx0" .\\Desktop.ini

if exist .\\Desktop.old >.\\Desktop.ini %__AppDir__%findstr.exe . <.\\Desktop.old

if exist .\\Folder.ico if exist .\\Desktop.ini (
     %__AppDir__%Attrib.exe -r +a .\.
     %__AppDir__%Attrib.exe +r -a .\.
     %__AppDir__%Attrib.exe +r -a .\\Folder.ico
     %__AppDir__%Attrib.exe +s +r +h -a .\\Desktop.ini
     >con: cd..\ && %comSpec% /e:off/v:off/q/r "ren "%%~dpnx1" "%%~nx1". 2>nul")

%:^|
2>nul del/q /f /a "%~f1\Desktop.old" & endlocal & <con: move nul 2>&0 ||goto :eOf
::-----BEGIN -----Wy5TaGVsbENsYXNzSW5mb10gDQpJY29uUmVzb3VyY2U9LlxGb2xkZXIuaWNvLDA
NCltWaWV3U3RhdGVdDQpNb2RlPQ0KVmlkPQ0KRm9sZGVyVHlwZT1HZW5lcmljDQo=-----END -----::

This code considers:

*

*That the entries in the registry have been made, and the path of the bat file is set in the registry correctly.

*A Folder.ico file already exists in the destination folder.

*If Desktop.ini is not in the target folder, a new one will be created, if it exists, the relevant edits to the Folder.ico file will be made in the existing Desktop.ini.

*

*The Set_Folder_Icon.reg file looks like:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon]
@="Set Folder Icon"
"Icon"="\"C:\\\\WINDOWS\\\\System32\\\\shell32.dll,71\""

[HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon\command]
@="\"F:\\\\2020-SU\\\\Q1635169\\\\Q1635169.cmd\" \"%V\""

; Just replace drive and folder\file name...

*

*The Remove_Set_Folder_Icon.reg file looks like:

Windows Registry Editor Version 5.00

[-HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon]

*

*To add register entries in command line, run as admin:

%__AppDir__%reg.exe add "HKCR\Directory\shell\Set_Folder_Icon" /ve /d "Set Folder Icon" /f
%__AppDir__%reg.exe add "HKCR\Directory\shell\Set_Folder_Icon\command" /ve /d "\"F:\\2020-SU\\Q1635169\\Q1635169.cmd\" \"%V\"" /f
%__AppDir__%reg.exe add "HKCR\Directory\shell\Set_Folder_Icon" /v Icon /t reg_sz /d "\"C:\\WINDOWS\\System32\\shell32.dll,71\"" /f

rem ::  Just replace F:\\2020-SU\\Q1635169\\Q1635169.cmd\"
rem ::  To the pertinent Drive:\\Folder\\Path\\To\\File\\Name.cmd

*

*To delete the register entries in command line, run as admin:

reg delete HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon /f

*

*You also can use a .cmd instead .reg file to add all entries in the Windows Register

*

*Save the contents below as File.cmd, and run as an administrator to add the registry entries.

Windows Registry Editor Version 5.00 2>nul

;The following line/commands run and add the current file by "itself"
;@(cls & %__APPDIR__%reg.exe import "%~f0" >nul 2>&1 & goto=:EOF )

[HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon]
@="Set Folder Icon"
"Icon"="\"C:\\\\WINDOWS\\\\System32\\\\shell32.dll,71\""

[HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon\command]
@="\"F:\\\\2020-SU\\\\Q1635169\\\\Q1635169.cmd\" \"%V\""

; Just replace drive and folder\file name...

*

*To do the same for remove all entries in the Windows Register

Windows Registry Editor Version 5.00 2<nul

;The following line remove HKCR\...\Set_Folder_Icon
;@(cls & %__APPDIR__%reg.exe import "%~f0" >nul 2>&1 & goto=:EOF )

[-HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon]

*

*Some further reading:

*

*If /?

*Set /?

*For /?

*For /F /?

*Attrib /?F

*Findstr /?

*Goto | Call :Label

*Redirection |, <, > 2>, ...

*DOS - String Manipulation

*Conditional Execution || && ...

*CertUtil /dostips.com

*Unicode, UTF, ASCII, ANSI format differences

*Base64 Encode or Decode (MacOS/Windows/Linux)
How does the Windows Command Interpreter cmd.exe Parse Scripts
How-to: Escape Characters, Delimiters and Quotes at the Windows command line


text:
Q: How to properly synchronize a list being accessed by multiple threads? I have a list that is being updated on one thread every 20 ms and being read on another thread every 16 ms. I have heard that in a case such as this it is generally better to use a synchronized list and not a copyonwritearraylist, correct?
Should I initialize this list originally as
List<Object> list = Collections.synchronizedList(new ArrayList<Object>());

?
Or should I make it a regular list and then every time i want to read from it use a method such as
public List<Object> synList(ArrayList<Object> list) {
    return Collections.synchronizedList(list);
}

Sorry if this is trivial, I'm really not sure. Thank you so much

A:
I have a list that is being updated on one thread every 20 ms and being read on another thread every 16 ms. I have heard that in a case such as this it is generally better to use a synchronized list and not a copyonwritearraylist, correct?

Yes.
CopyOnWriteArrayList is only really useful when you have way more reads than write, so the cost of copying the list is offset by the faster reads.
You have roughly the same number of writes and reads, so this doesn't apply.

Should I initialize this list originally as List<Object> list = Collections.synchronizedList(new ArrayList<Object>()); ? or should I make it a regular list and then every time i want to read from it use a method...

The second one is useless.
A synchronized list is only useful if all accesses to the underlying list are also synchronized on the same thing; basically, the only safe way to use it is to immediately wrap the list on creation, i.e. the first way.


text:
Q: How to download multiple files from firebase using downloadURL in javascript? I have this code:
 fetch("/downloadFiles?" + new URLSearchParams({ items: currCart })) // fetching from my server all the download urls
.then((res) => res.json())
.then((data) => { // data is returned as an object - {items: [array of urls]}
data.items.forEach((element, index) => {
  var link = document.createElement("a");
  link.download = currCart[index];
  link.href = element;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  });
})}

but instead of downloading the files it opens them in my browser.
The currCart[index] is just the wanted name of the downloaded file.
Any suggestions?

A: To download a file, we need to create a Cloud Storage reference to the file we want to download, to do that, you can create a reference by appending child paths to the root of your Cloud Storage bucket to then, download data via URL calling the getDownloadURL() method on a Cloud Storage reference.
If you want to download data directly from the SDK
(from version 9.5 and higher) it already provides these functions for direct download using getBlob(), getStream() available only in Node.js, getBlob() only for browser-like environments.
But if you need to download data directly in the browser, you must configure your Cloud Storage bucket for cross-origin access (CORS). Add this JSON to a file named cors.json.
[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

To deploy these restrictions and set your bucket, run the following command:
$ gsutil cors set cors.json gs://<your-cloud-storage-bucket>

JS file
import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

// Get the download URL
getDownloadURL(starsRef)
  .then((url) => {
    // <---------------- Insert url file here!
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

Doesn't matter what format you want to use, just insert the URL or the reference link (PDF,  GIF, image, video, etc) of the file we want to show inside the function getDownloadURL() and same process with the .

PDF file for example in HTML document is  tag with href attribute for the url or path if you are self hosting the file:

<!DOCTYPE html>

    <title>Title of the document</title>

PDF Example

Download PDF file here


text:
Q: Meaning of "down beside" in this context In a book of children's poem I found:

Twenty froggies went to school
  Down beside a rushy pool,
  .........

Being a learner I am having trouble understanding the need for the word down with beside.
Is it here for making the line look good?
Please explain the usage of down here.
Thanks in advance.

A: This is a very interesting question and perhaps one which should be migrated to English Language & Usage.
The OED sense 3 of the adverbial uses of down says the following:

*a. Without connotations of descent through space. To or at a place or locality regarded as lower in position; in a southerly direction or
position; to or at a distance from the capital or other centre.

Now this does not explain the down which you have identified - though it is starting to get close to it. However, sense 3c says:

3c. Preceding a prepositional phrase of place, without the implication
that this is lower in position or further south: at a moderate
distance from a point of reference; off, away.

A couple of examples may help explain this:

1970   A. Buzo Front Room Boys i, in Plays 20   If I were one of the back room boys, you wouldn't see me here before noon. I'd be down by
the pool.
2010   Times 11 Dec. (Sat. Review section) 1  He was an enthusiastic
reader, down at the local library three times a week.

It sort of carries an implication of being away from where one might usually be - often suggesting at leisure. It may be difficult for a non-native speaker to understand, but if you need further help I will let you have some more examples.

A: There is, as you indicate, some latitude given in poetry so that the rhythm, etc., sound good. I think part of good poetry is making the words natural regardless, but that's a different topic.
I've always taken "down" in this sort of use to mean that the pond was slightly downhill of its surroundings; either it's in a hollow of sorts or just behind a hill or something. Bodies of water are usually downhill of their surroundings in some dimension and to some extent; that's why the water collects there.


text:
Q: How can I create a 3D-grid in 3DS Max? I have been trying to develop a 3D data-visualization software, and now I need to find a way of quickly generating 3D grids in 3DS Max to use like a 3d-chart reference scale-map. I am new to 3DS but it is what I use to generate the objects I work with on the engine.
Is there any simple way of generating such "cage"?
Thank you.

A: 3ds Max has "grid" helper objects that should serve your purpose.
See "Autodesk 3ds Max Help > Precision and Drawing Aids > Helpers  > Standard Helper Objects > Grid Helper" in the user help.
Programmatically you can create and manipulate grid helper objects using MAXScript with the "grid" command. Search the MAXScript help for "grid".


text:
Q: How to link subdirs lib with QMake? I have a Qt project (called "scanner") built with QMake, where I have 2 subprojects : a static library called "scannerlib" and an application using that lib, called "app" (which, at the moment, is just a main.cpp file)
My "scanner" folder contains the file scanner.pro :
QT += core testlib
QT -= gui

CONFIG += c++14
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = subdirs

SUBDIRS = app scannerlib

app.depends = scannerlib

And two subfolders, containing a .pro file and source file related.
scannerlib/scannerlib.pro :
TARGET = scannerlib
TEMPLATE = lib
CONFIG += staticlib

#I ommited SOURCES and HEADERS here for brevity

app/app.pro :
TARGET = app
TEMPLATE = app
SOURCES = main.cpp
INCLUDEPATH += ../scannerlib
LIBS += -L../scannerlib -lscannerlib

I successfully build libscanner, but I can't link it in "app".

error : cannot find -lscannerlib

After checking, libscannerlib.a has been successfully built, so it should not be a problem.
If I remove -lscannerlib, I get an undefined reference. Which seems legit.
I can get a successful build if I move the created "libscannerlib.a" from the build folder to scanner/scannerlib, which allows qmake to find it.
So, the problem looks like it comes from "-L../scannerlib". What should I put there in such a way that qmake find the lib in the build folder ?

A: You may use DESTDIR in your both scannerlib and app projects.
scannerlib/scannerlib.pro :
TARGET = scannerlib
TEMPLATE = lib
CONFIG += staticlib
DESTDIR = ../bin

app/app.pro :
TARGET = app
TEMPLATE = app
SOURCES = main.cpp
DESTDIR = ../bin
INCLUDEPATH += ../scannerlib
LIBS *= -L$$OUT_PWD/$$DESTDIR -lscannerlib


text:
Q: Get specific pixel colour Javascript I am trying to write a scroll to top chrome extension that can automatically detect the colour scheme of the website that it is being placed on.
I thought that the best way to do this was by grabbing the very first (top left) pixel on the page and getting the colour of it.
I've searched around SO and found how to do it with an image which means that I could grab a screenshot of the page and just process the image, however I was hoping that there is a much more sophisticated way to do this. The search lead me here:
How to get a pixel's x,y coordinate color from an image?
I can include JS packages to do this but I can't seem to find any that can do the specific task that I want.
I currently use jQuery in my project so I can use either or to do this.


text:
Q: Queueing Analysis Arrival Rate Gamma distribution I want to write a program in python that simulates a queueing system.
I have a G/M/1 queue.
For the service time, I chose expovariate(1.0).
For the interarrival time, I chose gammavariate(2.0,a).
I change a to different values to make a curve about the arrival rate.
But what is the arrival rate of that distribution?
I know that the arrival rate $\lambda$ equals $\frac{1}{E[A]}$, with A the interarrival time. However what is the mean of this interarrival time, if it is a gamma distribution like gammavariate(2,a) in python?


text:
Q: regarding a py4j exception I have installed Java 11 and Python 3 on CentOS. Trying to run a code that worked perfectly fine on a Windows environment. Getting this exception:
ERROR:root:Exception while sending command.
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/py4j/java_gateway.py", line 1188, in
send_command
raise Py4JNetworkError("Answer from Java side is empty")
py4j.protocol.Py4JNetworkError: Answer from Java side is empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/py4j/java_gateway.py", line 1014, in send_command
response = connection.send_command(command)
File "/usr/lib/python3.4/site-packages/py4j/java_gateway.py", line 1193, in send_command
"Error while receiving", e, proto.ERROR_ON_RECEIVE)
py4j.protocol.Py4JNetworkError: Error while receiving
Traceback (most recent call last):
File "WordInformation.py", line 493, in
status = read_from_source("../Corpora/Bhandarkar Oriental Research Books")

File "WordInformation.py", line 473, in read_from_source
author, year)
File "WordInformation.py", line 381, in fetch_from_hwn
return read_store_properties(word, file, sentence, source, category, author,
year);
File "WordInformation.py", line 79, in read_store_properties
properties["synsets"] = get_other_props(word)
File "WordInformation.py", line 226, in get_other_props
output = gateway.jvm.Properties.getProperties(word)
File "/usr/lib/python3.4/site-packages/py4j/java_gateway.py", line 1286, in
call
answer, self.gateway_client, self.target_id, self.name)
File "/usr/lib/python3.4/site-packages/py4j/protocol.py", line 336, in
get_return_value
format(target_id, ".", name))
py4j.protocol.Py4JError: An error occurred while calling
z:in.ac.iitb.cfilt.jhwnl.examples.Properties.getProperties

Initialised the gateway as follows:
gateway = JavaGateway.launch_gateway(classpath="/home/gayatri/Code/hindiwn.jar")

Is this because of some dependency? I have set the JAVA_HOME and updated the PATH variable.

A: I don't have the reputation to comment, but
Answer from Java side is empty

But this error indicates that the Java code is not reachable.
Just to verify basic steps
1) Be sure that the java program is running
2) Be sure that you run the Python script after the java code is running
3) The java program is running the entire time.
If you are doing those two things, then an issue may be that the operating system may be already using a port.
You can try
Java
'GatewayServerBuilder server = new GatewayServerBuilder().javaPort(1001).build()'
'server.start()'

Python
java = JavaGateway(gateway_parameters=GatewayParameters(port=1001))


text:
Q: Proof of a necessary and sufficient condition between annuli centered at the origin What is a simple way to prove that two annuli $A_1 = {z: r_1 < |z| < R_1}$ and $A_2 = {z: r_2 < |z| < R_2}$ are conformally equivalent if and only if $R_1/r_1 = R_2/r_2$, using standard results of complex analysis?
I'm not looking for a concise proof so much as one that uses elementary concepts.


text:
Q: Make npm install faster An average npm install seems to take around 44 seconds on my machine for a new Angular project, when created using the Angular CLI.
I looked at the usage of the computer resources but I didn't see anything being used at 100% (CPU, RAM, Disk, Ethernet).
Is the install time that 'slow' due to the response times of the requests made during the process, or the speed of the server that feeds me the node modules or is there a specific hardware component that is slowing down the process?
Basically, I want to know if upgrading something on my computer could decrease the install time.


text:
Q: python dataframe group by column unique values and count group size I have a pandas dataframe df where the 'categories' column contains a variable length  of  string  labels   to that row. Each label represents a sub-category:
id         categories               number

1         'food','toy','science'    1
2         'animal'                  2
3         'plant','food','science'  5
....

Added code  here to generate such dataframe:
d = {'id': [1, 2,3], 'categories': [["food","toy","science"],["animal"], ["plant","food","science"]],\
     'number':[1,2,5]}
dd = pd.DataFrame(data=d)
dd['categories'] = dd['categories'].astype('str')
dd['categories'] = dd['categories'].str.replace('[','')
dd['categories'] = dd['categories'].str.replace(']','')

How could I do a group-by and count by each sub-category size in the column 'categories'?
df.groupby('categories').size()

if calculated this way, id1 and id3 will be grouped differently but id1 and id3 both belong to 'food' sub-category.
I could split 'categories' column into different columns and then do the groupby  column by  column. Since I have 200 strings in that categories column, this sounds cumbersome.
Any  elegant solution?
if I use df.to_dict it will be like:
{'id': {0: 1,
  1: 2,
  2: 3},
 'categories': {0: 'food','toy','science',
                1: 'animal',
                2: 'plant','food','science'}}

If I only use top 3 rows as example, expected output will be:
categories      size
food            2
toy             1
animal          1
plant           1
science         2

A: We can use explode to create a row for each sub-category for category column.
Starting with df DataFrame:
    id  categories  number
0   1   'food','toy'    1
1   2   'animal'    2
2   3   'plant','food','science'    5

Code
# Following steps
df['categories'] = df['categories'].str.split(',')    # convert categories from string to list
df2 = df.explode('categories')                        # explode categories
                                                      # category column now only has one sub-category per row
result = df2.groupby('categories').size()             # group sub-categories and
                                                      # count number of items in each group

result
categories
'animal'     1
'food'       2
'plant'      1
'science'    1
'toy'        1
Name: number, dtype: int64

A: Let us try str.extractall then value_counts
out = df.categories.str.extractall("'([^']*)'")[0].value_counts()
Out[947]:
science    2
food       2
plant      1
toy        1
animal     1
Name: 0, dtype: int64


text:
Q: how to send message to kafka producer using pipelindb? I am learning kafka and pipelinedb and I got across the following statements,
how to send message to kafka producer using pipelindb?
Do you have a example?

A: Read our SQL on Kafka post for a detailed walkthrough of how to use Kafka with PipelineDB. You can also read up on our Kafka integration in our technical docs.


text:
Q: Time complexity of A* and Dijsktra's search In a grid based environment, the number of edges E = O(V).
A* would, in the worst case, explore all the nodes of the grid.
So, number of nodes in open list would be E in the worst case.
Therefore, A's time complexity in worst case is O(E).
Now, as we know that Dijsktra's time complexity is O(E + VlogV).
And A* in worst case would explore same number of nodes as Dijkstra would explore.
Thus, the time complexity of A* should have been equal to Dijkstra = O(E).
But we have VlogV term extra in Dijkstra.
What am I missing here? I request for a detailed explanation.
Thanks in advance.


text:
Q: DragDrop from WinForms to WPF issue I have old WinForms application with DragDrop functionality (without any source code). Now I need to create new WPF application which can receive some data from old one with DragDrop. But DragDrop isn't working in WPF app and any events: DragEnter, DragOver, DragLeave, Drop doesn't fire. I've created other simple WinForms application only with DragDrop functionality and it's working OK. Also, I can do DragDrop from this simple WinForms app to WPF app.
I've tried to run my apps "As Administrator" and without this - nothing changed.
Does anybody know, how to fix this or what is root cause or can be the root cause of such strange behavior?

A: *

*Have you set the (AllowDrop="true") in wpf xaml?

*and if that was yes, do you handle the Drop event for the capturing form or control?

see this question on stackoverflow.com for more details:
WPF Drag and Drop

A: Ok, I was able to solve the issue. The reason - the old app use RegisterDragDrop for OleDataFormat, but new WPF - use RegisterDragDrop for DataFormat. The solution - set AllowDrop to false, and use RegisterDragDrop from ole32.dll for OleDataFormat with custom IDropTarget interface or from WinForms library.


text:
Q: PDFs are not embedded with IE11 I created a simple html file that was supposed to have an embedded pdf that was printable:

Try to print this sucka!

    <button id="btnPrint" onclick="frmPdf.contentWindow.focus(); frmPdf.contentWindow.print(); return false;">Push Me To Print</button>

This works fine on Chrome. I can print the document. However, on IE when I load the page I immediately get a download/save prompt at the bottom of the Window and the print button does nothing. If I enlarge the iframe I see that there is nothing in it at all.
I suspect this is an Adobe plugin problem. I downloaded the latest reader (DC) and installed it, then uninstalled it and reinstalled it. Then I disabled and re-enabled the plugin, but nothing works.
I opened the Preferences in Adobe Reader DC and went to the "Internet" section. The following options are enabled:

*

*Display in Read Mode by default

*Allow fast web view

*Allow speculative downloading in the background

It also says that the product available for use by browsers is "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe. However, when I open IE and go to the information for the adobe plugin, it says it is using C:\Program Files (x86)\Common Files\Adobe\Acrobat\ActiveX\AcroPDF64.dll. I don't know what that means.
How do I make the PDF plugin work?


text:
Q: pandas groupby and boolean selection I often end up doing things like this in pandas:
s2 = s1.groupby(level=1).sum()
s2 = s2[s2>25]

In words, I do some groupby operation and then want to keep only results that meet some condition for the result.
Is there a way to do with in one line? More specifically, is it possible to do this without creating the series and then doing the Boolean selection in a second step?

A: Assuming s1 is a pandas.Series

*

*You can pass level to pd.Series.sum

*pd.Series.compress is handy

s2.sum(level=1).compress(lambda s: s.gt(25))

Assuming s1 is a pandas.DataFrame
And that there is a column names 'col'
s.sum(level=1).query('col > 25')

A: .loc + lambda
Serise
df.groupby('name').a.sum().loc[lambda x: x>20]
Out[492]:
name
Chn     84
Fra    165
Ind     71

Dataframe
df.groupby('name').a.sum().to_frame().loc[lambda x: x['a']>20]
Out[490]:
        a
name
Chn    84
Fra   165
Ind    71

DataInput
df=pd.DataFrame({'name':['Ind','Chn','SG','US','SG','US','Ind','Chn','Fra','Fra'],'a':[5,6,3,4,7,12,66,78,65,100]})