text:
Q: union of two queries in one I have two queries with different result sets but only one of the conditions is additional in one of the queries. Both queries are fetching from the same table.
first query:
SELECT cm.ctm, count_big(*) AS TOTAL
                       FROM dbo_cm.cm
                       WHERE
                          cm.a= 'abc' AND
                          cm.b= 1 AND
                          cm.ps IS NOT NULL AND
                          datepart(MONTH, cm.ps) = 7 AND
                          datepart(YEAR, cm.ps) = 2015
                       GROUP BY cm.ctm

second query:
SELECT cm.ctm, count_big(*) AS TOTAL
                       FROM dbo_cm.cm
                       WHERE
                          cm.a= 'abc' AND
                          cm.b= 1 AND
                          cm.ps IS NOT NULL AND
                          datepart(MONTH, cm.ps) = 7 AND
                          datepart(YEAR, cm.ps) = 2015 and
                          cm.as>cm.ps
                       GROUP BY cm.ctm

How do I make this query simpler by merging it into one? We use decode in Oracle for this purpose.

A: You can merge these two queries into one by moving the additional condition in the second query to a case expression and returning null when the condition is not met. count_big, like any aggregate function, will just ignore the nulls:
SELECT   cm.ctm,
         COUNT_BIG(*) AS total1,
         COUNT_BIG(CASE WHEN cm.as > cm.ps THEN 1 ELSE NULL END) AS total2
FROM     dbo_cm.cm
WHERE    cm.a= 'abc' AND
         cm.b= 1 AND
         cm.ps IS NOT NULL AND
         DATEPART(MONTH, cm.ps) = 7 AND
         DATEPART(YEAR, cm.ps) = 2015 AND
GROUP BY cm.ctm

A: You can use SUM(CASE...) like:
SELECT
   cm.ctm,
   count_big(*) AS TOTAL1,
   SUM(CASE WHEN cm.[as]>cm.[ps] THEN 1 ELSE 0 END) AS TOTAL2
FROM dbo_cm.cm
WHERE cm.a= 'abc'
  AND cm.b= 1
  AND cm.ps IS NOT NULL
  AND datepart(MONTH, cm.ps) = 7
  AND datepart(YEAR, cm.ps) = 2015
GROUP BY cm.ctm


text:
Q: Codeigniter form submit but no Db Query using my model Learning CodeIgniter 3 and trying to do a simple search to query the Db... :-)
I built my Controller, The model that must query the Db, and the view that contains both the results and the search field...
My form actually submit and I get the $_POST array after submit on the form... But it seems the model, even being called (or not correctly!?!?!) is not querying the Db... Why not?
Search.php controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {
          public function __construct()
        {
                parent::__construct();
                $this->load->helper('url');
                $this->load->database();
                $this->load->helper('text');
                $this->load->library('pagination');
                $this->load->helper('form') ;
                //$this->load->library('MY_sphinxclient');

                $this->load->model('Search_model');
        }
    public function index()
    {

      if ($this->form_validation->run() === FALSE)
      {
        $this->load->view('search');
      }
      else
      {
      $data['search']=$this->input->get_post('search');
      $this->Search_model->get_search($data);
      $this->load->view('search');
      }
    }
      }

Search_model.php
<?php
        class Search_model extends CI_Model {

        public function __construct()
        {
        // Call the Model constructor
        parent::__construct();
        }
        public function get_search($search_submit)
        {
          $sql = "SELECT  ads.id AS id, 1 AS table_id, location, provLabel, text,
          R_rand, addate, adcat.name AS catname, adsubcat.name AS subname, f_value
          FROM ads
          JOIN search_town ON search_town.townId=ads.townId
          JOIN search_region ON search_region.regionId=search_town.relRegionId
          JOIN search_prov ON search_prov.provId=search_region.relProvId
          JOIN adcat ON adcat.id=ads.catid
          JOIN adsubcat ON adsubcat.id=ads.subcatid
          LEFT JOIN adfields ON adfields.ad_id=ads.id
          WHERE ads.adactive=1 AND ads.subcatid!=841 AND scam=0 AND ads.catid!=8
          AND (text LIKE '%$search_submit%' OR f_value LIKE '%$search_submit%')";
          $query = $this->db->query($sql);
          return $query->result();
          $result= $query->result();
          echo count($result);

        }

        }

My simple view search.php
<?php
echo 'Hello World!!!';
if(isset($_POST)){
var_dump($_POST);
}

echo form_open('search');
echo form_label('Search: ');
$data_name = array(
'name' => 'search',
'id' => 'search',
'placeholder' => 'Search'
);
echo form_input($data_name);
echo form_submit('submit', 'Submit');
echo form_close( );

if(isset($search)){
echo '
';
foreach($search as $rows) {
    echo '

            '.$rows->id.'
            '.$rows->text.'

';
}
echo '
';
}

search_submit();

A: Your model is named Search_model but you are using $this->search_model.
Shouldn't this:
$this->search_model

Be:
$this->Search_model

Or maybe you should specify a name when performing the load:
$this->load->model('Search_model', 'search');
$this->search->get_search();

Checking your latest edit:
$this->load->model('Search_model', 'search');
$this->search->get_search($seach); //Shouldn't $search be $this->input->get_post('search')

A:
Make your equals on form_validation instead of === use ==
Make sure you load form_validation library
Your missing form_validation->set_rules()
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {
    public function __construct() {
    parent::__construct();
        // I would autoload Database
        $this->load->database();

        $this->load->helper('url');

        $this->load->helper('text');
        $this->load->library('pagination');
        $this->load->helper('form');
        $this->load->model('search_model');
    }

    public function index() {

        $this->load->library('form_validation');

        $this->form_validation->set_rules('search', 'Search');

        if ($this->form_validation->run() == FALSE) {

            $this->load->view('search');

        } else {

            $data['search'] = $this->input->post_get('search');

            $this->search_model->get_search($data);

            $this->load->view('search');

        }

    }
}

A: Ok, I got this sorted.
To do a simple query of the Db, for example, to create a search form inside Codeigniter 3
Thanks for everybody's help!
The controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {
          public function __construct()
        {
                parent::__construct();
                $this->load->helper('url');
                $this->load->database();
                $this->load->helper('text');
                $this->load->library('pagination');
                $this->load->helper('form') ;
                $this->load->library('form_validation');
                $this->form_validation->set_rules('fsearch', 'Search', 'required');
                //$this->load->library('MY_sphinxclient');

                $this->load->model('Search_model');

        }
        public function index()
        {

          if ($this->form_validation->run() === FALSE)
          {
            $this->load->view('search');
          }
          else
          {
          $fsearch=$this->input->get_post('fsearch');
          $data['results']=$this->Search_model->get_search($fsearch);
          $this->load->view('search', $data);
          }
        }

      }

The Model:
<?php
        class Search_model extends CI_Model {

        public function __construct()
        {
        // Call the Model constructor
        parent::__construct();
        }
        public function get_search($search)
        {
          $sql = "SELECT  ads.id AS id, 1 AS table_id, location, provLabel, text,
          R_rand, addate, adcat.name AS catname, adsubcat.name AS subname, f_value
          FROM ads
          JOIN search_town ON search_town.townId=ads.townId
          JOIN search_region ON search_region.regionId=search_town.relRegionId
          JOIN search_prov ON search_prov.provId=search_region.relProvId
          JOIN adcat ON adcat.id=ads.catid
          JOIN adsubcat ON adsubcat.id=ads.subcatid
          LEFT JOIN adfields ON adfields.ad_id=ads.id
          WHERE ads.adactive=1 AND ads.subcatid!=841 AND scam=0 AND ads.catid!=8
          AND (text LIKE '%$search%' OR f_value LIKE '%$search%') GROUP BY ads.id ORDER BY ads.id DESC LIMIT 20";
          $query = $this->db->query($sql);
          return $query->result();
           echo 'Search Done';
        }

        }

?>

The View:
<?php
echo 'Hello World!!!';
if(isset($_POST)){
var_dump($_POST);
}

echo form_open('search');
echo form_label('Search: ');
$data_name = array(
'name' => 'fsearch',
'id' => 'search',
'placeholder' => 'Search'
);
echo form_input($data_name);
echo form_submit('submit', 'Submit');
echo form_close( );

if(isset($results)){
echo '
';
foreach($results as $rows) {
    echo '

            '.$rows->id.'
            '.$rows->text.'

';
}
echo '
';
}

?>
<?php echo validation_errors(); ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Local variable already defined when using 'is' keyword - goes against language reference As per the C# language reference at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#pattern-matching-with-is
expr is type varname

If expr is true and is is used with an if statement, varname is assigned and has local scope within the if statement only.

if(first_object is Folder folder)
{
    // ...
}

if(second_object is Folder folder) // ERROR!
{
    // ...
}

The above produces the following error:

A local variable or function named 'folder' is already defined in this scope

Why can't I reuse the variable name when it's supposed to be local only to each if statement?

A: As per the docs:
public static double ComputeAreaModernIs(object shape)
{
    if (shape is Square s)
        return s.Side * s.Side;
    else if (shape is Circle c)
        return c.Radius * c.Radius * Math.PI;
    else if (shape is Rectangle r)
        return r.Height * r.Length;
    // elided
    throw new ArgumentException(
        message: "shape is not a recognized shape",
        paramName: nameof(shape));
}

Let's examine both of those rules in detail, beginning with scope. The
  variable c is in scope only in the else branch of the first if
  statement. The variable s is in scope in the method
  ComputeAreaModernIs. That's because each branch of an if statement
  establishes a separate scope for variables. However, the if statement
  itself does not. That means variables declared in the if statement are
in the same scope as the if statement (the method in this case.) This
  behavior is not specific to pattern matching, but is the defined
  behavior for variable scopes and if and else statements.

Is it weird, and confusing (that if doesn't set up a scope, but else does)? Yes, yes it is. :)

A: *

*You have to understand that If is not scope limiting syntax.

*Means whatever out side of If statement are available.

*It will limit the scope for variable that declare inside If loop but not in If Condition it self.


text:
Q: Version of dart used in my existing project I have a flutter project. I want to know what version of dart language is used in development of the project. And i also want to know the version of flutter framework which is used for developing the project.
Is there any way to know these details?
I do not have documentation of the project.
I tried flutter doctor command but it gives current version of dart and flutter framework installed in my android studio.

A: in the pubspec.yaml, you will find the following
environment:
  sdk: ">=2.1.0 <3.0.0"

this indicates that this project works with dart 2.1.0 and above
learn more here if you like


text:
Q: Using OpenCV, how can I detect text orientation before performing OCR? I'm using OpenCV within an iOS application. I'd like to perform OCR on some text, but I first need to determine its orientation.
How do I do that in OpenCV?

A: I am not sure that one can reply to the question without providing OCR in Objective-C - something that can hardly be done in a few lines of text without using an OCR library.
Well, 20 years ago, I wrote an OCR system (without using any OCR library) to read bank checks in real-time. It was also authentifying hand-written signatures by the way.
The problem of checking the orientation was pregnant because checks could be inserted randomly (by human operators) in the small motorized bank-check scanner.
Since all banks were using different page layouts and decorations, the only way to find the orientation without relying on magnetic ink (that the scanner did not detect) was to actually attempt an OCR recognition on the first characters found at the top of the 'page'.
Some charcters are ambiguous like an 'O' but most others will tell you if the picture is inverted or mirrored so just reading the first 3-5 charcters will do the job (unless you have repetitions).
Good luck!

A: This answer was updated.

*

*If you need to detect the rotation angle of the text, take a look at this article (it shares source code):

*

*After the text has been deskewed, the OCR procedure can be executed and it's result compared to a dictionary. If the matching rate is high, you know the text was rotated properly and the orientation is now OK.

A: i ran into a similar problem a few weeks ago and only just started looking into it before i got distracted. Anyway, you can achieve what you want (to a degree) using discrete fourier transforms.  Blur or erode the image so that all the little white gaps in the individual words/lines fill into a solid black line (this helps remove alot of the high frequency noise from the image), take the DFT of the image, apply a low-pass or band-pass filter over it (frequency according to the desired font size relative to the image size), and analyze the resulting magnitude plot. You will have to a bit of research or someone else will need to elaborate, but this definitely seemed like the best solution that i found.
Im doing another project right now, but i will get back to this within a week or so and let you know more details about it then if someone else hasnt already done so. Ofcourse, this post is kinda old now, so i may not even get a response haha, but it will be a good reference for someone else looking in the future anyway.

A: Hough transform might help you. The maximum (to be precise it's the dominant cluster, but you'll need k-means with k=1 for this) on hough voting map will give you the desired angle.


text:
Q: Automated creation of "spatial bookmarks" The problem:
The respective geometries of a layer (geopackages) can not be displayed as single geometries in the viewport "Layer" to be able to zoom to the single surfaces. Here you have to go over the attribute table, which is not wanted. Also the splitting into single layers is not wanted.
Solution:
Automated creation of "spatial bookmarks".
Question:
Is it possible (e.g. via a virtual field) to create a spatial bookmark, which is automatically generated when the creation of a geometry/surface is completed? Additionally, the point to zoom to should be the center of the geometry.


text:
Q: Error in TCL Script i have return a command to invoke my RTL compiler (Cadence Tool)using tcl script line
puts [exec rc -f script.g ]

i am getting error like abort child process. while if write it directly on my console the to invoke the tool $-rc -f script.g it is getting perfectly exectuded.

A: exec returns an error condition if:

*

*the exec'ed command returns with a non-zero status

*or it prints to stderr

Do this
if {[catch {exec rc -f script.g} output] == 0} {
    # normal exit status
    puts $output
} elseif {$errorCode eq NONE} {
    # normal exit status, but some output to stderr (contained in $output)
    puts $output
} else {
    # some error condition.
    # see http://wiki.tcl.tk/1039 for ways to handle
    puts "some error occurred: $errorCode"
}


text:
Q: Keypress events in JavaScript & JQuery? I am making an HTML slideshow by myself and was able to create most of the thing. The place where I am stuck is the keyboard events. That is forward and backward arrow. I need to know how to handle these using JavaScript or JQuery. These button when pressed would trigger an event so as to move to the next slide or go to the previous one. I also want to mention that my slides are also interactive HTML, as in you can fill in data, validate etc using them. SO i dont want the keyboard events to hinder while the user is interacting with the form or other content on the page via Keyboard (eg. Filling in a form,date etc).
How to go about this ?

A: There are 3 different events for handling keyboard input: keyup, keydown, and keypress. Not all are fired on all keys, and some fire different codes depending on operating system. Check out quirksmode for more info.
jQuery has corresponding events for each of these.
From jQuery site:

Note that keydown and keyup provide a code indicating which key is
  pressed, while keypress indicates which character was entered. For
  example, a lowercase "a" will be reported as 65 by keydown and keyup,
  but as 97 by keypress. An uppercase "A" is reported as 65 by all
  events. Because of this distinction, when catching special keystrokes
  such as arrow keys, .keydown() or .keyup() is a better choice.

To avoid handling these events when user is interacting with the form, you might want to turn the behavior off any time a form field has focus, and turn it back on when the form fields are blurred. That way, using these arrows to navigate an input field wouldn't cause slideshow traversal.

A: $(window).keypress(function(e) {
    var keyCode = e.keyCode || e.which; //browser compatible
    switch (keyCode) {
        case 39:
            alert("right key pressed");
            break;
        case 37:
            alert("left key pressed");
            break;
        default:
            alert("other key pressed");
    }
});

fiddle : http://jsfiddle.net/3wdw7/

A: I would do something like this:
$(window).keydown(function(e) {
    if (e.target !== document.body) return;
    switch (e.keyCode) {
    case 39:
        alert("right");
        e.preventDefault();
        break;
    case 37:
        alert("left");
        e.preventDefault();
        break;
    }
});

You can check the target of the event to ignore key events on child elements like text fields, and you should probably prevent default on the event to stop the browser from performing its default action, like scrolling the page.
http://jsfiddle.net/3wdw7/2/


text:
Q: Convert Xml configuration to object graph - object lis always empty or null I need to read xml content into object graph.
My format xml is:
<?xml version="1.0"?>
<format>
    <fileheader>
        <tag name="firstname" length="2" order="1" padding=""></tag>
        <tag name="lastname" length="6" order="2" padding=""></tag>
        <tag name="date" length="5" order="3" padding=""></tag>
        <tag name="amount" length="16" order="4" padding="0">1000</tag>

    </fileheader>
    <filetrailer>
        <tag name="duration" length="8" order="1" padding=" "></tag>
        <tag name="count" length="6" order="2" padding=""></tag>
        <tag name="date" length="5" order="3" padding=""></tag>
        <tag name="totalAmount" length="16" order="4" padding="0">1000</tag>
    </filetrailer>
</format>

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Format {

  @XmlElement(name = "fileheader")
  private FileHeader fileHeader;

  @XmlElement(name = "filetrailer")
  private FileTrailer fileTrailer;

// getters setters
}

@XmlAccessorType(XmlAccessType.FIELD)
public class FileHeader {

  @XmlElementWrapper
  @XmlElement(name="tag")
  private  Tag[] tags;

// getters setters
}

@XmlAccessorType(XmlAccessType.FIELD)
public class FileTrailer {

  @XmlElementWrapper
  @XmlElement(name="tag")
  private  Tag[] tags;

// getters setters
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Tag {

  @XmlAttribute
  private String name;

  @XmlAttribute
  private int length;

  @XmlAttribute
  private int order;

  @XmlAttribute
  private String padding;

  @XmlValue
  private String defaultVal;

  // getters setters
}

Class Test{

  public void loadSettings() {
    logger.debug("loadsettings.......");
    try {
      ClassLoader classLoader = getClass().getClassLoader();
      InputStream xmlInputStream = classLoader.getResourceAsStream(FORMAT_FILE);
      JAXBContext jaxbContext = null;
      jaxbContext = JAXBContext.newInstance(Format.class);
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      Format format = (Format) unmarshaller.unmarshal(xmlInputStream);

    FileHeader fh = format.getFileHeader();
    logger.debug("fh-->>{}",fh);
    Tag[] tags=fh.getTags();
    logger.debug("printing tags ->{}",tags);

    }catch (Exception e) {
      logger.error("Error ", e);
    }

  }

}

when i calling loadSetting method the values of Tag list not getting printed.
seems to be something wrong with annotatins or any other problem with my code
My Output
fh-->>com.silverleap.cbsl.settlement.config.FileHeader@684c28bb
printing tags ->{}

A: Success with
@XmlElement(name = "tag")
  private List<Tag> tags;


text:
Q: Creating multiple profiles under one user to assign to particular posts I am working with WP Job Manager at the moment quite a lot and currently on each job you would like to post you enter a set of details about the company the job is with.
This info is then echoed out onto the particular job advert it is associated with.
In most cases I can see how this default behavior covers most bases and the info is stored ready for the next job saving the same info from been entered over and over again.
For my first step in a change of process I would like have these fields attributed to the user specifically, for example as part of their user profile. I have used ACF on a little test site locally and added a couple of fields to the user and with a little more work will get them echoed out onto each page... I hope.
What I would really like to do is allow the user to visit their "profile" on the front end of the site and be able to edit this info, rather than me go into the back end each time and do it for them.
So end result here is they set up their profile and each time they post a job it brings in the unique job details and their company profile.
The next step along the way, if it is even possible is to allow the user to have multiple profiles that they can then attribute specific jobs to.
The reason for this is that the people doing the posting are from the recruitment team based at the large owner company and they post all they jobs on job sites for their trading names of that company.
e.g. - Large PLC - Job Poster Posting Jobs
     -- Small Business - Job Poster Posts My Jobs
     -- Another Small Business - Job Poster Posts My Jobs
So the "Super User" can post a job and pick which little business that job is for and hay-presto it contains all the details from that company profile they had set up :)
Sorry for the long question but it is going to be a long development starting with the singular profiles first and then moving forward.
Any advice or plugins to point me to would be great!!
Craig

A: Sounds to me like "Profiles" should be a custom post type with custom fields. You can then relate the profiles to the users via a custom taxonomy or even more crudely by just storing the Profile post ids as meta data of the User. This would give you the flexibility of offering multiple profiles for a single user.
Creating a form on the frontend would then capture their changes and match it to the custom fields of the Profile post.


text:
Q: Python :string index out of range with trying to find first capital letter I am trying to get the first capital letter in the string but I am getting an index out of range error  I don't know if it is my base case for the recursion. Please can someone help me
This is my code:
def firstCapital(str, i):
    if (str[i] == None):
        return 0
    if (str[i].isupper()):
        return str[i]
    return firstCapital(str, i + 1)

name = "geoRge"
res = firstCapital(name, 0)
if (res == 0):
    print("No uppercase letter")
else:
    print(res)

A: str[i] will raise this index out of range exception if i is greater or equal to the length of str. You should change your base case to:
if (i >= len(str)):
    return 0

A: The line if (str[i] == None): doesn't do what you want it to do. This seems like it's trying to check if your index is off the end of the string, but strings in Python don't have None after the last real character. Rather, you get exactly the exception you describe when you try to index past the end.
Instead, you should be comparing i to len(str), which is the length of the string as a number. Since indexes start at zero, an index equal to len(str) is just past the end, so you probably want:
if i >= len(str):
    return 0

I'd also double check if returning zero is what you want to do there. If you find a capital letter, you're returning it from your other conditional case. It's not always ideal to return different types in different situations, as it can be tricky for the caller to know what APIs they can use on the result. Returning an empty string, or None might make more sense than returning a number.

A: using str[i]==None will 'force' python to determine the value of str[i], which doesn't exist, thus the index out of range error. You can determine that you reached the end of the string using len(str) and i instead:
def firstCapital(str, i):
    if i>len(str)-1: #Instead of str[i]==None
       return 0
    if str[i].isupper():
        return str[i]
return firstCapital(str, i + 1)

input : ('Ali',0)
Output: 'A'

Input: ('lia',0)
Output:0


text:
Q: Replace Infinite loop in Flex I want to access a webservice:getMonitorData() , on creationcomplete and returns an array, in an infinite loop so that the getIndex0.text is updated each time.
Flex is not able to handle an infinite loop and gives a timeout error 1502. If I run the for loop until i<2000 or so it works fine.
How can replace the loop so that my webservice is accessed continiously and the result is shown in getIndex0.text.
This is how my application looks like:
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
         xmlns:plcservicebean="server.services.plcservicebean.*"
         creationComplete="clientMonitor1()">
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.rpc.CallResponder;
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;

            [Bindable] public var dbl0:Number;

//-----------Infinite Loop, Works fine if condition = i<2000------------------------
            public function clientMonitor1():void{
                for(var i:int = 0; ; i++){
                    clientMonitor();
                }
            }

            public function clientMonitor():void{
                var callResp:CallResponder = new CallResponder();
                callResp.addEventListener(ResultEvent.RESULT, monitorResult);
                callResp.addEventListener(FaultEvent.FAULT, monitorFault);
                callResp.token = plcServiceBean.getMonitorData();
            }

            public function monitorResult(event:ResultEvent):void{
                var arr:ArrayCollection = event.result as ArrayCollection;
                dbl0 = arr[0].value as Number;
            }

            protected function monitorFault(event:FaultEvent):void{
                Alert.show(event.fault.faultString, "Error while monitoring Data ");
            }
        ]]>
    </fx:Script>
    <fx:Declarations>
        <plcservicebean:PlcServiceBean id = "plcServiceBean"
                                       showBusyCursor="true"
                                       fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" />
    </fx:Declarations>

    <mx:Form x="52" y="97"
             label="Double">
        <mx:FormItem label = "getMonitorValue">
            <s:TextInput id = "getIndex0"
                         text = "{dbl0}"/>
        </mx:FormItem>
    </mx:Form>

</s:Group>

A: Your problem is that your loop runs synchronously while the actual web service calls are asynchronous.  Flex uses a frame-based execution model and only has a single thread of execution -- when you make a call to the webservice, it initiates the connection and returns immediately.  Looping forever, then, means that you'll never actually get to the next frame, where the result could be processed.  Looping 2000 times means you spawn 2000 connections straight away, which will be queued up as you're not allowed to make that many connections at once.  They will then complete over the next few minutes.
The way to do what you want to do is probably to wait until one request is complete before firing the next.  To achieve this, you can call clientMonitor() from the end of your event handlers, or set up an extra event handler specifically to call clientMonitor() when the request completes.

A: Use a Timer.
Start the timer.  When it triggers, stop the timer, make the call.  When the call comes back, start the timer again.  Repeat.  This type of async/delayed timer loop will not use up cpu or halt other code.

A: It sounds to me like you need something like LifeCycle data services which will allow you to keep a socket open to the server and allow for push notifications from the server to the client.
Continuously hitting a remote web service just seems like a horribly bad idea to me.

A: You could implement pseudo-recursion by adding an event listener that calls clientMonitor() and then raise that same event at the end of clientMonitor(). Just call clientMonitor() once to start the process.


text:
Q: Is it possible to improve the research dpt results? Is there a point to build more than one research dpt?
Or to put more than one doctor at work in the research dpt ?

A: More doctors - yes! Each active researcher in the Research Department (i.e. a doctor who is able to sit at a free desk and get in and out of the room) will reduce the amount of time required for developments to be researched.
Additional research departments, however, are unlikely to provide a notable benefit. The only thing you'll get from two research departments would be two Auto-Autopsy machines, and there's unlikely to be a need for this; patients can queue outside your research department for their autopsy.
You should aim to build a single research department that is as large as reasonably possible - accommodating at least 2 desks, and anywhere up to 4-6 desks on later levels.


text:
Q: What machine learning method can i use to predict the next image in a sequence? I have a sequence of images below.

It takes a straight line, breaks it in half, and then morphs them into an angle image.
After the training is complete, I should be able to give it only one start image of any length, and it should give me the angle image as output.
What machine learning method can i use (given the training sequence) to predict the final output image?
[Edit] - I am not trying to classify an image. I am trying to make the AI generate an output image given a source image.


text:
Q: Wrong result of sizeof I have several files in a folder and i want to count them.
$folder = "images";
$allPics = scandir($folder);
$result = sizeof($allPics);
echo $result;

The result is 350 but it should be 348. I don't get it why it is showing me the result +2?
Am i missing something?!

A: http://php.net/manual/en/function.scandir.php
When looking at the documentation you can see the function return both '.' and '..', that's why you're having 2 more than you should have.
You can use this:
array_diff(scandir($folder), array('..', '.'));

To get rid of the dots you don't wanna have.

A: You are using the unix system and it have, 2 pointers in each directory, the pointer for the parent dirrectory that usualy is notted with .. and the pointer to the current directory that is notted as .


text:
Q: Set config variables in heroku using `cat example.file` I'm following this tutorial (best answer) SSH tunneling from Heroku
And they say to set some heroku config vars like MY_VAR=cat my.file to save the contents of the file to heroku. The problem is, I don't think this method works anymore. I'm looking for help on either how to do this the right way, or how to emulate this. Here is the traceback.
(bosnetvenv) michael@michael-VivoBook-ASUSLaptop-MJ401TA:~/projects/znet/bosnet$ heroku config:set ZEAL_FULL_NODE_PRIVATE_KEY=`cat ~/.ssh/heroku_id_rsa`
 ›   Warning: heroku update available from 7.35.0 to 7.38.1.
 ▸    RSA is invalid. Must be in the format FOO=bar.
(bosnetvenv) michael@michael-VivoBook-ASUSLaptop-MJ401TA:~/projects/znet/bosnet$ heroku config
 ›   Warning: heroku update available from 7.35.0 to 7.38.1.
=== zealchain Config Vars
DATABASE_URL:              REDACTED
IS_PRODUCTION:              True
ZEAL_FULL_NODE_PRIVATE_KEY:
(bosnetvenv) michael@michael-VivoBook-ASUSLaptop-MJ401TA:~/projects/znet/bosnet$ heroku config:set ZEAL_FULL_NODE_PUBLIC_KEY=`cat ~/.ssh/heroku_id_rsa.pub`
 ›   Warning: heroku update available from 7.35.0 to 7.38.1.
 ▸    REDACTED
 ▸    is invalid. Must be in the format FOO=bar.

Thank in advance.

A: needed quotes.
heroku config:set "MY_VAR=test.file"


text:
Q: How can I loop over pages and get data from every page with selenium? I want to do a google search and collect the links to all hits so that I can click those links and extract data from them after collecting all links. How can I get the link from every hit?
I've tried several solutions like using a for loop and a while True statement. I'll show some examples of the code below. I either get no data at all or I get only data (links) from 1 webpage. Can someone please help me figure out how to iterate over every page of the google search and get all the links so I can continue scraping those pages? I'm new to using Selenium so I'm sorry if the code doesn't make much sense, I've really confused myself with this one.
driver.get('https://www.google.com')
search = driver.find_element_by_name('q')
search.send_keys('condition')
sleep(0.5)
search.send_keys(Keys.RETURN)
sleep(0.5)

while True:
    try:
        urls = driver.find_elements_by_class_name('iUh30')
        for url in urls
        urls = [url.text for url in urls]

    sleep(0.5)

    element = driver.find_element_by_id('pnnext')
    driver.execute_script("return arguments[0].scrollIntoView();", element)
    sleep(0.5)
    element.click()

urls = driver.find_elements_by_class_name('iUh30')
urls = [url.text for url in urls]
sleep(0.5)

element = driver.find_element_by_id('pnnext')
driver.execute_script("return arguments[0].scrollIntoView();", element)
sleep(0.5)
element.click()

while True:
    next_page_btn = driver.find_element_by_id('pnnext')
    if len(next_page_btn) <1:
        print("no more pages left")
        break
    else:
        urls = driver.find_elements_by_class_name('iUh30')
        urls = [url.text for url in urls]
    sleep(0.5)

    element = driver.find_element_by_id('pnnext')
    driver.execute_script("return arguments[0].scrollIntoView();", element)
    sleep(0.5)
    element.click()

I expect a list of all urls from the google search that can be opened by Selenium so Selenium can get data from those pages.
I only get a list of urls from one page. The next step (scraping those pages) is working fine. But due to this restriction I only get 10 results while I'd like to see all results.

A: Try the following code. I have changed a bit.Hope this help.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

driver=webdriver.Chrome()
driver.get('https://www.google.com')
search = driver.find_element_by_name('q')
search.send_keys('condition')
search.submit()

while True:
    next_page_btn =driver.find_elements_by_xpath("//a[@id='pnnext']")
    if len(next_page_btn) <1:
        print("no more pages left")
        break
    else:
        urls = driver.find_elements_by_xpath("//*[@class='iUh30']")
        urls = [url.text for url in urls]
        print(urls)

    element =WebDriverWait(driver,5).until(expected_conditions.element_to_be_clickable((By.ID,'pnnext')))
    driver.execute_script("return arguments[0].scrollIntoView();", element)
    element.click()

OutPut :
['https://dictionary.cambridge.org/dictionary/english/condition', 'https://www.thesaurus.com/browse/condition', 'https://en.oxforddictionaries.com/definition/condition', 'https://www.dictionary.com/browse/condition', 'https://www.merriam-webster.com/dictionary/condition', 'https://www.collinsdictionary.com/dictionary/english/condition', 'https://en.wiktionary.org/wiki/condition', 'www.businessdictionary.com/definition/condition.html', 'https://en.wikipedia.org/wiki/Condition', 'https://www.definitions.net/definition/condition', '', '', '', '']
['https://www.thefreedictionary.com/condition', 'https://www.thefreedictionary.com/conditions', 'https://www.yourdictionary.com/condition', 'https://www.foxnews.com/.../woman-battling-rare-suicide-disease-says-chronic-pain-con...', 'https://youngminds.org.uk/find-help/conditions/', 'www.road.is/travel-info/road-conditions-and-weather/', 'https://roll20.net/compendium/dnd5e/Conditions', 'https://www.home-assistant.io/docs/scripts/conditions/', 'https://www.bhf.org.uk/informationsupport/conditions', 'https://www.gov.uk/driving-medical-conditions']
['https://immi.homeaffairs.gov.au/visas/already-have.../check-visa-details-and-condition...', 'https://www.d20pfsrd.com/gamemastering/conditions/', 'https://www.ofgem.gov.uk/licences-industry-codes-and.../licence-conditions', 'https://www.healthychildren.org/English/health-issues/conditions/Pages/default.aspx', 'https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html', 'https://www.ofcom.org.uk/phones-telecoms.../general-conditions-of-entitlement', 'https://www.rnib.org.uk/eye-health/eye-conditions', 'https://www.mdt.mt.gov/travinfo/map/mtmap_frame.html', 'https://www.mayoclinic.org/diseases-conditions', 'https://www.w3schools.com/python/python_conditions.asp']
['https://www.tremblant.ca/mountain-village/mountain-report', 'https://www.equibase.com/static/horsemen/horsemenareaCB.html', 'https://www.abebooks.com/books/rarebooks/...guide/.../guide-book-conditions.shtml', 'https://nces.ed.gov/programs/coe/', 'https://www.cdc.gov/wtc/conditions.html', 'https://snowcrows.com/raids/builds/engineer/engineer/condition/']
['https://www.millenniumassessment.org/en/Condition.html', 'https://ghr.nlm.nih.gov/condition', 'horsemen.ustrotting.com/conditions.cfm', 'https://lb.511ia.org/ialb/', 'https://www.nps.gov/deva/planyourvisit/conditions.htm', 'https://www.allaboutvision.com/conditions/', 'https://www.spine-health.com/conditions', 'https://www.tripcheck.com/', 'https://hb.511.nebraska.gov/', 'https://www.gamblingcommission.gov.uk/.../licence-conditions-and-codes-of-practice....']
['https://sports.yahoo.com/andrew-bogut-credits-beer-improved-022043569.html', 'https://ant.apache.org/manual/Tasks/conditions.html', 'https://www.disability-benefits-help.org/disabling-conditions', 'https://www.planningportal.co.uk/info/200126/applications/60/consent_types/12', 'https://www.leafly.com/news/.../qualifying-conditions-for-medical-marijuana-by-state', 'https://www.hhs.gov/healthcare/about-the-aca/pre-existing-conditions/index.html', 'https://books.google.co.uk/books?id=tRcHAAAAQAAJ', 'www.onr.org.uk/documents/licence-condition-handbook.pdf', 'https://books.google.co.uk/books?id=S0sGAAAAQAAJ']
['https://books.google.co.uk/books?id=KSjLDvXH6iUC', 'https://www.arcgis.com/apps/Viewer/index.html?appid...', 'https://www.trappfamily.com/trail-conditions.htm', 'https://books.google.co.uk/books?id=n_g0AQAAMAAJ', 'https://books.google.co.uk/books?isbn=1492586277', 'https://books.google.co.uk/books?id=JDjQ2-HV3l8C', 'https://www.newsshopper.co.uk/.../17529825.teenager-no-longer-in-critical-condition...', 'https://nbcpalmsprings.com/.../bicyclist-who-collided-with-minivan-hospitalized-in-cri...']
['https://www.stuff.co.nz/.../4yearold-christchurch-terrorist-attack-victim-in-serious-but-...', 'https://www.shropshirestar.com/.../woman-in-serious-condition-after-fall-from-motor...', 'https://www.expressandstar.com/.../woman-in-serious-condition-after-fall-from-motor...', 'https://www.independent.ie/.../toddler-rushed-to-hospital-in-serious-condition-after-hit...', 'https://www.nhsinform.scot/illnesses-and-conditions/ears-nose-and-throat/vertigo', 'https://www.rochdaleonline.co.uk/.../teenage-cyclist-in-serious-condition-after-collisio...', 'https://www.irishexaminer.com/.../baby-of-woman-found-dead-in-cumh-in-critical-cond...', 'https://touch.nihe.gov.uk/index/corporate/housing.../house_condition_survey.htm', 'https://www.nami.org/Learn-More/Mental-Health-Conditions', 'https://www.weny.com/.../update-woman-in-critical-but-stable-condition-after-being-s...']


text:
Q: Run fsck in the background on boot Running openSUSE 15.1 with systemd, when it determined the need, the boot processes will invoke fsck on a particular disk. By default, this check will run in the foreground, blocking the completion of the boot processes. This has led some to desire to stop the boot-time checking completely.
I understand if my OS partition may have undergone some data corruption, fsck should block before continuing to process data on the disk. However, some of my disks are less essential to the operation of the system. Can I indicate to the system to run the fsck in the background and mount the disk on success, but to let the system load normally otherwise, either via a flag in fstab or another method?


text:
Q: Problems reading data from 3 Kinect cameras I am trying to read data from multiple Kinect sensors (3 at the moment) and having issues when there's more than 2 devices.
I'm using Daniel Shiffman's OpenKinect Processing wrapper, slightly modified so it allows to open multiple Device instances. Everything works fine with 2 devices. The problem is when I use 3. One Kinect is connected straight into one of the available two usb ports, and the other two are plugged into a USB 2.0 Hub (that has it's own power adapter).
The devices all initialize succesfully:
org.openkinect.Device@1deeb40 initialized
org.openkinect.Device@2c35e initialized
org.openkinect.Device@1cffeb4 initialized

The problem is when I try to get the depth map from the 3rd device, I get an array filled with zeroes. I've thought it's the device, but if swap devices, it's always the 3rd (last connected device) that presents this behaviour.
Here's my code so far:
package librarytests;

import org.openkinect.Context;
import org.openkinect.processing.Kinect;

import processing.core.PApplet;
import processing.core.PVector;

public class PointCloudxN extends PApplet {

    // Kinect Library object
    int numKinects;// = 3;
    Kinect[] kinects;
    int[] colours = {color(192,0,0),color(0,192,0),color(0,0,192),color(192,192,0),color(0,192,192),color(192,0,192)};

    // Size of kinect image
    int w = 640;
    int h = 480;

    // We'll use a lookup table so that we don't have to repeat the math over and over
    float[] depthLookUp = new float[2048];

    // Scale up by 200
    float factor = 200;

    public void setup() {
        size(800,600,P3D);
        numKinects = Context.getContext().devices();
        kinects = new Kinect[numKinects];
        for (int i = 0; i < numKinects; i++) {
            kinects[i] = new Kinect(this);
            kinects[i].start(i);
            kinects[i].enableDepth(true);
            kinects[i].processDepthImage(false);
        }
        // Lookup table for all possible depth values (0 - 2047)
        for (int i = 0; i < depthLookUp.length; i++) {
            depthLookUp[i] = rawDepthToMeters(i);
        }
    }

    public void draw() {
        background(0);

        translate(width/2,height/2,-50);
        rotateY(map(mouseX,0,width,-PI,PI));
        rotateX(map(mouseY,0,height,-PI,PI));
        int skip = 4;//res
        //*
        for (int i = 0; i < numKinects; i++) {
            Kinect kinect = kinects[i];
            int[] depth = kinect.getRawDepth();
            //if(frameCount % 60 == 0 && i == 2) println(depth);
            if (depth != null) {

                // Translate and rotate

                for(int x=0; x<w; x+=skip) {
                    for(int y=0; y<h; y+=skip) {
                        int offset = x+y*w;

                        // Convert kinect data to world xyz coordinate
                        int rawDepth = depth[offset];
                        PVector v = depthToWorld(x,y,rawDepth);

                        stroke(colours[i]);
                        // Draw a point
                        point(v.x*factor,v.y*factor,factor-v.z*factor);

                    }
                }
            }
        }

        //*/
    }

    public void stop() {
        for (int i = 0; i < numKinects; i++) kinects[i].quit();
        super.stop();
    }

    public static void main(String _args[]) {
        PApplet.main(new String[] { librarytests.PointCloudxN.class.getName() });
    }

    // These functions come from: http://graphics.stanford.edu/~mdfisher/Kinect.html
    float rawDepthToMeters(int depthValue) {
        if (depthValue < 2047)  {
            return (float)(1.0 / ((double)(depthValue) * -0.0030711016 + 3.3309495161));
        }
        return 0.0f;
    }

    PVector depthToWorld(int x, int y, int depthValue) {

        final double fx_d = 1.0 / 5.9421434211923247e+02;
        final double fy_d = 1.0 / 5.9104053696870778e+02;
        final double cx_d = 3.3930780975300314e+02;
        final double cy_d = 2.4273913761751615e+02;

        PVector result = new PVector();
        double depth =  depthLookUp[depthValue];//rawDepthToMeters(depthValue);
        result.x = (float)((x - cx_d) * depth * fx_d);
        result.y = (float)((y - cy_d) * depth * fy_d);
        result.z = (float)(depth);
        return result;
    }

}

The only major change I've done to Daniel's Kinect class was adding an extra start() method:
public void start(int id) {

        context = Context.getContext();
        if(context.devices() < 1)
        {
            System.out.println("No Kinect devices found.");
        }
        device = context.getDevice(id);
        //device.acceleration(this);

        device.acceleration(new Acceleration()
        {
            void Acceleration(){
                System.out.println("new Acceleration implementation");
            }
            public void direction(float x, float y, float z)
            {
                System.out.printf("Acceleration: %f %f %f\n", x ,y ,z);
            }
        });

        kimg = new RGBImage(p5parent);
        dimg = new DepthImage(p5parent);
        running = true;

        super.start();
    }

I've also tried with MaxMSP/Jitter and the jit.freenect external and I get the same behaviour: I can get 2 depth maps, but the 3rd is not updating.

So it seems to be an issue related to the driver, not the wrapper, since the same behaviour is present using 2 different wrappers to libfreenect (Java/Processing and Max), but am clueless why this happens to be honest.
Has anyone had a similar issue (getting depth feeds from 3 devices) using the OpenKinect/libfreenect Driver ? Any ideas on how I can get past this issue ?

A: The Kinect is extremely demanding on USB - generally, you can only get one Kinect per USB host controller on your motherboard (most PCs and laptops have two). The only solution I've seen is to buy a PCI-E USB controller and plug the third one into it.
Also, you might be lucky if you reduce the bandwidth requirements by disabling the RGB stream on all the Kinects (I'm blithely assuming you aren't using it since it wasn't mentioned)


text:
Q: How to make Firebase get data from inside push() keys? Let's say I have this:
Campaigns:{
    UNIQUE_ID:{
     title: "Hello",
     description: "Desc"
  }
}

And a bunch of other UNIQUE_IDs, and I want to retrieve title and description and put them into a RecyclerView.

What I tried:
I tried making a custom Campaign class, with the strings description and title.
And I have this method:
 String title;
 String description;
 public Campaign(){}
 public Campaign(String title, String description) {
    this.title = title;
    this.description = description;
}
public String getTitle() {
    return title;
}

public String getDescription() {
    return description;
}

When I try getting the adapter, with this method:
 RecyclerView.Adapter mAdapter = new FirebaseRecyclerAdapter<Campaign,CampaignHolder>(Campaign.class, R.layout.recyclerview_template, CampaignHolder.class,ref){
        @Override
        public void  populateViewHolder(CampaignHolder viewHolder, Campaign campaign, int position){
            viewHolder.setTitle(campaign.getTitle());
            viewHolder.setDescription(campaign.getDescription());
        }
    };

campaign.getTitle() is obviously returning null, and I can see why, since I never called on the constructor. But, if I want to call the constructor, I need the parameters title,description. But where do I get this, or am I doing this wrong?

A: Your Campaign class will need either setters (in addition to the getters you already have):
public class Campaign {
     String title;
     String description;
     public Campaign(){}
     public Campaign(String title, String description) {
        this.title = title;
        this.description = description;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }
    public void setDescription(description) {
        this.description = description;
    }

}

Or alternatively, just make the fields public and remove the getters/setters:
public class Campaign {
     public String title;
     public String description;
     public Campaign(){}
     public Campaign(String title, String description) {
        this.title = title;
        this.description = description;
    }
}

Based on these public fields (or getters/setter), the Firebase Database client will automatically populate the data based on the JSON it reads from the database.


text:
Q: Does anyone can hide the references in mysql? I want to see the referenced table of previously created table.
What I Have :
I have a table zone_inout_log in DB trackcar. It contains various fields. I want to see the references of all the foreign keys used in this table.I don't know the referenced tables. All I have is table zone_inout_login which foreign keys are used , columns those are the foreign keys user_id , device_id , area_id etc.
What I Want
I want to see all the referenced tables like  which table do I get user_id from anddevice_id,area_id` and so on.
What I Tried :
 show table status from trackcar;

Also tried
show create table zone_inout_log;

| zone_inout_log | CREATE TABLE `zone_inout_log` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `device_id` int(11) NOT NULL,
  `area_id` int(11) NOT NULL,
  `lat` float(10,6) DEFAULT NULL,
  `lng` float(10,6) DEFAULT NULL,
  `date_time` datetime DEFAULT NULL,
  `inout_status` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`),
 KEY `user_id` (`user_id`),
  KEY `device_id` (`device_id`),
  KEY `area_id` (`area_id`),
  KEY `lat` (`lat`),
  KEY `lng` (`lng`),
  KEY `date_time` (`date_time`),
  KEY `inout_status` (`inout_status`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

But didn't get referenced table name . If someone can suggest something ?

A: Please check it-
SELECT constraint_schema,
table_name,
column_name, constraint_name,
referenced_table_schema,
referenced_table_name,
referenced_column_name
FROM information_schema.KEY_COLUMN_USAGE
WHERE referenced_table_schema ='your_db'
AND referenced_table_name ='your_table';


text:
Q: Mysql_fetch_array supplied argument is not a valid MYSQL result How do I fix the "Mysql_fetch_array supplied argument is not a valid MYSQL result" error?
This is the code that had the error:
<?php
    require "connect.php";
    $query = mysql_query("SELECT author, date
                            FROM articles
                           WHERE id = ' . $id . '") or die(mysql_error());
    $runrows = mysql_fetch_array('$query');

     $author = $runrows['author'];
     $date = $runrows['date'];
?>

A:   $query = mysql_query("SELECT author, date FROM articles WHERE id = ' . $id . '") or die(mysql_error());
  $runrows = mysql_fetch_array($query);

There should be no quotes for $query. Its a variable, not a string.

A: $runrows = mysql_fetch_array('$query');

Should be
$runrows = mysql_fetch_array($query);

or
$runrows = mysql_fetch_array("$query");

Using '$variable' just prints out $variable as text. You want to use the value of the variable.
SQL Injection is when you use that $id variable from user interaction.
E.g. you have the following URL:
http://example.com/articles.php?id=1
If you just add the id variable to your query people can inject code in the variable.
http://en.wikipedia.org/wiki/SQL_injection
To prevent this you can simply do:
    $id = mysql_real_escape_string($id);
Or use prepared statements if it is supported.
http://en.wikipedia.org/wiki/Prepared_statements#Parameterized_statements

A: Remove the dots and use something like this in the third line
$query = mysql_query("SELECT author, date FROM articles WHERE id = '$id'") or die(mysql_error());

A: This has happened to me when I had not closed the connection using mysql_close($conn).  I guess the socket between from the db was still open, and next time when i again connected to the same db, this particular error came.  There were no other issues.  Once I explicitly closed the connection and then again restarted the connection, this issue was resolved.  Hope it helps.


text:
Q: How do I fetch all the folders in Salesforce using REST API I need to fetch list of all the folders in Documents section in Salesforce using REST API. Current API gets the information for a particular folder using folderId but I need to fetch all the folders in one go.

A: You could use a SOQL query on Folder. Something like:
SELECT Id, Name, DeveloperName, AccessType FROM Folder where Type = 'Document'

Which would be a GET request to (change na5 to match your instance):
https://na5.salesforce.com/services/data/v33.0/query/?q=SELECT%20Id%2C%20Name%2C%20DeveloperName%2C%20AccessType%20FROM%20Folder%20where%20Type%20%3D%20%27Document%27

The JSON response will be something like:
{
    "totalSize": 15,
    "done": true,
    "records": [
        {
            "attributes": {
                "type": "Folder",
                "url": "/services/data/v33.0/sobjects/Folder/00l700000000001AAA"
            },
            "Id": "00l70000000wp7KAAQ",
            "Name": "Test",
            "DeveloperName": "Test",
            "AccessType": "Public"
        }, //...
    ]
}


text:
Q: SaveFileDialog - (File path) does not exist. Verify that the correct file name was given I want to save a new filename but now I can only save rewrite files. Every time I tried saving a new filename, a message box appears with a warning dialog:

(File path) does not exist. Verify that the correct file name was
  given."

Below is my code, can anyone please point out what is missing? Thank you.
private void button5_Click(object sender, EventArgs e)
{
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.Title = "Save File";
    saveFileDialog1.CheckFileExists = true;
    saveFileDialog1.CheckPathExists = true;
    saveFileDialog1.Filter = "Text files (*.txt)|*.txt| CONF(*.conf)|*.conf|All files (*.*)|*.*";
    saveFileDialog1.FilterIndex = 2;
    saveFileDialog1.ShowDialog();

    if (saveFileDialog1.FileName != "")
    {
        // Saves the Image via a FileStream created by the OpenFile method.
        System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
        // Saves the Image in the appropriate ImageFormat based upon the
        // File type selected in the dialog box.
        // NOTE that the FilterIndex property is one-based.
        switch (saveFileDialog1.FilterIndex)
        {
            case 1:
                saveFileDialog1.FileName = saveFileDialog1.FileName + ".txt";
                break;
            case 2:
                saveFileDialog1.FileName = saveFileDialog1.FileName + ".conf";
                break;
            default:
                saveFileDialog1.FileName = saveFileDialog1.FileName + ".txt";
                break;
        }

        fs.Close();
    }
}

A: You need to set CheckFileExists and CheckPathExists to false to prevent the dialog checking existence of the file, otherwise the dialog box displays a warning if the user specifies a path:
saveFileDialog1.CheckFileExists = false;
saveFileDialog1.CheckPathExists = false;


text:
Q: Database column(s) that relate to one of multiple tables I feel this is a very basic question, still I cant figure out a good way of doing it even though I've worked quite a bit with databases. Also can't seem to find anything when googling for it.
Let's say I have a bunch of tables, each describing a type of item.
For instance:
Table candles:
id█  name  █length█diameter▌burntime▌
▀▀█▀▀▀▀▀▀▀▀█▀▀▀▀▀▀█▀▀▀▀▀▀▀▀█▀▀▀▀▀▀▀▀▌
1 █ candle1█54    █  6     █  180   ▌
69█ candle2█29    █  16    █  145   ▌
80█ candle3█100   █ 40     █  110   ▌

Table coasters:
id█  name  █thickness█diameter▌color   ▌
▀▀█▀▀▀▀▀▀▀▀█▀▀▀▀▀▀▀▀▀█▀▀▀▀▀▀▀▀█▀▀▀▀▀▀▀▀▌
1 █coaster1█5        █  20    █#ffffff ▌
6 █coaster2█8        █  41    █#ff0051 ▌
8 █coaster3█7        █ 38     █#002199 ▌

Table baskets:
id█  name  █size█
▀▀█▀▀▀▀▀▀▀▀█▀▀▀▀█
1 █basket1 █5   █
2 █basket2 █8   █
3 █basket3 █22  █

Now I have another table. Let's call it shoppingcarts. Each record in this table needs to hold an array of these items. This is where I don't know how to proceed.
So I need a many to many relationship, which means I need a junction/pivot-table.
But how?
Should I have one junction-table for each type of item? With a foreign key for cart-id and one for the record-id for candle/coaster/etc.
Then when listing the content of the cart I need to check every single junction-table, one for each type of item. Doesn't sound very clean to me.
Or should I only have one single junction-table, which has a column for table-name and one for record-id?
Seems very dirty too.
I suppose there's a much better way of doing this, but I can't think of it.
How should this be done?

A: One potential way of tackling this problem is to think about the items you have as objects, then think about how you might model these relationally. If you treat all of your items as objects, with properties, that have values, then this is a common schema for storing this information.
This is often referred to as O/R Mapping
A simple relational example might look like:
Object - defines all of your items
+----+----------+---------+
| Id |   Name   |  Type   |
+----+----------+---------+
|  1 | Candle1  | Candle  |
|  2 | Coaster1 | Coaster |
|  3 | Basket1  | Basket  |
+----+----------+---------+

ObjectProperty - defines all of your properties
+----+-----------+----------+
| Id |   Name    | DataType |
+----+-----------+----------+
|  1 | Length    | Float    |
|  2 | Diameter  | Float    |
|  3 | Burntime  | Float    |
|  4 | Thickness | Float    |
|  5 | Color     | String   |
|  6 | Size      | Int      |
+----+-----------+----------+

ObjectPropertyValue - defines the relationships between objects and properties, and the values
+----+----------+------------+----------+------------+-----------+-------------+
| Id | ObjectId | PropertyId | ValueInt | ValueFloat | ValueDate | ValueString |
+----+----------+------------+----------+------------+-----------+-------------+
|  1 |        1 |          1 | NULL     | 54.0       | NULL      | NULL        |
|  2 |        1 |          2 | NULL     | 29.0       | NULL      | NULL        |
|  3 |        3 |          6 | 5        | NULL       | NULL      | NULL        |
+----+----------+------------+----------+------------+-----------+-------------+

To retrieve all of the values for a single object, you can run a query like:
SELECT          OP.Name,
                OP.DataType,
                OPV.ValueInt,
                OPV.ValueFloat,
                OPV.ValueDate,
                OPV.ValueString

FROM            ObjectProperty OP
INNER JOIN      ObjectPropertyValue OPV ON OP.Id = OPV.PropertyId

WHERE           OPV.ObjectId = 1

There are several advantages to storing information in this format:

*

*It's extensible so you don't need a new table every time a new object
type comes along

*You can have as many properties as you need per
object

*Typing the property values means you can still do relevant queries
based on data types

i.e. To search for all candles with a length less than 50:
SELECT      O.Id,
            O.Name,
            OP.Name,
            OPV.ValueFloat
FROM        Object O
INNER JOIN  ObjectPropertyValue OPV ON O.Id = OPV.ObjectId
INNER JOIN  OpjectProperty OP ON OPV.PropertyId = OP.Id

WHERE       OP.Name = 'Length'
AND         O.Type = 'Candle'
AND         OPV.ValueFloat <= 50.0;

However, there are also disadvantages:

*

*It's hard to build queries on the fly without dynamic sql because you first need to know what kind of properties you are looking for on particular objects, and then choose the appropriate columns to search on in ObjectPropertyValue

*Squeezing objects into generic structures can sometimes make very simple operations quite complex. Compare how easy it would be to get the candles in your table structure vs the query above for example.

There are other disadvantages too, but a good place to start reading about this subject in detail is O/R Mapping and Relational Data
Finally, an alternative solution for solving this problem is the concept of NoSQL, an alternative mechanism to storing objects relationally.
Jeff Atwood also has a great article on this very subject.


text:
Q: ASP.NET disable "C:\fakepath" in FileUpload control ASP.NET 4.0
I've checked that using both  or  control (which is a wrap of html file input) will display "C:\fakepath\MyFile" in both Google Chrome 12.0 and IE8.0 on my Windows 7. It only displays "MyFile" in FF3.6. I am trying to not display "C:\fakepath\" string since it's not usual to most users.
I already enabled displaying full path in IE security setting which mentioned in another SO thread, so that shouldn't be just an IE security issue. Not to mention GC is showing fakepath too.
I am more suspecting it's because of my compilation environment -- Windows 7 + VS2010 SP1 + MVC3 installed. Can the community tell me how to disable this?

A: It can't be disabled, it's a browser security feature.  It ensures the server doesn't have access to any file information on the client.  Some browsers handle it differently, which is why in FF you just see the file name.
See this related question:
Javascript loading clients local media


text:
Q: Event listeners in ar.js I am developing a project which involves ar.js that is displaying 3d objects and text to teach children the alphabet on both mobile devices and laptops. I was trying to add an event listener as an extra to make the children interact more. My target is to click/touch on the model displayed and it will enlarge or change color or rotation. Attached find my code. Hopefully you could solve my issue.
HTML Code
<!DOCTYPE html>
<html>
    <head>
<script src = "https://aframe.io/releases/1.0.3/aframe.min.js"></script>
        <script src = "https://cdn.rawgit.com/jeromeetienne/AR.js/1.6.0/aframe/build/aframe-ar.js"></script>
        <script src = "event.js"></script>
        <script src="https://rawgit.com/donmccurdy/aframe-extras/master/dist/aframe-extras.loaders.min.js"></script>
     </head>
    <body>
<a-scene embedded arjs = 'sourceType: webcam; debugUIEnabled:false;'>
<a-assets>
                <a-asset-item id = "apple" src = "apple/scene.gltf"></a-asset-item>
        </a-assets>
 <a-marker id = "appleM" type = "pattern" url = "Asset/pattern-apple.patt"
        markerhandler emitevents = "true" cursor="rayOrigin: mouse">

            <a-entity id = "animatedApple" gltf-model = "#apple" position = "0 -1 0" scale = ".05, .05, .05"></a-entity>

            <a-text value="A for Apple"  color = "purple" position = "-1.3 1 0" scale = '2, 2, 2'></a-text>
</a-marker>
<a-entity camera></a-entity>
      </a-scene>
    </body>
</html>

event.js (file for the event handlers)
init: function() {
        const animatedMarker = document.querySelector('#appleM');
        const aEntity = document.querySelector('#animatedApple');

        // every click, we make our model grow in size :)
        animatedMarker.addEventListener('click', function(ev, target){
            const intersectedElement = ev && ev.detail && ev.detail.intersectedEl;
            if (aEntity && intersectedElement === aEntity) {
                const scale = aEntity.getAttribute('scale');
                Object.keys(scale).forEach((key) => scale[key] = scale[key] + 1);
                aEntity.setAttribute('scale', scale);
            }
        });
}});

A: I think the main issue is something with a-frame version 1.0.X. For some reason the addEventListerner('click') won't work if I use that.
Below is my code, you click your model and it should increase the scale. Note: there is issue about the click event not at the expected spot.
<!DOCTYPE html>
<html>
<head>
    <script src="https://aframe.io/releases/0.9.2/aframe.min.js"></script>
    <script src="https://cdn.rawgit.com/jeromeetienne/AR.js/1.7.2/aframe/build/aframe-ar.js"></script>
    <!-- IDK Why If I Use This, The addEventListener('click') won't work-->
    <!--     <script src = "https://aframe.io/releases/1.0.3/aframe.min.js"></script>    -->
    <!--     <script src = "https://cdn.rawgit.com/jeromeetienne/AR.js/1.6.0/aframe/build/aframe-ar.js"></script>  -->
    <script>

        AFRAME.registerComponent('button', {
            init: function() {

                const gltf = document.querySelector('#animatedApple');
                var x = gltf.getAttribute('scale').x;
                var y = gltf.getAttribute('scale').y;
                var z = gltf.getAttribute('scale').z;

                // every click, we make our model grow in size :)
                gltf.addEventListener('click', function(ev, target){
                    console.log(gltf.getAttribute('scale'));
                    gltf.setAttribute('scale', x + " " + y + " "+ z);
                    x += 0.1;
                    y += 0.1;
                    z += 0.1;
                });
            }
        });
    </script>
    <script src="https://rawgit.com/donmccurdy/aframe-extras/master/dist/aframe-extras.loaders.min.js"></script>
</head>
<body>
    <a-scene embedded arjs = 'sourceType: webcam; debugUIEnabled:false;'>
    <a-assets>
        <a-asset-item id = "apple" src = "apple/scene.gltf"></a-asset-item> <!-- change to your assets -->
    </a-assets>
    <a-marker id = "appleM" preset="hiro" emitevents="true" button> <!-- change to your marker, i use default hiro.jpg -->
        <a-entity cursor="rayOrigin: mouse" raycaster="objects: .clickable; useWorldCoordinates: true;"></a-entity> <!-- important for addEventListener('click'). Notice the '.clickable'-->
        <a-entity class="clickable" id ="animatedApple" gltf-model = "#apple" position = "0 0 0" rotation="270 0 0" scale = "0.5 0.5 0.5"></a-entity> <!-- Notice the '.clickable'-->

        <a-text id="aText" value="A for Apple"  color = "purple" position = "0 0 0" rotation="270 0 0" scale = "2 2 2"></a-text>
    </a-marker>
    <a-entity camera></a-entity>
    </a-scene>
</body>
</html>


text:
Q: Vertical Scaling resources (CPU, RAM) for Kafka Production cluster Currently we are using three node kafka Cluster in Prod with hardware specifications : Zookeeper : CPU 2 Core Ram 4GB Kafka : CPU 4 Core Ram 8GB
We want to vertically scale our Kafka cluster to double the resources we currently have. Could anyone please tell how can we perform this activity with no downtime and without creating a separate cluster ?


text:
Q: Пропал jquery.min.js с админки wp в админку заходит, но пропал jquery.min.js из за этого некоторые модули отрабатывают некорректно, нигде запретов неувидел, functions.php в этом плане чист
Ставил в functions.php непомогает, как решить проблему?
add_action( 'admin_enqueue_scripts', 'true_include_in_admin', 25 );

function true_include_in_admin() {

    wp_deregister_script( 'jquery' );
    wp_enqueue_script( 'jquery', 'https://code.jquery.com/jquery-3.6.0.min.js' );

}

причем все остальные скрипты подключены

A: Для подключения jQuery в Wordpress не надо указывать URL, те в вашем случае:
add_action( 'wp_enqueue_scripts', 'true_include_in_admin' );
function true_include_in_admin(){
    wp_enqueue_script( 'jquery' );
}


text:
Q: How to pass arguments to boilermake Apologies if this is not the place to post this. I'm not really sure where is.
I'm new to make and after a lot of research I stumbled across boilermake and have implemented it successfully on my project.
I build a release version of my project by default. I would like to know how to build a debug version of my project by supplying a command line argument such as debug. E.g.
make debug
which changes some of the compiler options set in CXXFLAGS in my top-level makefile.
However, I've not been able to get this to work.
Here is my makefile, which is included by the top-level makefile of boilermake.
INCDIRS := \
    ../component1/include \
    ../component2/include \
    ../component3/include

CXXFLAGS := O2 -pipe -std=c++11 -Wall -Wextra -Wold-style-cast -pedantic \
    -isystem boost

SUBMAKEFILES := \
    ../component1/build/component1.mk \
    ../component2/build/component3.mk \
    ../component3/build/component4.mk

TARGET := my-project

TGT_LDFLAGS := -L. -L${TARGET_DIR}

TGT_LDLIBS  := -lcomponent1 -lcomponent2 -lcomponent3 \
    libboost_date_time-mt-sd.a \
    libboost_filesystem-mt-sd.a
    libcrypto.a \
    libssl.a \
    -lz \
    -ldl \
    -lpthread

TGT_PREREQS := \
    libcomponent1.a \
    libcomponent2.a \
    libcomponent3.a

SOURCES := \
    main.cpp

Here is the boilermake makefile.
# boilermake: A reusable, but flexible, boilerplate Makefile.
#
# Copyright 2008, 2009, 2010 Dan Moulding, Alan T. DeKok
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Caution: Don't edit this Makefile! Create your own main.mk and other
#          submakefiles, which will be included by this Makefile.
#          Only edit this if you need to modify boilermake's behavior (fix
#          bugs, add features, etc).

# Note: Parameterized "functions" in this makefile that are marked with
#       "USE WITH EVAL" are only useful in conjuction with eval. This is
#       because those functions result in a block of Makefile syntax that must
#       be evaluated after expansion. Since they must be used with eval, most
#       instances of "$" within them need to be escaped with a second "$" to
#       accomodate the double expansion that occurs when eval is invoked.

# ADD_CLEAN_RULE - Parameterized "function" that adds a new rule and phony
#   target for cleaning the specified target (removing its build-generated
#   files).
#
#   USE WITH EVAL
#
define ADD_CLEAN_RULE
    clean: clean_${1}
    .PHONY: clean_${1}
    clean_${1}:
    $$(strip rm -f ${TARGET_DIR}/${1} $${${1}_OBJS:%.o=%.[do]})
    $${${1}_POSTCLEAN}
endef

# ADD_OBJECT_RULE - Parameterized "function" that adds a pattern rule for
#   building object files from source files with the filename extension
#   specified in the second argument. The first argument must be the name of the
#   base directory where the object files should reside (such that the portion
#   of the path after the base directory will match the path to corresponding
#   source files). The third argument must contain the rules used to compile the
#   source files into object code form.
#
#   USE WITH EVAL
#
define ADD_OBJECT_RULE
${1}/%.o: ${2}
    ${3}
endef

# ADD_TARGET_RULE - Parameterized "function" that adds a new target to the
#   Makefile. The target may be an executable or a library. The two allowable
#   types of targets are distinguished based on the name: library targets must
#   end with the traditional ".a" extension.
#
#   USE WITH EVAL
#
define ADD_TARGET_RULE
    ifeq "$$(suffix ${1})" ".a"
        # Add a target for creating a static library.
        $${TARGET_DIR}/${1}: $${${1}_OBJS}
        @mkdir -p $$(dir $$@)
        $$(strip $${AR} $${ARFLAGS} $$@ $${${1}_OBJS})
        $${${1}_POSTMAKE}
    else
        # Add a target for linking an executable. First, attempt to select the
        # appropriate front-end to use for linking. This might not choose the
        # right one (e.g. if linking with a C++ static library, but all other
        # sources are C sources), so the user makefile is allowed to specify a
        # linker to be used for each target.
        ifeq "$$(strip $${${1}_LINKER})" ""
            # No linker was explicitly specified to be used for this target. If
            # there are any C++ sources for this target, use the C++ compiler.
            # For all other targets, default to using the C compiler.
            ifneq "$$(strip $$(filter $${CXX_SRC_EXTS},$${${1}_SOURCES}))" ""
                ${1}_LINKER = $${CXX}
            else
                ${1}_LINKER = $${CC}
            endif
        endif

        $${TARGET_DIR}/${1}: $${${1}_OBJS} $${${1}_PREREQS}
        @mkdir -p $$(dir $$@)
        $$(strip $${${1}_LINKER} -o $$@ $${LDFLAGS} $${${1}_LDFLAGS} \
            $${${1}_OBJS} $${LDLIBS} $${${1}_LDLIBS})
        $${${1}_POSTMAKE}
    endif
endef

# CANONICAL_PATH - Given one or more paths, converts the paths to the canonical
#   form. The canonical form is the path, relative to the project's top-level
#   directory (the directory from which "make" is run), and without
#   any "./" or "../" sequences. For paths that are not  located below the
#   top-level directory, the canonical form is the absolute path (i.e. from
#   the root of the filesystem) also without "./" or "../" sequences.
define CANONICAL_PATH
$(patsubst ${CURDIR}/%,%,$(abspath ${1}))
endef

# COMPILE_C_CMDS - Commands for compiling C source code.
define COMPILE_C_CMDS
    @mkdir -p $(dir $@)
    $(strip ${CC} -o $@ -c -MP -MD ${CFLAGS} ${SRC_CFLAGS} ${INCDIRS} \
        ${SRC_INCDIRS} ${SRC_DEFS} ${DEFS} $<)
endef

# COMPILE_CXX_CMDS - Commands for compiling C++ source code.
define COMPILE_CXX_CMDS
    @mkdir -p $(dir $@)
    $(strip ${CXX} -o $@ -c -MP -MD ${CXXFLAGS} ${SRC_CXXFLAGS} ${INCDIRS} \
        ${SRC_INCDIRS} ${SRC_DEFS} ${DEFS} $<)
endef

# INCLUDE_SUBMAKEFILE - Parameterized "function" that includes a new
#   "submakefile" fragment into the overall Makefile. It also recursively
#   includes all submakefiles of the specified submakefile fragment.
#
#   USE WITH EVAL
#
define INCLUDE_SUBMAKEFILE
    # Initialize all variables that can be defined by a makefile fragment, then
    # include the specified makefile fragment.
    TARGET        :=
    TGT_CFLAGS    :=
    TGT_CXXFLAGS  :=
    TGT_DEFS      :=
    TGT_INCDIRS   :=
    TGT_LDFLAGS   :=
    TGT_LDLIBS    :=
    TGT_LINKER    :=
    TGT_POSTCLEAN :=
    TGT_POSTMAKE  :=
    TGT_PREREQS   :=

    SOURCES       :=
    SRC_CFLAGS    :=
    SRC_CXXFLAGS  :=
    SRC_DEFS      :=
    SRC_INCDIRS   :=

    SUBMAKEFILES  :=

    # A directory stack is maintained so that the correct paths are used as we
    # recursively include all submakefiles. Get the makefile's directory and
    # push it onto the stack.
    DIR := $(call CANONICAL_PATH,$(dir ${1}))
    DIR_STACK := $$(call PUSH,$${DIR_STACK},$${DIR})

    include ${1}

    # Initialize internal local variables.
    OBJS :=

    # Ensure that valid values are set for BUILD_DIR and TARGET_DIR.
    ifeq "$$(strip $${BUILD_DIR})" ""
        BUILD_DIR := build
    endif
    ifeq "$$(strip $${TARGET_DIR})" ""
        TARGET_DIR := .
    endif

    # Determine which target this makefile's variables apply to. A stack is
    # used to keep track of which target is the "current" target as we
    # recursively include other submakefiles.
    ifneq "$$(strip $${TARGET})" ""
        # This makefile defined a new target. Target variables defined by this
        # makefile apply to this new target. Initialize the target's variables.
        TGT := $$(strip $${TARGET})
        ALL_TGTS += $${TGT}
        $${TGT}_CFLAGS    := $${TGT_CFLAGS}
        $${TGT}_CXXFLAGS  := $${TGT_CXXFLAGS}
        $${TGT}_DEFS      := $${TGT_DEFS}
        $${TGT}_DEPS      :=
        TGT_INCDIRS       := $$(call QUALIFY_PATH,$${DIR},$${TGT_INCDIRS})
        TGT_INCDIRS       := $$(call CANONICAL_PATH,$${TGT_INCDIRS})
        $${TGT}_INCDIRS   := $${TGT_INCDIRS}
        $${TGT}_LDFLAGS   := $${TGT_LDFLAGS}
        $${TGT}_LDLIBS    := $${TGT_LDLIBS}
        $${TGT}_LINKER    := $${TGT_LINKER}
        $${TGT}_OBJS      :=
        $${TGT}_POSTCLEAN := $${TGT_POSTCLEAN}
        $${TGT}_POSTMAKE  := $${TGT_POSTMAKE}
        $${TGT}_PREREQS   := $$(addprefix $${TARGET_DIR}/,$${TGT_PREREQS})
        $${TGT}_SOURCES   :=
    else
        # The values defined by this makefile apply to the the "current" target
        # as determined by which target is at the top of the stack.
        TGT := $$(strip $$(call PEEK,$${TGT_STACK}))
        $${TGT}_CFLAGS    += $${TGT_CFLAGS}
        $${TGT}_CXXFLAGS  += $${TGT_CXXFLAGS}
        $${TGT}_DEFS      += $${TGT_DEFS}
        TGT_INCDIRS       := $$(call QUALIFY_PATH,$${DIR},$${TGT_INCDIRS})
        TGT_INCDIRS       := $$(call CANONICAL_PATH,$${TGT_INCDIRS})
        $${TGT}_INCDIRS   += $${TGT_INCDIRS}
        $${TGT}_LDFLAGS   += $${TGT_LDFLAGS}
        $${TGT}_LDLIBS    += $${TGT_LDLIBS}
        $${TGT}_POSTCLEAN += $${TGT_POSTCLEAN}
        $${TGT}_POSTMAKE  += $${TGT_POSTMAKE}
        $${TGT}_PREREQS   += $${TGT_PREREQS}
    endif

    # Push the current target onto the target stack.
    TGT_STACK := $$(call PUSH,$${TGT_STACK},$${TGT})

    ifneq "$$(strip $${SOURCES})" ""
        # This makefile builds one or more objects from source. Validate the
        # specified sources against the supported source file types.
        BAD_SRCS := $$(strip $$(filter-out $${ALL_SRC_EXTS},$${SOURCES}))
        ifneq "$${BAD_SRCS}" ""
            $$(error Unsupported source file(s) found in ${1} [$${BAD_SRCS}])
        endif

        # Qualify and canonicalize paths.
        SOURCES     := $$(call QUALIFY_PATH,$${DIR},$${SOURCES})
        SOURCES     := $$(call CANONICAL_PATH,$${SOURCES})
        SRC_INCDIRS := $$(call QUALIFY_PATH,$${DIR},$${SRC_INCDIRS})
        SRC_INCDIRS := $$(call CANONICAL_PATH,$${SRC_INCDIRS})

        # Save the list of source files for this target.
        $${TGT}_SOURCES += $${SOURCES}

        # Convert the source file names to their corresponding object file
        # names.
        OBJS := $$(addprefix $${BUILD_DIR}/$$(call CANONICAL_PATH,$${TGT})/,\
                   $$(addsuffix .o,$$(basename $${SOURCES})))

        # Add the objects to the current target's list of objects, and create
        # target-specific variables for the objects based on any source
        # variables that were defined.
        $${TGT}_OBJS += $${OBJS}
        $${TGT}_DEPS += $${OBJS:%.o=%.d}
        $${OBJS}: SRC_CFLAGS   := $${$${TGT}_CFLAGS} $${SRC_CFLAGS}
        $${OBJS}: SRC_CXXFLAGS := $${$${TGT}_CXXFLAGS} $${SRC_CXXFLAGS}
        $${OBJS}: SRC_DEFS     := $$(addprefix -D,$${$${TGT}_DEFS} $${SRC_DEFS})
        $${OBJS}: SRC_INCDIRS  := $$(addprefix -I,\
                                     $${$${TGT}_INCDIRS} $${SRC_INCDIRS})
    endif

    ifneq "$$(strip $${SUBMAKEFILES})" ""
        # This makefile has submakefiles. Recursively include them.
        $$(foreach MK,$${SUBMAKEFILES},\
           $$(eval $$(call INCLUDE_SUBMAKEFILE,\
                      $$(call CANONICAL_PATH,\
                         $$(call QUALIFY_PATH,$${DIR},$${MK})))))
    endif

    # Reset the "current" target to it's previous value.
    TGT_STACK := $$(call POP,$${TGT_STACK})
    TGT := $$(call PEEK,$${TGT_STACK})

    # Reset the "current" directory to it's previous value.
    DIR_STACK := $$(call POP,$${DIR_STACK})
    DIR := $$(call PEEK,$${DIR_STACK})
endef

# MIN - Parameterized "function" that results in the minimum lexical value of
#   the two values given.
define MIN
$(firstword $(sort ${1} ${2}))
endef

# PEEK - Parameterized "function" that results in the value at the top of the
#   specified colon-delimited stack.
define PEEK
$(lastword $(subst :, ,${1}))
endef

# POP - Parameterized "function" that pops the top value off of the specified
#   colon-delimited stack, and results in the new value of the stack. Note that
#   the popped value cannot be obtained using this function; use peek for that.
define POP
${1:%:$(lastword $(subst :, ,${1}))=%}
endef

# PUSH - Parameterized "function" that pushes a value onto the specified colon-
#   delimited stack, and results in the new value of the stack.
define PUSH
${2:%=${1}:%}
endef

# QUALIFY_PATH - Given a "root" directory and one or more paths, qualifies the
#   paths using the "root" directory (i.e. appends the root directory name to
#   the paths) except for paths that are absolute.
define QUALIFY_PATH
$(addprefix ${1}/,$(filter-out /%,${2})) $(filter /%,${2})
endef

###############################################################################
#
# Start of Makefile Evaluation
#
###############################################################################

# Older versions of GNU Make lack capabilities needed by boilermake.
# With older versions, "make" may simply output "nothing to do", likely leading
# to confusion. To avoid this, check the version of GNU make up-front and
# inform the user if their version of make doesn't meet the minimum required.
MIN_MAKE_VERSION := 3.81
MIN_MAKE_VER_MSG := boilermake requires GNU Make ${MIN_MAKE_VERSION} or greater
ifeq "${MAKE_VERSION}" ""
    $(info GNU Make not detected)
    $(error ${MIN_MAKE_VER_MSG})
endif
ifneq "${MIN_MAKE_VERSION}" "$(call MIN,${MIN_MAKE_VERSION},${MAKE_VERSION})"
    $(info This is GNU Make version ${MAKE_VERSION})
    $(error ${MIN_MAKE_VER_MSG})
endif

# Define the source file extensions that we know how to handle.
C_SRC_EXTS := %.c
CXX_SRC_EXTS := %.C %.cc %.cp %.cpp %.CPP %.cxx %.c++
ALL_SRC_EXTS := ${C_SRC_EXTS} ${CXX_SRC_EXTS}

# Initialize global variables.
ALL_TGTS :=
DEFS :=
DIR_STACK :=
INCDIRS :=
TGT_STACK :=

# Include the main user-supplied submakefile. This also recursively includes
# all other user-supplied submakefiles.
$(eval $(call INCLUDE_SUBMAKEFILE,main.mk))

# Perform post-processing on global variables as needed.
DEFS := $(addprefix -D,${DEFS})
INCDIRS := $(addprefix -I,$(call CANONICAL_PATH,${INCDIRS}))

# Define the "all" target (which simply builds all user-defined targets) as the
# default goal.
.PHONY: all
all: $(addprefix ${TARGET_DIR}/,${ALL_TGTS})

# Add a new target rule for each user-defined target.
$(foreach TGT,${ALL_TGTS},\
  $(eval $(call ADD_TARGET_RULE,${TGT})))

# Add pattern rule(s) for creating compiled object code from C source.
$(foreach TGT,${ALL_TGTS},\
  $(foreach EXT,${C_SRC_EXTS},\
    $(eval $(call ADD_OBJECT_RULE,${BUILD_DIR}/$(call CANONICAL_PATH,${TGT}),\
             ${EXT},$${COMPILE_C_CMDS}))))

# Add pattern rule(s) for creating compiled object code from C++ source.
$(foreach TGT,${ALL_TGTS},\
  $(foreach EXT,${CXX_SRC_EXTS},\
    $(eval $(call ADD_OBJECT_RULE,${BUILD_DIR}/$(call CANONICAL_PATH,${TGT}),\
             ${EXT},$${COMPILE_CXX_CMDS}))))

# Add "clean" rules to remove all build-generated files.
.PHONY: clean
$(foreach TGT,${ALL_TGTS},\
  $(eval $(call ADD_CLEAN_RULE,${TGT})))

# Include generated rules that define additional (header) dependencies.
$(foreach TGT,${ALL_TGTS},\
  $(eval -include ${${TGT}_DEPS}))

A: If you make the command as:
make debug=true
Then in one of your makefiles:

ifeq (debug,true)
    CXXFLAGS += -DDEBUG
else
    CXXFLAGS += -DNDEBUG
endif


text:
Q: pandas query rows by list I have a pandas data frame and want to return the rows from the data frame corresponding to the customer ids that appear in a list of target ids.
For example, if my data frame looks like this:
id    Name    ...    ...
-------------------------
1     Bob     ...    ...
2     Dave    ...    ...
2     Dave    ...    ...
3     Phil    ...    ...
4     Rick    ...    ...
4     Rick    ...    ...

Basically I want to return the rows for customers who appear more than once in this data frame. So I want to return all the ids that occur more than once.
id    Name    ...    ...
-------------------------
2     Dave    ...    ...
2     Dave    ...    ...
4     Rick    ...    ...
4     Rick    ...    ...

I can get a list of the ids by doing the following
grouped_ids = df.groupby('id').size()
id_list = grouped_ids[grouped_ids>1].index.tolist()

And now I'd like to go back to the data frame and return all the rows corresponding to those ids in the list.
Is this possible?
Thanks for the help.

A: I guess you are looking for isin():
In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'customer_id':range(5), 'A':('a', 'b', 'c', 'd', 'e')})

In [3]: df
Out[3]:
   A  customer_id
0  a            0
1  b            1
2  c            2
3  d            3
4  e            4

In [4]: df[df.customer_id.isin((1,3))]
Out[4]:
   A  customer_id
1  b            1
3  d            3

[edit] To match a given target list, just use it as argument for the isin() method:
In [5]: mylist = (1,3)

In [6]: df[df.customer_id.isin(mylist)]
Out[6]:
       A  customer_id
1  abcde            1
3  abcde            3


text:
Q: How to merge multiple LSTM models and to fit them I am trying to merge two LSTM Sequential models, but without success. I am using the Concatenate() method from tensorflow.keras.layers . Whenever I try to concatenate the models it says ValueError: A Concatenate layer should be called on a list of at least 2 inputs which doesn't make sense, because the two models are passed in the list.
This is the code that I have for the models:
# Initialising the LSTM
regressor = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))
regressor.add(Dropout(0.2))

# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))

regressor.add(Dense(units = 1))

lstm_model = Sequential()

lstm_model.add(LSTM(units = 4, activation = 'relu', input_shape = (X_train.shape[1], 1)))

# returns a sequence of vectors of dimension 4

# Adding the output layer
lstm_model.add(Dense(units = 1))

merge = Concatenate([regressor, lstm_model])
hidden = Dense(1, activation = 'sigmoid')
conc_model = Sequential()
conc_model.add(merge)
conc_model.add(hidden)
conc_model.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics=['mae', 'acc'])

history = conc_model.fit(X_train, y_train, validation_split=0.1, epochs = 50, batch_size = 32, verbose=1, shuffle=False)

How to concatenate and fit those models? I don't understand what I am doing wrong.

A: you are using Sequential and concatenate together, this is wrong.
you should used Input and Model keyword to define model.
inp_layer1 = Input(shape=(1,))
m1 = Dense(1) (inp_layer1)

inp_layer2 = Input(shape=(1,))
m2 = Dense(1) (inp_layer2)

m3 = concatenate([m1,m2])
model = Model(inputs=[inp_layer1,inp_layer2],outputs=m3)

A: The problem is cause by your fit input, it should be a list of two inputs instead of one input, because your conc_model require two inputs
Check the docs of fit function, it says: Input data could be a Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs)
So you need to split the X_train into list of two array, first one for regressor second for lstm_model


text:
Q: Can't get php/html pages to display characters with accents (é, á ) correctly I can't get my php/html pages to display characters with accents (é, á ) correctly. My database is set up correctly. When I run show variables like 'char% I get satisfactory output:
character_set_client        utf8
character_set_connection    utf8
character_set_database      utf8
character_set_filesystem    binary
character_set_results       utf8
character_set_server        utf8
character_set_system        utf8
character_sets_dir      /usr/share/mysql/charsets/

Data is encoded and stored correctly in the DB when I insert it from a form on my site.
But something weird happens on my display page.
If I put header('Content-Type: text/html; charset=utf-8'); at the top just inside the php opening tag, data from my DB is displayed correctly but characters that I type manually into the page within HTML tags (as Table Column Headers or just descriptive para text) display with rubbish: �.
If I REMOVE header('Content-Type: text/html; charset=utf-8'); from the top of the page, data from my DB is displayed INCORRECTLY but the text that I write into the page within HTML is fine.
I've tried everything I know. Has anyone come across this before?

A: The only thing I can think of in addition to what you've done on the server side is to add:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
To the <head> tag in your html file.

A: Try changing your file encoding to UTF-8. Notepad++, SciTE, PhpStorm and many others can do it.


text:
Q: LSTM Autoencoder Output Layer I am trying to get a LSTM autoencoder to recreate its inputs. So far I have:
class getSequence(nn.Module):
    def forward(self, x):
        out, _ = x
        return out

class getLast(nn.Module):
    def forward(self, x):
        out, states = x
        states = states[len(states) - 1]
        return states

class AEncoder(nn.Module):
    def __init__(self, input_size, first_layer, second_layer, n_layers):
        super(AEncoder, self).__init__()
        self.n_layers = n_layers
        self.encode = nn.Sequential(nn.LSTM(input_size, first_layer, batch_first=True),
                                    getSequence(),
                                    nn.ReLU(True),
                                    nn.LSTM(first_layer, second_layer),
                                    getLast())
        self.decode = nn.Sequential(nn.LSTM(second_layer, first_layer),
                                    getSequence(),
                                    nn.ReLU(True),
                                    nn.LSTM(first_layer, input_size),
                                    getSequence())

    def forward(self, x):
        x = x.float()
        x = self.encode(x)
        x = x.repeat(32, 1, 1) # repeating last hidden state of self.encode
        x = self.decode(x)
        return x

While researching I have been seeing some people adding a time-distributed dense layer at the end of the self.decode. I am confused if that final layer is specific to other tasks autoencoders are used for, if so, can I ignore that layer if I am only trying to recreate inputs?

A: The time-distributed dense layer as name suggested just an ordinary dense layer that apply to every temporal slice of an input, you can think it as special form of RNN cell, i.e without recurrent hidden state.
So you can using any layer that is time-distributed as your output layer for an Autoencoder that deal with time-distributed inputs, e.g RNN layer with LSTM Cell, GRU Cell, Simple RNN Cell or time-distributed dense layer; As in research paper that propose the LSTM-Autoencoder, it basic model for reconstruct sequence of  vectors (image patches or features) only using one LSTM layer in both encoder and decoder, model structure is:

Following is an example to using time-distributed dense layer in decoder:
class Decoder(nn.Module):

  def __init__(self, seq_len, input_dim=64, n_features=1):
    super(Decoder, self).__init__()

    self.seq_len, self.input_dim = seq_len, input_dim
    self.hidden_dim, self.n_features = 2 * input_dim, n_features

    self.rnn = nn.LSTM(
      input_size=input_dim,
      hidden_size=self.hidden_dim,
      num_layers=1,
      batch_first=True)

    self.output_layer = nn.Linear(self.hidden_dim, n_features)

  def forward(self, x):
    x = x.repeat(self.seq_len, self.n_features)
    x = x.reshape((self.n_features, self.seq_len, self.input_dim))
    x, (hidden_n, cell_n) = self.rnn(x)
    x = x.reshape((self.seq_len, self.hidden_dim))
    return self.output_layer(x)


text:
Q: Computing theta functions of lattices in practice I am motivated by a problem in 2d CFT to compute "generalized theta functions," expressions of the form
\begin{equation}
\vartheta_{L,u}(\tau) := \sum_{\alpha \in L} u(\alpha) q^{{\langle\alpha,\alpha\rangle}/2}\,,
\end{equation}
where $u:L\to \{\pm 1\}$ is some function I'll know explicitly. If it matters, $L$ will always be a sublattice of the $E_8$ lattice.
By "compute," I really mean present the RHS in terms of "nice" functions like $\theta_{1,2,3,4}$, but I'm open to alternatives (say Eisenstein series). One thing of moderate importance is the ability to look at q-expansions in, say, Mathematica. My hope is that lattice pros already have techniques to evaluate these sums and I am not re-inventing various wheels below.
I'm caustiously optimistic that if I can do this for regular theta functions (i.e. with $u(\alpha) = 1$), that I can do it with minus signs, as it will just flip some $\theta_{2,3}$s to $\theta_{1,4}$s.
My Attempt: Calculating $\vartheta_{A_2}$
My trick thus far is to turn the calculation into sums over integers, then abuse integer shift-symmetry and re-write sums to remove "cross-terms." For example, for the $A_2$ lattice
\begin{align}
\sum_{\alpha\in A_2} q^{\langle\alpha,\alpha\rangle/2}
&= \sum_{n_1,n_2\in\mathbb{Z}} q^{n_1^2-n_1n_2+n_2^2}\\
&=(\sum_{n_2 \textrm{ odd}}+\sum_{n_2 \textrm{ even}})\sum_{n_1}q^{n_1^2-n_1n_2+n_2^2}\\
&=\sum_{k}\sum_{n_1}q^{1 + 4 k + 4 k^2 - 2 k n_1  - n_1 + n_1^2}+\sum_{k}\sum_{n_1}q^{4 k^2 - 2 k n_1 + n_1^2}\\
&=\sum_{k}\sum_{n_1}q^{1 + 3 k + 3 k^2 + n_1 + n_1^2}+\sum_{k}\sum_{n_1}q^{3 k^2 + n_1^2}\\
&=\theta_2(6\tau)\theta_2(2\tau)+\theta_3(6\tau)\theta_3(2\tau)\,.
\end{align}
In going from the second to third line I've just written $n_2=2k+1$ and $n_2=2k$, and for third to fourth I've shifted $n_1 \mapsto n_1 + k + 1$ and $n_1 \mapsto n_1 + k$ for the respective sums.
Problem 1: $\vartheta_{E_6}$ is a lot!
This approach gets involved very quickly. For a rank $N$ lattice, I have at least $N$ sums, and I don't always get to break each sum into 2. e.g. maybe I need to replace $n_i$ with $n_i = 3k, 3k+1, 3k+2$.
On page 127 of Conway & Sloane's book, they give $\theta_{E_6}$ in terms of $\theta_{2,3}$ as
\begin{equation}
\theta_{E_6}(\tau) = \frac{1}{4}f(\tau)^3+\theta_{A_2}(\tau)^3
\end{equation}
where
\begin{equation}
f(\tau) = \theta_{A_2}\left(\frac{\tau}{3}\right)+\theta_{A_2}(\tau)
\end{equation}
Question 1.A): Can I obtain this answer without using that $A_2 \times E_6$ is a $\mathbb{Z}_3$ fixed sublattice of $E_8$?
I imagine a technique where I present the inner product $\langle \alpha,\alpha\rangle/2$ as coming from an upper triangular matrix. i.e. write $\alpha$ as an integer sum over simple roots $\alpha = \sum_{i} n_i \alpha_i$ then
\begin{equation}
\langle \alpha,\alpha\rangle/2 =
\begin{pmatrix}n_1\\ n_2\\ \vdots \\ n_N \end{pmatrix}
\begin{pmatrix}
    1 & c_{12} & \dots  & c_{1N} \\
      & 1      & \dots  & c_{2N} \\
      &        & \ddots & \vdots \\
      &        &        & 1
\end{pmatrix}
\begin{pmatrix}n_1\\ n_2\\ \vdots \\ n_N \end{pmatrix}\,.
\end{equation}
My hope is that shift-symmetry and breaking up sums have natural actions in some linear algebra approach like this.
Question 1.B): Does such a technique exist already, or is there a quicker way to do these computations?
Problem 2: Recognizing Theta-Functions
When I extend this procedure and try it on the next-simplest lattice, $A_3$, I don't obtain an answer which is obviously products of theta functions like I did for $A_2$. In particular, I can make my sums decouple, but I get arbitrary "blocks" of the form
\begin{align}
\mathbb{B}_{A,B,C}
&:=\sum_{k} q^{\frac{1}{2}(A k^2 + B k + C)}\\
&= q^{\frac{C}{2}}\vartheta\left(\frac{B\tau}{2},A\tau\right)\\
&= q^{\frac{C}{2}}(q^A;q^A)_\infty\theta\left(-q^{(A+B)/2},q^A\right)
\end{align}
where $\vartheta(z,\tau)$ is the regular Jacobi-theta function $\theta(w,q)$ is the q-theta function with $w=e^{i\pi z}$. For special $\{A,B,C\}$ the relationships to $\theta_{1,2,3,4}$ are clear. And maybe that's the best I can do unless I can find some identities relating an arbitrary $\mathbb{B}_{A,B,C}$ to $\theta_{1,2,3,4}$, or other similarly "nice" functions.
Question 2: Are there better expressions for my "blocks"?