text:
Q: Model association in sequelize [erro]{ this.name}.hasMany called with something that's not a subclass of Sequelize.Model I'am try created a project and use node.js + sequelize, the project have two model Fator and Sub_fator. They have a association 1:N, but when  create fator, returned an erro:

Error: Fator.hasMany called with something that's not a subclass of Sequelize.Model

any sugestion for solved the error?
model Fator
'use strict';
const Sub_Fator = require('./sub_fator');

module.exports = (sequelize, DataTypes) => {
  const Fator = sequelize.define('Fator', {
    descricao: DataTypes.STRING
  }, {});
  Fator.associate = function(models) {
      Fator.hasMany(Sub_Fator, {
      foreignKey: 'fatorId',
      as: 'fatores'
    });
  };
  return Fator;
};

model Sub_fator
'use strict';
const Fator = require('./fator');

module.exports = (sequelize, DataTypes) => {
  const Sub_Fator = sequelize.define('Sub_Fator', {
    fatorId: DataTypes.INTEGER,
    descricao: DataTypes.STRING
  }, {});
  Sub_Fator.associate = function(models) {
    Sub_Fator.belongsTo(Fator, {
      foreignKey: 'fatorId',
      as: 'fatores'
    });
  };
  return Sub_Fator;
};

A: //Removed this import because is not an object of Model it's a definition
module.exports = (sequelize, DataTypes) => {
  const Fator = sequelize.define('Fator', {
    descricao: DataTypes.STRING
  }, {});
  Fator.associate = function(models) {
      Fator.hasMany(models.Sub_Fator, {//Change to this instead of Sub_Fator
        foreignKey: 'fatorId',
        as: 'fatores'
    });
  };
  return Fator;
};

The reason is Because you define the model here, but then in your models/index.js or something like that you have to import it to generate an object model, this is just a model definition and it's not a SubClass of Sequelize.Model.
PS: Your index should something like this if you generated sequelize in your project:
'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/server-config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;


text: Q: how to calculate enthalpy and internal energy in relation to heat capacities? I remember that $\mathrm du=c\mathrm dT$ and $\mathrm dh=c\mathrm dT$ with $c$ being two different heat capacities, but I can't find anything about it, any help?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как конвертировать c++ builder в си. Здравствуйте!
Есть код. http://ideone.com/HC5EeV
Меня не интересует его визуализация, а интересен алгоритм. Я, к сожалению, не знаю c++ builder. Есть ли инструмент, которые автоматом перепишет его на Си или хотя бы c++.
Спасибо.


text:
Q: How to Correctly Handle Reference Loop .NET Entity Framework API I have two tables and related code files, Request and RequestLine. One Request can have many RequestLines. I used a database first approach and the models were automatically created using scaffolding. I am using Entity Framework and DTOs etc
I have run into an issue where i'm getting a Reference Loop error in my API when running the POST method.
The issue occurs because the scaffold put a Request property in the RequestLine object
    public virtual Request Request { get; set; } = null!;

With my GET method, in the controller I was able to point it to its related DTO, where I removed the Request field which would have caused the reference loop but i'm not sure how I would achieve the same with the POST method. I created a RequestCreateDTO and RequestLineCreateDTO without the reference field loop but I can't figure out how to use this in my POST.
I have found two ways of avoiding this issue
The first is to remove the Request property from RequestLine model, then remove the relationship from RequesLine context
Alternatively, I can add this to my Program.cs to ignore the Reference Loop
builder.Services.AddControllers().AddJsonOptions(x =>
                x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

Although both work, neither seems like to correct way to handle this. So I was wondering how I go about handling it properly? I want to POST a Request, which contains a RequestLine - But I want them to use my RequestCreateDTO and RequestLineCreateDTO.
The related code is below.
The data context for Request and RequestLines is:
        modelBuilder.Entity<Request>(entity =>
        {
            entity.ToTable("Request", "rmr");

            entity.Property(e => e.CreatedOn).HasColumnType("datetime");

            entity.Property(e => e.RaisedBy).HasMaxLength(256);

            entity.Property(e => e.WorklistName).HasMaxLength(32);

            //entity.HasOne(d => d.WorklistNameNavigation)
            //    .WithMany(p => p.Requests)
            //    .HasForeignKey(d => d.WorklistName)
            //    .HasConstraintName("FK_RMR_REQUEST_WORKLIST");
        });

        modelBuilder.Entity<RequestLine>(entity =>
        {
            entity.HasKey(e => new { e.RequestId, e.LineNumber })
                .HasName("PK_RMR_REQUESTLINE");

            entity.ToTable("RequestLine", "rmr");

            entity.Property(e => e.Batch).HasMaxLength(32);

            entity.Property(e => e.CancelBy).HasMaxLength(256);

            entity.Property(e => e.CancelDate).HasColumnType("datetime");

            entity.Property(e => e.CostCentre).HasMaxLength(32);

            entity.Property(e => e.Destination).HasMaxLength(32);

            entity.Property(e => e.FirstDeliveryDate).HasColumnType("datetime");

            entity.Property(e => e.ProcessOrder).HasMaxLength(32);

            entity.Property(e => e.Sku)
                .HasMaxLength(32)
                .HasColumnName("SKU");

            entity.Property(e => e.SubmittedDate).HasColumnType("datetime");

            //entity.HasOne(d => d.DestinationNavigation)
            //    .WithMany(p => p.RequestLines)
            //    .HasForeignKey(d => d.Destination)
            //    .OnDelete(DeleteBehavior.ClientSetNull)
            //    .HasConstraintName("FK_RMR_REQUESTLINE_DESTINATION");

            entity.HasOne(d => d.Request)
                .WithMany(p => p.RequestLines)
                .HasForeignKey(d => d.RequestId)
                .HasConstraintName("FK_RMR_REQUESTLINE_REQUEST");
        });

The related data models are as follows:
Request
public partial class Request
{
    public Request()
    {
        RequestLines = new HashSet<RequestLine>();
    }

    public long Id { get; set; }
    public string RaisedBy { get; set; } = null!;
    public DateTime CreatedOn { get; set; }
    public string? WorklistName { get; set; }

    //public virtual Worklist? WorklistNameNavigation { get; set; }
    public virtual ICollection<RequestLine> RequestLines { get; set; }
}

RequestLine
public partial class RequestLine
{
    public long RequestId { get; set; }
    public int LineNumber { get; set; }
    public string Sku { get; set; } = null!;
    public string Batch { get; set; } = null!;
    public int Quantity { get; set; }
    public string? CostCentre { get; set; }
    public string? ProcessOrder { get; set; }
    public string Destination { get; set; } = null!;
    public DateTime FirstDeliveryDate { get; set; }
    public DateTime? SubmittedDate { get; set; }
    public DateTime? CancelDate { get; set; }
    public string? CancelBy { get; set; }
     }
}

and the DTOs for the POST method is:
Request
public class RequestCreateDTO
{
    public RequestCreateDTO()
    {
        RequestLines = new HashSet<RequestLineCreateDTO>();
    }

    [Required]
    [StringLength(256)]
    public string RaisedBy { get; set; } = null!;

    [Required]
    public DateTime CreatedOn { get; set; }

    [Required]
    [StringLength(32)]
    public string? WorklistName { get; set; }

    //public virtual Worklist? WorklistNameNavigation { get; set; }
    public virtual ICollection<RequestLineCreateDTO> RequestLines { get; set; }
}

RequestLine
public class RequestLineCreateDTO
{
    [Required]
    public int LineNumber { get; set; }

    [Required]
    [StringLength(32)]
    public string Sku { get; set; } = null!;

    [Required]
    [StringLength(32)]
    public string Batch { get; set; } = null!;

    public int Quantity { get; set; }

    [StringLength(32)]
    public string? CostCentre { get; set; }

    [StringLength(32)]
    public string? ProcessOrder { get; set; }

    [Required]
    [StringLength(32)]
    public string Destination { get; set; } = null!;

    public DateTime FirstDeliveryDate { get; set; }
    public DateTime? SubmittedDate { get; set; }
    public DateTime? CancelDate { get; set; }

    [Required]
    [StringLength(256)]
    public string? CancelBy { get; set; }
}

The point at which i'm having an issue is my POST method and the controller looks like this
    [HttpPost]
    public async Task<ActionResult<RequestCreateDTO>> PostRequest(RequestCreateDTO requestDto)
    {
        var request = mapper.Map<Request>(requestDto);
        //var requestLine = mapper.Map<RequestLine>(requestLineDto);

        if (_context.Requests == null)
        {
          return Problem("Entity set 'RawcliffeDatastoreContext.Requests'  is null.");
        }
        await _context.Requests.AddAsync(request);
        //await _context.RequestLines.AddAsync(requestLine);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetRequest), new { id = request.Id }, request);
    }


text:
Q: toggle function doesnt work on server I'm making a webpage with a submenu that appears when you click on the main menu. At the same time I wanted to include a transparent background that covers the whole page when the submenu is activated so that it stands out from the background page.
Up until this point everything seems fine, I've tried it in the Dreamweaver preview and it functions correctly. The problem occurs when I upload it to the server. The menu works fine but the transparent background doesn't appear.
This is the website www.whitedogstudio.org and as you will see when you open the menu a transparent background should appear to make the menu more visible.
this is the website: http://www.whitedogstudio.org/
<script>
jQuery(document).ready(function($){
    $(".menu").on("click", function(){
        deactivateAll(this);
        toggle(this);

    });

    function deactivateAll(current) {
        $( "li" ).each(function( index, elem ){
            if (elem != current && $(elem).hasClass("active")) {
                toggle(elem);
            }
        });
    }

    function toggle(elem) {
        $(elem).find("ul").toggle ("fast","linear");
        $( "#transparencia" ).toggle();
        $(elem).toggleClass("active");

     }
 });
 </script>


text:
Q: If then esle PHP script to check database access for Wordpress We've had a lot of problems recently with mysql being down at our hosting company which causes our Wordpress site to display Unable to connect to Database instead of the Wordpress site.  I would like to add some code into the index.php script that checks the status of the database connection and if it fails, the load a simple html file.  Otherwise, it the database connection is good, the index.php script continues as normal to load Wordpress.  Below is the current index.php script for Wordpress.
<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );

A: You can customize the error message when there is no database connection available.
Just create a file with the filename WP_CONTENT_DIR . '/db-error.php'. This will be require_once()ed once the connection is not successful.
If the file doesn't exist, the builtin error message is displayed.
Reference to source code: https://github.com/WordPress/WordPress/blob/master/wp-includes/wp-db.php#L1652


text:
Q: How to Change IBAction Event Type Once Created? When I control+drag to my .m from a text field to create an IBAction it asks for what type of events should this IBAction be called. I mistakenly set the wrong event type (Editing Did End) and want to change it to Editing Changed.
This is minor, I know, because I can just create the new IBAction with the correct event and copy the innards, but I'd like to know if changing the event of an already created IBAction is possible.

A: Right click on textview.
Remove IBAction for Editing Did End.
Set to Editing Changed.


text:
Q: retrieve the text from HTMLbox Does anyone know how to retrieve the text from HTMLbox rich text editior?

A: Htmlbox is just an plugin that extends upon the html element textarea .You can treat it like normal textarea html element.
For eg..
$(function()
{
 $('#textboxid').htmlbox({
        toolbars:[
             [
            "separator","bold","italic","underline","strike","sup","sub",
            "separator","removeformat"
            ],
            ["separator","fontsize","fontfamily","fontcolor","highlight"]
        ],
        skin:"blue"
        });
alert($('#textboxid').val());
}

A: To use HtmlBox's built-in functions, do this:
Assign the return of htmlbox() to a variable and then call HtmlBox's methods using that variable (e.g. hb_full.get_html(); or any other method). See code example below.
<script type="text/javascript">
    var hb_full;
$(document).ready(function(){
        hb_full = $("#htmlbox_full").css("height", "300").css("width", "100%").htmlbox({
            toolbars: [
                [
                    // Cut, Copy, Paste
                    "separator", "cut", "copy", "paste",
                    // Undo, Redo
                    "separator", "undo", "redo",
                    // Bold, Italic, Underline, Strikethrough, Sup, Sub
                    "separator", "bold", "italic", "underline", "strike", "sup", "sub",
                    // Left, Right, Center, Justify
                    "separator", "justify", "left", "center", "right",
                    // Ordered List, Unordered List, Indent, Outdent
                    "separator", "ol", "ul", "indent", "outdent",
                    // Hyperlink, Remove Hyperlink, Image
                    "separator", "link", "unlink", "image"
                ],
                [
                    // Show code
                    "separator", "code",
                            // Formats, Font size, Font family, Font color, Font, Background
                    "separator", "formats", "fontsize", "fontfamily",
                    "separator", "fontcolor", "highlight",
                ],
                [
                    //Strip tags
                    "separator", "removeformat", "striptags", "hr", "paragraph",
                    // Styles, Source code syntax buttons
                    "separator", "quote", "styles", "syntax"
                ]
            ],
            about: true, // "false" to hide About button
            idir: "./img/HtmlBoxImg/",
            icons: "default", //all options: "default", "silk"
            skin: "blue"      //all options: "silver", "blue", "green", "red"
        });
    });

    function getHtmlFromEditor()
    {
        var HtmlFromEditor = hb_full.get_html();
        alert(HtmlFromEditor);
    }
    </script>

    <textarea id="htmlbox_full"></textarea>
<button onclick="getHtmlFromEditor();">Display HTML</button>


text:
Q: Sending email with attachment google sheet ERROR I want to emails with attachment but I have an error

SyntaxError: Invalid or unexpected token (row 17, file "try.gs")

and I don't understand why?. The pdf named "i.pdf" is in my google drive
here is my code :
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // Start at second row because the first row contains the data labels
var numRows = 3; // Put in here the number of rows you want to process

// Fetch the range of cells A3:E3
// Column A = Name, Column B = Email, Column C = Message, Column D = Message1, Column E = Message2
var dataRange = sheet.getRange(startRow, 1, numRows, 4)

// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[2]; // First column of selected data
var message = "Hey "; // Assemble the body text
var subject = "Sending emails from a Spreadsheet";
var file = DriveApp.getFilesByName('i.pdf');
if (file.hasNext())
MailApp.sendEmail(emailAddress, subject, message, {
attachments: [file.next().getAs(MimeType.PDF)],
name: 'Simple mail'});

}
}

Can someone help me pls

A: The error is caused by the use of typographic / curly / single quotation characters = ''.
Replace them by straight single or double quotation characters '' o "".
Related

*

*Notify via email when a cell is updated in google spreadsheet

*Google AppScript syntax error for sendemail. Can't ID my problem

A: You have two typos when you declare var file and in the MailApp.sendEmail() function . Try this instead:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // Start at second row because the first row contains the data labels
var numRows = 3; // Put in here the number of rows you want to process

// Fetch the range of cells A3:E3
// Column A = Name, Column B = Email, Column C = Message, Column D = Message1, Column E = Message2
var dataRange = sheet.getRange(startRow, 1, numRows, 4)

// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[2]; // First column of selected data
var message = "Hey "; // Assemble the body text
var subject = "Sending emails from a Spreadsheet";
var file = DriveApp.getFilesByName("i.pdf");
if (file.hasNext())
MailApp.sendEmail(emailAddress, subject, message, {
attachments: [file.next().getAs(MimeType.PDF)],
name: "Simple mail"});

}
}


text:
Q: Passing value from second activity to main throws NPE When i press button in second Activity, intent sends a string to the MainActivity. It's in onClick method:
        Intent intent = new Intent(this, MainActivity.class);
        String wynik = "clear";
        intent.putExtra("clearList", wynik);

and main activity, in onCreate method:
 Intent intent2 = getIntent();
    wynik = intent2.getStringExtra("clearList");
    if (wynik.equals("clear")) {

        tempLukasz = 0;
        tempMarcelina = 0;
        tempKarolina = 0;
        foodCategorySum = 0;
        catCategorySum = 0;
        othersCategorySum = 0;
        lukaszJedzenie = 0;
        lukaszKot = 0;
        lukaszInne = 0;
        marcelinaJedzenie = 0;
        marcelinaKot = 0;
        marcelinaInne = 0;
        karolinaJedzenie = 0;
        karolinaKot = 0;
        karolinaInne = 0;
        newPayments.clear();
        wynik = "";
    }

so when MainActivity receives this "clear" message it should set my numbers to 0 and clear the list. Pic.1 is example of my main activity window:

and in second pic is what i want to have AFTER button in second activity is pressed
Unfortunately it does not work: this line throws NullPointerException:
 if (wynik.equals("clear")) {

Any ideas where am I making a mistake ? I thought that checking if ( getIntent() != null ) will solve this or just surrount my IF clase with try-catch but it does not work either.

A: The problem is that when first time the onCreate() gets called it's checking for the String extra that should have been filled by the Second Activity which hasn't been called yet.  So you'd definitely get a NPE when launching the app.
If you need to start another activity and receive a result back you should call startActivityForResult() instead of startActivity().
When the user is done with the second activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:
1. The request code you passed to startActivityForResult().
2.A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backedout or the operation failed for some reason.
3.An Intent that carries the result data.
Look here for full description Launching an explicit activity for getting back result

A: It's not enough checking if the intent is null, you also need to check if the String itself is null.
From developer.android.com:
Returns
the value of an item that previously added with putExtra() or null if no String value was found.
Source: http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)
So change it to:
if (intent2 != null && wynik != null && wynik.equals("clear")) {
    ...
}

A: The main thing that I notice odd on this attempt is the null exeception that should occur on start, another thing is intents when used to pass values backwards we tend to use onActivityResult for this.
Such when setting your intent
Intent intent = new Intent(this, MainActivity.class);
String wynik = "clear";
intent.putExtra("clearList", wynik);

we set the result to
setResult(x, intent);

and then we recieve the intent in the main class by calling onActivityResult
such as
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
      //dosomething with intent
 }

but also need to remember to set the intent that called the second activity to
     startActivityForResult(intent, x);

A: the problem is like zulkarnain said .....
try to make a  static Boolean value in the second activity and name it for example : "  check_for_activity" (name it any name you want)
then after the put extra .. set the "check_for_activity" to true  ..
and in main activity ..and before the getIntent line .. type : if(secondActivity.check_for_activity == true ){
// put here the code for getting the value from the second activity
}
Just try that and it maybe work :) (y)

A: When you are running MainActivity first time then the extra is not set by secondActivity. So its showing error. Try following
if(getIntent() != null && getIntent().getExtras() != null)
myBoolean = getIntent().getExtras().getBoolean("clearList");

Then
 if(myBoolean)

 {
  Intent intent2 = getIntent();
  wynik = intent2.getStringExtra("clearList");
if (wynik.equals("clear")) {

    tempLukasz = 0;
    tempMarcelina = 0;
    tempKarolina = 0;
    foodCategorySum = 0;
    catCategorySum = 0;
    othersCategorySum = 0;
    lukaszJedzenie = 0;
    lukaszKot = 0;
    lukaszInne = 0;
    marcelinaJedzenie = 0;
    marcelinaKot = 0;
    marcelinaInne = 0;
    karolinaJedzenie = 0;
    karolinaKot = 0;
    karolinaInne = 0;
    newPayments.clear();
    wynik = "";
}
 }


text:
Q: if else stament in php Good Day. Here my question:
i want to display the result if the count get from the SQL is more than 0, if the count is 0, then the result will not display.
Here the current output after adding if else statement in my php :
    {"result":[]}

This is the output before adding if else statement in my php:
 { "result": [
    {"day":"1","count":"0"},
    {"day":"2","count":"2"},
    {"day":"3","count":"0"},
    {"day":"4","count":"0"}....

I want the result only like tis :
    {"result":[
      {"day":"2","count":"2"}
    ]}

Here my php code:

define('HOST','xx');
define('USER','xx');
define('PASS','xx');
define('DB','x');

//$month = $_POST['month'];
//$year = $_POST['year'];

$month = 10;
$year=2016;

$con = mysqli_connect(HOST,USER,PASS,DB);

$result = array();
 for ($day=1 ; $day<=31 ; $day++) {
     $sql = "select count(entryID) from Entry where
         EXTRACT(DAY FROM(entryTime)) = '$day'  AND
         EXTRACT(MONTH FROM(entryTime)) = '$month' AND
         EXTRACT(YEAR FROM(entryTime))= '$year'";
     $res = mysqli_query($con,$sql);

if($row[0] >0)
     $day2 = (string)$day;
     while($row = mysqli_fetch_array($res)) {
         array_push($result,
         array('day' =>$day2,
            'count' => $row[0]
         ));

         }
}

 }

 echo $appear . json_encode(array("result"=>$result));

mysqli_close($con);

?>

A:
Your Variable $row within your Conditional Check Block if($row[0] > 0) { was not yet defined at the Point where it was used. In other words; the entire Conditional Logic should be moved into the while Loop Construct...Perhaps, the snippet below sheds some light:

<?php

    define('HOST','xx');
    define('USER','xx');
    define('PASS','xx');
    define('DB','x');

    $con    = mysqli_connect(HOST,USER,PASS,DB);
    $month  = 10;
    $year   = 2016;
    $result = array();
    /****************************|
    | $month  = $_POST['month']; |
    | $year   = $_POST['year'];  |
    |****************************/

    for($day=1; $day<=31; $day++) {
        $sql    = " SELECT COUNT(entryID) ";
        $sql   .= " FROM Entry WHERE ";
        $sql   .= " EXTRACT( DAY FROM(entryTime) )      = '$day'   ";
        $sql   .= " AND EXTRACT(MONTH FROM(entryTime))  = '$month' ";
        $sql   .= " AND EXTRACT(YEAR FROM(entryTime))   = '$year'  ";
        $res    = mysqli_query($con,$sql);

        while($row = mysqli_fetch_array($res)) {
            if($row[0] > 0) {        //<== CONDITIONAL LOGIC HERE, INSTEAD
                $day2 = (string)$day;
                array_push($result,
                    array('day'     => $day2,
                          'count'   => $row[0]
                    )
                );
            }
        }
    }

    //NOTICE: THE $appear VARIABLE IS NOT DEFINED IN YOUR CODE.
    echo $appear . json_encode(array("result"=>$result));
    mysqli_close($con);


text:
Q: What does 'a ## b' mean in C? From usbtiny/defs.h (AVR libc USB code for ATTiny controllers):
#define CAT2(a,b)               CAT2EXP(a, b)
#define CAT2EXP(a,b)            a ## b
#define CAT3(a,b,c)             CAT3EXP(a, b, c)
#define CAT3EXP(a,b,c)          a ## b ## c

What is the ## operator? I've been doing this for 30 years, and I'm stumped. And google isn't helping because I don't think they're indexing those chars.

A: The ## symbol in a macro definition represents concatenation.
So
#define concat(a,b) a ## b

will mean that
concat (pri, ntf) ("hello world\n");

post-processes to
printf("hello world\n");

Documentation here.
Similarly useful is the stringify operator (#), with which this should not be confused.
A test:
/* test with
 *    gcc -E test.c
 * having removed the #include lines for easier to read output
 */

#include <stdio.h>
#include <stdlib.h>

#define concat(a,b) a ## b

int
main (int argc, char **argv)
{
  concat (pri, ntf) ("Hello world\n");
  exit (0);
}

And why the extra level of indirection? As Deduplicator points out in the comments to his answer below, without that, it will concatenate the literal terms specified, rather than the macro substituted terms. A useful list of such pitfalls is here.

A: CAT2 and CAT3 are the macros which should be called, the other two are part of their internal working.
#define CAT2(a,b)               CAT2EXP(a, b)
#define CAT2EXP(a,b)            a ## b

So, what happens if you call CAT2?
Well, first CAT2 is replaced, which macro-expands the literal arguments:
CAT2(a_eval, b_eval)

Which is replaced by concatenating both arguments to make one token, by the ## token concatenation operator.


text:
Q: Can any one have the link to compose the api from scratch in bluemix api connect? I have imported one api with wsdl file using the SOAP operation of API connect(Bluemix), for the same endpoint i want to compose the api from scratch without using the wsdl. I'm facing some issues when i'm doing it without wsdl

A: There is a great tutorial provided in developerWorks that will show you how to use APIConnect on Bluemix to create, configure and publish APIs. I would recommend following along to gain the experience you are looking for:
API Connect Tutorial: Mastering the API Assembly


text:
Q: Android - Open URL in background There is this website for example http://website.com You can like stuff there, with a link like this for example: http://website.com/3020/hype. You have to go to that link to get the article (3020) liked. You can only like stuff when loged in.
I have this:
HttpClient client = new DefaultHttpClient();
            String getURL = "http://website.com/3020/hype/";
            HttpGet get = new HttpGet(getURL);
            HttpResponse responseGet = client.execute(get, cookieStuff);

Where cookieStuff is the cookie string I got from loggin in.
This works, but it takes ages. Is there another option?

A: Yes there is a nother option.. Internet connections and Database Connection should made in a AyncTask or Handler.. This will improve the time taken for connection (the connections will make in Background)..
here is a example for an async task:

private class YourTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... s) {

        //Here you have to make the loading / parsing tasks
        //Don't call any UI actions here. For example a Toast.show() this will couse Exceptions
        // UI stuff you have to make in onPostExecute method

    }

    @Override
    protected void onPreExecute() {
        // This method will called during doInBackground is in process
        // Here you can for example show a ProgressDialog
    }

    @Override
    protected void onPostExecute(Long result) {
        // onPostExecute is called when doInBackground finished
        // Here you can for example fill your Listview with the content loaded in doInBackground method

    }

}

To execute an AsyncTask:

new YourTask().execute("");


text:
Q: change value to corresponding value from another column in pandas i have a data frame that looks as following
     col1 col2 col3
0   a     d    0
1   b     e    1
2   c     f    0
3   x     t    1
.................

i want to change col3 with value 1 to corresponding value in col2
the result would be
   col1 col2 col3
0   a     d    0
1   b     e    e
2   c     f    0
3   x     t    t
.................

df[['col1','col2','col3']].applymap(lambda x: df['col2'] if x==1 else x)

the above gives error somehow
any one have idea how to do it with pandas?

A: Use:
df.loc[df.col3 == 1, 'col3'] = df.col2

Or:
df.col3 = df.col3.mask(df.col3 == 1, df.col2)
#df.col3 = df.col3.where(df.col3 != 1, df.col2)
#df.col3 = np.where(df.col3 == 1, df.col2, df.col3)

print (df)
  col1 col2 col3
0    a    d    0
1    b    e    e
2    c    f    0
3    x    t    t

EDIT:
Slowier solution with apply + lambda:
df = df.apply(lambda x: x['col2'] if x['col3']==1 else x, axis=1)

Timings:
#[40000 rows x 3 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [42]: %timeit df.col3 = np.where(df.col3 == 1, df.col2, df.col3)
100 loops, best of 3: 3.97 ms per loop

In [43]: %timeit df.loc[df.col3 == 1, 'col3'] = df.col2
100 loops, best of 3: 6.81 ms per loop

In [44]: %timeit df.col3 = df.col3.mask(df.col3 == 1, df.col2)
100 loops, best of 3: 4.95 ms per loop

In [45]: %timeit df.col3 = df.col3.where(df.col3 != 1, df.col2)
100 loops, best of 3: 4.8 ms per loop

In [47]: %timeit df.apply(lambda x: x['col2'] if x['col3']==1 else x, axis=1)
1 loop, best of 3: 3.39 s per loop


text:
Q: regular expression url rewrite based on folder I need to be able to take /calendar/MyCalendar.ics where MyCalendar.ics coudl be about anything with an ICS extention and rewrite it to /feeds/ics/ics_classic.asp?MyCalendar.ics
Thanks

A: C:\x>perl foo.pl
Before: a=/calendar/MyCalendar.ics
After: a=/feeds/ics/ics_classic.asp?MyCalendar.ics

...or how about this way?
(regex kind of seems like overkill for this problem)
b=/calendar/MyCalendar.ics
index=9
c=MyCalendar.ics (might want to add check for ending with '.ics')
d=/feeds/ics/ics_classic.asp?MyCalendar.ics

Here's the code:
C:\x>type foo.pl
my $a = "/calendar/MyCalendar.ics";
print "Before: a=$a\n";
my $match = (
   $a =~ s|^.*/([^/]+)\.ics$|/feeds/ics/ics_classic.asp?$1.ics|i
);
if( ! $match ) {
   die "Expected path/filename.ics instead of \"$a\"";
}
print "After: a=$a\n";
print "\n";
print "...or how about this way?\n";
print "(regex kind of seems like overkill for this problem)\n";
my $b = "/calendar/MyCalendar.ics";
my $index = rindex( $b, "/" ); #find last path delim.
my $c = substr( $b, $index+1 );
print "b=$b\n";
print "index=$index\n";
print "c=$c (might want to add check for ending with '.ics')\n";
my $d = "/feeds/ics/ics_classic.asp?" . $c;
print "d=$d\n";
C:\x>

General thoughts:
If you do solve this with a regex, a semi-tricky bit is making sure your capture group (the parens) exclude the path separator.
Some things to consider:
Are your paths separators always forward-slashes?
Regex seems like overkill for this; the simplest thing I can think of of to get the index of your last path separator and do simple string manipulation (2nd part of sample program).
Libraries often have routines for parsing paths.  In Java I'd look at the java.io.File object, for example, specifically
    getName()
    Returns the name of the file or directory denoted by
    this abstract pathname. This is just the last name in
    the pathname's name sequence

A: Regular expressions are meant for searching/matching text. Usually you will use regex to define what you search for some text manipulation tool, and then use a tool specific way to tell the tool with what to replace the text.
Regex syntax use round brackets to define capture groups inside the whole search pattern. Many search and replace tools use capture groups to define which part of the match to replace.
We can take the Java Pattern and Matcher classes as example. To complete your task with the Java Matcher you can use the following code:
Pattern p = Pattern.compile("/calendar/(.*\.(?i)ics)");

Matcher m = p.matcher(url);

String rewritenUrl = "";
if(m.matches()){
    rewritenUrl = "/feeds/ics/ics_classic.asp?" + url.substring( m.start(1), m.end(1));
}

This will find the requested pattern but will only take the first regex group for creating the new string.
Here is a link to regex replacement information in (imho) a very good regex information site: http://www.regular-expressions.info/refreplace.html


text:
Q: Table style not working in PHP, MySql The table pattern was working before adding the below line
echo "Download	";

but after adding the above line the table style is gone.
here is the full table code, please help me in this

                Quote ID
                File Name
                File
                Size
                Created

          <?php
            while($row = $result->fetch_assoc()) {
            if ($row["status"]!="Approved")
            {
                 echo "
";
                 echo "" . $row['quote_id'] . "	";
                 echo "" . $row['name'] . "	";
                 echo "" . $row['mime'] . "	";
                 echo "" . $row['size'] . "	";
                 echo "" . $row['created'] . "	";
                 echo "Download	";
                 echo "
";
            }}
            ?>

A: You have 5
And
6
That is why its not working.
Change:

    Quote ID
    File Name
    File
    Size
    Created

To

    Quote ID
    File Name
    File
    Size
    Created
    Download

Also, Change
echo "Download	";

To
echo 'Download	';


text:
Q: date Ym adding +1 month I need to add/substract +1/-1 month for a dynamic navigation. Here is what I've got so far - still struggling with the date-things: events.html?month=201401
<?php
$getdate=stripslashes((isset($_GET['month'])) ? $_GET ['month'] : "");
?>
<a href="events.html?month=<?php if($getdate=="")echo date('Ym',strtotime(date('Y-m-d').' +1 month')); else echo date('Ym',strtotime($getdate.' +1 month')); ?>">month +

This should endup like these:
<november    actual    january>

Can anyone help out, please? Still got 201401 as href, which is correct for the first click. But it stays 201401 on second click and so on.

A: This should work:
$month = isset($_GET['month']) ? $_GET['month'] : date('Ym');

$curr = DateTime::createFromFormat('!Ym', $month);
$prev = clone $curr; $prev->modify('-1 month');
$next = clone $curr; $next->modify('+1 month');

echo "PREV: " . $prev->format('F Y') . "\n";
echo "CURR: " . $curr->format('F Y') . "\n";
echo "NEXT: " . $next->format('F Y') . "\n";

DEMO

A: Fixed:
$currentDate = !empty($_GET['month']) ? $_GET['month'] : date('Ym');
$currentTimespan = mktime(0, 0, 0, substr($currentDate, 4, 2), 1, substr($currentDate, 0, 4));

$actual = date('Ym', $currentTimespan);
$previous = date('Ym', strtotime('-1 month', $currentTimespan));
$next = date('Ym', strtotime('+1 month', $currentTimespan));

A: This will do.
<?php
$date = new DateTime('2000-01-01'); // you can add you date here coming via $_GET['month']
$date->add(new DateInterval('P1M'));
echo $date->format('Y-m-d') . "\n";
?>

Ref : http://www.php.net/manual/en/datetime.add.php

A: Your problem is that the format you use (Ym) isn't recognised by the strtotime() function so you have to use the ATOM format("Y-m-d\TH:i:sP") sub-string, or some other normalized format. ;)
<?php
$getdate = (strlen($_GET['month'])>0)?$_GET['month']:date('Y-m');
$month = date("Y-m", strtotime("+1 month", strtotime($getdate)));
echo 'month +';
?>

A: very simple.
Add a month and then get only the month:
$time = new DateTime();
$time->modify('+1 month');
$month = $time->format('m');
print_r ($month);


text:
Q: Parallel solving Ax=b?
Cross posted on StackOverflow.

I have some extremely large sparse matrices created using spMatrix function from the matrix package.
Using the solve() function works for my Ax=b issue, but it takes a very long time. Several days.
I noticed that http://cran.r-project.org/web/packages/RScaLAPACK/RScaLAPACK.pdf appears to have a function that can parallelize the solve function, however, it can take several weeks to get new packages installed on this particular server.
The server already has the snow package installed it.
So

*

*Is there a way of using snow to parallelize this operation?

*If not, are there other ways to speed up this type of operation?

*Are there other packages like RScaLAPACK? My search on RScaLAPACK
seemed to suggest people had a lot of issues with it.

Thanks.
Additional details

*

*The matrices are about 370,000 x 370,000. I'm using it to solve for
alpha centrality, http://en.wikipedia.org/wiki/Alpha_centrality.

*I was originally using the alpha centrality function in the igraph
package, but it would crash R.

*This is on a single machine with 12 cores and 96 gigs of memory (I believe)

*It's a directed graph along the lines of paper citation
relationships.

*Calculating condition number and density will take awhile. Will post
as it comes available.

A: Have you tried QR decomposition?  See Theorem 3 here for solving $Ax=b$.
Finding the inverse of a matrix (even a small one) is a slow process.  Methods such as QR or Cholesky decomposition are used in practice when 'inverting' is needed (at least in my experience in statistical programming).

A: You can decompose this operation into a set of smaller operations that are easy to parallelize.
Suppose you wish to solve $\mathbf{m}\mathbf{v}=\mathbf{u}$ for an $N$ by $N$ matrix $\mathbf{m}$ and $N$-vector $\mathbf{u}$.  Writing $N=n+m$ (intending $n\approx m$), decompose $\mathbf{m}$ into four blocks $\mathbf{a}_{n \times n}$, $\mathbf{b}_{n \times m}$, $\mathbf{c}_{m\times n}$, and $\mathbf{d}_{m \times m}$, and also decompose $\mathbf{u}$ into its first $n$ components $\mathbf{e}_n$ and its last $m$ components $\mathbf{f}_m$ while similarly expressing $\mathbf{v}$ as the concatenation of the $n$-vector $\mathbf{x}$ and the $m$-vector $\mathbf{y}$.  The original system is readily seen to be equivalent to the sequence
$$\eqalign{
\mathbf{a} \mathbf{z} &= \mathbf{e} \\
\mathbf{a} \mathbf{w} &= \mathbf{b} \\
\left(\mathbf{d}-\mathbf{c}\mathbf{w}\right)\mathbf{y}& = \mathbf{f} - \mathbf{c}\mathbf{z} \\
\mathbf{a}\mathbf{x} &= \mathbf{e} - \mathbf{b}\mathbf{y}
}$$
The first two form $m+1$ systems of $n$ equations (having a common matrix); the third is a single system of $m$ equations (depending on the solutions to the first two); and the last is a single system of $n$ equations (depending on the solution to the third).  By choosing $m \approx n \approx N/2$, you have reduced the sizes of the matrices involved and you have created an opportunity to run the first $m+1$ systems in parallel.  If this is not enough, the technique can be applied recursively.
This approach works no matter what algorithm for solving a linear system you may favor.


text:
Q: How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line? The unzip command doesn't have an option for recursively unzipping archives.
If I have the following directory structure and archives:

/Mother/Loving.zip
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes.zip

And I want to unzip all of the archives into directories with the same name as each archive:

/Mother/Loving/1.txt
/Mother/Loving.zip
/Scurvy/Sea Dogs/2.txt
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes/3.txt
/Scurvy/Cures/Limes.zip

What command or commands would I issue?
It's important that this doesn't choke on filenames that have spaces in them.

A: A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:
find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';'

Note that you can easily make it handle more file types (such as .jar) by adding them using -o, e.g.:
find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...

A: Here's one solution that extracts all zip files to the working directory and involves the find command and a while loop:
find . -name "*.zip" | while read filename; do unzip -o -d "`basename -s .zip "$filename"`" "$filename"; done;

A: You could use find along with the -exec flag in a single command line to do the job
find . -name "*.zip" -exec unzip {} \;

A: This works perfectly as we want:
Unzip files:
find . -name "*.zip" | xargs -P 5 -I FILENAME sh -c 'unzip -o -d "$(dirname "FILENAME")" "FILENAME"'

Above command does not create duplicate directories.
Remove all zip files:
find . -depth -name '*.zip' -exec rm {} \;

A: Something like gunzip using the -r flag?....
Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).
http://www.computerhope.com/unix/gzip.htm

A: If you're using cygwin, the syntax is slightly different for the basename command.
find . -name "*.zip" | while read filename; do unzip -o -d "`basename "$filename" .zip`" "$filename"; done;

A: If you want to extract the files to the respective folder you can try this
find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;

A multi-processed version for systems that can handle high I/O:
find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"'

A: I realise this is very old, but it was among the first hits on Google when I was looking for a solution to something similar, so I'll post what I did here. My scenario is slightly different as I basically just wanted to fully explode a jar, along with all jars contained within it, so I wrote the following bash functions:
function explode {
    local target="$1"
    echo "Exploding $target."
    if [ -f "$target" ] ; then
        explodeFile "$target"
    elif [ -d "$target" ] ; then
        while [ "$(find "$target" -type f -regextype posix-egrep -iregex ".*\.(zip|jar|ear|war|sar)")" != "" ] ; do
            find "$target" -type f -regextype posix-egrep -iregex ".*\.(zip|jar|ear|war|sar)" -exec bash -c 'source "<file-where-this-function-is-stored>" ; explode "{}"' \;
        done
    else
        echo "Could not find $target."
    fi
}

function explodeFile {
    local target="$1"
    echo "Exploding file $target."
    mv "$target" "$target.tmp"
    unzip -q "$target.tmp" -d "$target"
    rm "$target.tmp"
}

Note the <file-where-this-function-is-stored> which is needed if you're storing this in a file that is not read for a non-interactive shell as I happened to be. If you're storing the functions in a file loaded on non-interactive shells (e.g., .bashrc I believe) you can drop the whole source statement. Hopefully this will help someone.
A little warning - explodeFile also deletes the ziped file, you can of course change that by commenting out the last line.

A: Another interesting solution would be:
DESTINY=[Give the output that you intend]

# Don't forget to change from .ZIP to .zip.
# In my case the files were in .ZIP.
# The echo were for debug purpose.

find . -name "*.ZIP" | while read filename; do
ADDRESS=$filename
#echo "Address: $ADDRESS"
BASENAME=`basename $filename .ZIP`
#echo "Basename: $BASENAME"
unzip -d "$DESTINY$BASENAME" "$ADDRESS";
done;

A: You can also loop through each zip file creating each folder and unzip the zip file.
for zipfile in *.zip; do
  mkdir "${zipfile%.*}"
  unzip "$zipfile" -d "${zipfile%.*}"
done

A: this works for me
def unzip(zip_file, path_to_extract):
    """
    Decompress zip archives recursively
    Args:
        zip_file: name of zip archive
        path_to_extract: folder where the files will be extracted
    """
    try:
        if is_zipfile(zip_file):
            parent_file = ZipFile(zip_file)
            parent_file.extractall(path_to_extract)
            for file_inside in parent_file.namelist():
                if is_zipfile(os.path.join(os.getcwd(),file_inside)):
                    unzip(file_inside,path_to_extract)
            os.remove(f"{zip_file}")
    except Exception as e:
        print(e)


text:
Q: How to get a name from Tempfriend object (1) in django? my tempfriends/models.py
class Tempfriend(core_models.TimeStampedModel):
    name = models.CharField(max_length=30)
    belongs_to = models.ForeignKey(
        user_models.User, on_delete=models.CASCADE, related_name="belongs_to")

as you see, tempfriends have a relation with usermodels.
so when user make a moneybook, user can choose there companion(tempfriends), but there is a problem.
form.companion print out :
Tempfriend object (1)
these are the code.
moneybook_form.html

                    {{form.companion.label}}

                        {{form.companion}}

            {% if form.companion.errors %}
                {% for error in form.companion.errors %}
                    >{{error}}
                {% endfor %}
            {% endif %}

how can I print object name instead of Tempfriend object (1)?


text:
Q: Save data from REST POST call in Node I want to be able to save different API calls that I do into functions, so that I can call these functions to get the data I need. Here is the code I had in Node.js:
"use strict";

var rp = require('request-promise');

function getAccessToken() {
  return new Promise((resolve, reject) => {
    var options = {
        method: 'POST',
        uri: 'some_uri',
        body: {
           "username": "username",
           "password": "password"
        },
        json: true // Automatically stringifies the body to JSON
    };
    rp(options)
        .then(function (parsedBody) {
             resolve(parsedBody.accessToken);
        })
        .catch(function (err) {
             reject(err);
        });
     }
)}

Is there any way for me to basically save the data from this function to a variable? Instead of returning a promise, can I return something else and be able to do
var token = getAccessToken();

console.log(token);

A: request-promise library returns promise only, its not at all required to wrap rp with Promise inside the getAccessToken() function.
In the following snippet, perform all your executions in init() method. It is async function. It waits for the getAccessToken() execution and assign the value to variable token
"use strict";

var rp = require('request-promise');

function getAccessToken() {
    var options = {
        method: 'POST',
        uri: 'some_uri',
        body: {
           "username": "username",
           "password": "password"
        },
        json: true // Automatically stringifies the body to JSON
    };
    return rp(options);
)

async function init() {
    try {
        var tokenInfo = await getAccessToken();
        console.log(tokenInfo);
    } catch (e) {
        // Console err
    }
}

init();

Note: Not tested code


text:
Q: Pandas: use of aggregate with a MultiIndex I have a question about the correct use of agg in pandas. The specific problem I am working on is in the field of finance and, more specifically, is to calculate a liquidity measure from the full limit order book.
My data contain the ask side of the order book (which represents how many shares people want to sell at a particular moment and at which price) and I want to calculate the hypothetical price for buying 50 shares at a specific moment in time. Assume for example that the order book for stock X at 9am looks like this:
example_data=pd.DataFrame({'price':[100.023,100.031,100.039,100.109,100.219 ],'avail_shares':      [40,1,20,23,15],'midpoint':[99.996 ,99.996 ,99.996 ,99.996,99.996 ]})

where price is the price at which shares are sold, avail_shares the number of shares available at each price and midpoint the average of the best ask and bid price in the order book. To get a liquidity measure that takes into account that a large order can hit multiple price levels at once (i.e. 'walk the book')  I define the following cost-to-trade (ctt) function:
def ctt_ask(dfrm,level=50):
    dfrm['cumshares']=dfrm['avail_shares'].cumsum()
    dfrm['indicator']=0
    dfrm['indicator'].ix[dfrm.cumshares<level,]=dfrm.cumshares
    dfrm['indicator'].ix[(dfrm.cumshares>level) & (dfrm.cumshares.shift(1)<level),]=(level-  dfrm.cumshares.shift(1))
   liquidity_measure=((dfrm.price-dfrm.midpoint)*dfrm.indicator).sum()
    return liquidity_measure

This works just fine (i.e. ctt_ask(example_data) yields 2.90) for the above example but my real dataset has several stocks and many date times (it has a MultiIndex). When I use groupby and agg to apply this function to every stock-date time combination (    full_book_ask.groupby(level=[0,1]).agg(ctt_ask)) I get an error: KeyError: 'avail_shares'. This is strange because I do have a column named avail_shares in my actual dataset.  I have also tried the same with the apply functionality but this raises the error message Exception: cannot handle a non-unique multi-index!
. I can't seem to figure out what I'm doing wrong here. Any input would be much appreciated!


text:
Q: Post Request stuck on Postman I am learning to build API using Node.js, Express and MongoDB. I am on early learning phase.
My code are as follow.
const app = express();

const mongojs = require("mongojs");

const { body, param, validationResult } = require("express-validator");

const db = mongojs("travel", ["records"]);

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get("/api/records", function (req, res) {
  const options = req.query;

  const sort = options.sort || {};
  const filter = options.filter || {};
  const limit = 2;
  const page = parseInt(options.page) || 1;
  const skip = (page - 1) * limit;

  for (var i in sort) {
    sort[i] = parseInt(sort[i]);
  }

  db.records
    .find(filter)
    .sort(sort)
    .skip(skip)
    .limit(limit, function (err, data) {
      if (err) {
        return res.sendStatus(500);
      } else {
        return res.status(200).json({
          meta: {
            filter,
            sort,
            skip,
            limit,
            page,
            total: data.length,
          },
          data,
          links: {
            self: req.originalUrl,
          },
        });
      }
    });
});

app.post("/api/records", function (req, res) {
  db.records.insert(req.body, function (err, data) {
    if (err) {
      return res.status(500);
    }

    const _id = data._id;
    res.append("Location", "/api/records/" + _id);
    return res.send(201).json({
      meta: { _id },
      data,
    });
  });
});

app.listen(8000, function () {
  console.log("Server running at port 8000...");
});

When I try GET request on Postman, it works fine. But when I try POST request, it shows like the following. error msg image link.
Please let me know what is wrong here.
Thanks in advance


text:
Q: java.lang.ClassCastException com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to com.sun.xml.bind.api.JAXBRIContext I have exposed a web service however when client trying to consume the service I can see there is a ClassCastException exception in the server log. and request is not reaching the web service. When I am trying to call the web service it is working from SOAP UI.
java.lang.ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to com.sun.xml.bind.api.JAXBRIContext.

I have tried using these two solution
java.lang.ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to com.sun.xml.bind.api.JAXBRIContext
ClassCastException: Cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor
However in my weblogic folder I could not find the conflicting jar.

A: After investigation I found the issue It was due to wrong wsdl used by the client to call the webservice. Client was using the old wsdl and webservice hosted had a different wsdl.
To trace the issue I enabled http logging on server to check the request send by the client. After comparing the SOAP-UI request with client request I found one namespace was different in the request. After identifying the issue I asked the client to generate the stubs classes using new wsdl and call the webservice and it worked.
The confusion was due to below exception. All the solution were asking to check conflicting jar.
java.lang.ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to com.sun.xml.bind.api.JAXBRIContext.


text:
Q: Append element on d3 dragstart I'm trying to use d3 to make a circle that is draggable, but leaves a copy of the original in place. Here is the circle:
g.selectAll('circle')
    .data([{
    cx: 90,
    cy: 80,
    r: 30 }])
  .enter().append('circle')
    .attr('cx', function (d) {return d.cx})
    .attr('cy', function (d) {return d.cy})
    .attr('r', function(d) {return d.r})
    .attr('class','original')
    .call(dragOriginal);

Here is the drag behavior:
var dragOriginal = d3.behavior.drag()
    .on('dragstart', cloneSpeciesMaker)
    .on('drag', function (d, i) {
    d.cx += d3.event.dx;
    d.cy += d3.event.dy;
    d3.select(this).attr('cx', d.cx).attr('cy', d.cy)
});

And here is the dragstart function:
function cloneSpeciesMaker(d) {
    var svg = d3.select('svg');
    //original becomes copy
    d3.select(this)
        .classed('original',false)
        .attr('class','copy');
    // creates new 'original' in place
    var data = [{cx:d.cx,cy:d.cy,r:d.r}];
    svg.append('circle')
        .data(data)
        .attr('class','original')
        .attr("cx",function(d) {return d.x})
        .attr("cy",function(d) {return d.y})
        .attr("r",function(d) {return d.r})
        .style("fill","purple")
        .attr("class","original")
        .call(dragOriginal);
}

Right now, I'm succeeding in making the original circle become a 'copy' and dragging it around, but it the part where I append a new circle in its old place isn't working, can anyone explain why?

A: One problem I can see from the code is in this section:
function cloneSpeciesMaker(d) {
    var svg = d3.select('svg');
    //original becomes copy
    d3.select(this)
        .classed('original',false)
        .attr('class','copy');
    // creates new 'original' in place
    var data = [{cx:d.cx,cy:d.cy,r:d.r}];
    svg.append('circle')
        .data(data)
        .attr('class','original')
        .attr("cx",function(d) {return d.x})
        .attr("cy",function(d) {return d.y})
        .attr("r",function(d) {return d.r})
        .style("fill","purple")
        .attr("class","original")
        .call(dragOriginal);
}

You are setting the data like this
var data = [{cx:d.cx,cy:d.cy,r:d.r}];

But you are doing which is incorrect d.x and d.y is not defined by you in data.
.attr("cx",function(d) {return d.x})
.attr("cy",function(d) {return d.y})

This should have been:
.attr("cx",function(d) {return d.cx})
.attr("cy",function(d) {return d.cy})


text:
Q: Laravel 5.7 Routing not Working for Subdomain For my Laravel application, I want to use subdomains to link to different spas with Vue.js. The only thing I have to do is link in the web.php to the Laravel Blade file but for some reason, it's not working.
<?php

Route::domain('test.mysite.test')->group(function () {
    return view('test');
});

I run Laravel Valet for my virtual host. Does anyone have an idea what the problem could be?

A: Edit your code like this:
Route::domain('test.mysite.test')->group(function () {
  Route::get('/', function () {
    return view('test');
  });
});

and be sure that you registered your subdomain virtual host too


text:
Q: Import \mathbbit{q} from stix I am trying to import the following symbol
\mathbbit{q}

from stix library,

see the following code, please:
\documentclass{article}
\usepackage{amsmath}
\DeclareFontEncoding{LS1}{}{}
\DeclareFontSubstitution{LS1}{stix}{m}{n}
\newcommand*\qq{%
\text{%
\fontencoding{LS1}%
\fontfamily{stixbb}%
\fontseries{\textmathversion}%
\fontshape{n}%
\selectfont\symbol{`q}}}
\makeatletter
\newcommand*\textmathversion{\csname textmv@\math@version\endcsname}
\newcommand*\textmv@normal{m}
\newcommand*\textmv@bold{b}
\makeatother
\begin{document}
  $\qq$ {\boldmath$\qq$}
\end{document}

Unfortunately, there is no
ls1stixbbit.fd

font in the /stix folder, only
ls1stixbb.fd

is available. Therefore, I am able to create only non-italic or bold q:

Is there any way of importing italic, black-boarded q from stix?

A: Use \fontshape{it}: the same .fd file defines several font shapes.
The code can be simplified.
\documentclass{article}
\usepackage{amsmath}

\DeclareFontEncoding{LS1}{}{}
\DeclareFontSubstitution{LS1}{stix}{m}{n}

\newcommand*\qq{%
  \text{\usefont{LS1}{stixbb}{\textmathversion}{n}q}%
}
\newcommand*\qqit{%
  \text{\usefont{LS1}{stixbb}{\textmathversion}{it}q}%
}

\makeatletter
\newcommand*\textmathversion{\csname textmv@\math@version\endcsname}
\newcommand*\textmv@normal{m}
\newcommand*\textmv@bold{b}
\makeatother

\begin{document}

$\qq$ {\boldmath$\qq$}

$\qqit$ {\boldmath$\qqit$}

\end{document}


text:
Q: Getting radeon driver working and set higher resolution on GNU/Linux X11 X.org AMD Radeon When trying to set a higher resolution using xrandr, I get
Failed to get size of gamma for output default

Also lsmod | grep radeon returns no output meaning that the Radeon driver is not in use. According to this page, my graphics card is fully supported.
What I have tried so far:

*

*After reading this, I tried to disable/removing my /etc/x11/xorg.conf but it didn't help.

*Load video driver at boot time with /etc/rc.conf: kld_list="radeonkms" (from freebsd.org)
I have the following Kernel: Linux 3.13.0-xx-lowlatency on Ubuntu 14.04 LTS Trusty Thar
My graphics card is in the Evergreen family.
What can I do to get the radeon driver working?

A: I managed to get the radeon driver working. It was blacklisted, so I had to disable (rename or remove) the file /etc/modprobe.d/disable-radeon.conf. Additionally, I added radeon to /etc/modules and put options radeon modeset=1 in /etc/modprobe.d/.
Now reboot and check lsmod | grep radeon.
Radeon KMS and DRI2


text:
Q: Build *.java files generated as part of build in ant My ant has:
<target name="createJava">
   <javac ... />
</target>
<target name="build" depends="createJava, compile" />

The createJava task adds a few java files under src root.
However, main build target always compile except them. How can I add java files created in the middle of build?

A: Looks like the files for "compile" has been set before "createJava" and no updated before "compile".


text:
Q: High-order function mapping notation I know that $f: X \to Y$ means that $f(x) = y \in Y$ where $x \in X$.
But what is the difference between $f: X \to Y^2$ and $f: X \to 2^Y$. I know that one of the notations denotes $f(x) = (y_1,y_2)$, but I'm not sure which one of these two.
And finally, what does $R: A \to 2^{W \times W}$ mean when $A$ is a set $A = \{a_1,a_2\}$ and $W$ is a set $W = \{w_1,w_2,w_3\}$?

A: In analogy with $\mathbb{R}^2$, the Cartesian plane, $Y^2$ is the set of all pairs $(y_1,y_2)$ with $y_1,y_2\in Y$.
On the other hand, $2^Y$ is the set of all functions from $Y$ into $2=\{0,1\}$. (This is sometimes also identified with the power set of $Y$, with a function $\chi: Y \to \{0,1\}$ being identified with $\chi^{-1}(1)$.)
Thus, $R: A \to 2^{W\times W}$ sends a point $a\in A$ to a function $R(a): W\times W \to \{0,1\}$ (alternatively, a subset of $W\times W$). Since $A=\{a_1,a_2\}$, $R$ picks out two subsets of $W\times W$ (of which there are $2^{3\cdot 3}=2^9$ of them).


text:
Q: Sending Json Form from Flash AS3 i am having one form accepting json post in Asp.net which i need to call from Flash As3...
i am using  below code to do that. I have seen some post in which they say its working fine.
But i am encountering below Error
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here is my code.
        var messages:Array = new Array ();

        messages.push({"From":fromemailTxt.text,"To": ToemailTxt.text,"Body": BodyText.text,"Subject":SubjectText.text});

        var JsonObj:String = JSON.encode(messages);
        trace(JsonObj);

        var variables:URLVariables=new URLVariables(JsonObj);

        RequestURL= srvStringURL;

        var JSONLoader:URLLoader = new URLLoader();
        JSONLoader.dataFormat=URLLoaderDataFormat.TEXT;

        JSONLoader.addEventListener(IOErrorEvent.IO_ERROR, GetBookmarkURLError, false, 0, true);
        JSONLoader.addEventListener(Event.COMPLETE, parseBookmarkURLResult, false, 0, true);

        var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");

        var request:URLRequest = new URLRequest(RequestURL);
        request.requestHeaders.push(hdr);
        request.data=variables;
        request.method = URLRequestMethod.POST;

        try
        {
            JSONLoader.load(request);
        }
        catch (error:ArgumentError)
        {
            trace("An ArgumentError has occurred."+error.errorID.toString());
        }
        catch (error:SecurityError)
        {
            trace("A SecurityError has occurred.");
        }
        catch (error:Error)
        {
            trace("Unable to load requested document.");
        }

Anybody have any idea on this??
Thanks

A: The error is, because you are passing incorrect string to URLVariables constructor. Do not use URLVariables. Instead pass data as string: request.data=JsonObj;

A: Below is the code I am using to consume REST Web service and pass json parameter to service it shows. Error #2032: Stream Error.
Andy idea what is going wrong
var ldr:URLLoader = new URLLoader();
ldr.dataFormat = URLLoaderDataFormat.TEXT;

var strData:String = "{\"gparam\": [ {\"productid\": \"" + productId + "\"},{\"message\": \"" + mesage + "\"},{\"googleappid\": \"" + googleappid + "\"},{\"senderid\": \"" + senderid + "\"},{\"appname\": \"" + appName + "\"},{\"userid\": \"" + userId + "\"},{\"receiverid\": \"" + receiverId + "\"} ]}";

var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest("http://localhost/AndroidGCM/GCMNotification.svc/SendGCM");
req.requestHeaders.push(hdr);
req.method = URLRequestMethod.POST;
req.data = strData;

trace("data: " + req.data);

ldr.addEventListener(Event.COMPLETE,onComplete);
ldr.addEventListener(IOErrorEvent.IO_ERROR , onError);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR ,onSecurityErr);

ldr.load(req);

function onComplete(e:Event):void
{
    trace("LOAD COMPLETE: " + ldr.data);
TextField(parMC.getChildByName("txtCheck")).appendText("\n LOAD COMPLETE: " + ldr.data);
}
function onSecurityErr(e:SecurityErrorEvent):void
{
    trace("error: " + e.text );
}
function onError(e:IOErrorEvent):void
{
    trace("error: " + e.toString());
}


text:
Q: Alternative Definitions of Complete Theories I'm reading Manin et al's "A Course in Mathematical Logic for Mathematicians". There is a definition of a complete theory that I can't square with others I've previouly read. I'll give the relevant definitions below:
Let L1 be the class of first-order languages. Let L be a language in L1. Let $\phi$ be an interpretation of L. Let $T_{\phi}L$ be the set of $\phi$-true formulas [i.e., what I refer to as a theory above], where a $\phi$-true formula is a formula that, given an interpretation, is true for all elements of the universe of discourse that we could assign to the free variables in the formula. The set $T_{\phi}L$ is in fact complete, meaning that for any closed formula P, either P or $\neg$P lies in $T_{\phi}L$.
Now, this sounds like the definition of syntactic completion, except that syntactic completion says that any formula or its negation is provable, and first-order logic is not syntactically complete--if I understand the incompleteness theorem at a layman's level. I haven't found anything to backup the assertion that any formula of a first-order language or its negation is true, nor a definition of this as completeness, so I'm reaching out here.

A: I am assuming that by

where a $\phi$-true formula is a formula that, given an interpretation, is true for all elements of the universe of discourse that we could assign to the free variables in the formula.

you actually meant

where a $\phi$-true formula is a formula that, given the interpretation, is true for all elements of the universe of discourse that we could assign to the free variables in the formula.

With that said there is nothing wrong with $T_\phi(L)$ being complete.
Indeed the only closed formulas in $T_\phi(L)$ are those which are true in the interpretation $\phi$ and it can be proved by the definition of the semantics for first-order logic languages that every closed formula is either true or false once you fix an interpretation, hence either it will belong to $T_\phi(L)$ or its negation will do.
The fact that $T_\phi(L)$ is complete does not imply in any way that the first-order logic (of language $L$) is complete.
In particular $T_\phi(L)$ is not the set of logic formulas which hold in every possible $L$-structure, that is, by the completeness theorem, the set of all formulas provable by first-order logic's inference rules.
So there is no problem with the incompleteness theorems here.


text:
Q: TINYMCE set focus... just will not work I've tried
tinyMCE.execInstanceCommand("content", "mceFocus");

I've tried
tinyMCE.execCommand('mceFocus', false, "content");

None of them seem to work :-(

A: Well, I was stuck in the same problem. But I believe it depends where you execute the code. Here are various links that I've found so far:
http://tinymce.moxiecode.com/forum/viewtopic.php?id=8238
http://tinymce.moxiecode.com/forum/viewtopic.php?pid=91307#p91307
But I solved my issue the following, and it might not apply to yours:
this.focus();
this.tinymce.execCommand('mceFocus', false, 'yourTinyMCEtextAreaID_goes_here');
This code was applied inside the tiny_mce_src.js -> InsertHorizontalRule, just so you can have an idea of the scope.
Hope that helps.

A: There is an even simpler way than the previous suggested code. When you initialize tinymce, there is an option to set the configuration parameters. Just make sure that you set the AUTOFOCUS option.
var editorOptions = {
    script_url: "/scripts/tinymce/tiny_mce.js",
    theme: "advanced",
    entities: "",
    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "left",
    theme_advanced_statusbar_location: "bottom",
    theme_advanced_resizing: true,
    content_css: "/styles/site.css",
    template_external_list_url: "lists/template_list.js",
    external_link_list_url: "lists/link_list.js",
    external_image_list_url: "lists/image_list.js",
    media_external_list_url: "lists/media_list.js",
    theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,bullist,numlist,|,undo,redo,|,link,unlink,anchor,image,help",
    theme_advanced_buttons2: "",
    theme_advanced_buttons3: "",
    theme_advanced_buttons4: "",
    width: "640",
    height: "220",
    auto_focus: "body2"
};


text:
Q: What is this syntax, parentheses around variable/property names at declaration site? val (_,time) = time { Thread.sleep(1000) }

I see the Left Hand Side (LHS) has a val, so its declaring a variable. LHS also has some kind of a function syntax which does not look like a lambda declaration. What is (_,time)? Don't you have to give a type to the time on the LHS? I understand the RHS perfectly well: it is a function which accepts a lambda as parameter and is named 'time'. Original code

A: The left hand side is called destructuring.
If you try to assign an instance of a data class (or any class which has componentN functions) to a variable you can desturcture it. This means that you can assign its internals to variables. The _ syntax indicates that you don't care about the first item.
Example:
class Foo(val first: String, val second: String) {

    operator fun component1() = first

    operator fun component2() = second
}

Usage:
val (first, second) = Foo("first", "second")

If you use data classes you don't need to create the componentN functions, they are generated for you.
Equivalent data class:
data class Foo(val first: String, val second: String)


text:
Q: SMTP server not sending Email after registration Why doesn't the SMTP in this code send notification to the email that has been inputted by the user?
Controller :
    .
    using System.Net.Mail;
    using System.Net;
    .

    db_userEntities db = new db_userEntities();

[HttpPost]
public ActionResult Regisration([Bind(Exclude = "IsEmailVerified,ActivationCode")] tbl_user user)
{
    bool Status = false;
    string message = "";
    //
    // Model Validation
    if (ModelState.IsValid)
    {

        // Email already exists
        var isExist = IsEmailExist(user.email_user);

        if (isExist)
        {
            ModelState.AddModelError("EmailExist", "Email already exist");
            return View();
        }

        // Generate Activation Code
        user.ActivationCode = Guid.NewGuid();

        // Password Hashing
        user.password_user = Crypto.Hash(user.password_user);

        user.IsEmailVerified = false;

        try
        {
            // TODO: Add insert logic here
            db.tbl_user.Add(user);
            db.SaveChanges();

            SendVerificationLinkEmail(user.email_user, user.ActivationCode.ToString());
            message = "Registration successfully done. Account activation link " +
                " has been sent to your email id:" + user.email_user;
            Status = true;

        }
        catch
        {
            return View();
        }
    }
    else
    {
        message = "Invalid Request";
    }

    ViewBag.Message = message;
    ViewBag.Status = Status;
    return View();
}

and for the controller to send the email:
[NonAction]
public void SendVerificationLinkEmail(string email, string activationCode)
{
    var verifyUrl = "/User/VerifyAccount/" + activationCode;
    var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);

    var fromEmail = new MailAddress("admin@gmail.com", "Test");
    var toEmail = new MailAddress(email);
    var fromEmailPassword = "********"; // Replace with actual password
    string subject = "Your account is successfully created!";

    string body = "

We are excited to tell you that your Test account is" +
        " successfully created. Please click on the below link to verify your account" +
        "

" + link + " ";

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
    };

    using (var message = new MailMessage(fromEmail, toEmail)
    {
        Subject = subject,
        Body = body,
        IsBodyHtml = true
    })
        smtp.Send(message);
}

What is wrong? I've seen the other ways but I try to keep it the same SMTP doesn't send email to the user's email, the code above is the code I'm currently using

A: Your code is fine! It's seems that internet is slow. To prevent this, try to set a higher timeout limit. It is in milliseconds.
Try this:
[NonAction]
        public void SendVerificationLinkEmail(string email, string activationCode)
        {
            var verifyUrl = "/User/VerifyAccount/" + activationCode;
            var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);

            var fromEmail = new MailAddress("admin@gmail.com", "Test");
            var toEmail = new MailAddress(email);
            var fromEmailPassword = "********"; // Replace with actual password
            string subject = "Your account is successfully created!";

            string body = "

We are excited to tell you that your Test account is" +
                " successfully created. Please click on the below link to verify your account" +
                "

" + link + " ";

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Timeout = 10000,
                Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
            };

            using (var message = new MailMessage(fromEmail, toEmail)
            {
                Subject = subject,
                Body = body,
                IsBodyHtml = true
            })
                smtp.Send(message);
        }


text:
Q: Execute mysql query over multiple tables I have three tables:

*

*users: contains the registered users.

*courses: contains available courses.

*userscourses: has two columns: user_id and course_id. Whenever a user joins  a course, a new record is created that relate that course with the user.

I want to create a mysql query that; given a user_id, is going to fetch all courses joined by the user. Also, with each course row, I want to add a column that represents how many users are in that course.
I made a query but it does not give me the desired result:
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses.userId) AS JoinedUsersNumber
FROM courses, users, usersCourses
WHERE users.id = courses.userId
AND usersCourses.courseId = courses.id
AND usersCourses.courseId=courses.id
AND usersCourses.userId='31'

Can anybody tell me how to achieve this or tell me what's wrong with my query?
EDIT
This is an example:
users table
   id       |     username
--------------------------
   u1       |      user01
   u2       |      user02
   u3       |      user03
   u4       |      user04

courses table:
   id       |     name
--------------------------
   c1       |    course01
   c2       |    course02
   c3       |    course03
   c4       |    course04

userscourses table:
 userId     |    courseId
--------------------------
   u1       |      c1
   u1       |      c2
   u1       |      c3
   u2       |      c1
   u3       |      c1
   u4       |      c1
   u2       |      c2
   u3       |      c2

Expected Result (user_id=u1):
  name      |  Joined Users
--------------------------
 course01   |       4
 course02   |       3
 course03   |       1

A: Joining back on the userscourses table to get all the users on that course:-
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses2.userId) AS JoinedUsersNumber
FROM users
INNER JOIN usersCourses
ON users.id = usersCourses.userId
INNER JOIN courses
ON usersCourses.courseId = courses.id
INNER JOIN usersCourses usersCourses2
ON usersCourses.courseId = usersCourses2.courseId
WHERE usersCourses.userId='31'
GROUP BY courses.id AS CourseID, courses.name AS Name

or if you want the count of users on that course to exclude the selected users (ie, you want a count of other users):-
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses2.userId) AS JoinedUsersNumber
FROM users
INNER JOIN usersCourses
ON users.id = usersCourses.userId
INNER JOIN courses
ON usersCourses.courseId = courses.id
LEFT OUTER JOIN usersCourses usersCourses2
ON usersCourses.courseId = usersCourses2.courseId
AND users.id != usersCourses2.userId
WHERE usersCourses.userId='31'
GROUP BY courses.id AS CourseID, courses.name AS Name

A: First make a query that returns the course user counts:
 SELECT course.id, course.name, count(*) as JoinedUsersNumber
 FROM course
 JOIN usersCourses
 ON course.id=usersCourses.courseId
 GROUP BY course.id, course.name

then use this as a sub-query, so something like
SELECT
  c.id AS CourseID,
  c.name AS Name,
  c.JoinedUsersNumber
FROM
     SELECT course.id, course.name, count(*) as JoinedUsersNumber
     FROM course
     JOIN usersCourses
     ON course.id=usersCourses.courseId
     GROUP BY course.id, course.name
) c
JOIN
  usersCourses ON c.id = usersCourses.courseId =
JOIN
  users ON users.id = usersCourses.userId
WHERE usersCourses.userId=31

A: your query is
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses.userId) AS JoinedUsersNumber
FROM courses, users, usersCourses
WHERE users.id = courses.userId
AND usersCourses.courseId = courses.id
AND usersCourses.courseId=courses.id
AND usersCourses.userId='31'

according to your schema

*

*you have joined users.id = courses.userId  but you donot have userId in your courses table

*you have not created joined condition of user with its bridge table. you have joined same column twice

AND usersCourses.courseId = courses.id
    AND usersCourses.courseId=courses.id

hope this will help you.
 SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses.userId) AS JoinedUsersNumber
        FROM courses, users, usersCourses
        WHERE
        usersCourses.courseId = courses.id
        AND usersCourses.userId=users.userId
        AND usersCourses.userId='31'
        Group By courses.name

A: Your join is in a deprecated style and probably wrong in content as well. Also, you need to add a Group by on courses id and name. Try this:
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses.userId) AS JoinedUsersNumber
FROM courses
INNER JOIN usersCourses ON usersCourses.courseId=courses.id
WHERE usersCourses.userId='31'
GROUP BY courses.id, courses.name

A: Here's my SQL Fiddle: http://sqlfiddle.com/#!9/6a134/4/0
SELECT *
FROM
  (
    SELECT
      userscourses.user_id   AS user_id,
      users.user_name        AS user_name,
      userscourses.course_id AS course_id,
      courses.course_name    AS course_name
    FROM
      users, courses, userscourses
    WHERE
      users.user_id = userscourses.user_id
      AND courses.course_id = userscourses.user_id
      AND userscourses.user_id = 1
  ) userTable
  LEFT JOIN
  (
    SELECT
      course_id,
      COUNT(user_id) AS sum_participant
    FROM
      userscourses
    GROUP BY
      course_id
  ) courseTable
    ON userTable.course_id = courseTable.course_id

A: This would work :
SELECT C.name,
   COUNT(U.username) As JoinedUser
FROM usercourse UC INNER JOIN users U ON UC.userId = U.id
INNER JOIN courses C ON C.id = UC.courseId
WHERE U.userId = '31'
GROUP BY C.name


text:
Q: type case Icollection object into collection object in c# How can i cast an ICollection object of string type into a Collection object of string type again in c#
So one of my methods return
public static ICollection<type1> Filter()

and i need to get this into
 Collection<type1> list=Filter();

thanks

A: var list = new Collection<type1>(Filter());

A: I think Erno is on the right track becuase you really can't count on your ICollection< T > actually being a Collection< T >. Many many classes including custom classes could implement that interface and that's a very good thing.
Erno's solution 'does the cast' by creating a new Collection by consuming the contents of your ICollection. If that works for you then great.
But I'm not really sure why do you need to 'cast back' in the first place.


text:
Q: Create SharePoint Document Set URL dynamically I have created custom content type, inherited it from Document Set parent content type and attached it to document library on SharePoint 2013 in Office 365.
Now i want to dynamically create URL to add new document set to that document library.
New (decoded) document set URL is :
https://someSiteName/sites/siteName/_layouts/15/NewDocSet.aspx?List=ecc261fd-bedc-4ca7-acaa-e9af6f9aa27b&ContentTypeId=0x0120D52000DC8614ED8780EC4099731DA643B72155
00690255D5A1270C44B9C372797D0606EF&RootFolder=/sites/siteName/Certifications
If we observe query string parameters,
List = ListID,
ContentTypeId = ID of my custom content type,
RootFolder = Where document set is to be created
I have an issue getting ContentTypeId,
ContentTypeId=0x0120D52000DC8614ED8780EC4099731DA643B72155
00690255D5A1270C44B9C372797D0606EF
I am unable to find the highlighted part of GUID.
I can only find ContentTypeId=0x0120D52000DC8614ED8780EC4099731DA643B72155 from the URL when i navigate to SiteSettings > SiteContentType > Click on custom document set content type.

A: It is the id of content type in document library. You can get it like below.
/_api/web/lists(listid)/contenttypes


text:
Q: Package python codes which uses __import__ function My directory structure is:
./
├── foo
│   ├── bar.py
│   ├── foo.py
│   └── __init__.py
└── main.py

with:
bar.py:
def get_data():
    return 'ha'

foo.py:
class foo:
    def __init__(self):
        self.lib = __import__('bar', fromlist=['bar'])
        self.data = self.lib.get_data()

    def print_data(self):
        print(self.data)

if __name__=='__main__':
    f = foo()
    f.print_data()

__init__.py:
from foo import foo

and main.py:
from foo import foo

a = foo()
a.print_data()

Running python foo.py I get ha correctly, but running python main.py I get the following message:
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    a = foo()
  File ".../foo/foo.py", line 3, in __init__
    self.lib = __import__('bar')
ImportError: No module named bar

My requirements are 1) making foo to work like a package, 2) using __import__ in foo.py's __init__ function instead of import in the first line of foo.py.
I changed line 3 of foo.py to self.lib = __import__('foo.bar', fromlist=['bar']), and then got the correct answer. But that is not I want, since running python foo.py will lead to a failure and that is not a package solution when the whole directory ./ become another package. It seems an import path problem that I cannot figure out.

A: Changing foo.py to that makes it work correctly:
import importlib

class foo:
    def __init__(self):
        self.lib = importlib.import_module('foo.bar')
        self.data = self.lib.get_data()

    def print_data(self):
        print(self.data)

if __name__=='__main__':
    f = foo()
    f.print_data()


text:
Q: Pass command line arguments as string in Lua I'm trying to execute Sox from a Lua script.
It works fine when I pass literals as arguments.
os.execute('"C:\\Sox\\sox.exe" -S C:\\SoX\\test.wav -r 22050 C:\\Sox\\SoX_out.wav')

or
os.execute [["C:\\Sox\\sox.exe" -S C:\\SoX\\test.wav -r 22050 C:\\Sox\\SoX_out.wav]]

however, what I'd like to do (as example), when I try this:
filename = "C:\\SoX\\test.wav"
os.execute('"C:\\Sox\\sox.exe" -S filename -r 22050 C:\\Sox\\SoX_out.wav')

I get:

C:\Sox\sox.exe FAIL formats: can't open input file `filename': No such file or directory

So my question is how to pass a string properly as command argument ?

A: In Lua, a string literal is exactly and only that string. Strings don't know anything about variables, the global environment, local variables, etc. They're just strings. The string "filename" in Lua will always be a string of 8 characters. It will not go out and try to find a variable named filename and extract something from it.
What you want is to build a string, from multiple strings. Part of the string will come from literals, and part will come from a variable. Lua has several tools for that. The simplest is the .. concatenation operator:
[["C:\Sox\sox.exe" -S ]] .. filename .. [[ -r 22050 C:\Sox\SoX_out.wav]]

This builds a new string from a string literal, the contents of the filename variable, and another string literal. The spaces you see at the end of the first literal and the beginning of the second are necessary, since Lua will not insert spaces between the two concatenated pieces.
For more complex cases, it's useful to just build a table of parameters and use table.concat to build a string out of them:
local params =
{
  [[C:\Sox\sox.exe]],
  "-S",
  filename,
  "-r 22050",
  [[C:\Sox\SoX_out.wav]]
}

os.execute(table.concat(params, " "))

Note the lack of spaces in the string literals. This is because table.concat's second parameter is a string to be inserted between the entries in the array. So between each array element will be a space; we don't need to manually add them.


text:
Q: Trocar background image de página Asp .Net MVC dinamicamente Estou pesquisando mas não consegui nada que fale a respeito. Já havia feito isso antes, em páginas Web Forms, mas em MVC eu ainda não tinha necessitado.
Preciso trocar a imagem de fundo da página a cada vez que ela é carregada. Por exemplo: tenho 10 imagens, e a cada load da _layout.cshtml, está teria que ser carregada com uma das 10 imagens. Fazer o random e pegar a imagem é fácil, o problema e como aplicar o estilo.
No Web Forms era fácil, pois eu tinha o código onde eu criava o método e chamava no load da Page. Só que no MVC, eu não tenho load.
Método usado no Web Forms:
  public static void ChangeBGs(HtmlControl oMainBody)
    {
        Random voRandom = new Random();
        int vi = voRandom.Next(1, 10);
        oMainBody.Attributes.Add("style", $"background-image: url('/Background/Fundo ({vi}).jpg')");
    }

Nesse método, eu consigo trocar o estilo do Body da página, pois no WF, eu tenho acesso.
Como fazer algo semelhante no MVC, mais especificamente na _Layout.cshtml. Se eu tiver como aplicar o estilo já criados, e só ir trocando também seria interessante.
Grato.

A: Usando JQuery coloque esse script no _Layout.cshtml.
<script>
    $(document).ready(function() {
        var i = Math.floor(Math.random() * 9) + 1;
        $("body").css("background-image", "url(/Background/Fundo (" + i + ").jpg);");
    });
</script>

A: Caríssimos, bom dia.
Já consegui resolver meu problema.
   <script type="text/javascript">
    function Trocar() {
        $(document).ready(function () {
            var oBody = document.getElementById('myBody');
            var i = Math.floor(Math.random() * 9) + 1;
            oBody.style.backgroundImage = "url('../images/Foto" + i + ".jpg')";
        });
    }
</script>

Grato.


text:
Q: Add Event Listener to Inner class I'm trying to add an event listener to a 'Subclass' (is that what its called?). But it fails to take effect.
The JS:
var Station_Button = function(status_id)
{
      var alert_txt, class_txt;

      switch( status_id )
      {
        case 1:
        {
            alert_txt = "Complete! This Station is complete.";
            class_txt = "alert alert-success";
        }
        case 2:
        {
        alert_txt = "Error! This Station has failed!";
            class_txt = "alert alert-info";
        }
      }

      document.getElementById("notify").innerHTML = alert_txt;
      document.getElementById("notify").className = class_txt;
      return false;
}

var ta_butt = document.getElementsByClassName("ta_butt.error");

for(var i=0;i<ta_butt.length;i++)
{
    ta_butt[i].addEventListener('click', function() {Station_Button(2)}, false);
}

It works fine, if I take away the .error, but this of course applies the event to all of my 'ta_butt' buttons - I only want it on the ones marked error.
If it interests anyone the CSS:
.ta_butt {
    color: white;
    border-radius: 7px;
    font-size:150%;
    text-align:center;
    float: left;
    margin: 1px;
    width: 100%;
    padding: 1px;
    cursor: pointer;
    cursor: hand;
    background: -webkit-linear-gradient(top, #0066FF, #4D94FF); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(bottom, #0066FF, #4D94FF); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(bottom, #0066FF, #4D94FF); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to bottom, #0066FF, #4D94FF); /* Standard syntax (must be last) */
}

.ta_butt.error {
    background: -webkit-linear-gradient(top, #CC0000, #DB4D4D); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(bottom, #CC0000, #DB4D4D); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(bottom, #CC0000, #DB4D4D); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to bottom, #CC0000, #DB4D4D); /* Standard     syntax (must be last) */
}

.ta_butt.error:hover {
    background: -webkit-linear-gradient(top, #DB4D4D, #CC0000); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(bottom, #DB4D4D, #CC0000); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(bottom, #DB4D4D, #CC0000); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to bottom, #DB4D4D, #CC0000); /* Standard syntax (must be last) */
}

A: For multiple classes use a space between the class names:
var ta_butt = document.getElementsByClassName("ta_butt error");


text:
Q: Alamofire can't get response closure to execute Mac OS X 10.11.3 El-Capitan, XCode 7.2.1, Alamofire 3.5.1 via Carthage
Trying to get the most basic Alamofire example I can think of to work. Although a seasoned developer I am new to XCode so I am sure I am just missing something basic. I setup a new project, added Alamofire via Carthage, added a simple get request in main.swift. Code builds and runs, but nothing from my response closure ever gets called. I added the sleep to try and be sure to wait long enough for the closure to get called. I have Little Snitch on and see that my project is calling httpbin.org. I have tried a variety of the response* methods. But closure never runs, what am I missing?
main.swift
import Alamofire

print("Start")
var x : String = "main"

Alamofire.request(.GET, "https://httpbin.org/get")
  .responseString {resp in
    print("in response handler")
    print("response \(resp)")
    x = "response"
}

sleep(90)
print("End \(x)")

Console Output
Start
End main

XCode
xcode screenshot

A: I think Alamofire by default calls the response handler in the main queue so if you make the request, sleep and print in the main queue/thread, the responseString is not executed from the main queue before the app terminates. Don't know about .responseString, but with .response you can specify the queue:
public func response<T: ResponseSerializerType>(
        queue queue: dispatch_queue_t? = nil,
        responseSerializer: T,
        completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
        -> Self

A: Not sure why, but running the completion block on another thread didnt work for my command line tool; it still completed before waiting on the callback. I found a really nice alternative at
http://mgrebenets.github.io/swift/2015/10/08/async-swift-scripting
This method uses RunLoop to keep the program running until the callback fires.
summary code
var keepAlive = true

Alamofire.request("http://httpbin.org/get", parameters: ["foo": "bar"])
            .response(
    responseSerializer: DataRequest.jsonResponseSerializer()) { response in

        print(response.result.value ?? "")
        keepAlive = false
    }

let runLoop = RunLoop.current
while keepAlive && runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.1)) {
    // Run, run, run
}

A: Github repo of working example


text:
Q: "Bookmark" button? Is there anything like a bookmark button using Javascript or HTML or PHP that we can bookmark the website ? without doing manually.
Like,
When the user clicks the button.The webpage should automatically bookarmed by the browser.
Thanks

A: Not really. There used to be some hacks for some browsers, but I doubt they still work.
If a user knows how to find and follow an existing bookmark (which is what you really want), he will also know how to add it with his browser feature.


text:
Q: How to programmatically select nodes in Package Explorer in Eclipse plugin Does anybody know or have an example on how to select node(s) programmatically in the Package Explorer view in Eclipse plugin? I see some help on how to get current selection but not on how to set them.
Thanks.

A: Although a commenter has already pointed to a solution, it uses internal API.  If you wanted a a portable API implementation try this.  It will select all "open" projects in your workspace.
List<Object> openProjects = new ArrayList<Object>();

for( IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects() )
{
    if( project.isOpen() )
    {
        final IJavaProject javaProject = JavaCore.create( project );

        if( javaProject != null )
        {
            openProjects.add( javaProject );
        }

        openProjects.add( project );
    }
}

Object[] projectsToSelect = openProjects.toArray();
IViewPart view = window.getActivePage().showView( "org.eclipse.jdt.ui.PackageExplorer" );
view.getSite().getSelectionProvider().setSelection( new StructuredSelection( projectsToSelect ) );


text:
Q: using $.getJSON to retrieve CSV data I'm trying to retrieve stock data using Yahoo's Finance API:
        $.ajax({
            dataType: "json",
            url: 'http://download.finance.yahoo.com/d/quotes.csv',
            data: 's=RHT+MSFT&f=sb2b3jk&callback=?',
            success: function (d) {
                console.log(JSON.stringify(d));
            },
            error: function (d, a, b) {
                console.log(JSON.stringify(d));
                console.log(JSON.stringify(a));
                console.log(JSON.stringify(b));
            },
            complete: function (d, a, b) {
                console.log(JSON.stringify(d));
                console.log(JSON.stringify(a));
                console.log(JSON.stringify(b));
            }
        });

The call works and I can see the csv text in the response (using Chrome's developer tools):

Now, my problem is I can't access the text contained in the response.
As you can see in the original script, I've tried capturing the responses in the "success", "error", and "complete" callbacks, but the response text is not contained in any of them.  Also, only the "error" and "complete" callback is raised.
I'd appreciate any insight on this, thanks in advance!
ps. Reason I'm using the CSV query, as opposed to the YQL query is the CSV query is easier to specify fields I need.  I've found the YQL query much more cumbersome to use.

A: The $.getJSON() method accepts text/json content types and the CSV is not of this type.

This is a shorthand Ajax function, which is equivalent to:
$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

The complete executes because it executes regardless of whether the request resulted in a success or error.


text:
Q: error making upstream request 403 sts vault from aws instance I have attached one IAM role to the aws instance. The role my-role has administrative permissions and sts permissions as well.
I ran the following commands but I get error.
export VAULT_ADDR=https://somevaultsite.com
vault login -tls-skip-verify -address=https://somevaultsite.com -method=aws role=my-role

Error authenticating: Error making API request.

URL: PUT https://somevaultsite.com/v1/auth/aws/login
Code: 400. Errors:

* error making upstream request: received error code 403 from STS: <ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
  <Error>
    <Type>Sender</Type>
    InvalidClientTokenId
    <Message>The security token included in the request is invalid</Message>
  </Error>
  <RequestId>SOME-REQUEST-ID</RequestId>
</ErrorResponse>

And when I run the vault command by passing the region I get the error as
vault login -tls-skip-verify -address=https://somevaultsite.com -method=aws role=my-role region=us-gov-west-1

Error authenticating: Error making API request.

URL: PUT https://somevaultsite.com/v1/auth/aws/login
Code: 400. Errors:

* error making upstream request: received error code 403 from STS: <ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
  <Error>
    <Type>Sender</Type>
    SignatureDoesNotMatch
    <Message>Credential should be scoped to a valid region, not 'us-gov-west-1'. </Message>
  </Error>
  <RequestId>SOME-REQUEST-ID</RequestId>
</ErrorResponse>

I have bounded the role in vault also.
vault write auth/aws/role/my-role auth_type=iam policies=my-policy max_ttl=1h bound_iam_principal_arn=arn:aws-us-gov:iam::xxxxx:role/my-role

Note:- I added -tls-skip-verify option because the certificate is not a valid one.

A: We should set the sts endpoint
vault write auth/aws/config/client sts_endpoint=https://sts.us-gov-west-1.amazonaws.com

Then run your login command
vault login -tls-skip-verify -address=https://somevaultsite.com -method=aws role=my-role region=us-gov-west-1

Success! You are now authenticated. The token information displayed below is already stored in the token helper. You do NOT need to run "vault login" again. Future Vault requests will automatically use this token.

Here's a Google group link with discussion
Another link for sts.