text:
Q: Replacing a plugin created textarea by WP editor Need your help guys. I have a page where by Private Content plugin I create a simple textarea field. What I need to do is to improve that textarea by adding rich text editor to it, I think standard WP one should be fine.
Can you please provide direct instruction which code I need to past and where exactly should I do that? Coding is not my strong suit as you can see. Trying google and searching here and there is some results but it is not clear enough for me to implement correctly.
Hope for your help!

A: Using the function
wp_editor( $content, $editor_id, $settings = array() );

you can display a default wordpress editor. Quick (unsanitized) example:
Your form content (don't forget to add <form> tags):
<?php wp_editor( 'I am a prefilled sample text', 'editorname' ?>

The script reading from that:
$editor_content = $_POST['editorname']
//do stuff, perhaps put to database
save_to_db( $editor_content ) //for example

A few quick things to note

*

*the editor is rendered aka directly echoed, so you don't have to add echo

*the $editor_id can only contain lower cased letters. no underscores.

but have a look yourself here: https://codex.wordpress.org/Function_Reference/wp_editor

A: Use this code :
wp_editor( $content, 'content_id', array('textarea_name' => 'content_id', 'editor_class'=>'requiredField', 'textarea_rows'=>'6', 'media_buttons' => true ,'tinymce' => true)  );


text:
Q: Hide / show div toggle I have the following mark up with a basic and advanced search divs.

     <form>
         <input type="text" name="first_name">
         <input type="text" name="last_name">

         <input type="text" name="location">

       + show advanced fields

         <input type="text" name="first_name2">
         <input type="text" name="last_name2">
         <input type="text" name="street">
         <input type="text" name="town">
         <input type="text" name="country">

     </form>

     - hide advanced fields

The toggle is achieved with the following script
 function HideDiv() {
         $('.slide').hide();
     }
     function ShowDiv(ctrl) {
         HideDiv();
         $('#' + ctrl).show();
     }
     ShowDiv('Basic');

I also have trhe following JQuery in place that shows the adv div if a user returns to the page from a results page assuming he completed any input fields from the search form initially
//show adv div based on input value data
$(function(){
    if($("#Adv input[value!='']").length)
        $('#Adv').show(); // if this is the element you want to show.
 });

I need to eliminate the need of using both links. I need to have only one link depending on state. So if the div basic is shown as default the link will say show advanced. When the advanced is shown the anchor link should switch to hide advanced
How do I need to edit my jQuery and mark up.

A: $(function(){
    $(".toggler").click(function(e) {
        e.preventDefault();
        $(this).find("span").toggle();
        $(".togglee").slideToggle();
    });

    //show adv div based on input value data
    if($("#Adv input[value!='']").length) {
        $('.toggler').click(); // if this is the element you want to show.
    }

});

And the HTML:

            <form>
                <input type="text" name="first_name">
                <input type="text" name="last_name">

                    <input type="text" name="location">

                    <input type="text" name="first_name2">
                    <input type="text" name="last_name2">
                    <input type="text" name="street">
                    <input type="text" name="town">
                    <input type="text" name="country">

            </form>

                + show advanced fields
                - hide advanced fields

jsFiddle example here.

A: html
toggle advanced fields

js
$('.toggle-link').on('click.toggle', function(evt) {
   var tgt = $($(this).attr('href'));  /* tgt = $("#Adv") */
   evt.preventDefault();

   if (tgt.length) { /* if $("#Adv") exists */
      $(this).toggleClass(".expanded"); /* add or remove this class for the link */
      tgt.toggleClass(".hidden"); /* add or remove this class in the target element */
   }
});

css
.toggle-link:before { content: "+"; padding-right: 1em; }
.toggle-link.expanded:before { content: "-"; }

in this example, the information about the element to hide/show is passed along with href attribute, and the event handler is not inline, so you can avoid to call the same function multiple times mixing javascript and markup together.
See example fiddle : http://jsfiddle.net/SnKHg/

A: This function can made better ofcourse, but it is one way to do this.
Make a link Click.
The jQuery function toggles the class, thus the functionality.
$('a.show').click(function(e) {
    e.preventDefault();
    if($(this).hasClass('basic'))
    {
        ('#adv').hide();
        ('#basic').show();
        $(this).addClass('adv');
        $(this).removeClass('basic');
    }
    else if($(this).hasClass('adv'))
    {
        ('#basic').hide();
        ('#adv').show();
        $(this).addClass('basic');
        $(this).removeClass('adv');
    }
});

But a jQuery UI accordeon is better for this, especially when you have more containers that you want to show/hide.

A: You could do
js
$("a.toggle").click(function() {
    $(this).closest('div.form').find("#Adv").toggle();
    $(this).toggleClass("hide");
    if ($(this).hasClass("hide")) {
        $(this).text("hide advanced fields");
    } else {
        $(this).text("show advanced fields");
    }

});

html

 <form>
     <input type="text" name="first_name">
     <input type="text" name="last_name">

     <input type="text" name="location">

     <input type="text" name="first_name2">
     <input type="text" name="last_name2">
     <input type="text" name="street">
     <input type="text" name="town">
     <input type="text" name="country" value="gh">

 </form>

 show advanced fields

fiddle here http://jsfiddle.net/c27dW/

A: Find below.

     <form>
         <input type="text" name="first_name">
         <input type="text" name="last_name">

         <input type="text" name="location">

       + show advanced fields

         <input type="text" name="first_name2">
         <input type="text" name="last_name2">
         <input type="text" name="street">
         <input type="text" name="town">
         <input type="text" name="country">

     </form>

I've modified the javascript part as well.
  function Hide() {
             $('.slide').hide();
         }

    function Show() {

      $('.slide').show();
    }
         function ShowHideDiv() {

           var str = $("#bttn").text();
           if(str === '+ show advanced fields'){

             $("#bttn").text('- hide advanced fields');
             Show();

           }
           else {
              $("#bttn").text('+ show advanced fields');
             Hide();

           }

         }

A: in addition to other answer, may be if u want some animation then u should have look at this http://jqueryui.com/demos/toggle/#option-options

redpajama_set_name: RedPajamaStackExchange


text:
Q: boost::thread_group in C++11? Is there anything like boost::thread_group in C++11?
I'm just trying to port my program from using boost:thread to C++11 threads and wasn't able to find anything equivalent.

A: thread_group didn't make it into C++11, C++14, C++17 or C++20 standards.
But a workaround is simple:
  std::vector<std::thread> grp;

  // to create threads
  grp.emplace_back(functor); // pass in the argument of std::thread()

  void join_all() {
    for (auto& thread : grp)
        thread.join();
  }

Not even worth wrapping in a class (but is certainly possible).

A: No, there's nothing directly equivalent to boost::thread_group in C++11. You could use a std::vector<std::thread> if all you want is a container. You can then use either the new for syntax or std::for_each to call join() on each element, or whatever.


text:
Q: Logger basicConfig - can't set a specific file folder I'm trying to set the log file to a specific folder.
The path is project-folder/logs/test_num/test_number.log
for exmaple:
logging.basicConfig(level=logging.INFO, format="%(asctime)s  %(name)s :%(levelname)s :%(message)s", filename=project-folder/logs/123/123.logs, filemode="a", force=True)

When trying to set to this path, log file isn't created, and if there are other files under this path they been deleted.
When I'm trying to set to project-folder/logs it works fine. What am I doing wrong?


text:
Q: Unable to Create Multiple User Defined Functions in SQL Server Using System.Data.SqlClient I am trying to create multiple user defined functions from within the same .sql file. I am using SQL Server and am executing my queries using the SqlClient from C#'s System.Data.
Contents of the .sql file:
CREATE FUNCTION [dbo].[GetUserId] (@username VARCHAR(32))
RETURNS INT
AS
BEGIN
    DECLARE @userId INT = -1

    SET @userId = (SELECT DISTINCT UserId FROM Users WHERE UserName = @username)

    RETURN @userId
END
GO

CREATE FUNCTION [dbo].[GetUserId2] (@username2 VARCHAR(32))
RETURNS INT
AS
BEGIN
    DECLARE @userId2 INT = -1

    SET @userId2 = (SELECT DISTINCT UserId FROM Users WHERE UserName = @username2)

    RETURN @userId2
END

Here's the error that is thrown when I execute the statement:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'GO'.
  Must declare the scalar variable "@username2".
  Incorrect syntax near 'END'.'

Any ideas? I'm new to SQL in general but this seems to be a lack of understanding syntax/batching to me.
EDIT: It has come to my attention that 'GO' is part of SQL Server Management Studio, and not the SqlClient. If I remove the 'GO' from my .sql file, then I get this error:

'CREATE FUNCTION' must be the first statement in a query batch.

How do I separate CREATE FUNCTION statements without using 'GO'?

A: You cannot run multiple batches in a single statement.
I would suggest you to split your TSQL statement using GO and then execute the batches one by one.
string multipleUDFs = "CREATE FUNCTION... " +
"GO" +
"CREATE FUNCTION ";
List<string> statementsToExecute = multileUDFs.Split("GO").ToList();

// Create the command
var command = new SqlCommand(myConnection);

foreach(string sqlcommand in statementsToExecute)
{

// Change the SQL Command and execute
command.CommandText = sqlcommand;
command.ExecuteNonQuery();
}

A: Below is an example using the Server Management Objects (SMO) API with the latest preview NuGet package. Unlike SqlClient, SMO can run scripts with GO batch terminators, similarly to SSMS and SQLCMD.
using System.IO;
using System.Data.SqlClient;
//reference latest NuGet preview package https://www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects/160.1911221.0-preview#
using Microsoft.SqlServer.Management.Common;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var connection = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
            {
                var serverConnection = new ServerConnection(connection);
                connection.Open();
                var sqlScript = File.ReadAllText(@"C:\temp\ScriptWithGoBatchTerminators.sql");
                serverConnection.ExecuteNonQuery(sqlScript);
            }
        }
    }
}

A: In addition to Dan Guzman's answer using SMO, you can also split your SQL script text into separate SQL batches and execute each one in turn on the same connection.  That is all that SSMS and SMO do anyway:
    /// <summary>
    /// Executes a script-like SQL string, using GOs to break it into
    /// seperate batches within the same session
    /// </summary>
    public void ExecSqlScript(string sqlScript, SqlConnection conn)
    {
        // change all line-breaks to LF
        string script = sqlScript.Replace("\r\n", "\n").Replace("\r", "\n");

        // split the script into separate batches using "GO"
        string[] batches = script.Split(new[] { "\nGO\n", "\ngO\n", "\nGo\n", "\ngo\n" }, StringSplitOptions.RemoveEmptyEntries);

        // execute each batch on the same connection/session
        foreach(string batch in batches)
        {
            SqlCommand cmd = new SqlCommand(batch, conn);
            cmd.ExecuteNonQuery();
        }
    }

Note: Untested


text:
Q: Issues with pushing another UINavigationController onto another UINavigationController? In trying to solve this issue of pushing/popping view controllers with different orientations, one solution seems to be two UINavigationControllers, one to handle the portrait orientations and the second to handle landscape orientations.
Assume A and B are portrait view controllers; C and D are landscape view controllers.
In other words, pushing B->C should yield landscape, C->D should also be landscape, but popping from C->B should be portrait.
UINavigationController1 is a custom UINavigationController class that always forces portrait.
UINavigationController2 is another custom class, but this one forces landscape.
A and B are embedded inside UINavigationController1.
C and D are embedded inside UINavigationController2.
When pushing from B->C, we push UINavigationController2 onto the stack of UINavigationController1.
So far in testing it seems to work, but is anyone aware of any potential gotchas? The fear is there are some lurking performance/behavioral issues that won't surface until much later.


text:
Q: Swift Image gallery with fullscreen slider I want to build a facebook-like image gallery but don't know where to start from.
Here's what i think i should do:

*

*CollectionView that shows thumbnails based on an array

*On row-click, i modally open a pageViewController based on the same array of images

*On Swipe left-right, i go to the next or previous image

*On Swipe up-down, i close this view and go back to my collectionview

Is this logic correct/the best practice?
Maybe it's been already done by someone.

A: You can use banana library for showing images in slider view in Swift
get banana from https://github.com/gauravkatoch007/banana
import banana

@IBOutlet weak var imageScrollView: UIScrollView!

// Here imageArray can be a string array of Image URLs
var imageArray = [String]()

//or imageArray can be a array of UIImages
var imageArray = [UIImage]()

var imageScroll = banana( imageScrollView :self.imageScrollView )
//Load to load images in memory and display them in User Interface
imageScroll!.load(imageArray)

//Call startScroll for autoScrolling. Default scrolling timer is 8 seconds
imageScroll!.startScroll()

//Call this function to stop autoScrolling on touch or swipe.
imageScroll!.assignTouchGesture()

A: Update I resolved in this way:

*

*Gallery is a collection view

*On cell selected, i modally segue to another view, which contains a scrollview in which i put 5 images one (right) after the other, and handle paginating.

*My image will always be the third in the middle, after every scroll, i choose the 5 images of my entire array which centers the index, or the 5 which contain this.

here's my class PhotoViewController: UIViewController, UIScrollViewDelegate {
var screenSize: CGRect = UIScreen.mainScreen().bounds

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var blackView: UIView!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var photoActions: UIImageView!

var img1:UIImageView = UIImageView(image: UIImage())
var img2:UIImageView = UIImageView(image: UIImage())
var img3:UIImageView = UIImageView(image: UIImage())
var img4:UIImageView = UIImageView(image: UIImage())
var img5:UIImageView = UIImageView(image: UIImage())

var w1: UIImage!
var w2: UIImage!
var w3: UIImage!
var w4: UIImage!
var w5: UIImage!
var pageIndex: Int!
var currentPage: Int!
var oldPage: Int!
var endFrame: CGRect!
var arrayIndex: Int!

// placeholder for if the image frame is scrolled
var scrolledPhotoFrame: CGRect!

override func viewDidLoad() {
    super.viewDidLoad()
    RightSize()
    LoadData()
}

func LoadData(){
    // data passed from feedViewController gets stored here
    img1.image = w1
    img2.image = w2
    img3.image = w3
    img4.image = w4
    img5.image = w5
    // set the right endFrame based on the selectedImage

    switch pageIndex {
    case 0:
        img1.frame = endFrame
        img1.frame.origin.x = 0
    case 1:
        img2.frame = endFrame
        img2.frame.origin.x = screenSize.width
    case 2:
        img3.frame = endFrame
        img3.frame.origin.x = (screenSize.width * 2)
    case 3:
        img4.frame = endFrame
        img4.frame.origin.x = (screenSize.width * 3)
    case 4:
        img5.frame = endFrame
        img5.frame.origin.x = (screenSize.width * 4)
    default:
        break
    }
    currentPage = pageIndex
    oldPage = pageIndex

    scrollView.contentSize = CGSize(width: screenSize.width*5, height: screenSize.height)
    scrollView.contentOffset.x = CGFloat(pageIndex * Int(screenSize.width))
    println(scrollView.contentOffset.x)
    // default value of scrolledPhotoFrame is unscrolled position of photoImageView
    scrolledPhotoFrame = endFrame

    // required for registering scroll events
    scrollView.delegate = self
   // RightSize()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func doneDidPress(sender: AnyObject) {
    dismissViewControllerAnimated(true, completion: nil)
}

// called while scrolling
func scrollViewDidScroll(scrollView: UIScrollView) {

    currentPage = Int(scrollView.contentOffset.x / screenSize.width)
    if (currentPage != oldPage){
        //Ho cambiato pagina
        if (currentPage>oldPage){
            //Sono andato di 1 foto avanti
            println("Avanti")
            arrayIndex = arrayIndex+1
            CambioPagina()

        }else{
            //Sono andato di 1 foto indietro
            arrayIndex = arrayIndex-1
            println("indietro")
        }

        oldPage=currentPage
    }
    var alpha = CGFloat(1 - abs(scrollView.contentOffset.y) / 100)
    var alpha2 = CGFloat(1 - abs(scrollView.contentOffset.y) / 20)

    blackView.alpha = alpha
    doneButton.alpha = alpha2
    photoActions.alpha = alpha2
}

// This method is called right as the user lifts their finger
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    var offsetY = scrollView.contentOffset.y
    var alpha = CGFloat(1 - abs(scrollView.contentOffset.y) / 240)

    if (abs(offsetY) > 100) {
        scrolledPhotoFrame.origin.y = scrolledPhotoFrame.origin.y - offsetY
        blackView.hidden = true
        scrollView.hidden = true // could be wrong
        doneButton.hidden = true
        dismissViewControllerAnimated(true, completion: nil)
    }
}

// selecting the view to zoom
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    switch currentPage {
    case 0:
        return img1
    case 1:
        return img2
    case 2:
        return img3
    case 3:
        return img4
    case 4:
        return img5
    default:
        return nil
    }
}

func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView!) {
    img2.hidden = true
    img3.hidden = true
    img4.hidden = true
    img5.hidden = true
}

func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {

}

//Controllo per cambio pagina..! chissa!
func CambioPagina(){
    switch arrayIndex{
    case 0:
        w1 = UIImage(named: arrayFoto[arrayIndex])
        w2 = UIImage(named: arrayFoto[arrayIndex+1])
        w3 = UIImage(named: arrayFoto[arrayIndex+2])
        w4 = UIImage(named: arrayFoto[arrayIndex+3])
        w5 = UIImage(named: arrayFoto[arrayIndex+4])
        pageIndex = 0
    case 1:
        w1 = UIImage(named: arrayFoto[arrayIndex-1])
        w2 = UIImage(named: arrayFoto[arrayIndex])
        w3 = UIImage(named: arrayFoto[arrayIndex+1])
        w4 = UIImage(named: arrayFoto[arrayIndex+2])
        w5 = UIImage(named: arrayFoto[arrayIndex+3])
        pageIndex = 1
    case (arrayFoto.count-2):
        w1 = UIImage(named: arrayFoto[arrayIndex-3])
        w2 = UIImage(named: arrayFoto[arrayIndex-2])
        w3 = UIImage(named: arrayFoto[arrayIndex-1])
        w4 = UIImage(named: arrayFoto[arrayIndex])
        w5 = UIImage(named: arrayFoto[arrayIndex+1])
        pageIndex = 3
    case (arrayFoto.count-1):
        w1 = UIImage(named: arrayFoto[arrayIndex-4])
        w2 = UIImage(named: arrayFoto[arrayIndex-3])
        w3 = UIImage(named: arrayFoto[arrayIndex-2])
        w4 = UIImage(named: arrayFoto[arrayIndex-1])
        w5 = UIImage(named: arrayFoto[arrayIndex])
        pageIndex = 4
    default:
        w1 = UIImage(named: arrayFoto[arrayIndex-2])
        w2 = UIImage(named: arrayFoto[arrayIndex-1])
        w3 = UIImage(named: arrayFoto[arrayIndex])
        w4 = UIImage(named: arrayFoto[arrayIndex+1])
        w5 = UIImage(named: arrayFoto[arrayIndex+2])
        pageIndex = 2
    }
    LoadData()
}
func RightSize(){
    img1.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
    scrollView.addSubview(img1)
    img2.frame = CGRect(x: screenSize.width, y: 0, width: screenSize.width, height: screenSize.height)
    scrollView.addSubview(img2)
    img3.frame = CGRect(x: (screenSize.width*2), y: 0, width: screenSize.width, height: screenSize.height)
    scrollView.addSubview(img3)
    img4.frame = CGRect(x: (screenSize.width*3), y: 0, width: screenSize.width, height: screenSize.height)
    scrollView.addSubview(img4)
    img5.frame = CGRect(x: (screenSize.width*4), y: 0, width: screenSize.width, height: screenSize.height)
    scrollView.addSubview(img5)
    img1.contentMode = .ScaleAspectFit
    img2.contentMode = .ScaleAspectFit
    img3.contentMode = .ScaleAspectFit
    img4.contentMode = .ScaleAspectFit
    img5.contentMode = .ScaleAspectFit
}

Any better approach will be great, for example, i cannot handle image zoom


text:
Q: C2DM Php implementation I have tried using the php code found in the following link
https://github.com/lytsing/c2dm-php
I am getting the response http code as "0".

A: I have found a different php c2dm implementation in the below link
http://code.google.com/p/plic-opensource-mti2012/source/browse/trunk/server/library/c2dm.php?r=72
It's working fin now.


text:
Q: How to implement the JMS Inbound & Outbound configuration in separate spring integration application? My use case is notification service implementation in our project.
We have used spring with jms and its working fine with rest services. Able to send message to queue from one application and receive a message from queue in another application using JMSTemplate's convertAndSend(), convertAndReceive() functions.
Now I want to do this using spring integration's java dsl approach. We did a sample by using Jms's inboundGateway() and outboundGateway() in single application with ActiveMQ.
How to use spring integration's java dsl in different application for only sending/receiving messages?
Here is my code,
@Bean
public IntegrationFlow jmsInboundFlow() {
    return IntegrationFlows
            .from(Jms.inboundGateway(this.connectionFactory)
                    .destination("pan.outbound"))
            .transform((String s) -> s.toUpperCase())
            .channel("in-bound-request-channel")
            .get();
}

@Bean
public IntegrationFlow jmsOutboundGatewayFlow() {
    return IntegrationFlows.from("out-bound-request-channel")
            .handle(Jms.outboundGateway(this.connectionFactory)
                        .requestDestination("pan.outbound"))
            .log()
            .bridge()
            .get();
}

@MessagingGateway
interface EchoGateway {

    @Gateway(requestChannel = "out-bound-request-channel")
    String send(String message);

}

A: You have only to split configuration - JMS inbound adapter in one application and JMS outbound in second.
The way is exactly the same as in one application ? (Maybe I missed some information?)


text:
Q: How do I write a yocto/bitbake recipe to copy a directory to the target root file system I have a directory of  'binary' (i.e. not to be compiled) files and just want them to be installed onto my target root file system.
I have looked at several articles, none of which seem to work for me.
The desired functionality of this recipe is:
myRecipe/myFiles/ --> myRootFs/dir/to/install
My current attempt is:
SRC_URI += "file://myDir"

do_install() {
         install -d ${D}/path/to/dir/on/fs
         install -m ${WORKDIR}/myDir ${D}/path/to/dir/on/fs
}

I can't complain about the Yocto documentation overall, it's really good! Just can't find an example of something like this!

A: Take care that with a simple recursive copy, you will end up having host contamination warnings so you would need to copy with the following parameters:
do_install() {
     [...]
     cp --preserve=mode,timestamps -R ${S}${anydir}/Data/* ${D}${anyotherdir}/Data
     [...]
}

As other recipes in poky do, or just follow the official recommendations to avoid problems with ownership and permissions.

A: For a recipe folder like this:
.
├── files
│   ├── a.txt
│   ├── b.c
│   └── Makefile
└── myrecipe.bb

You can use the following recipe to install it on a specific folder into your rootfs:
SRC_URI = " file://*"
do_install() {
    install -d ${WORKDIR}/my/dir/on/rootfs
    install -m 0755 ${S}/* ${WORKDIR}/my/dir/on/rootfs/*
}
FILES_${PN} = "/my/dir/on/rootfs/* "

A: You just have to copy these files into your target rootfs. Do not forget to pakage them if they are not installed in standard locations.
SRC_URI += "file://myDir"

do_install() {
    install -d ${D}/path/to/dir/on/fs
    cp -r ${WORKDIR}/myDir ${D}/path/to/dir/on/fs
}
FILES_${PN} += "/path/to/dir/on/fs"

A: I think it did not work for you becuase you forgot to add mode value, after "install -m",
see man page of install command:
https://linux.die.net/man/1/install
install -m [mode] src destination


text:
Q: Getting database results from Array of IDs Apologies for the newbishness of this question. I'm just starting a project and I have an array of IDs to grab certain records from a table. What's the best way to go about this?
Will the following work?
public function getWork($slideIDs) {
    $params = array();
    $params = $slideIDs;

    $count = count($params);

    for($i=0;$i<$count;$i++) {
        $STH = $this->_db->prepare("SELECT *
            FROM slides
            WHERE slideID = :slideID;");

        $STH->execute($params[$i]);
    }

    $result = $STH->fetchAll(PDO::FETCH_ASSOC);

    return $result;
}

Thanks.

A: Adjust your PHP to create a single query string with this format:
SELECT *
FROM slides
WHERE slideID IN (2,5,11)

Do not execute multiple queries. :)

A: Better to execute just one SQL statement using an IN clause
SELECT * FROM slides WHERE slideID IN (1,2,3,4,5, ...)

Since fewer connections and trips to the database is generally better for performance.
So just build that SQL string in your loop, then move the Execute to the bottom (outside your loop.)

A: Same as others ;)
Use implode($array, ",") to get the part which should go into the IN() statement

A: The following should work. Used implode to create the required string containing the IDs separated by comma to pass to SQL.
    function getWork($slideIDs) {
    $params = implode(",",$slideIDs);
    $STH = $this->_db->prepare("SELECT *
            FROM slides
            WHERE slideID in ( :slideID );");

    $STH->execute($params);

    $result = $STH->fetchAll(PDO::FETCH_ASSOC);

    return $result;
    }


text:
Q: Use a variable in a postgresql execute statement I am trying to have a parameter when creating a trigger function.
I have been trying to use this code:
DO $DO$
BEGIN
EXECUTE format($TRIGGER$
  CREATE OR REPLACE FUNCTION my_schema.my_trigger_fcn() RETURNS trigger AS
  $BODY$
    DECLARE
      my_geom geometry(MultiPoint,%1$s);
    BEGIN
      my_geom = st_collect(NEW.situation_geometry)::geometry(MultiPoint,%$1s);
      NEW.geometry = my_geom;
      RETURN NEW;
    END;
  $BODY$
  LANGUAGE plpgsql;
$TRIGGER$, :SRID);
END
$DO$;

and trying to run this code with psql -v SRID=2056 -f myfile.
But I get a syntax error.
I have also tried the SQL execute command, but prepared statements are not allowed to create trigger function.
Any idea?

SOLUTION:
Thanks to @Pavel Stehule, here is the code that works:
SELECT set_config('my.srid', :SRID::text, false);
DO $DO$
BEGIN
EXECUTE format($TRIGGER$
  CREATE OR REPLACE FUNCTION qgep_od.my_trigger_fcn() RETURNS trigger AS
  $BODY$
    DECLARE
      my_geom geometry(MultiPoint,%1$s);
    BEGIN
      my_geom = st_collect(NEW.situation_geometry)::geometry(MultiPoint,%1$s);
      NEW.geometry = my_geom;
      RETURN NEW;
    END;
  $BODY$
  LANGUAGE plpgsql;
$TRIGGER$, current_setting('my.srid'));
END
$DO$;

A: You cannot to use psql variables inside any SQL string. The string is body of DO command too. You can use session variables:
\set myvar xxx
select set_config('my.myvar', :'myvar', false);
do $$
begin
  execute format('create or replace function fx() returns void as $_$begin raise notice %L; end$_$ language plpgsql', current_setting('my.myvar'));
end;
$$;

postgres=# \sf fx
CREATE OR REPLACE FUNCTION public.fx()
RETURNS void
LANGUAGE plpgsql
AS $function$begin raise notice 'xxx'; end$function$

Other possibility is do this replacement before psql - you can use sed


text:
Q: How to change chdir in python3 with comandline args How to change chdir in python3 with comandline args like
python3 project_name/manage.py --chdir=/project_name

Actually I try to setup Docker to run flask app with next settings
version: '3'

services:

  flask:
    build: .
    restart: always
    container_name: 'project_name'
    command: python3 /project_name/manage.py --chdir=/project_name
#    command: gunicorn --bind 0.0.0.0:8000 --worker-class=gevent --workers=4 --chdir /flask --reload wsgi:app
    volumes:
      - .:/flask
    ports:
      - '8000:8000'
    environment:
        - PATH=/project_name:$PATH

And after all python says that it cannot find db file, I know why, because chdir is not root of project, chdir is a folder under the project dir

A: bash -c "cd /project_name && python3 manage.py"


text:
Q: PySpark Aggregation on Comma Seperated Column

I have a huge DataFrame with two of many columns: "NAME", "VALUE". One of the row value for "NAME" column is "X,Y,V,A".
I want to transpose my DataFrame so the "NAME" values are columns and the average of the "VALUE" are the row values.
I used the pivot function:
df1 = df.groupby('DEVICE', 'DATE').pivot('NAME').avg('VALUE')

All NAME values except for "X,Y,V,A" work well with the above. I am not sure how to separate the 4 values of "X,Y,V,A" and aggregate on individual value.

A: IIUC, you need to split and explode the string first:
from pyspark.sql.functions import split, explode
df = df.withColumn("NAME", explode(split("NAME", ",")))

Now you can group and pivot:
df1 = df.groupby('DEVICE', 'DATE').pivot('NAME').avg('VALUE')


text:
Q: The vertical lines in my tabular environment are scattered I'm using pdflatex and have some trouble: the vertical lines in my tabular environment are all scattered.
\documentclass{article}
\begin{document}

\begin{tabular}{| l | c | l |}
  \hline
  Abbreviation & Description & Relation\\
  2 & einstein & $E = m*c^2$
  \\\hline\\
  3 & pythagoras  & $c^2=\sqrt{a^2+b^2}$\\
  \hline
\end{tabular}

\end{document}

It's probably connected to the formula inside the cell. Any help is greatly appreaciated.

A: You need two ampersands to create columns in the empty line.
\documentclass{article}
\begin{document}

\begin{table}
\centering
\begin{tabular}{| l | c | l |}
\hline
Abbreviation & Description & Relation\\
2 & einstein & $E = m*c^2$ \\\hline && \\
3 & pythagoras  & $c^2=\sqrt{a^2+b^2}$\\
\hline
\end{tabular}

\end{table}
\end{document}

A: I have provided a quick fix. See MWE below:
\documentclass{article}
\usepackage{booktabs}
\begin{document}
{%
\renewcommand{\arraystretch}{1.3}
\begin{tabular}{| l | c | l |}
  \hline
  Abbreviation & Description & Relation\\\hline
  2 & einstein & $E = m*c^2$
  \\\hline
  3 & pythagoras  & $c^2=\sqrt{a^2+b^2}$\\
  \hline
\end{tabular}
}

\vspace*{1cm}
{%
\renewcommand{\arraystretch}{1.3}
\begin{tabular}{ l  c l }
  \toprule
  Abbreviation & Description & Relation\\
  \midrule
  2 & einstein & $E = m*c^2$
  \\
  3 & pythagoras  & $c^2=\sqrt{a^2+b^2}$\\
  \bottomrule
\end{tabular}
}
\end{document}


text:
Q: influxdb - some values become null when request with mean() or median() i have an issue with influxdb query.
when I query normally:
SELECT "distance" FROM "testdb"."autogen"."laserdistance" WHERE time > timeA AND time < timeB

I will get back all the data without error.
if I query with either mean() or median():
SELECT mean("distance") AS "mean_distance" FROM "testdb"."autogen"."laserdistance" WHERE time > timeA AND time < timeB GROUP BY time(some_interval) FILL(null)

I will sure get back some null value in a very inconsistent pattern(sometime a lot, sometime not so much).
I understand that FILL(null) is the one responsible for the null issue to fill in the interval that don't have value.
is there a way to get the nearest value instead of fill it with null?

A: Use FILL(linear):

linear - Reports the results of linear interpolation for time intervals with no data.

Doc: https://docs.influxdata.com/influxdb/v1.7/query_language/data_exploration/#group-by-time-intervals-and-fill


text:
Q: javascript not working for URL re-direct Can anyone help me with this script I'm trying to get working? I need a text box with a submit button, when a certain id is entered I need them to be re-directed to a certain site (below examples in the script are are yahoo, bing, etc).
This below is what I have so far, but the submit button doesn't show up and when the submit button is hit it doesn't seem to execute the script.
I just get a #? added to the url...  I'm working in opencart so I think part of the problem might be with opencart.

<form id="urllauncher" action='#'>
Site id
<input type="text" id="siteid">
<button type="submit" id="gobutton">Go</button>
</form>

Thanks for any help on this!

A: You should add your script at the end of the body.
You are calling document.getElementById("gobutton").addEventListener too early, at this point the button is not yet present in the page DOM, so no event is attached to it.
Working code :

        <form id="urllauncher" action='#'>
            Site id
            <input type="text" id="siteid">
            <button type="submit" id="gobutton">Go</button>
        </form>

PS : try to indent your code prior to posting it !

A: I think if you remove that form tag ,it will solve all your problems.

A: I think there's no need for it be of submit type and have a form at all
Just remove those and the event.preventDefault()


text:
Q: Unable to ping between two devices in two subnets connected via router I have two systems running on Windows, the first one S1 in subnet 192.168.3.0 and the second one S2 in subnet 192.168.2.0. Both are connected to my Linux box, say R1, which I want to act as router for pinging between these Windows systems.
S1 is connected via eth0 NIC of R1 and S2 is connected via eth2 NIC of R1 as below:

Following are the configs of NIC's of R1:

*

*IP address of eth0 of R1- 192.168.3.6

*IP address of eth2 of R1- 192.168.2.8.

The IP address of eth0 of R1, i.e., 192.168.3.6 is assigned as the default gateway in Windows S1 as shown in figure below

The IP address of eth2 of R1 i.e., 192.168.2.8 is assigned as the default gateway in Windows S2 as shown in figure below:

I aim to ping S1 from S2 and vice versa, and it is not working. However, ping from S1 to R1 & S2 to R1 is fine
Below is the routing table in my router R1.

Please assist me if any configuration is further required.

A: Check out the /etc/sysctl.conf file of your Linux box. Is there this string net.ipv4.ip_forward = 1 there? Add one if no and reboot then.


text:
Q: AWS LEX menu based chat bot I am trying to create a chatbot with AWS Lex. The chatbot should have menu based responses and when a user selects an option the bot then continues the conversation based on the selected item.
Example conversation:
user: can you tell me the weather
bot: which city do you live in
A. London
B. New York
C. Mumbai
D. Tokyo
user: C
bot: The weather in Mumbai is .....


text:
Q: Magento 2 custom authentication for API I want to implement custom ACL for my custom API. Can someone assist me how to achieve this.
Below is my webapi.xml file content:
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">

    <route url="/V1/mymethod/show/:num1/:num2" method="GET">
        <service class="MyNamespace\CoreApi\Api\CoreApiInterface" method="show"/>
        <resources>
            <resource ref="self"/>
        </resources>
    </route>

</routes>

Now instead of <resource ref="self"/> or <resource ref="anonymous"/>, is there any alternative available which is depends on my custom authentication rather than Magento.
The reason behind this is right now I'm build up custom API in which all of my frontend customer having a unique key say API key (We planned to develop this as well). And using this API key they will able to communicate with my custom API. And according to my requirements, I guess creating consumer key and secret through Magento admin (System > Extensions > Integrations) is not to be the advisable solution.
Is there any possibility to do so with Magento 2?

A: I'm a bit of confusion, but you can try this

create acl.xml and put some rules, then next, edit your webapi.xml to

something like this:
<route url="/V1/mymethod/show/:num1/:num2" method="GET">
    <service class="MyNamespace\CoreApi\Api\CoreApiInterface" method="show"/>
    <resources>
        <resource ref="[module name]::[acl rule id]"/>
    </resources>
</route>

A: Check the example in Magento
vendor/magento/module-sales/etc/webapi.xml
<route url="/V1/order/:orderId/ship" method="POST">
        <service class="Magento\Sales\Api\ShipOrderInterface" method="execute"/>
        <resources>
            <resource ref="Magento_Sales::sales" />
        </resources>
</route>

Similarly you can use your own module ACL


text:
Q: Python API client for Elastic Search: can't connect due to Connection timed out I am working with the Python API client for Elastic Search and I am trying to connect to it.
I create the client like this:
def setup_es():
    ES_USER = os.getenv("ES_USER")
    ES_PASS = os.getenv("ES_PASS")
    print(f"Setting up ES with HOST={ES_HOST}, USER={ES_USER}, PASS={ES_PASS}")
    return Elasticsearch([ES_HOST], basic_auth=(ES_USER, ES_PASS))

But whenever I try using the client, I always get a connection timed out error.
For example:
   client.info()

or
    client.options(ignore_status=[400,404]).indices.delete(index=MY_INDEX)

Always produce:
***_transport.ConnectionTimeout: Connection timed out

I know the host, user and password are right. Am I missing something else? Any ideas please?

A: I solved this issue by specifying port 443 in the elastic search host variable.


text:
Q: R caper package: reading in phylogeny error I'm fairly new to R and I'm trying Phylogenetic Generalised Least Squares (PGLS) for the first time, using the addon package 'caper'. My phylogeny consists of 125 species. I'm getting an error when I read in the phylogeny that I created in Mesquite software (saved as a Nexus file):
##reading in my phylogeny

reptilephylogeny <- read.nexus ("reptile_phylogeny_new_edit.nex", tree.names = NULL)

##it gives me the following warning message:

Warning message:
In matrix(x, ncol = 2, byrow = TRUE) :
 data length [253] is not a sub-multiple or multiple of the number of rows [127]

##So I checked how R is treating the tip labels:

reptilephylogeny$tip.label

  [1] "Apalone_spinifera"          "Staurotypus_triporcatus"
  [3] "Gehyra_variegata"           "Egernia_whitii"
  [5] "Ameiva_erythrocephala"      "Lacerta_vivipara"
  [7] "Lacerta_agilis"             "Podarcis_muralis"
  [9] "Podarcis_sicula"            "Psammodromus_algirus"
  [11] "Tropidurus_itambere"        "Tropidurus_torquatus"
  [13] "Cyclura_nubila"             "Ctenosaura_bakeri"
  [15] "Uta_stansburiana"           "Sceloporus_graciosus"
  [17] "Sceloporus_scalaris"        "Sceloporus_jarrovi"
  [19] "19"                         "20"
  [21] "21"                         "22"
  [23] "23"                         "24"
  [25] "25"                         "26"
  [27] "27"                         "28"
  [29] "29"                         "30"
  [31] "31"                         "32"
  [33] "33"                         "34"
  [35] "35"                         "36"
  [37] "37"                         "38"
  [39] "39"                         "40"
  [41] "41"                         "42"
  [43] "43"                         "44"
  [45] "45"                         "46"
  [47] "47"                         "48"
  [49] "49"                         "50"
  [51] "51"                         ""
  [53] "Basiliscus_vittatus"        "Emoia_atrocostata"
  [55] "Lygosoma_laterale"          "Tropidurus_albemarlensis"
  [57] "Tropidurus_semitaeniatus"   "Varanus_bengalensis"
  [59] "Intellagama_lesueurii"      "Alligator_mississippiensis"
  [61] "Caiman_latirostris"         "Caiman_crocodilus"
  [63] "Caiman_yacare"              "Caretta_caretta"
  [65] "Carettochelys_insculpta"    "Chelodina_longicollis"
  [67] "Chelonia_mydas"             "Chelydra_serpentina"
  [69] "Chrysemys_dorsalis"         "Chrysemys_picta"
  [71] "Clemmys_guttata"            "Crocodylus_acutus"
  [73] "Crocodylus_moreletii"       "Crocodylus_johnstoni"
  [75] "Crocodylus_niloticus"       "Crocodylus_porosus"
  [77] "Crocodylus_palustris"       "Crotalus_horridus"
  [79] "Cuora_flavomarginata"       "Deirochelys_reticularia"
  [81] "Dermatemys_mawii"           "Emydoidea_blandingii"
  [83] "Emydura_macquarii"          "Emys_orbicularis"
  [85] "Eretmochelys_imbricata"     "Gopherus_agassizii"
  [87] "Gopherus_berlandieri"       "n86"
  [89] "n87"                        "n88"
  [91] "n89"                        "n90"
  [93] "n91"                        "n92"
  [95] "n93"                        "n94"
  [97] "n95"                        "n96"
  [99] "n97"                        "n98"
 [101] "n99"                        "n100"
 [103] "n101"                       "n102"
 [105] "n103"                       "n104"
 [107] "n105"                       "n106"
 [109] "n107"                       "n108"
 [111] "n109"                       "n110"
 [113] "n111"                       "n112"
 [115] "n113"                       "n114"
 [117] "n115"                       "n116"
 [119] "n117"                       "n118"
 [121] "n119"                       "n120"
 [123] "n121"                       "n122"
 [125] "n123"                       "n124"
 [127] "1"

It seems as though R isn't filling the data rows/columns consistently - in my species list, there are no gaps between each species, yet clearly here R thinks there are spaces (in this case numbers) between the species names. Does anyone have an idea of why this might be happening?
Thanks,
Greg


text:
Q: Unknown encoder 'libmp3lame' I'm using ffmpeg to convert my files but when I tried to convert WAV -> MP3 I got this error.
It's surprising for me cause I installed this one yesterday.
What could happen?

A: Try installing libavcodec-extra-52, libavcodec-extra-53 or libavcodec-extra-54:
sudo apt-get install libavcodec-extra-52
sudo apt-get install libavcodec-extra-53
sudo apt-get install libavcodec-extra-54

A: libmp3lame is not part of the stock ffmpeg on Ubuntu.
What you want to do is compile ffmpeg from source so it includes libmp3lame. They tell you how to make your ffmpeg with more option on this page. The particular item you want is --enable-libmp3lame.


text:
Q: Find pre/post-decessor in pandas for each group To reduce the complexity, I reworked the whole post:
So, what do I want to achieve:
For a list of campaigns with given start at end dates, I want to return the previous campaign. Previous means that a campaign starts after the end day of the previous one. However, if there are several previous campaings, I want to return the campaign with the same type. This shall be done for every campaign I have (typically, I will have grouped data, (think of item/campaign pairs, where one campaing has several items and I'm interested in the previous campaign for a single item)
Consider the following data
Campaign | StartDay | EndDay | Type
---------|----------|--------|------
    1    |    1     |   10   |  1
    2    |    5     |   15   |  1
    3    |    7     |   15   |  2
    4    |   11     |   20   |  1
    5    |   16     |   25   |  2

So in this case, the desired output is the following
Campaign | PreviousCampaign
---------|-----------------
    1    |     NAN
    2    |     NAN
    3    |     NAN
    4    |      1
    5    |      3

If the first entries vanish, it's ok. Note that the predecessor of 5 is 3 due to the type condition.
I'm able to do this merging the table on itself via campaign, querying the correct rows and several steps to ensure that the type costraint is satisfied.
Without the type type constraint this is a bit easier.
However, studying "modern pandas" by tom augspurger, I have the feeling that pivoting, stacking, melting or a combination should work. But I haven't figured out how, yet.


text:
Q: Display order keeps getting reset and buggy Display settings When I use my laptop at work, I usually plug in two monitors and close the lid. Before Ubuntu 17.10, the system remembered the order that I chose the previous time that I connected them. After Ubuntu 17.10 however, I have to manually order them every time that I connect them.
Also, the "Displays" windows is very buggy: it sometimes does not want a screen to be dragged, sometimes snapping does not work all the time or at places that I do not want:

and the most annoying bug is that the window often does not show the "apply" button (i.e. it shows this:

instead of this:

).
Does anybody know where these problems come from and how I would be able to fix them?

An example of the order should be:

An example of how the displays are ordered most of the time:


text:
Q: how to remove line break '%0D' from file name in csh I want to download some data using wget command from list of files, I used foll. code:
    foreach file(`cat Model_list1.txt`)

     echo $file
     wget https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/LISCOAST/10011/LATEST/EURO-CORDEX/EUR-11/SMHI-RCA4/"$file"/BC/historical/prAdjust_EUR-11_"$file"_historical_r1i1p1_SMHI-RCA4_v1-JRC-SBC-EOBS10-1981-2010_day_19810101-20101231.nc.gz
end

However, for every file name I am getting %0D at the end of the file name. I tried sed as follow to change the name of the file located in the file Model_list but still I am getting the same error. Kindly help me out. Thanks
sed 's/%0D//g' Model_list.txt > Model_list1.txt

where my Model_list.txt is
CNRM-CERFACS-CNRM-CM5
ICHEC-EC-EARTH
IPSL-IPSL-CM5A-MR
MOHC-HadGEM2-ES
MPI-M-MPI-ESM-LR


text:
Q: How do I write an array to color all jpanels I needed I want to write an array to color JPanels that I needed
        jPanel_day_trans.setBackground(new Color(0,0,0,100));
        jPanel_product.setBackground(new Color(0,0,0,100));
        jPanel_Day.setBackground(new Color(0,0,0,100));
        jPanel_Day_past.setBackground(new Color(0,0,0,100));
        jPanel_month.setBackground(new Color(0,0,0,100));
        jPanel_wedd.setBackground(new Color(0,0,0,100));
        jPanel_sidepanel_trans.setBackground(new Color(0,0,0,165));
        jPanel_Day_Day.setBackground(new Color(0,0,0,100));
        jPanel_Month.setBackground(new Color(0,0,0,100));
        jPane_Product.setBackground(new Color(0,0,0,100));
        jPane_Weddings.setBackground(new Color(0,0,0,100));
        jLabel_Date.setBackground(new Color(0,0,0,100));

A: The easiest to set the background the same for all panels it to simply use:
panel.setBackground( null );

when you create the panel. Then the panel will have the same background as its parent panel. So there is no need for an array. You simply change the background of the top level panel in your frame.
This approach will only work if the background color is opaque.
You can't really use transparent backgrounds on all your panels because the transparency is additive. So each time you add a panel to another panel the child panel will be less transparent and therefore darker in color.
Instead, if you are trying to set the background of all the panels on the frame then the easiest way is to make all panels transparent:
panel.setOpaque( false );

Then you would set the background color of the top panel that is used as the content pane:
frame.getContentPane().setBackground( Color(0, 0, 0, 100) );


text:
Q: Atlas with different projections in QGIS I have created an atlas -- i.e. a map with a layer defining some regions of interest -- in QGIS. I can render maps of each region using the "atlas" feature of the print composer, but I want to show different regions with different projections. Is that possible?

A: No, it's not possible at the moment. Maps within the composer will always use the same projection as the main map canvas.


text:
Q: Find path from one city to other and then reverse with no city revisited I found a problem on Algorithms on usaco, I cannot link to real problem as it requires authentication so pasting it.

You have just won a contest where the prize is a free vacation in Canada. You must travel via air, and the cities are ordered from east to west. In addition, according to the rules, you must start at the further city west, travel only east until you reach the furthest city east, and then fly only west until you reach your starting location. In addition, you may visit no city more than once (except the starting city, of course).
Given the order of the cities, with the flights that can be done (you can only fly between certain cities, and just because you can fly from city A to city B does not mean you can fly the other direction), calculate the maximum number of cities you can visit.

This is part of tutorial text on dynamic programming. There is suggestion for solution also given in the tutorial.

Imagine having two travelers who start in the western most city. The travelers take turns traveling east, where the next traveler to move is always the western-most, but the travelers may never be at the same city, unless it is either the first or the last city. However, one of the traveler is only allowed to make "reverse flights," where he can travel from city A to city B if and only if there is a flight from city B to city A.
It's not too difficult to see that the paths of the two travelers can be combined to create a round-trip, by taking the normal traveler's path to the eastern-most city, and then taking the reverse of the other traveler's path back to the western-most city. Also, when traveler x is moved, you know that the traveler y has not yet visited any city east of traveler x except the city traveler y is current at, as otherwise traveler y must have moved once while x was west of y.

As far as I understood the solution, I think that the solution can be done by keeping a one dimensional table for outgoing city in forward direction and a table for outgoing city in reverse direction.
eg. If I have 5 cities, A,B...E orientated in required direction and directed graph between cities is A is starting city and E is the destination.
   A | B | C | D | E
A  0 | 1 | 0 | 0 | 0
B  0 | 0 | 1 | 1 | 0
C  1 | 0 | 0 | 0 | 1
D  0 | 0 | 0 | 0 | 1
E  0 | 0 | 1 | 0 | 0

I am keeping two tables one for outgoing city I will fill it by initializing first city as 1 ie. number of maximum cities visited and then for each next entry scan all the previous cities from which a path exists to the current city and then choose maximum, doing the same for reverse traveler.
table[i] = Max(j=i to 0) (table[j])

I will have maximum at the destination city, but this doesn't guarantee that any city is not repeated. If I keep one more entry in the array field along with maximum number I won't be able to switch it from forward to reverse. I am learning dynamic programming so may be I did not get correct idea.
This is the table which I constructed for the graph
A | B | C | D | E
1 | 2 | 3 | 3 | 4
1 | 1 | 2 | 1 | 3

so will take maximum from both. Please provide directions/hints so that I can proceed in right direction.
PS. this is not a homework question

A: Your approach with the two tables models the state for each traveler independently, as the number of cities already visited, combined with the location where that traveler is currently staying. As you found out yourself, that won't prevent visiting a city twice.
Instead, I'd use three elements to model state: the city where one traveler is currently located, the city where the other is located, and the number of cities they have visited in total, i.e. the sum of their individual counts. So you'd have a single 2d table, instead of your two 1d tables. Cell (f, r) would contain the best known number of total cities visited when the forward traveler is in city f and the reverse traveler is in city r.
You'd probably iterate over these states in order of their minimal element. That means you'll next expand a state which you have not expanded yet, and where the smaller of these two numbers is minimal among all unexpanded states. If in that state, f < r, then you'd use it to update states (f', r) with f' > r, if there is a flight from f to f'. On the other hand, if r < f you update (f, r') with r' > f and a flight from r' to r.
In pseudocode:
first = (f: 0, r: 0)  # tuple with two members, called f and r
todo = set { first }  # a set with a tuple as its only element
visited = a map from tuples to integers, unset values defaulting to 0
visited[first] = 1
while todo is not empty:
  best = ∞
  cur = null
  for t in todo:
    if min(t.f, t.r) < best:
      best = min(t.f, t.r)
      cur = t
  todo.remove(cur)
  if (cur.f < cur.r):
    for f' in cities where flights from f arrive:
      next = (f: f', r: cur.r)  # keep r but use f' as the new f
      todo.add(next)            # will do nothing if it already is in the set
      visited[next] = max(visited[next], visited[cur] + 1)
  else:
    for r' in cities where flights to r depart:
      next = (f: cur.f, r: r')
      todo.add(next)
      visited[next] = max(visited[next], visited[cur] + 1)
best = 0
for cur in keys of visited:
  if best < visited[cur]:
    if there is a flight from cur.f to cur.r: # can close the tour
      best = visited[cur]
return best


text:
Q: Eclipse Oomph upgrade I installed Eclipse version 2020-03 using oomph and after that, I upgraded eclipse version to a newer but there are many conflicts with plugins and dependencies.
Are there some way to upgrade oomph profile to a new version of eclipse? Now my eclipse is in 2022-06 version but oomph is 2020-03.


text:
Q: Js Custom sorting I'm trying to sort array of strings ['d', 'CC', 'BB', 'b', 'a', 'Am','AMG']
in such order ["AMG", "Am", "a", "BB", "b", "CC", "d"]
Using
arr.sort(function (a, b) {
  return a.toLowerCase().localeCompare(b.toLowerCase());
});

I get ["a", "Am", "AMG", "b", "BB", "CC", "d"]

A: You could chain some sort criteria, after swapping the case of the letters, then

*

*sort by first lower case characters ascending,

*sort by length descending

*sort by string ascending

function swap(s) {
    return Array.from(s, c => c.toUpperCase() === c ? c.toLowerCase() : c.toUpperCase()).join('');
}

var array = ['d', 'CC', 'BB', 'b', 'bb', 'a', 'Am', 'AMG'];

array.sort((a, b) => {
    var aa = swap(a),
        bb = swap(b);

   return a[0].toLowerCase().localeCompare(b[0].toLowerCase())
       || bb.length - aa.length
       || aa.localeCompare(bb);
});

console.log(array); // ["AMG", "Am", "a", "BB", "b", "CC", "d"]


text:
Q: How to run typeorm mysql commands from sql file? I would like to run mysql commands in a migration from an sql file. Can somebody help me, how to solve it?
import {MigrationInterface, QueryRunner} from "typeorm";
import * as fs from "fs";

var queries = fs.readFileSync(__dirname + '/geoinfo.sql').toString()
    .replace(/(\r\n|\n|\r)/gm," ") // remove newlines
    .replace(/\s+/g, ' '); // excess white space

export class HungarianStatesAndCities1564393283405 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.query(queries.toString() );
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.query("");
    }
}

A: you can use split queries by ';' and run individual query
const readSqlFile = (filepath: string): string[] => {
      return fs
        .readFileSync(path.join(__dirname, filepath))
        .toString()
        .replace(/\r?\n|\r/g, '')
        .split(';')
        .filter((query) => query?.length);
    };

public async up(queryRunner: QueryRunner): Promise<void> {
    const queries = readSqlFile('/geoinfo.sql');

    for (let i = 0; i < queries.length; i++) {
      await queryRunner.query(queries[i]);
    }
  }

A: Wrapped into the library at npm. Now you can include it in your project easily.
https://www.npmjs.com/package/node-sql-reader


text:
Q: "I work" vs "I am working" / "I live" vs "I am living"? I just watched two IELTS speaking videos. The first one's result is 8.5-9.0 and the second one's result is 9.0.
IELTS speaking Band Score 8.5-9.0: https://www.youtube.com/watch?v=wzzOowpCryw
IELTS speaking Band Score 9.0: https://www.youtube.com/watch?v=HjrlnyFKVKU
In the first video, there is this simple question:
A: ...Do you work or study?
B: I am still studying in my final year

In the second video, there is more or less the same kind of question:
A: ...Where do you live in your country?
B: I live in Hyderabad....

I asked my two British native friends. One said it should be "I am working" or "I am living", but the other one said both of those are fine.
So my question is which one is better to answer such question?

*

*"I work" vs "I am working" ?

*"I live" vs "I am living" ?

A: You question is about the differences between the present tense (I work) and the present progressive (I am working). Both are acceptable in both instances. The present progressive tense implies that you have been doing the activity for some period of time, and in the examples given (work, life), could imply that you are doing something in contrast to either what you did just before (I am living in New York [these days]), or what you plan to do afterwards (I am studying literature [but I plan to graduate and do other things with my life]).
These subtleties are minor, though, and highly contextual.


text:
Q: Aligning text to bottom of label I have several labels with a height of 3em. I'd like to align the text to the bottom of each label, such that a label with one line of text would have the text appear at the bottom of the label, while a label with two lines would have the second line appear at the bottom of the label.
For context, I have several columns in a Bootstrap row, each of which contains a label and a textarea. Some of the labels have longer text than others, which results in them taking up two lines of text when the width of the page is made smaller. I also set the height of each of the labels to 3em in order to prevent the textareas from appearing at different heights. However, I would like the text of the shorter labels to align with the bottom row of the longer labels (regardless of whether the longer labels are currently taking up one or two rows).
Example:

                    Short
                    <textarea id="textArea1"></textarea>

                    Short
                    <textarea id="textArea2"></textarea>

                    A longer label
                    <textarea id="textArea3"></textarea>

                    A longer label
                    <textarea id="textArea4"></textarea>

A: You can do this by putting the text in a span and using flex to align the span to the bottom of the label which will need to have display: flex. The simplest approach is margin-top:auto on the span in the label that has display: flex, or using justify-content: flex-end to force the spans to the bottom of the labels.
EDIT: Spans removed following feedback. THX

.row {
  margin: 0 -15px
}

.col-lg-3 {
  width: 25%;
  float: left;
  padding: 0 15px;
  margin-bottom: 15px
}

.titleLabel {
  height: 3em;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end
}

          A short one line label
          <textarea id="textArea1"></textarea>

          A longer label with at least two lines
          <textarea id="textArea3"></textarea>

          A longer label with enough text to run over three lines and will be very long
          <textarea id="textArea4"></textarea>


text:
Q: Unexpected end-of-input: expected close marker for Object (start marker at [Source: {; line: 1, column: 1]) at [Source: {; line: 1, column: 3] I need to deserialize a json object using Jackson.
After several efforts and internet search, all effort to resolve the error:
Exception in thread "main" com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input: expected close marker for Object (start marker at [Source: {; line: 1, column: 1])
     at [Source: {; line: 1, column: 3]

have failed.
I tried JacksonMixInAnnotations without success.
An example of the json is
{
    "imageDigest": "sha256:7cc1145883e4e6741fd4f02b8d01636ac341038de51e7923b9a5acf98329602a",
    "vulnerabilities": [
        {
            "fix": "None",
            "package": "apt-1.0.9.8.4",
            "severity": "Negligible",
            "url": "https://security-tracker.debian.org/tracker/CVE-2011-3374",
            "vuln": "CVE-2011-3374"
        }
    ],
    "vulnerability_type": "os"
}

My deserialization code:
String line = "";
    File file = new File ("C:\\xxxxxxx\\xxxxxx\\kbastani-movie-microservice04.json");
    Anchore anchore = new Anchore();
    ObjectMapper mapper = new ObjectMapper();
    BufferedReader breader = new BufferedReader(new FileReader(file));
    while((line= breader.readLine()) != null) {
    anchore = mapper.readValue(line, Anchore.class);
    System.out.println(anchore);
    List <Vulnerability> vulnerability = anchore.getVulnerabilities();
    System.out.println(vulnerability.get(1));

    }

    breader.close();

Anchore class
public class Anchore {
    @JsonProperty("imageDigest")
    private String imageDigest;
    @JsonProperty("vulnerabilities")
    private List<Vulnerability> vulnerabilities = null;
    @JsonProperty("vulnerability_type")
    private String vulnerabilityType;

    public Anchore() {
    }

     public Anchore(String imageDigest, List<Vulnerability> vulnerabilities, String vulnerabilityType) {
        super();
        this.imageDigest = imageDigest;
        this.vulnerabilities = vulnerabilities;
        this.vulnerabilityType = vulnerabilityType;
    }
}

Vulnerability class
@JsonIgnoreProperties(ignoreUnknown = true)
public class Vulnerability {

        @JsonProperty("fix")
        private String fix;
        @JsonProperty("package")
        private String imagePackage;
        @JsonProperty("severity")
        private String severity;
        @JsonProperty("url")
        private String url;
        @JsonProperty("vuln")
        private String vuln;

        public Vulnerability() {
        }
}

A: when you call breader.readLine(), you read a single line.
You need to read the whole json before calling mapper.readValue(line, Anchore.class);, this should be outside the loop.

*

*read the whole file into a string

*transform the string into your object with the ObjectMapper.

edit: to read a file:
String path = "C:\\xxxxxxxxxx\\xxxxxxxxxx\\kbastani-movie-microservice04.json";
byte[] encoded = Files.readAllBytes(Paths.get(path));
String json = new String(encoded, StandardCharsets.UTF_8);
anchore = mapper.readValue(json, Anchore.class);

A: You n have few mistakes

*

*You need to read the all file before you parsing your json to an object

*You trying to get vulnerability.get(1) while you have only one vulnerability in your json.

Here is a simple & cleaner way to achieve what you are looking for :
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class MainJackson {
    public static void main(String[] args) throws IOException {

        Path jsonPath = Paths
                .get("jsonPath.json")
                .toAbsolutePath();

        String jsonText = Files.lines(jsonPath)
                .reduce("", String::concat);

        ObjectMapper mapper = new ObjectMapper();

        Anchore anchore = mapper.readValue(jsonText, Anchore.class);
        System.out.println(anchore);

        List<Vulnerability> vulnerability = anchore.getVulnerabilities();
        System.out.println(vulnerability.get(0));

    }
}


text:
Q: Dynamic injection of bean properties based on a locale variant in Spring Consider the following class DialgBean.java, which defines the properties of a dialog box on a web page. Below is the class and its bean definition
public class DialogBean{
  private int height;

  public void setHeight(int height)
  ...
}

<bean id="dialogBean" class="org.springhelp.DialogBean">
 <property name="height" value="${dialogBean.height}"/>
 ...
</bean>

From the above example you can see that the DialogBean's height property is being fetched by a PropertyPlaceholderConfigurer.
The problem is that the application I am working on supports multiple clients, and most clients have separate requirements for the height parameter of a dialog box. Therefore, I can not simply pull the height parameter from one properties file.
So, how do I inject a client specific height parameter into a DialogBean using the bean definition described above, where the client id is stored as the variant in the java.util.Locale object?
Is there a way to pass to a custom bean factory post processor run time data like the Locale?

A: Sounds like you need a ResourceBundle or, in Spring parlance, a MessageSource. Inject that into your bean, and programmatically resolve the value you want at runtime.
MessageSource can wrap the basic ResourceBundle, and is much easier to use.

A: The simpler, but more cumbersome solution, is

*

*declare one bean per local variant and extend from a parent (base) bean.

*create a thin wrapper for the BeanFactory that accepts the Locale

*upon lookup for a Locale based bean, the wrapper creates bean name options from the parent (base) bean name and the Locale

*traverse over the list of bean defintion names and find the first one that matches the list of created name options.

Of course, the list of options have to be in order of priority.


text:
Q: Use python to automate series of file comparison functions against directory of files The functions below must be run in order to output cosine similarity in degrees and radians between two files. I want to automate this to process 500 files in same directory against the first file (one file at a time against first file): RUMO4009_M.txt. I would like the keep the output for all processed files to see output for each of the 500 files compared with first file. Example Output:

File RUMO4009_M.txt : 2836 lines,  509 words,  278 distinct words File
RUMO5038_M.txt : 2672 lines,  479 words,  212 distinct words The
cosine between the documents is  0.768315. The angle between the
documents is  0.694592 radians or  40 degrees.

import math
import string
import sys

##################################
### Read a text file ###
##################################
def read_file(filename):
    try:
        with open(filename, 'r') as f:
            data = f.read()
        return data
    except IOError:
        print("Error opening or reading input file: ", filename)
        sys.exit()

# using a global variable to map upper case to lower case which will help functions speed up further down.
translation_table = str.maketrans(string.punctuation+string.ascii_uppercase," "*len(string.punctuation)+string.ascii_lowercase)

#################################################
### Split the text lines into words ###
#################################################
def get_words_from_line_list(text):
    text = text.translate(translation_table)
    word_list = text.split()
    return word_list
get_words_from_line_list(read_file('RUMO4009_M.txt'))

#################################################
### Split the text lines into words ###
#################################################
def get_words_from_line_list(text):
    text = text.translate(translation_table)
    word_list = text.split()
    return word_list
get_words_from_line_list(read_file('RUMO5038_M.txt'))

#################################################
### Define dotProduct and vector_angle ###
#################################################

def dotProduct(P1, P2):
    tot=0.0

    for key in P1:

        if key in P2:
            tot+=(P1[key]*P2[key])

    return tot

# angle in radians between document vectors
def vector_angle(P1, P2):
    num=dotProduct(P1, P2)
    den=math.sqrt(dotProduct(P1, P1)*dotProduct(P2, P2))

    return math.acos(num/den)

##############################################
### Count frequency of each word ###
##############################################
def count_frequency(word_list):
    D = {}
    for new_word in word_list:
        if new_word in D:
            D[new_word] = D[new_word] + 1
        else:
            D[new_word] = 1
    return D

count_frequency(get_words_from_line_list(read_file('RUMO4009_M.txt')))

##############################################
### Count frequency of each word ###
##############################################
def count_frequency(word_list):
    D = {}
    for new_word in word_list:
        if new_word in D:
            D[new_word] = D[new_word] + 1
        else:
            D[new_word] = 1
    return D

count_frequency(get_words_from_line_list(read_file('RUMO5038_M.txt')))

###### Define Word Frequencies #########

def word_frequencies_for_file(filename,verbose=False):

    line_list = read_file(filename)
    word_list = get_words_from_line_list(line_list)
    freq_mapping = count_frequency(word_list)

    print("File", filename, ":", )
    print(len(line_list), "lines, ", )
    print(len(word_list), "words, ", )
    print(len(freq_mapping), "distinct words")
    return freq_mapping

word_frequencies_for_file('RUMO4009_M.txt')

def word_frequencies_for_file(filename,verbose=False):

    line_list = read_file(filename)
    word_list = get_words_from_line_list(line_list)
    freq_mapping = count_frequency(word_list)

    print("File", filename, ":", )
    print(len(line_list), "lines, ", )
    print(len(word_list), "words, ", )
    print(len(freq_mapping), "distinct words")
    return freq_mapping

word_frequencies_for_file('RUMO5038_M.txt')

##### Cosine Similarity function #######

def document_similarity(filename_1, filename_2, verbose=True):
    """DOCSTRING"""
    '''document_similarity function compares two docs for similarities in line, word, and distinct words count.
    The line: sorted_word_list_1 = word_frequencies_for_file(filename_1, verbose) is biggest
    issue with efficiency.'''
    sorted_word_list_1 = word_frequencies_for_file(filename_1, verbose)
    sorted_word_list_2 = word_frequencies_for_file(filename_2, verbose)
    cosine = vector_angle(sorted_word_list_1,sorted_word_list_2)
    # Use f-strings; see https://realpython.com/python-f-strings/ for more information
    if verbose:
        print(f"The cosine between the documents is {cosine : 0.6f}.")
        print(f"The angle between the documents is {math.acos(cosine) : 0.6f} radians or {math.acos(cosine)*180/math.pi : .0f} degrees.")

document_similarity('RUMO4009_M.txt','RUMO5038_M.txt')

OUTPUT:
File RUMO4009_M.txt :
2836 lines,
509 words,
278 distinct words
File RUMO5038_M.txt :
2672 lines,
479 words,
212 distinct words
File RUMO4009_M.txt :
2836 lines,
509 words,
278 distinct words
File RUMO5038_M.txt :
2672 lines,
479 words,
212 distinct words
The cosine between the documents is  0.768315.
The angle between the documents is  0.694592 radians or  40 degrees.

A: ### COSINE SIMILARITY
### USE THIS BELOW TO LOOP THROUGH DIRECTORY OF TXT DOCUMENTS
### COMPARED TO SINGLE SPECIFIED TXT FILE

### %%writefile example.txt

# Import libraries
import math
import string
import sys
import glob

# Locate filenames
filenames = glob.glob('*.txt')
print(filenames)

# Using a global variable to map upper case to lower case which will help functions speed up further down.
translation_table = str.maketrans(string.punctuation+string.ascii_uppercase," "*len(string.punctuation)+string.ascii_lowercase)

##################################
### Read a text file ###
##################################

def read_file(filename):
    try:
        with open(filename, 'r') as f:
            data = f.read()
        return data
    except IOError:
        print("Error opening or reading input file: ", filename)
        sys.exit()

#################################################
### Split the text lines into words ###
#################################################

def get_words_from_line_list(text):
    text = text.translate(translation_table)
    word_list = text.split()
    return word_list

#################################################
### Define dotProduct and vector_angle ###
#################################################

# dotProduct
def dotProduct(P1, P2):
    tot=0.0

    for key in P1:

        if key in P2:
            tot+=(P1[key]*P2[key])

    return tot

# angle in radians between document vectors
def vector_angle(P1, P2):
    num=dotProduct(P1, P2)
    den=math.sqrt(dotProduct(P1, P1)*dotProduct(P2, P2))

    return math.acos(num/den)

##############################################
### Count frequency of each word ###
##############################################

def count_frequency(word_list):
    D = {}
    for new_word in word_list:
        if new_word in D:
            D[new_word] = D[new_word] + 1
        else:
            D[new_word] = 1
    return D

##############################################
### Define Word Frequencies ###
##############################################

def word_frequencies_for_file(filename,verbose=False):

    line_list = read_file(filename)
    word_list = get_words_from_line_list(line_list)
    freq_mapping = count_frequency(word_list)

    print("File", filename, ":", )
    print(len(line_list), "lines, ", )
    print(len(word_list), "words, ", )
    print(len(freq_mapping), "distinct words")
    return freq_mapping

##############################################
### Cosine Similarity function  ###
##############################################

def document_similarity(filename_1, filename_2, verbose=True):
    """DOCSTRING"""
    '''document_similarity function compares two docs for similarities in line, word, and distinct words count.
    The line: sorted_word_list_1 = word_frequencies_for_file(filename_1, verbose) is biggest
    issue with efficiency.'''
    sorted_word_list_1 = word_frequencies_for_file(filename_1, verbose)
    sorted_word_list_2 = word_frequencies_for_file(filename_2, verbose)
    angle = vector_angle(sorted_word_list_1,sorted_word_list_2)
    # Use f-strings; see https://realpython.com/python-f-strings/ for more information
    if verbose:
        print(f"The cosine between the documents is {math.cos(angle) : 0.6f}.")
        print(f"The angle between the documents is {angle : 0.6f} radians or {angle*180/math.pi : .0f} degrees.")
    return math.cos(angle)

# create empty list
cosine_array=[]

# LOOP THROUGH DIRECTORY OF TXT DOCUMENTS
# s represents all target TXT files to compare against source (main) TXT 1 i.e.: 'RUMO4009.M.txt')
for s in filenames:
    get_words_from_line_list(read_file('RUMO4009_M.txt')) #Change TXT 1 here to compare all files against
    get_words_from_line_list(read_file(s))
    count_frequency(get_words_from_line_list(read_file('RUMO4009_M.txt'))) #Change TXT 1 to compare all files against
    count_frequency(get_words_from_line_list(read_file(s)))
    new_cosine = document_similarity('RUMO4009_M.txt',s) #Change TXT 1 to compare all files against; keep s variable
    cosine_array.append((new_cosine,s))

### NOW SORT RESULTS IN COSINE DESCENDING ORDER ###
# Most similar target txt files (to source file) will be listed first
# 1.0 value is highest value of similarity; if your source txt is in the target directory,
# it will be compared with itself and have the highest similarity possible: a cosine of 1.0.
# 0.0 value would be the lowest cosine value of similarity

cosine_array.sort(reverse=True,key=lambda x: x[0])

### NOW PRINT OUT SORTED RESULTS ###

cosine_array

### NOW PLACE SORTED RESULTS INTO A PANDAS DATAFRAME AND EXPORT TO CSV FILE ###

import pandas as pd

df=pd.DataFrame(cosine_array)
df=df.rename(columns={0:'Cosine between Source and Target TXT',1:'Target TXT'})
df.to_csv("results.csv",index=False)
df


text:
Q: CropZoom not working with IIS 7.5 but works with IIS 7.5 Express This is rather strange to me.  I could generalize this question to be javascript/webserver specific but i'll give you the details.
I've integrated image cropping into my asp.net webforms application.  this is the image cropper i am using:
http://www.gastonrobledo.com.ar/cropzoom/index.html
it works fine in VS development server & IIS express 7.5, but as soon as i deploy it to IIS 7.5 full version on Windows 2008 R2, the cropper functionality stops working in IE8 & IE9 browsers only!  Everything else in my web app works fine.  This is really strange as I am using all the default settings in both IIS Express and IIS full version (i've switched the authentication mode to 'Windows' in both)
I'm not sure were to start looking as far as IIS 7.5 settings relating to javascript and or css files.  Any ideas on how to troubleshoot this?  I have checked all the trivial stuff (making sure im deploying all the files, etc)

A: Probably this tool uses some server side code/script which requires higher privileges.
IIS Express (and also VS development server) run as current logged on user, whereas IIS runs with app pool identity. Try running IIS with an app pool that has higher privileges.


text:
Q: How to solve $T(n)=T((4/5)n+1)+n^2$. I have a problem with this recurrence relation. I have to find the Theta notation. I tried to solve it with the iterative method. The generic formula I calculated is:
\begin{equation}
T(n)=T[(4/5)^k n]+[(4/5)^{k+1} n]^2+[(4/5)^{k+2} n]^2+\cdots+n^2
\end{equation}
$n=(4/5)^k\Rightarrow k=\log_{4/5}(n)$.
At this point I tried to calculate the geometric series, forgetting the square elevation. I don't know how to continue.
Thanks for your attention.

A: Hint.
Asymptotically $T(n)\approx T(an)-n^2$ with $a= \frac 45$.
Now making $n=a^m$ and substituting we arrive to the equivalent recurrence
$$
R(m) = R(m-1) - \frac{a^{2m}}{a^2}
$$
with solution
$$
R(m) = c_0-\frac{a^{2m}-1}{a^2-1}
$$
now we can go backwards making $m = \log_a n$, hence $T(n) = \mathcal{O}(n^2)$
Follows a MATHEMATICA script simulating the recurrence (red) as well as the asymptotic approximation (blue)
Clear[Rec, f]
a = 4/5;
f[n_] := (n^2 - 1)/(1 - a^2)
nmin = 5;
nmax = 2000;

Rec[n_] := Module[{}, If[n < nmin, Return[0]];
  If[n == nmin, Return[0]];
  Return[Rec[Floor[a n + 1]] + n^2]
  ]

tab = Table[{n, Rec[n]}, {n, nmin, nmax}];
gr1 = ListPlot[tab, PlotRange -> All, Filling -> Axis, PlotStyle -> {Thick, Red}];
gr2 = Plot[f[x], {x, nmin, nmax}, PlotStyle -> {Blue, Thick}];
Show[gr1, gr2, PlotRange -> All]


text:
Q: Annotating swagger models (@ApiModelProperty) and apis/resources in different binaries/packages Is annotating your data models in a different library/package and apis in a different package supported? Has any one tried this?

A: There shouldn't be any problem with that as long as everything is loaded within the scope of a single classloader. The scanning will be done on anything that's reachable.


text:
Q: Graphs are not rendering in Rstudio using ggplot I am trying to create Graphs using ggplot2 but it is not rendering eveen though there are no errors thrown.
The R version am using is 3.6.1
airquality <- airquality[complete.cases(airquality),]

p <- ggplot(airquality, aes(Ozone,Temp))+
  geom_point(color = "steelblue", size = 3, alpha = 0.5)+
  facet_grid(.~Month)+
  geom_smooth(method = "lm")

The plot area is blank when I run the code

A: you are assigning the plot to p. either remove the assignment (p <-) or add a print statement print(p).


text:
Q: Безопасно ли сравнивать переменные с присвоенными значениями константы между собой? Есть код:
const double Pi = 3.14;
double a = Pi;
double b = Pi;

кода типа:
double x = 3.;
double b = (4.0 - x) * Pi;

в программе быть не может, т.е. всегда идет присваивание var = Pi.
Корректно ли в этом (и только в этом) случае сравнивать a == b?
Чуть добавлю. Присвение константы в программе может выглядеть примерно так:
double b = some_expression;
if (b < Pi + epsilon && Pi - epsilon < b) b = Pi;

И никак иначе.
П.С. Использвание числа, похожего на математическое "пи" - только для примера, к реальности отношения не имеет.
Попробуем сформулировать вопрос более широко. Есть две строки кода, идущие подряд.
double x = some_value;
double y = x;
// not double y = some_expression_that_equal_to_x;

Типы x, y одинаковые, это важно. Гарантированно ли одинаковое двоичное представление x и y?

A: Если компилятор случайно подставит константу в выражение как long double, а переменная будет double, то неожиданно окажется, что они всё-таки не равны. Так что лучше не надо, если только ты не стопроцентно уверен, что твоя константа точно представима в типе double.

A: Ответ на более "широкий" вопрос. Да, одинаковое двоичное представление гарантировано. Без вариантов. В противном случае (помимо просто абсурдности) были бы возможны всякие интересные штуки например, при:
double a = 3.14;

операция
a = a;

меняла бы двоичное представление a.


text:
Q: How to get overlapping edges using igraph? I am trying to create a network graph with overlapping edges.
require(igraph)
g <- graph( c(1,2, 1,2, 1,2, 1,2, 1,2, 1,2, 1,2, 1,2, 1,3, 2,3, 3,5), n=5, directed=FALSE )
V(g) #Vertex sequence
E(g) #Edge sequence
plot(g, layout=layout.circle, vertex.label=c("a","b","c","d","e"))

This results in 8 non-overlapping edges between 'a' and 'b'. What can I do to replace these non-overlapping lines with a thicker line (proportional to 8 times a single line)?

A: Set curved to FALSE, and width to the number of multiple edges using count.multiple, see the details in the manual: http://igraph.org/r/doc/plot.common.html
E(g)$curved <- FALSE
E(g)$width <- count.multiple(g)
plot(g, layout=layout.circle, vertex.label=c("a","b","c","d","e"))

A: Used edge.curved=FALSE and got the result.


text:
Q: Is it possible to dynamically change the style/template of a control? I am creating a UserControl in Silverlight 4 which has a watermarked background.
The watermark should change depending on the underlying 'type' the UserControl is representing.
The watermark is created using a Path and I have extracted all the properties into a style.
I was wondering if it would be possible to change the style of the Path at runtime based on some known value.
I am using MVVM and Unity.  Perhaps I could bind the style somehow?  Or could I inject the style when the view is created?
I may have to do this with control templates, hence the reference in the title.
Thanks...

A: Instead of using control templates to change the style of the watermark, why dont you use the VisualStateManager to change the state of the watermark based on the 'type'.


text:
Q: python - openchange provision failure Ubuntu 12.04.5
When I get to the part where I need to provision openchange detailed here: http://www.openchange.org/cookbook/configuring.html
I am directed to type in the following command:
:~/openchange# sudo PYTHONPATH=$PYTHONPATH ./setup/openchange_provision --standalone

I keep getting the following error:
NOTE: This operation can take several minutes
[+] Step 1: Register Exchange OIDs
[+] Step 2: Add Exchange attributes to Samba schema
schema_data_add: updates are not allowed: reject request

Error: "(53, 'schema_data_add: updates are not allowed: reject request\n')" when adding element:

 ms-Exch-Access-Control-Map
 Contains the mapping for the access controls.

dn: CN=ms-Exch-Access-Control-Map,CN=Schema,CN=Configuration,DC=stremblay,DC=local
objectClass: top
objectClass: attributeSchema
cn: ms-Exch-Access-Control-Map
distinguishedName: CN=ms-Exch-Access-Control-Map,CN=Schema,CN=Configuration,DC=stremblay,DC=local
attributeID: 1.2.840.113556.1.4.7000.102.64
attributeSyntax: 2.5.5.12
isSingleValued: TRUE
showInAdvancedViewOnly: TRUE
adminDisplayName: ms-Exch-Access-Control-Map
adminDescription: ms-Exch-Access-Control-Map
oMSyntax: 64
searchFlags: 0
lDAPDisplayName: msExchAccessControlMap
name: ms-Exch-Access-Control-Map
 schemaIDGUID: 8ff54464-b093-11d2-aa06-00c04f8eedd8
isMemberOfPartialAttributeSet: FALSE
objectCategory: CN=Attribute-Schema,CN=Schema,CN=Configuration,DC=stremblay,DC=local

[!] error while provisioning the Exchange schema classes (53): schema_data_add: updates are not allowed: reject request

Traceback (most recent call last):
  File "./setup/openchange_provision", line 109, in <module>
    openchange.provision(setup_path, provisionnames, lp, creds)
  File "/usr/local/samba/lib/python2.7/site-packages/openchange/provision.py", line 777, in provision
    install_schemas(setup_path, names, lp, creds, reporter)
  File "/usr/local/samba/lib/python2.7/site-packages/openchange/provision.py", line 447, in install_schemas
    provision_schema(sam_db, setup_path, names, reporter, schema['path'], schema['description'], schema['modify_mode'])
  File "/usr/local/samba/lib/python2.7/site-packages/openchange/provision.py", line 233, in provision_schema
    sam_db.add_ldif(el, ['relax:0'])
  File "/usr/local/samba/lib/python2.7/site-packages/samba/__init__.py", line 224, in add_ldif
    self.add(msg, controls)
_ldb.LdbError: (53, 'schema_data_add: updates are not allowed: reject request\n')
root@mail:~/openchange# error while provisioning the Exchange schema classes (53): schema_data_add: updates are not allowed: reject request

Any help to solve this error

A: Add this on your smb.conf
sudo nano /etc/samba/smb.conf

# [global]
dsdb:schema update allowed=true


text:
Q: Optaplanner VariableListener corruption I'm facing a problem with Optaplanner.
It started when I was trying to implement a solution of type Pick and Delivery base on the VehicleRoutingProblem.
In one of my tests I see something wrong in the debug but the result seems to be the best solution.
This is what I see :

*

*Agent-0

*Customer-11_PICKUP_1_[1]

*Customer-12_DELIVERY_1_[]

*Customer-21_PICKUP_2_[2]

*Customer-22_DELIVERY_2_[]

*Customer-41_PICKUP_4_[4]

*Customer-42_DELIVERY_4_[]

*Customer-31_PICKUP_3_[4, 3]

*Customer-32_DELIVERY_3_[4]

This it the path of the linked list of customers.
The Agent-0 is the agent.
The Customer-XX is the customer.
PICKUP_X or DELIVERY_X is the type of thing the agent must do and the X represent the number of the item.
The thing in bracket is the content of the agent.
As you can see in the example, after the DELIVERY_4, the item numbered 4 appears but it is already delivered ...
I think there is a problem with the variablelistener.
There is a shadow variable (agentContents) in the Customer that tracks what the agent has.
So I decided to turn on the FULL_ASSERT.
And what I see is pretty interesting.
There is an exception :
java.lang.IllegalStateException: Solving failed.
    at org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame$SolveWorker.done(SolverAndPersistenceFrame.java:298)
    at javax.swing.SwingWorker$5.run(Unknown Source)
    at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.run(Unknown Source)
    at sun.swing.AccumulativeRunnable.run(Unknown Source)
    at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.actionPerformed(Unknown Source)
    at javax.swing.Timer.fireActionPerformed(Unknown Source)
    at javax.swing.Timer$DoPostEvent.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: VariableListener corruption: the entity (Customer-32)'s shadow variable (Customer.agentContents)'s corrupted value ([4]) changed to uncorrupted value ([]) after all VariableListeners were triggered without changes to the genuine variables.
Probably the VariableListener class for that shadow variable (Customer.agentContents) forgot to update it when one of its sources changed after completedAction (Undo(Customer-21 {Customer-12 -> Customer-32})).
    at org.optaplanner.core.impl.score.director.AbstractScoreDirector.assertShadowVariablesAreNotStale(AbstractScoreDirector.java:349)
    at org.optaplanner.core.impl.phase.scope.AbstractPhaseScope.assertExpectedUndoMoveScore(AbstractPhaseScope.java:144)
    at org.optaplanner.core.impl.localsearch.decider.LocalSearchDecider.doMove(LocalSearchDecider.java:153)
    at org.optaplanner.core.impl.localsearch.decider.LocalSearchDecider.decideNextStep(LocalSearchDecider.java:121)
    at org.optaplanner.core.impl.localsearch.DefaultLocalSearchPhase.solve(DefaultLocalSearchPhase.java:72)
    at org.optaplanner.core.impl.solver.DefaultSolver.runPhases(DefaultSolver.java:214)
    at org.optaplanner.core.impl.solver.DefaultSolver.solve(DefaultSolver.java:176)
    at org.optaplanner.examples.common.business.SolutionBusiness.solve(SolutionBusiness.java:307)
    at org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame$SolveWorker.doInBackground(SolverAndPersistenceFrame.java:287)
    at org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame$SolveWorker.doInBackground(SolverAndPersistenceFrame.java:1)
    at javax.swing.SwingWorker$1.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at javax.swing.SwingWorker.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

The undo move seems to trigger the problem.
But I can't see where is the problem exactly. I think my variablelistener is offending.
Plus I don't undestand how to read this : Undo(Customer-21 {Customer-12 -> Customer-32})).
Have you some way to debug this ?
I can give you some code if needed.
Thank you.


text:
Q: Disabled button in WPF I'm trying to do something very simple and basic. Correct me if I'm wrong:
Think of a simple button and then methods associated to it as following. However, I'm getting either none (a disabled button) of if I change returning type on DrawShapeCanExecute() then I would get an error message as:
bool WpfApplication8.DrawingCanvas.DrawShapeCanExecute(object, System.Windows.Input.CanExecuteRoutedEventArgs)' has the wrong return type
public static RoutedCommand DrawShape = new RoutedCommand();

private void DrawShapeCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
} **//Isn't this enough to make it enable?**

private void DrawShape_Executed(object sender, ExecutedRoutedEventArgs e)
{

}

its xaml portion has:
<Button Margin="0,2,2,2" Width="70" Content="Line"
        Command="{x:Static local:DrawingCanvas.DrawShape}"
        CommandTarget="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
            AncestorType={x:Type Window}}, Path=DrawingTarget}"
        CommandParameter="Line">
</Button>

A: You need to mark the event as handled:
e.CanExecute = true;
e.Handled = true;

A: From http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx I see you need to bind the CanExecute and Executed handlers. It would be something like:
<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:DrawingCanvas.DrawShape }"
                Executed="DrawShape_Executed"
                CanExecute="DrawShapeCanExecute" />
</Window.CommandBindings>

<Button Margin="0,2,2,2" Width="70" Content="Line"
    Command="{x:Static local:DrawingCanvas.DrawShape}"
    CommandTarget="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
        AncestorType={x:Type Window}}, Path=DrawingTarget}"
    CommandParameter="Line">
</Button>

A: Adding this statement in MainWindow.xaml.cs solves it:
public IInputElement DrawingTarget { get { return _canvas; } }
The point is that we are adding a menubar not on form but on a canvas.


text:
Q: How to create a game trainer in python using pointer and offset Hi guys I would like to make my first game trainer in python. I am using the Pymem library for editing the memory. Initially, I found pointers using a cheat engine and it works when I open the game and finds the address of the variables. But I would like to do it programmatically using python and make a game trainer with python so i need to write code to get pointers (or addresses). How to to use a pointer with offset, all while pointer changes during the game so that I can modify variables of the game. Thank you and sorry for my bad english :)
Example:
import pymem
import pymem.process
import pymem.memory

process = pymem.process
mem = pymem.memory

DMC5 = pymem.Pymem("ac_client.exe")
DMC5_base = DMC5.process_handle

adress = 0x029AA270
value = 99

mem.write_int(DMC5_base, adress, value)

The varable Address change when reopen the game, therefore my question is, how get the new address value or a pointer to write the variable again?


text:
Q: Does Java 8 work on Android api 24 and above Or you can use in lower api? In android, based on this page Java 8 Languages Features, does android work only in API 24 and above, or you can use in API lower than API 24, and if you can use these features, which most miniature version of API in android support these features

A: Update
The Jack toolchain is deprecated. Java8 features are coming to the standard toolchain if you use the android plugin version 2.4.0-alpha4 (or higher). More info here.
Original answer
The Java 8 features are available on API N and newer with exception of lambdas. Lambdas are back-ported (using anonymous classes) back to Gingerbread.

The Android N bases its implementation of lambda expressions on
  anonymous classes. This approach allows them to be backwards
  compatible and executable on earlier versions of Android.

To test this you need Android Studio 2.1 preview, JDK 8 installed and the latest build tools.
Example build config:
android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0 rc1"

    defaultConfig {
        minSdkVersion 23
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        jackOptions {
            enabled true
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

A: Update:
Beginning with Android Studio 2.4, the Jack compiler will be deprecated and Java 8 Support will be integrated in the default build chain. Some Java 8 features are available on any API level, some are still limited to API >= 24, see:
https://developer.android.com/studio/preview/features/java8-support.html
Old answer:
The Java 8 features are available beginning from API level 9, but only if you use Android Studio 2.1 (preview) and the Android N Preview SDK
http://android-developers.blogspot.de/2016/03/first-preview-of-android-n-developer.html

Improved Java 8 language support - We're excited to bring Java 8 language features to Android. With Android's Jack compiler, you can now use many popular Java 8 language features, including lambdas and more, on Android versions as far back as Gingerbread. The new features help reduce boilerplate code. For example, lambdas can replace anonymous inner classes when providing event listeners. Some Java 8 language features --like default and static methods, streams, and functional interfaces -- are also now available on N and above. With Jack, we're looking forward to tracking the Java language more closely while maintaining backward compatibility.

A: Update
Starting with Android Studio 2.4, the Jack compiler will be deprecated.
Android Studio 3.0 and later supports all Java 7 language features and a subset of Java 8 language features that vary by platform version.
All info in the official doc:
https://developer.android.com/studio/write/java8-support
You can also configure it directly in the corresponding build.gradle file:
Just configure:
android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  // For Kotlin projects
  kotlinOptions {
    jvmTarget = "1.8"
  }
}