text:
Q: VS 2012 naming mangling still applied to dll exports Why is name mangling still applied to func3()'s signature.
What am I missing? I've reviewed these previously asked questions 1, 2
NO DEF files are being referenced.
// dllmain.cpp
#include "stdafx.h"

extern "C"  __declspec( dllexport ) double __cdecl func1(int id, double t)
{
    return(1.01);
};

extern "C" __declspec( dllexport ) int __cdecl func2(int id)
{
    return(2);
};

extern "C" __declspec( dllexport ) int __cdecl func3(char* file)
{
    return(1);
};

......

Here's output from dumpbin /EXPORTS:
    00000000 characteristics
    51B78F5E time date stamp Tue Jun 11 13:58:06 2013
        0.00 version
           1 ordinal base
           3 number of functions
           3 number of names

    ordinal hint RVA      name

          1    0 00003870 func1 = func1
          2    1 00003880 func2 = func2
          3    2 00001A00 func3 = ?do_encoding@codecvt_base@std@@MEBAHXZ (protected: virtual int __cdecl std::codecvt_base::do_encoding(void)const )

A: The exports are not mangled, you can clearly see the unmangled name in the dumpbin.exe output.  You also see the mangled name.  That's dumpbin.exe being a bit too helpful, perhaps, it also reads the .pdb file to find the actual name of the function.  It displays it on the right-hand side of the =
Simply delete the .pdb file and run dumpbin.exe again to see the difference.
You don't have a problem, it worked.


text:
Q: Flags returned by OSVERSIONINFOEX.wSuiteMask Does anybody know what the following constants (defined in WinNT.h) mean?
#define VER_SUITE_COMMUNICATIONS            0x00000008
#define VER_SUITE_EMBEDDED_RESTRICTED       0x00000800
#define VER_SUITE_SECURITY_APPLIANCE        0x00001000

The values are returned in the wSuiteMask field of the OSVERSIONINFOEX struct.

A: The suite mask is part of the operating system version. The complete list of suite mask constants, along with some explanation, is here. It indicates whether the version of Windows being run is an Enterprise edition, Data Center edition, home edition, etc.
VER_SUITE_COMMUNICATIONS = This is a version of Microsoft Office Communications Server
VER_SUITE_EMBEDDED_RESTRICTED = Embedded Windows (I'm not sure what the RESTRICTED indicates)
VER_SUITE_SECURITY_APPLICANCE = This is a version of Windows Appliance Edition.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ViewPager is cut off I have a TabLayout, below a SwipeRefreshLayout containing a ViewPager (each page has a RecyclerView). I used to have the SRL in each page fragment but now changed it so I only have one which is way more convenient.
For some reason the ViewPager gets cut off and I'm unable to scroll all the way up to the top of the RecyclerView.
Does anyone have a solution for that?

Here are my layout xmls:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.design.widget.TabLayout
    android:id="@+id/mainTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:tabGravity="fill" />

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/mainSwipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/mainViewPager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/mainTabLayout" />

</android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>

the fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/mainRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

A: Replace your RelativeLayout by a LinearLayout in your activity_main.


text:
Q: Entity Framework Foreign Key multiple table mapping I have this Scenario:
public class Application
{
    [Key]
    public string Code { get; set; }
}

public class Table1
{
    [Key]
    public string Table1Code { get; set; }

    [Key, ForeignKey("ApplicationObject")]
    public string Application { get; set; }
    public virtual Application ApplicationObject { get; set; }
}

public class Table2
{
    [Key]
    public string Table2Code { get; set; }

    [Key, ForeignKey("ApplicationObject")]
    public string Application { get; set; }
    public virtual Application ApplicationObject { get; set; }
}

public class Table3
{
    [Key, ForeignKey("Table1Object")]
    public string Table1Code { get; set; }
    public virtual Table1 Table1Object { get; set; }

    [Key, ForeignKey("Table2Object")]
    public string Table2Code { get; set; }
    public virtual Table2 Table2Object { get; set; }

    [Key, ForeignKey("Table1Object")]
    public string ApplicationCodeTab1 { get; set; }

    [Key, ForeignKey("Table2Object")]
    public string ApplicationCodeTab2 { get; set; }
}

In the table1 and table2 the property applicationCode must be key because i can have the same code for different application.
In the Table3 i have referenced Table1 and Table2. How Can I add Foreign Key for the ApplicationCode Property without duplicate the property?
For Example:
public class Table3
{
    [Key, ForeignKey("Table1Object")]
    public string Table1Code { get; set; }
    public virtual Table1 Table1Object { get; set; }

    [Key, ForeignKey("Table2Object")]
    public string Table2Code { get; set; }
    public virtual Table2 Table2Object { get; set; }

    [Key]
    public string ApplicationCode { get; set; }
}

The ApplicationCode property in Table3 can rapresent the Foreign Key for Table1 and Table2 in same time?

A: The key is to move the ForeignKey attribute to the navigation property and specify a the foreign key columns.
Like this:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp6
{

    public class Application
    {
        [Key]
        public string Code { get; set; }
    }

    public class Table1
    {
        [Key]
        [Column(Order = 0)]
        public string Table1Code { get; set; }

        [Key, ForeignKey("ApplicationObject")]
        [Column(Order = 1)]
        public string Application { get; set; }
        public virtual Application ApplicationObject { get; set; }
    }

    public class Table2
    {
        [Key]
        [Column(Order = 0)]
        public string Table2Code { get; set; }

        [Key, ForeignKey("ApplicationObject")]
        [Column(Order = 1)]
        public string Application { get; set; }
        public virtual Application ApplicationObject { get; set; }
    }

    public class Table3
    {
        [Key]
        [Column(Order = 0)]
        public string Table1Code { get; set; }

        [Key]
        [Column(Order = 1)]
        public string Table2Code { get; set; }

        [Key]
        [Column(Order = 2)]
        public string ApplicationCode { get; set; }

        [ForeignKey("Table1Code,ApplicationCode")]
        public virtual Table1 Table1Object { get; set; }

        [ForeignKey("Table2Code,ApplicationCode")]
        public virtual Table2 Table2Object { get; set; }

    }
    class Db: DbContext
    {

        public DbSet<Table1> Table1 { get; set; }
        public DbSet<Table2> Table2 { get; set; }
        public DbSet<Table3> Table3 { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConvention>();
            base.OnModelCreating(modelBuilder);
        }

    }
    class Program
    {

        static void Main(string[] args)
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {
                db.Database.Log = m => Console.WriteLine(m);

                db.Database.Initialize(true);

            }

            Console.ReadKey();

        }
    }
}


text:
Q: Why do we need to determine the definiteness of the Hessian to decide what a critical point is? In univariate calculus, if we know that $f'(c)=0$, we can determine if the function $f$ has a minimum at $c$ by checking that $f''(c) > 0$. The multivariate analogue of the second derivative is the Hessian matrix. I now learned that to decide between extreme and saddle points in this case, it has to be checked whether the Hessian is positive definite, negative definite or indefinite. This can be achieved by checking its eigenvalues.
I have several questions regarding this:

*

*Why is it not sufficient to check the sign of the values in the Hessian, but we need to check for definiteness?

*Does the definiteness just make sure some convexity or concavity properties check out, or is there a more meaningful interpretation of that?

*How do the eigenvalues of a matrix tell us its definiteness?

*Addendum: What do the off-diagonal entries in the Hessian even mean? How the slope in a certain dimension changes by making changes in a different dimension?

A: The proof of the second derivative test at a critical point ($Df_a = 0$) runs as follows: for a given sufficiently smooth map $f: \Bbb{R}^n \to \Bbb{R}$, and a point $a \in \Bbb{R}^n$, we write a second order Taylor expansion at the point $a$:
\begin{align}
f(a+h) - f(a) &= \dfrac{1}{2}(D^2f_a)(h,h) + o(\lVert h\rVert^2).
\end{align}
In other words, there is a "remainder term", which is a function $\rho$, such that $\lim_{h \to 0} \rho(h) = 0$, and
\begin{align}
f(a+h) - f(a) &= \dfrac{1}{2}(D^2f_a)(h,h) + \rho(h) \lVert h\rVert^2.
\end{align}
If the Hessian $D^2f_a$ is positive definite say, then there is a positive constant $\lambda$ such that for all $h \in \Bbb{R}^n$, $D^2f_a(h,h) \geq \lambda \lVert h\rVert^2$ (with equality if and only if $h=0$). Hence,
\begin{align}
f(a+h) - f(a) &\geq \dfrac{\lambda}{2} \lVert h\rVert^2 + \rho(h) \lVert h\rVert^2 \\
&= \left( \dfrac{\lambda}{2} + \rho(h)\right) \lVert h\rVert^2.
\end{align}
Since $\rho(h) \to 0$ as $h \to 0$ and $\lambda > 0$, the term in brackets will be strictly positive if $h$ is sufficiently small in norm. Hence, for all $h$ sufficiently small in norm, $f(a+h) - f(a) \geq 0$ (with equality if and only if $h =0$).  This is the proof for why a positive-definite Hessian implies you have a strict local minimum at a critical point $a$.
Of course, a similar proof holds for a negative-definite Hessian implying a strict local maximum.

Roughly speaking, the idea of the proof is that the local behaviour of $f(a+h) - f(a)$ is entirely determined by the behaviour of the Hessian, in the term $D^2f_a(h,h)$ (because the error term is "small"). So, to answer your questions,

*

*The proof of the theorem above shows that we need to ensure that the entire term $D^2f_a(h,h)$ is positive (in fact bounded below by a positive multiple of $\lVert h \rVert^2$), so that  we can conclude that $f(a+h) - f(a) \geq 0$. But just because an $n \times n$ matrix has all positive entires, it doesn't mean it is positive-definite (Robert's answer gives an explicit counter example).

*Hopefully the proof I gave above justifies why definiteness comes into play (it's to ensure you have a good lower/upper bound on the $D^2f_a(h,h)$ term).

*A matrix is positive(negative) definite if and only if all its eigenvalues are strictly positive (strictly negative). If there are some positive and some negative, then the matrix is indefinite. If this is the case for your Hessian, it means you have a saddle point (because the function is increasing along some directions while decreasing along others).

A: 1) For example, the function $f(x,y) = x^2 + 4 x y + y^2$ has all entries of the Hessian matrix $> 0$, but the critical point $(0,0)$ is a saddle (e.g. $f(t,-t) < 0$ for $t \ne 0$).
2) A smooth function of $n$ variables is convex in an open set $R$ iff its Hessian is positive semidefinite there.
3) A real symmetric matrix is positive definite, positive semidefinite, negative semidefinite, or negative definite iff its eigenvalues are all $> 0$, $\ge 0$, $\le 0$, $< 0$ respectively.

A: When you Taylor expand a multivariable function, it looks like:
$$f(x+h)=x+(Df)\cdot h+h^T(D^2f)h+o(h^Th)...,$$
so locally around a critical point, it looks like $x+h^T(D^2f)h.$
It's clear now that if $(D^2f)$ is positive definite, then locally, $f(x)$ increases in any direction away from $x$. The opposite occurs when it's negative definite. Otherwise, when it's indefinite or semidefinite, you get either a saddle or need to look at higher order derivatives to conclude.

A: You can think of a multivariate function around a critical point as a quadratic form (as long as the higher order Taylor terms are negligible). So the whole discussion amounts to analyzing the behavior of a (hyper-)quadric, defined by the Hessian matrix.
The study is made easy by diagonalizing this matrix, so that by a change of coordinates,
$$\frac1{2!}p^THp$$ reduces to (dropping the constant factor) $$q^T\Lambda q$$
or
$$\lambda_1u^2+\lambda_2v^2+\cdots\lambda_dw^2.$$

*

*For a critical point to be a maximum or a minimum, all terms must have the same sign, hence some definiteness. The signs of the individual Hessian elements does not allow you to conclude about definiteness.

*Indeed, just concavity or convexity.

*Should be obvious from the diagonalized form.

*Nothing by themselves, but they indirectly contribute to the Eigenvalues/the definiteness.


text:
Q: Vue 3 TypeScript Class Component props don't work properly Whenever I define that my custom component has props, I get the following error in build:
Uncaught (in promise) TypeError: _components_Menu_vue__WEBPACK_IMPORTED_MODULE_12__.default is not a constructor
I'm basically building a Menu with SubMenu capability, and running into an issue when trying to define a SubMenu as the root, in which case, it should show a label as a "header" instead of a button.
Here's the code for the SubMenu:
<template>

      <template v-for="(item, i) of items">

          <template v-if="!!root">

              {{ item.label }}

            <SubMenu v-if="visible(item)"
                     :items="item.items" />
          </template>
          <template v-else>
            <router-link v-if="item.to"
                         :to="item.to"
                         :target="item.target">

              {{ item.label }}

            </router-link>

              {{ item.label }}

            <SubMenu v-show="activeIndex === i"
                     v-if="visible(item)"
                     :items="item.items"
                     @menuitem-click="$emit('menuitem-click', $event)" />
          </template>

      </template>

</template>

And the code for Menu:
<template>

    <SubMenu :items="model" :root="true" />

</template>

The particular error points to the type: Boolean, default: false line, and I've tried to use type: PropType<Boolean>, and set default to Boolean(false) too, but nothing seems to work. Even when I get rid of the root prop, it complains about the other props. What am I doing wrong?


text:
Q: Dynamically updating a GridPane with new Buttons in JavaFX -> how to repaint? I have a grid pane which contains a number of buttons (normally something between 10 and 25) with five buttons per row (and however many are left in the last row). The number of buttons (and the buttons itself) might change during program execution. When that happens, the new buttons should be displayed. How can I achieve that? Here is a mini-example:
public class GridButtons extends Application {
    List<String> buttonTexts = new ArrayList<>();
    GridPane buttonGrid = new GridPane();
    GridPane bgGrid = new GridPane();

    @Override
    public void start(Stage primaryStage) {
        Button changeButtonsButton = new Button("Change BTNs");
        changeButtonsButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                changeButtonTexts();
            }
        });
        bgGrid.add(changeButtonsButton, 0, 0);
        changeButtonTexts();
        bgGrid.add(buttonGrid, 1, 0);

        Scene scene = new Scene(bgGrid, 440, 140);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void updateButtonsGrid() {
        buttonGrid = new GridPane();
        for (int i = 0; i < buttonTexts.size(); i++) {
            Button button = new Button(buttonTexts.get(i));
            button.setMinWidth(70);
            button.setMaxWidth(70);
            buttonGrid.add(button, i % 5, i / 5);
            System.out.println(buttonTexts.get(i));
        }
        // now the new GridPane should be displayed -> how?
    }

    public void changeButtonTexts() {
        buttonTexts.clear();
        Random random = new Random();
        int buttonCount = random.nextInt(15) + 10;
        for (int i = 0; i < buttonCount; i++) {
            buttonTexts.add("Button " + i);
        }
        updateButtonsGrid();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Or are there better options than using a GridPane? Using a ListView<Button> and an ObservableList<Button> would work, but then the buttons are not displayed in a tabular form with five buttons in each row.

A: Creating a new GridPane is probably not what you want here. In the function updateButtonsGrid, change the line
buttonGrid = new GridPane();

to
buttonGrid.getChildren().clear();

If, for some reason, you are absolutely sure you need a new instance of GridPane, remove the old one from bgGrid, and add the new one. In your current code example the new instance of GridPane is never added to the scene graph.


text:
Q: how to get has_many through: across servers working I have a JRuby application that I am trying to create has_many through: relationships for databases that live on two completely different servers. I understand that joins will not work across tables on different servers. What I would like is to simulate the joins so that a developer using the model doesn't have to be (as) aware of the cross-server join.
There are some additional complexities in this setup:

*

*The remote database is read-only

*The table names and primary keys in the remote database do not follow rails naming conventions. (The remote database is a Data Warehouse)

*I would like to be able to use the model as though a has_and_belongs_to_many was in it.

I've considered writing my own custom association, but that's a bit complex and I can't find any guides or really any starting points other then reading through the Rails code.
Is there an easy way to do this that I'm missing?
Is building a custom ActiveRecord association the best way to do this? and if so, where do I start?
Code similar to my setup:
config/database.yml
development:
  adapter: postgresql
  encoding: unicode
  database: main
  username: username
  password: password
  host: localhost
  pool: 5

remote_development: # Read only
  adapter: jdbcmssql
  driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
  url: 'jdbc:sqlserver://foo.com;databaseName=main'
  username: username
  password: password

app/models/account.rb
class Portfolio < ActiveRecord::Base
  #has_and_belongs_to_many :dim_users, join_table: :accounts_dim_user
end

app/models/remote_model_base.rb
class RemoteModelBase
  require "#{Rails.root}/lib/sqljdbc4.jar"
  self.abstract_class = true
  establish_connection "remote_#{Rails.env}".to_sym
  after_initialize :readonly!
end

app/models/dim_user.rb
class DimUser < RemoteModelBase
  self.table_name = 'DimUser'
  self.primary_key = 'dwidDimUser'

  #has_and_belongs_to_many :accounts, join_table: :accounts_dim_user
end

config/schema.rb
ActiveRecord::Schema.define(version: 20140925200106) do

  create_table "accounts", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "accounts_dim_user", force: true, id: false do |t|
    t.integer  "dwidUser"
    t.integer  "account_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  # Defined in the remote database but it might look something like this
  # create_table "DimUser" do |t|
  #   t.integer dwidUser
  #   # ...
  # end

A: Just ran through a quick scenario for you, here's the repo: https://github.com/beneggett/many_db_example
In the repo, I just did 2 different db's on my local, but it won't matter, the principal is the same:
This seemed to work well for me:
Tell the account about the account_dim_users join table association, but manually map the has_many through/habtm.
class Account < ActiveRecord::Base
  has_many :account_dim_users

  def dim_users
    account_dim_users.map {|account_dim_user| DimUser.find_by(dwidUser: account_dim_user.dwidUser) }
  end
end

This is important, because, as you well know, the standard join will not work; however mapping it through the model works fine.
AccountDimUser join table looks standard (I explicitly mapped the keys)
class AccountDimUser < ActiveRecord::Base
  has_many :accounts
  has_many :dim_users, primary_key: :dwidUser, foreign_key: :dwidUser

end

Manually map the account_dim_users association, and manually map the accounts association
class DimUser < ActiveRecord::Base
  establish_connection "other_db".to_sym
  after_initialize :readonly!
  self.table_name = 'DimUser'
  self.primary_key = 'dwidUser'

  def account_dim_users
    AccountDimUser.where(dwidUser: self.dwidUser)
  end

  def accounts
    account_dim_users.map {|account_dim_user| Account.find(account_dim_user.account_id) }
  end
end

This approach allows you to still use your Ruby objects in the standard way:
a = Account.first
  Account Load (0.6ms)  SELECT  "accounts".* FROM "accounts"   ORDER BY "accounts"."id" ASC LIMIT 1
=> #<Account:0x00000102d263d0> {
          :id => 1,
        :name => "New account",
  :created_at => Mon, 29 Sep 2014 15:07:07 UTC +00:00,
  :updated_at => Mon, 29 Sep 2014 15:07:07 UTC +00:00
}

--
a.account_dim_users
=> #<ActiveRecord::Associations::CollectionProxy [#<AccountDimUser id: 1, dwidUser: 1, account_id: 1, created_at: "2014-09-29 15:08:47", updated_at: "2014-09-29 15:08:47">, #<AccountDimUser id: 3, dwidUser: 5, account_id: 1, created_at: "2014-09-29 15:24:17", updated_at: "2014-09-29 15:25:06">]>

--
a.dim_users
  AccountDimUser Load (0.3ms)  SELECT "account_dim_users".* FROM "account_dim_users"  WHERE "account_dim_users"."account_id" = $1  [["account_id", 1]]
  DimUser Load (0.9ms)  SELECT  "DimUser".* FROM "DimUser"  WHERE "DimUser"."dwidUser" = 1 LIMIT 1
  DimUser Load (0.3ms)  SELECT  "DimUser".* FROM "DimUser"  WHERE "DimUser"."dwidUser" = 5 LIMIT 1
=> [
  [0] #<DimUser:0x0000010981af10> {
            :id => 1,
      :dwidUser => 1,
    :created_at => Mon, 29 Sep 2014 15:06:44 UTC +00:00,
    :updated_at => Mon, 29 Sep 2014 15:06:44 UTC +00:00
  },
  [1] #<DimUser:0x00000109838b00> {
            :id => 5,
      :dwidUser => 5,
    :created_at => Mon, 29 Sep 2014 15:23:01 UTC +00:00,
    :updated_at => Mon, 29 Sep 2014 15:23:01 UTC +00:00
  }
]

--
d = DimUser.first
  DimUser Load (0.5ms)  SELECT  "DimUser".* FROM "DimUser"   ORDER BY "DimUser"."dwidUser" ASC LIMIT 1
=> #<DimUser:0x0000010990aad8> {
          :id => 1,
    :dwidUser => 1,
  :created_at => Mon, 29 Sep 2014 15:06:44 UTC +00:00,
  :updated_at => Mon, 29 Sep 2014 15:06:44 UTC +00:00
}

--
d.account_dim_users
  AccountDimUser Load (0.5ms)  SELECT "account_dim_users".* FROM "account_dim_users"  WHERE "account_dim_users"."dwidUser" = 1
=> #<ActiveRecord::Relation [#<AccountDimUser id: 1, dwidUser: 1, account_id: 1, created_at: "2014-09-29 15:08:47", updated_at: "2014-09-29 15:08:47">]>

--
 d.accounts
  AccountDimUser Load (0.5ms)  SELECT "account_dim_users".* FROM "account_dim_users"  WHERE "account_dim_users"."dwidUser" = 1
  Account Load (0.4ms)  SELECT  "accounts".* FROM "accounts"  WHERE "accounts"."id" = $1 LIMIT 1  [["id", 1]]
=> [
  [0] #<Account:0x000001099788d0> {
            :id => 1,
          :name => "New account",
    :created_at => Mon, 29 Sep 2014 15:07:07 UTC +00:00,
    :updated_at => Mon, 29 Sep 2014 15:07:07 UTC +00:00
  }
]

There is probably some optimizations that could be done to this when dealing with large quantities of records, but it's a good base.
The other approach might be to do lookups on the association table itself, like:
  def find_dim_user
    DimUser.find_by(dwidUser: self.dwidUser)
  end

But I very much prefer the first way I suggested, as it lets you do your normal ruby method chaining approach to associations.
Any other questions, let me know!
Edit: You could change the map function to use Active Record Relations or similar as well, enabling more functionality:
class Account < ActiveRecord::Base
  has_many :account_dim_users

  def dim_users
    dim_user_ids = account_dim_users.map {|account_dim_user| account_dim_user.dwidUser }
    DimUser.where(dwidUser: dim_user_ids)
  end
end

A: Use dblink http://www.postgresql.org/docs/9.3/static/dblink.html , you will have the other table in the same database. Problem solved.


text:
Q: Filter object ObservableCollection of some type I have a ObservableCollection<Object> that holds two different types of objects: Directory and File. This collection is bound to a control and at some time, I want to filter out the Files.
I have the following code, which is not working:
var files = (from File f in (from Directory d in selectedDirs
                             select d.Childs)
             where f is File
             select f);

I'm getting this error:

Unable to cast object of type
  'System.Collections.ObjectModel.ObservableCollection`1[System.Object]'
  to type 'CMBraga_FileExplorer.File'.

How can I get my values? I know they are Files.
// this was ran without explicit conversion ( just as an example )

? myCollection
Count = 5
    [0]: {CMBraga_FileExplorer.File}
    [1]: {CMBraga_FileExplorer.File}
    [2]: {CMBraga_FileExplorer.File}
    [3]: {CMBraga_FileExplorer.File}
    [4]: {CMBraga_FileExplorer.File}

A: I suspect the reason you're getting the exception is because you are declaring the types of your query variable (i.e., from File f in ...).  By doing that, you are trying to cast the objects to the specified type.  It would appear that your types of some of the items in d.Childs are ObservableCollection<Object>.  Those are clearly not File objects hence the cast error.
Use the Enumerable.OfType() extension method here to do the filtering.  This is exactly what it was made for.
var files = selectedDirs
    .Cast<Directory>() // this cast might not even be necessary
    .SelectMany(d => d.Childs)
    .OfType<File>(); // filter selecting only File objects

A: You can use Linq expression for that:
using System.Linq;
// ...
ObservableCollection<object> list;
// ...
IEnumerable<CMBraga_FileExplorer.File> castedList = list.Cast<CMBraga_FileExplorer.File>();


text:
Q: How do I prevent failed to create session error in keras? I am new to tensorflow and Keras, below is my code
import numpy as np
np.random.seed(123)  # for reproducibility

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist

(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 5. Preprocess input data
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

# 6. Preprocess class labels
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)

# 7. Define model architecture
model = Sequential()

model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=
(28,28,1)))
model.add(Convolution2D(32, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))

# 8. Compile model
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

# 9. Fit model on training data
model.fit(X_train, Y_train,
          batch_size=32, nb_epoch=10, verbose=1)

# 10. Evaluate model on test data
score = model.evaluate(X_test, Y_test, verbose=0)

I keep getting the following error after running this code
2018-07-31 19:25:45.099850: I C:\users\nwani_bazel_nwani\mmtm6wb6\execroot\org_tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2018-07-31 19:25:45.711357: I C:\users\nwani_bazel_nwani\mmtm6wb6\execroot\org_tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1356] Found
device 0 with properties:
name: GeForce 840M major: 5 minor: 0 memoryClockRate(GHz): 1.124
pciBusID: 0000:04:00.0
totalMemory: 2.00GiB freeMemory: 1.66GiB
2018-07-31 19:25:45.718218: I C:\users\nwani_bazel_nwani\mmtm6wb6\execroot\org_tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1435] Adding visible gpu devices: 0
2018-07-31 19:25:45.722718: E C:\users\nwani_bazel_nwani\mmtm6wb6\execroot\org_tensorflow\tensorflow\core\common_runtime\direct_session.cc:154] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version
Traceback (most recent call last):
  File "c:\Users\Seth Siva\Documents\mnist digit recognizer.py", line 44, in
    batch_size=32, nb_epoch=10, verbose=1)
  File "C:\Users\Seth Siva\anaconda\lib\site-packages\keras\engine\training.py", line 1042, in fit
    validation_steps=validation_steps)
  File "C:\Users\Seth Siva\anaconda\lib\site-packages\keras\engine\training_arrays.py", line 199, in fit_loop
    outs = f(ins_batch)
  File "C:\Users\Seth Siva\anaconda\lib\site-packages\keras\backend\tensorflow_backend.py", line 2653, in call
    if hasattr(get_session(), '_make_callable_from_options'):
  File "C:\Users\Seth Siva\anaconda\lib\site-packages\keras\backend\tensorflow_backend.py", line 183, in get_session
    _SESSION = tf.Session(config=config)
  File "C:\Users\Seth Siva\anaconda\lib\site-packages\tensorflow\python\client\session.py", line 1560, in init
    super(Session, self).init(target, graph, config=config)
  File "C:\Users\Seth Siva\anaconda\lib\site-packages\tensorflow\python\client\session.py", line 633, in init
    self._session = tf_session.TF_NewSession(self._graph._c_graph, opts)
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.


text:
Q: How to stop the transition animation in QML? There is window, its layout designed by states and transition.  we know that when the state change, the transition-animation will start automatically,  but when the transition animation doesn't finished, i change the state, it make troubles.  just like slow in reacting;  how to fix it? thank you...
it something like this :

Flickable {
            id: content
            anchors.fill: parent
            flickableDirection: Flickable.HorizontalFlick
            contentWidth: width * 2
            contentHeight: height
            clip: true

            onFlickStarted: {
                if(horizontalVelocity > 0) {
                    regAndFind.state = "Find"
                }
                else {
                    regAndFind.state = "Register"
                }
            }  .......
}

states: [
    State {
        name: "Register"
        PropertyChanges {
            target: slider
            x: 0
        }
        PropertyChanges {
            target: content
            contentX: 0
        }
    },
    State {
        name: "Find"
        PropertyChanges {
            target: slider
            x: parent.width / 2
        }
        PropertyChanges {
            target: content
            contentX: parent.width
        }
    }
]

transitions: [
    Transition {
        NumberAnimation {
            target: slider
            property: "x"
            duration: 600
        }
        NumberAnimation {
            target: content
            property: "contentX"
            duration: 600
        }
    }
]

A: Read about the animation element in Qml.
Before you move to other state, you can call the Animation::stop () function to stop the animation in between. Note that it will stop the animation immediately, and the animation will have no further effect on the property values.


text:
Q: How to subset a multidimensional contingency table with values of a vector (i.e. each value specifies a dimension)? I have a multidimensional contingency table of 4 variables. And I need to get the values out of that table, using a length-4 vector. The whole reason for doing this is to be able to get a huge list of such vectors and find a corresponding output from the contingency table.
Is there a good way to convert c(1,2,3,4) into my.table[1,2,3,4]?
Here's an example of what I'm currently doing with only one vector as an input:
v = c(1,2,3,4)
my.table = table(my.data.frame[,c("x","y","z","w")])
eval(str2lang(paste0("my.table[", paste0(v, collapse = ", "), "]")))

And this is what I'm doing with a big list of input vectors, which is in my case a data frame:
data.frame.of.inputs = data.frame(x = sample(1:4, 100, T), y = sample(1:4, 100, T),
                                  z = sample(1:4, 100, T), w = sample(1:4, 100, T))
my.table = table(some.other.data.frame[,c("x","y","z","w")])
apply(data.frame.of.inputs,1,function(rw)
eval(str2lang(paste0("my.table[", paste0(rw, collapse = ", "), "]"))))

Note: to make this code run you can initialize my.data.frame and some.other.data.frame with the same statement:
data.frame(x = sample(1:4, 100, T), y = sample(1:4, 100, T),
           z = sample(1:4, 100, T), w = sample(1:4, 100, T))

I don't like my current solution not just because it is ugly, but also because it seems to be a very long way of doing something simple.
Also, as a side-quest of mine: is there a way to subset a table via attributes(my.table)$variable.name?

A: From ?"[":

When indexing arrays by '[' a single argument 'i' can be a
matrix with as many columns as there are dimensions of 'x';
the result is then a vector with elements corresponding to
the sets of indices in each row of 'i'.

With one vector:
my.table[rbind(v)]

(i.e., convert the vector into a one-row matrix)
Multiple inputs:
my.table[as.matrix(data.frame.of.inputs)]


text:
Q: primeng paginator not working IE 11 when deployed on server I have used pagination via p-table. In the image below, when user clicks on the very last page, the data in last page gets displayed but the page number is not updated in bottom right. This issue occurs in IE that too when deployed on server (works locally).
Below we can see the page number as 879 but in extreme right it does not show the correct page number

Expected behavior:
On click of last page, the specific page number should be displayed
If the current behavior is a bug or you can illustrate your feature request better with an example,
Environment:
IE 11
Angular version: 10.1.2
PrimeNG version: 10
<p-table #dt [columns]="cols"  [exportFilename]="" [value]="" [lazy]="true" (onLazyLoad)="load($event)"
[paginator]="true" [(first)]="0" [rows]="rowsPerPage" [totalRecords]="totalCount" [loading]="loading"
tableStyleClass="table table-hover table-striped">


text:
Q: Auto close uifigure upon deletion of handle from workspace Say I have a GUI class that creates an uifigure (see below). I can create an instance of this class in my workspace:
tG = testGUI('hi!');

I can close the GUI by calling the delete method: tG.delete(). Is it also possible to automatically close the GUI when the handle tG is cleared from the workspace by e.g.
clear tG

This would prevent opening many instances of the class when running some script multiple times, while the handle to the GUI is already deleted.
Update

*

*removing the registerApp(app, app.UIFigure) call in the constructor first seemed to solve the issue, however this did not work in my real GUI.

*Adding a callback to the button in the test GUI reproduces the issue in my MVCE.

classdef testGUI < matlab.apps.AppBase

    properties (Access = public)
        % The figure handle used.
        UIFigure
        % app name
        name
    end

    properties (Access = private)
        pushButton
    end

    methods (Access = public)

        function app = testGUI(name)
            %TESTGUI - Constructor for the testGUI class.

            % property management
            app.name = name;

            % create GUI components
            createComponents(app)

            % Register the app with App Designer
            %registerApp(app, app.UIFigure); % removing this does not solve the issue
        end

        function delete(app)
            delete(app.UIFigure)
        end
    end

    methods (Access = private)

        function createComponents(app)
            %Create the components of the GUI

            app.UIFigure = uifigure('Name', app.name);
            app.UIFigure.Visible = 'on';

            % some button
            app.pushButton = uibutton(app.UIFigure, 'push');
            app.pushButton.Text = 'This is a button';
            app.pushButton.ButtonPushedFcn = @(src,event) someCallBack(app);
        end

        function someCallBack(app)
            fprintf('this is someCallBack\n')
        end
    end
end


text:
Q: Chartist.js: how to set pie chart slice colors I have a variable length series array which I feed to the Chartist.js pie chart. It draws slices in terrible red colors.
There is an HSL color example in the Documentation, but it starts from red too. How do I start with a color #0099ff for the max value and then set different tints to the rest?
The slice color can be set by:
.on('draw', function(data) {
    if (data.type === 'slice') {
        data.element.attr({
            style: 'fill: hsl(?,?,?);'
        });
    }
})

I can't figure out how to manipulate the hsl() string to start with #0099ff and then change the max color tint based on the value.


text:
Q: Is it possible to create a "negative" ACL? Is it possible to create an ACL to deny access to a specific user (say jdoe) to a specific file?
I'm not interested in the trivial solution of an ACL that gives access to the file to all users except jdoe. This solution has the disadvantage that any user created successively in the system won't have access to the file.
Creating a group of all users except jdoe and granting group access to the file bears the same disadvantage.
The command setfacl -x u:jdoe /path/file won't work as it removes only created ACLs.

A: Sure, to demonstrate, as root...
touch /tmp/test
setfacl -m u:jdoe:--- /tmp/test
getfacl /tmp/test
su - jdoe
cat /tmp/test
exit
rm /tmp/test

It could be done to every file in a directory by default as well:
mkdir /var/data/not-for-jdoe
setfacl -m u:jdoe:--- /var/data/not-for-jdoe
setfacl -d -m u:jdoe:--- /var/data/not-for-jdoe

Above, the -m switch is the mask and the -d switch makes it the default mask for all new filesystem objects in the directory. The --- can have other permission values, e.g.:

*

*rwx

*r--

*rw-

*r-x

*7

*4

*6

*5
The group and other masks work the same way: g:groupname:--- or in combination: u:username:---,g:groupname:---,o::---. Not specifying a username or group name applies the mask to current user/group ownership.

A: setfacl is a command from the deprecated because withdrawn in 1997 POSIX ACL draft proposal that was never standardized.
setfacl cannot do this.
If you have a modern OS that supports NFSv4/NTFS ACLs, you can do this.
See e.g. http://schillix.sourceforge.net/man/man1/chmod.1.html
Check the examples starting at page 19.
This is for Solaris, but AIX and OSX also support NFSv4 ACLs.


text:
Q: ASP.NET5 MVC6 Deploy on Amazon (AWS) - unable to deploy properly I am trying to deploy ASP.NET5 MVC6 web application on to Amazon Web Services via Code Deploy.
The problem is I have no idea where to place the appspec.yml and before-install.bat file as the has been a change in the folder structure with ASP.NET5 with the introduction of wwwroot folder, and also all of my .cshtml files are in the view folder.
Thank you

A: *

*appspec.yml must be placed in the root of an application's source code's directory structure(then you bundle the whole folder).

*You can put your personal script anywhere you want inside you bundle, as long as you give the correct source file directory in side your appspec.yml

*An example of the appspec.yml file can be seen here: http://docs.aws.amazon.com/codedeploy/latest/userguide/app-spec-ref.html#app-spec-ref-example

A: Install bower as explained here: http://ruleoftech.com/2015/setting-up-bower-and-gulp-in-windows. Restart the Windows OS. You are done. Before you install bower you have to have Git, Node.js in this precise order. You will install bower from git bash.


text:
Q: Marshal.Copy not copying from bytes array into structure starting at the address provided in an IntPtr (This is in some sense a follow-up question to Extracting structs in the middle of a file into my structures other than accessing the file byte for byte and compose their value.)
I am having a file containing a structure record in its stream:
[Start]...[StructureRecord]...[End]

The contained structure fits into this layout, of which exists a variable:
Public Structure HeaderStruct
    Public MajorVersion As Short
    Public MinorVersion As Short
    Public Count As Integer
End Structure

private grHeaderStruct As HeaderStruct

It is into this variable I want a copy of the structure residing in the file.
Required namespaces:
'File, FileMode, FileAccess, FileShare:
Imports System.IO

'GCHandle, GCHandleType:
Imports System.Runtime.InteropServices

'SizeOf, Copy:
Imports System.Runtime.InteropServices.Marshal

My FileStream is named oFS.
Using oFS = File.Open(sFileName, FileMode.Open, FileAccess.Read)
    ...

Assume, that oFS is positioned at the start of [StructureRecord] now.
So there are 8 bytes (HeaderStruct.Length) to read from the file, and copy these into a record instance of this structure. To do so, I wrap the logic to read from file the required number of bytes and transfer them to my structure record into a generic method ExtractStructure. The destination is instantiated just before the call to the routine.
    grHeaderStruct = New HeaderStruct
    ExtractStructure(Of HeaderStruct)(oFS, grHeaderStruct)
    ...
End Using

(Before suggesting techniques to read just these 8 bytes outside of a dedicated method, you should probably know, that the whole file consists of structures, which depend on each other. The Count field says, that 3 child structures are to follow, but these contain Count fields themselves, etc. I think a routine to get them is not a too bad idea.)
However, this is the routine which causes my current head-ache:
'Expects to find a structure of type T at the actual position of the
'specified filestream oFS. Reads this structure into a byte array and copies
'it to the structure variable specified in oStruct.
Public Shared Sub ExtractStructure(Of T As Structure) _
    (oFS As FileStream, ByRef oStruct As T)

    Dim oGCHandle As GCHandle
    Dim oStructAddr As IntPtr
    Dim iStructLen As Integer
    Dim abStreamData As Byte()

    'Obtain a handle to the structure, pinning it so that the garbage
    'collector does not move the object. This allows the address of the
    'pinned structure to be taken. Requires the use of Free when done.
    oGCHandle = GCHandle.Alloc(oStruct, GCHandleType.Pinned)

    Try
        'Retrieve the address of the pinned structure, and its size in bytes.
        oStructAddr = oGCHandle.AddrOfPinnedObject
        iStructLen = SizeOf(oStruct)

        'From the file's current position, obtain the number of bytes
        'required to fill the structure.
        ReDim abStreamData(0 To iStructLen - 1)
        oFS.Read(abStreamData, 0, iStructLen)

        'Now both the source data is available (abStreamData) as well as an
        'address to which to copy it (oStructAddr). Marshal.Copy will do the
        'copying.
        Marshal.Copy(abStreamData, 0, oStructAddr, iStructLen)
    Finally
        'Release the obtained GCHandle.
        oGCHandle.Free()
    End Try
End Sub

The instruction
oFS.Read(abStreamData, 0, iStructLen)

does read the correct number of bytes with the correct values, as per immediate window:
?abstreamdata
{Length=8}
    (0): 1
    (1): 0
    (2): 2
    (3): 0
    (4): 3
    (5): 0
    (6): 0
    (7): 0

I can not use Marshal.StructureToPtr here, because, well, a bytes array is not a structure. However, the Marshal class has also a Copy method.
Only that I obviously miss a point here, because
Marshal.Copy(abStreamData, 0, oStructAddr, iStructLen)

does not do the intended copy (but it also does not throw an exception):
?ostruct
    Count: 0
    MajorVersion: 0
    MinorVersion: 0

What do I fail to understand, why this copy is not working?
The MS documentation does not tell too much for Marshal.Copy: https://msdn.microsoft.com/en-us/library/ms146625(v=vs.110).aspx:

source - Type: System.Byte()
  The one-dimensional array to copy from.
startIndex - Type: System.Int32
  The zero-based index in the source array where copying should start.
destination - Type: System.IntPtr
  The memory pointer to copy to.
length - Type: System.Int32
  The number of array elements to copy.

Looks as if I have set up right everything, so is it possible that Marshal.Copy does not copy to the structure, but to some other place?
oStructAddr surely does look like an address (&H02EB7B64), but where is that?
Edit
Between the instantiation of the parameter receiving the result and the call to the routine
    grHeaderStruct = New HeaderStruct
    ExtractStructure(Of HeaderStruct)(oFS, grHeaderStruct)

I filled the instantiated record with some test data to see whether it is actually passed correctly:
#Region "Test"
    With grMultifileDesc
        .MajorVersion = 7
        .MinorVersion = 8
        .Count = 9
    End With
#End Region

In the procedure, I check the value of the record before and after Marshal.Copy in the immediate window. Both times I obtain:
?ostruct
{MyProject.MyClass.HeaderStruct}
    Count: 9
    MajorVersion: 7
    MinorVersion: 8

(Re-arrangement of the record's fields is the same in the caller as in the callee, which of course is an issue in itself, as the data is read from a file and would be wrongly copied into the structure. However, this is not the topic of the question.)
Conclusion: Data obtained, but no Marshal.Copy made already in the callee. So it is not just a "returns wrong data" problem.
Edit 2
It turns out,that Marshal.Copy does not copy data, as stated in the documentation, but a pointer to the data.
Marshal.ReadByte(oStructAddr) does return the byte array's first byte, Marshal.ReadByte(oStructAddr + 1) its second byte, etc.
But how do I return this data in the Out argument?

A: I can not say for certain why the updated bytes copied to the pinned address are not reflected in the original structure, but I suspect that the interop-marshaller makes a copy.  see: Copying and Pinning.
I do know that if you pin a byte array, that changes made by using Marshal.Copy are propagated back to the managed array.  With that said, here is an example that you should be able to use for your needs.
Dim lenBuffer As Int32 = Marshal.SizeOf(Of HeaderStruct)
Dim buffer As Byte() = New Byte(0 To lenBuffer - 1) {}
Dim gchBuffer As GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned)
Dim hs As New HeaderStruct With {.MajorVersion = 4, .MinorVersion = 2, .Count = 5}

' copy to pinned byte array
Marshal.StructureToPtr(hs, gchBuffer.AddrOfPinnedObject, True)
' buffer = {4, 0, 2, 0, 5, 0, 0, 0} ' array can be written to file

' change the data - simulates array read from file
buffer(0) = 1 ' MajorVersion = 1
buffer(2) = 3 ' MinorVersion = 3
buffer(4) = 2 '.Count = 2

' read from pinned byte array
Dim hs2 As HeaderStruct = Marshal.PtrToStructure(Of HeaderStruct)(gchBuffer.AddrOfPinnedObject)
gchBuffer.Free()

Edit:  Based on a comment, it seems that the OP believes that the technique shown above can not be implemented as generic methods for reading/writing to a stream.  So here is a copy/paste example.
Sub Example()
    Using ms As New IO.MemoryStream
        Dim hs As New HeaderStruct With {.MajorVersion = 4, .MinorVersion = 2, .Count = 5}
        Debug.Print($"Saved structure:  {hs}")
        WriteStruct(ms, hs)  'write structure to stream

        ms.Position = 0 ' reposition stream to start
        Dim hs2 As New HeaderStruct ' target for reading from stream
        ReadStruct(ms, hs2)
        Debug.Print($"Retrieved structure: {hs2}")
    End Using
End Sub

Sub WriteStruct(Of T As {Structure})(strm As IO.Stream, ByRef struct As T)
    Dim lenBuffer As Int32 = Marshal.SizeOf(Of T)
    Dim buffer As Byte() = New Byte(0 To lenBuffer - 1) {}
    Dim gchBuffer As GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned)
    Marshal.StructureToPtr(struct, gchBuffer.AddrOfPinnedObject, True)
    strm.Write(buffer, 0, lenBuffer)
    gchBuffer.Free()
End Sub

Sub ReadStruct(Of T As {Structure})(strm As IO.Stream, ByRef struct As T)
    Dim lenBuffer As Int32 = Marshal.SizeOf(Of T)
    Dim buffer As Byte() = New Byte(0 To lenBuffer - 1) {}
    strm.Read(buffer, 0, buffer.Length)
    Dim gchBuffer As GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned)
    struct = Marshal.PtrToStructure(Of T)(gchBuffer.AddrOfPinnedObject)
    gchBuffer.Free()
End Sub

Public Structure HeaderStruct
    Public MajorVersion As Short
    Public MinorVersion As Short
    Public Count As Integer
    Public Overrides Function ToString() As String
        Return $"MajorVersion = {MajorVersion}, MinorVersion = {MinorVersion}, Count = {Count}"
    End Function
End Structure

Output of Example:

Saved structure:  MajorVersion = 4, MinorVersion = 2, Count = 5
Retrieved structure: MajorVersion = 4, MinorVersion = 2, Count = 5

A: The ExtractStructure method needs to be rewritten like this:
'Expects to find a structure of type T at the actual position of the
'specified filestream oFS. Reads this structure into a byte array and copies
'it to the structure variable specified in oStruct.
Public Shared Sub ExtractStructure(Of T As Structure) _
    (oFS As FileStream, ByRef oStruct As T)

    Dim iStructLen As Integer
    Dim abStreamData As Byte()
    Dim hStreamData As GCHandle
    Dim iStreamData As IntPtr

    'From the file's current position, read the number of bytes required to
    'fill the structure, into the byte array abStreamData.
    iStructLen = Marshal.SizeOf(oStruct)
    ReDim abStreamData(0 To iStructLen - 1)
    oFS.Read(abStreamData, 0, iStructLen)

    'Obtain a handle to the byte array, pinning it so that the garbage
    'collector does not move the object. This allows the address of the
    'pinned structure to be taken. Requires the use of Free when done.
    hStreamData = GCHandle.Alloc(abStreamData, GCHandleType.Pinned)
    Try
        'Obtain the byte array's address.
        iStreamData = hStreamData.AddrOfPinnedObject()

        'Copy the byte array into the record.
        oStruct = Marshal.PtrToStructure(Of T)(iStreamData)
    Finally
        hStreamData.Free()
    End Try
End Sub

Works.


text:
Q: Creating a popup dialog when an error occurs Jquery Mobile I want a dialog box to appear when an error occurs however I dont know how to do it. Where I would like the code to appear can be seen in the code below. So when this function is called a popup dialog box appears.
.fail(function(){
            alert("$.get failed!"); //replace with failed dialog
        })
    });

A: So I'm guessing this is what you are talking about.
http://api.jquerymobile.com/popup/
Have this embedded in your html somewhere.

 Close

I have a close button at the top left corner with simple HTML markup.

And then in your fail function just call this.
$( "#popupCloseLeft" ).popup("open");


text:
Q: How do I express this? I'm trying to work out how to write the following:
total = (value * 0.95 ^ 0) + (value * 0.95 ^ 1) + (value * 0.95 ^ 2) ...

or:
x = (y * z ^ 0) + (y * z ^ 1) + (y * z ^ 2) + (y * z ^ 3) ...

This expresses how to calculate x for 4 iterations, but how can I express this to work with a variable number of iterations? Obviously I could create a loop and add the values together, but I'd really like to find a single equation that solves this.
I'm using c++ but I guess this isn't really a language specific problem (sorry I literally don't know where else to ask this question!).
Any ideas?
Thanks,
Chris.

A: There is no need for a loop here, you "just" need to employ some maths.
Note that you can rewrite that as
y * (z0 + z1 + ... + zn)
Now, the series
z0 + z1 + ... + zn
sums to
(z(n+1) - 1) / (z - 1)
so your equation would be
x = y * (z(n+1) - 1) / (z - 1)

A: Equation-wise solving, this is a geometric series and can therefore be calculated with
double geometric_series(double y, double z, int N) {
  return y * (std::pow(z, N) - 1.0) / (z - 1.0);
}

but the same result can be obtained with some fun C++ metaprogramming: if you know the number of iterations in advanced and you're allowed to use C++17 features and fold expressions you could do as follows
template<std::size_t... N>
double calculate_x(double y, double z, std::index_sequence<N...>) { // [0;N[
 auto f = [](double y_p, double z_p, double exp) {
   return y_p * std::pow(z_p, exp);
 };
 return (f(y, z, N) + ...);
}

template <std::size_t N>
auto calculate_x(double y, double z) {
  return calculate_x(y, z, std::make_index_sequence<N>{});
}

Alternatively this can also be done with pre-C++17 templates
template <int N>
double calculate_x(double y, double z) {
  return calculate_x<N-1>(y, z) + (y * std::pow(z, N - 1));
}

template <>
double calculate_x<0>(double, double) {
  return 0;
}

Otherwise a simpler solution would be to just use a loop
double calculate_x_simple(double y, double z, int N) {
  double ret = 0.0;
  for (int i = 0 ; i < N ; ++i)
    ret += y * std::pow(z, i);
  return ret;
}

Driver for the code above
int main() {

   // x = (y * z ^ 0) + (y * z ^ 1) + (y * z ^ 2) + (y * z ^ 3)
   double y = 42.0;
   double z = 44.5;
   std::cout << (calculate_x<3>(y, z) == calculate_x_simple(y, z, 3)); // 1

}

A: If a loop would be the only option:
double x = 0;
int n = 5;
for(int exponent = 0; exponent <= n; ++exponent)
  x += y*pow(z, exponent);

A: As you mentioned, it seems reasonable to use a loop. But if you know the amount of iterations at compile time, you could use templates like this:
template <int n>
double foo(double y, double z)
{
    return foo<n-1>(y, z) + y * std::pow(z, n);
}

template <>
double foo<-1>(double, double)
{
    return 0;
}

With just a little bit of optimisation this will unfold to a single equation.
Example:
#include <iostream>
#include <cmath>

template <int n>
double foo(double y, double z)
{
    return foo<n-1>(y, z) + y * std::pow(z, n);
}

template <>
double foo<-1>(double, double)
{
    return 0;
}

int main()
{
    std::cout << foo<2>(2,3) << std::endl;
}

Output: 26

A: you can just use math.pow function with a for loop
#include <stdio.h>
#include <math.h>

int main(void) {
    int i;
    int n = 5;
    double y = 0.5;
    double z = 0.3;
    double answer = 0;
    for (i = 0  ; i < n ; i++)
        answer += y * pow(z,i);

    printf("%f", answer);
    return 0;
}

A: Using n as the number of iterations,
#include <cmath>
double foo(double y, double z, int n)
{
   double x =0;
   for(int i = 0 ; i<n; ++i){
      x+=y*std::pow(z,i);
   }
   return x;
}

Where std::pow is the power function.

A: It can be expressed as a sum from n=0 to m. It can be expressed in a single formula, according to wolframalpha.

A: Don't know if this fulfills your purpose, but you can use recursion(which in real terms is a loop only :) )
int x = evaluate(y, z, count);

int evaluate(y,z, count)
{
   if (count <= 0)
    return 0;

   return (evaluate(y, z, count-1) + y*z^count);
}


text:
Q: Correct way to create or update with multiple belongs_to in Rails New to Rails and Ruby and trying to do things correctly.
Here are my models. Everything works fine, but I want to do things the "right" way so to speak.
I have an import process that takes a CSV and tries to either create a new record or update an existing one.
So the process is 1.) parse csv row 2.) find or create record 3.) save record
I have this working perfectly, but the code seems like it could be improved. If ParcelType wasn't involved it would be fine, since I'm creating/retrieving a parcel FROM the Manufacturer, that foreign key is pre-populated for me. But the ParcelType isn't. Anyway to have both Type and Manufacturer pre-populated since I'm using them both in the search?
CSV row can have multiple manufacturers per row (results in 2 almost identical rows, just with diff mfr_id) so that's what the .each is about
manufacturer_id.split(";").each do |mfr_string|
  mfr = Manufacturer.find_by_name(mfr_string)

  # If it's a mfr we don't care about, don't put it in the db
  next if mfr.nil?

  # Unique parcel is defined by it's manufacturer, it's type, it's model number, and it's reference_number
  parcel = mfr.parcels.of_type('FR').find_or_initialize_by_model_number_and_reference_number(attributes[:model_number], attributes[:reference_number])
  parcel.assign_attributes(attributes)

  # this line in particular is a bummer. if it finds a parcel and I'm updating, this line is superfulous, only necessary when it's a new parcel
  parcel.parcel_type = ParcelType.find_by_code('FR')

  parcel.save!
end

class Parcel < ActiveRecord::Base
  belongs_to :parcel_type
  belongs_to :manufacturer

  def self.of_type(type)
    joins(:parcel_type).where(:parcel_types => {:code => type.upcase}).readonly(false) unless type.nil?
  end
end

class Manufacturer < ActiveRecord::Base
  has_many :parcels
end

class ParcelType < ActiveRecord::Base
  has_many :parcels
end

A: It sounds like the new_record? method is what you're looking for.

new_record?() public
Returns true if this object hasn't been saved yet — that is, a record
  for the object doesn't exist yet; otherwise, returns false.

The following will only execute if the parcel object is indeed a new record:
parcel.parcel_type = ParcelType.find_by_code('FR') if parcel.new_record?

A: What about 'find_or_create'?
I have wanted to use this from a long time, check these links.

*

*Usage:
http://rubyquicktips.com/post/344181578/find-or-create-an-object-in-one-command

*Several attributes:
Rails find_or_create by more than one attribute?

*Extra:
How can I pass multiple attributes to find_or_create_by in Rails 3?


text:
Q: On the direction of steepest ascent of a plane in $\mathbb{R}^3$. Suppose we have a plane  in $\mathbb{R}^3$ whose equation is given by $$z=ax+by,$$
and let  $\textbf{n}(-a,-b,1)$ be a vector normal to this plane.
How can we intuitively explain why the projection of $\textbf{n}$ onto the $xy$-plane, $\textbf{n}'(-a,-b)$, points toward the steepest slope (with respect to a point in the $xy$-plane)?


text:
Q: Laravel - How to add a JOIN and CASE-WHEN using Query Builder or Eloquent? I have the following working, raw SQL statement that I'm finding incredibly tough to convert into PHP, using Laravel/Query Builder/Eloquent.
SELECT aa.filepath,
       aa.filename,
       inst.instrument,
       rl.raga,
       ks.keysig,
       aa.id    AS AAID,
       likes.id AS LikesID
FROM   (audioassets aa)
       INNER JOIN instruments inst
               ON aa.instrument_id = inst.id
       INNER JOIN keysigs ks
               ON aa.keysig_id = ks.id
       LEFT JOIN ragalist rl
              ON aa.raga_id = rl.i
       LEFT JOIN likes
              ON aa.id = likes.audioassets_id
                 AND CASE likes.user_id
                       WHEN 1 THEN true
                       ELSE false
                     END
WHERE  ks.keysig LIKE '%'
       AND inst.instrument LIKE '%';

My Notes:

*

*the issue I'm encountering is with trying to get the CASE-WHEN code to work in Laravel

*the "1" after "WHEN" is meant to be a variable, so it's just for testing right now

*all I'm trying to do is display a list of files on a "dashboard" AND show which files the currently logged in user has "liked" (no one else's likes)
Here is my Laravel Eloquent code:
$query = \App\Audioassets::where('instruments.instrument', 'LIKE', "%$ddinstselected%")
        ->where('keysigs.keysig', 'LIKE', "%$ddkeyselected%")
        ->join('instruments', 'audioassets.instrument_id', '=', 'instruments.id')
        ->leftjoin('ragalist', 'audioassets.raga_id', '=', 'ragalist.id')
        ->join('keysigs', 'audioassets.keysig_id', '=', 'keysigs.id')
        ->leftjoin('likes', 'likes.audioassets_id', '=', 'audioassets.id')
        ->where('likes.user_id', '=', $authuserid)
        ->select('audioassets.filepath', 'audioassets.filename',
'instruments.instrument', 'ragalist.raga', 'keysigs.keysig', 'audioassets.id', 'likes.id as likesid');

This works fine in Laravel but does not incorporate the CASE-WHEN SQL, so all the "likes" are shown for all the users.
Any help would be greatly appreciated!

A: You can try with below query
myFriendsData = DB::table('audioassets as aa')
    ->where('ks.keysig', 'LIKE', '%')
    ->join('instruments', 'audioassets.instrument_id', '=', 'instruments.id')
    ->leftjoin('ragalist', 'audioassets.raga_id', '=', 'ragalist.id')
    ->join('keysigs', 'audioassets.keysig_id', '=', 'keysigs.id')
    ->join('likes ',audioassets.id = likes.audioassets_id, function() {})
    ->whereRaw(
        '(
            CASE
                 WHEN likes.user_id = 1 THEN true ELSE false
            END
        )'
    )
    ->select('audioassets.filepath', 'audioassets.filename','instruments.instrument', 'ragalist.raga', 'keysigs.keysig', 'audioassets.id', 'likes.id as likesid');
    ->get();

A: You can use advance join clauses and DB::raw():
<?php
$query = \App\Audioassets::where('instruments.instrument', 'LIKE', "%$ddinstselected%")
    ->where('keysigs.keysig', 'LIKE', "%$ddkeyselected%")
    ->join('instruments', 'audioassets.instrument_id', '=', 'instruments.id')
    ->leftjoin('ragalist', 'audioassets.raga_id', '=', 'ragalist.id')
    ->join('keysigs', 'audioassets.keysig_id', '=', 'keysigs.id')
    // Use join clause.
    ->leftJoin('likes', function ($join) {
        $join->on('aa.id', '=', 'likes.audioassets_id')
             // CASE WHEN by DB::raw()
             ->on(DB::raw('CASE likes.user_id WHEN 1 THEN true ELSE false'));
    )
    ->where('likes.user_id', '=', $authuserid)
    ->select(
        'audioassets.filepath',
        'audioassets.filename',
        'instruments.instrument',
        'ragalist.raga',
        'keysigs.keysig',
        'audioassets.id',
        'likes.id as likesid'
    );

Join Clause API Reference: Illuminate\Database\Query\JoinClause | Laravel API

A: Thanks for all the help!
I didn't get back around to responding to all the great helpers in this thread, but the answer was a mix of the two answers provided above. Here's the final code that works flawlessly:
$query = \App\Audioassets::where('instruments.instrument', 'LIKE', "%$ddinstselected%")
->where('keysigs.keysig', 'LIKE', "%$ddkeyselected%")
->leftJoin('likes', function ($join) use ($authuserid) {
    $join->on('audioassets.id', '=', 'likes.audioassets_id');
    $join->whereRaw(
        '(
                CASE
                    WHEN likes.user_id=? THEN true ELSE false
                END
        )'
        , [$authuserid]);
    })
->join('instruments', 'audioassets.instrument_id', '=', 'instruments.id')
->leftjoin('ragalist', 'audioassets.raga_id', '=', 'ragalist.id')
->join('keysigs', 'audioassets.keysig_id', '=', 'keysigs.id')
->select('audioassets.filepath', 'audioassets.filename', 'instruments.instrument', 'ragalist.raga', 'keysigs.keysig', 'audioassets.id', 'likes.id as likesid');


text:
Q: Why do Three.js trackball controls freeze if camera.position === controls.target? I'm working on a Three.js scene with Trackball controls in which I programmatically move the camera, and I've noticed that if I set the camera.position and the controls.target to identical values, the controls totally freeze and users can no longer zoom/pan, etc. [codepen]:

// Create the scene and a camera to view it
var scene = new THREE.Scene();

/**
* Camera
**/

// Specify the portion of the scene visiable at any time (in degrees)
var fieldOfView = 75;

// Specify the camera's aspect ratio
var aspectRatio = window.innerWidth / window.innerHeight;

// Specify the near and far clipping planes. Only objects
// between those planes will be rendered in the scene
// (these values help control the number of items rendered
// at any given time)
var nearPlane = 0.1;
var farPlane = 1000;

// Use the values specified above to create a camera
var camera = new THREE.PerspectiveCamera(
  fieldOfView, aspectRatio, nearPlane, farPlane
);

// Finally, set the camera's position in the z-dimension
camera.position.z = 5;

/**
* Renderer
**/

// Create the canvas with a renderer
var renderer = new THREE.WebGLRenderer();

// Specify the size of the canvas
renderer.setSize( window.innerWidth, window.innerHeight );

// Add the canvas to the DOM
document.body.appendChild( renderer.domElement );

/**
* Controls
**/

var controls = new THREE.TrackballControls(camera, renderer.domElement);

setTimeout(function() {
  controls.target = new THREE.Vector3(1, 1, 1)
  camera.position.set(1, 1, 1)
  alert('freeze!')
}, 2500)

/**
* Cube
**/

// Create a cube with width, height, and depth set to 1
var geometry = new THREE.BoxGeometry( 1, 1, 1 );

// Use a simple material with a specified hex color
var material = new THREE.MeshBasicMaterial({ color: 0xffff00 });

// Combine the geometry and material into a mesh
var cube = new THREE.Mesh( geometry, material );

// Add the mesh to our scene
scene.add( cube );

/**
* Render!
**/

function animate() {
requestAnimationFrame( animate );
  renderer.render( scene, camera );
  controls.update();
}
animate();
* {
margin: 0;
padding: 0;
background: black;
*
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>
<script src="https://s3.amazonaws.com/duhaime/blog/tsne-webgl/assets/js/trackball-controls.js"></script>

To resolve the problem, I can set the camera.position and controls.target to slightly different values, but I'd like to understand just why the controls freeze when those values are set identically.
Does anyone know what might cause the controls to freeze in this case? I'd be very grateful for any advice others have on this question.

A: If you look into the source code of THREE.TrackballControls(), for example here, then you'll notice that the internal variable _eye will have coordinates [0, 0, 0] and its length will be 0, when you set position of your camera and control's target to the same coordinates.
This leads to that all cross-products with _eye will produce a vector of [0, 0, 0] with zero length. Actually, all calculations (cross(), .crossVectors(), .setFromAxisAndAngle()) with this variable will have a result of zero vector, or zero length, or zero quaternion. Thus, no pan, no zoom, no rotation.
P.S. Maybe greater specialists will add more information or even correct me, if I'm wrong )


text:
Q: Apache2 reverse proxy https <-> http with digest authentication Sorry, If I posted a repeated question. Didn't find my answer yet.
What I have is:

*

*a webservice on LAN which is only accesable over HTTP ans uses Digest Auth

*another server in LAN which has Apache2 service, that I would like to use as HTTP/HTTPS proxy

I enabled listen to 8888 port and added this config:
<VirtualHost *:8888>
    ServerName local_domain
    ServerAdmin webmaster@localhost
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    ProxyPreserveHost On
    ProxyPass /cam http://local_ip
    ProxyPassReverse /cam http://local_ip
</VirtualHost>

Proxy works, but the authentication doesn't go through. On visit a login popup show. If I enter wrong credentials, the response is ok, 401 Authorization required. But if I enter correct credentials I receive error 400 Bad Request.
What's the issue? I guess something is either missin or incorrect in HTTP header? Should somehow the cookie be forwarded?
Can you give me a hint? :)
thanks!
Mario


text:
Q: ActiveSupport Inflection library for Past Tense in Ruby? Is there a past tense library for ruby, to convert words into the past tense?

A: Past tense of English verbs is a lot more complicated than pluralization. You'll need a lingustic analysis engine and a corresponding database (due to the irregularity of the English language). If you're interested in pursuing this further, you can look at Ruby-WordNet which uses the WordNet lexical database.

A: Check out the 'verbs' ruby gem ( github | rubygems | documentation ).
Type this in the command-line:
gem install verbs

Add this to your gemfile:
gem "verbs", "~> 2.1.0"

And make sure to restart your rails server and exit your rails console before implementing.


text:
Q: spring field service required a bean of type I'm working on Spring over Hibernate project an i'm only in the beginning. I'm trying to have a SpringBootApplication which writes to MySql some Location objects. But every time i'm faceing some error. I did everything from my end refer everything still can't resolve it. Please help me out.
This is my error

APPLICATION FAILED TO START
***************************

Description:

Field service in com.project.abhishek.location.controller.LocationController
required a bean of type'com.project.abhishek.location.service.LocationService' that could not be
found.

Action:

Consider defining a bean of type'com.project.abhishek.location.service.LocationService' in your configuration.

Application class
@SpringBootApplication
@ComponentScan(basePackages= {"com.project.abhishek.location.controller"})
@EntityScan(value ="com.project.abhishek.location.entity")
@EnableJpaRepositories(basePackages = {"com.project.abhishek.location.repos"})

public class StudentApplication {

public static void main(String[] args) {
    SpringApplication.run(StudentApplication.class, args);
}}

Controller
@Controller
public class LocationController {

@Autowired
private LocationService service;

@RequestMapping("/saveLoc")
public String saveLocation(@ModelAttribute("location") Location location, ModelMap modelMap) {
    Location locationSaved = getService().saveLocation(location);

    String msg = "Location save with id:" +locationSaved.getId();
    modelMap.addAttribute("msg", msg);
    return "createLocation";
}

public LocationService getService() {
    return service;
}

public void setService(LocationService service) {
    this.service = service;
}

Service Class
@Service
public class LocationServiceImpl implements LocationService {

@Autowired
private LocationRepos locationRepos;

@Override
public Location saveLocation(Location location) {

    return locationRepos.save(location);
}

@Override
public Location updateLocation(Location location) {
    return locationRepos.save(location);
}

@Override
public void deleteLocation(Location location) {
    locationRepos.delete(location);
}

@Override
public Location getLocation(int id) {
    Optional<Location> optional = locationRepos.findById(id);
    Location location = optional.get();
    return location;
}

@Override
public List<Location> getAllLocation() {
    return locationRepos.findAll();
}

public LocationRepos getLocationRepos() {
    return locationRepos;
}

public void setLocationRepos(LocationRepos locationRepos) {
    this.locationRepos = locationRepos;
}

}
Entity
@Entity
public class Location {

@Id
private int id;
private String code;
private String name;
private String type;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

@Override
public String toString() {
    return "Location [id=" + id + ", code=" + code + ", name=" + name + ", type=" + type + "]";
}

My packages structure are
com.project.abhishek.location---application classs
com.project.abhishek.location.controller---controller class
com.project.abhishek.location.entity---entity class
com.project.abhishek.location.repos---repository class
com.project.abhishek.location.service---service class

A: Just include com.project.abhishek.location.service in your @ComponentScan or simply delete @ComponentScan(this way it will scan spring boot application package com.project.abhishek.location and all packages below it).
By defining @ComponentScan(basePackages= {"com.project.abhishek.location.controller"}) you overrode default component scan path com.project.abhishek.location and told spring to only scan com.project.abhishek.location.controller and packages below it, so it didn't scan com.project.abhishek.location.service.
Check this https://dzone.com/articles/spring-spring-boot-and-component-scan for more details on defining @ComponentScan. This is similar to your situation:

However, let's say one of the components is defined in package
com.in28minutes.springboot.somethingelse
In this case, you would need to add the new package into Component
Scan.
You have two options:
Define @ComponentScan("com.in28minutes.springboot")  This would scan
the entire parent tree of com.in28minutes.springboot.
Or define two
specific Component Scans by using an array.
@ComponentScan({"com.in28minutes.springboot.basics.springbootin10steps","com.in28minutes.springboot.somethingelse"})

A: Nothing is required in Spring Boot, it's already there, @SpringBootApplication is sufficient.
Just make below changes and you will be good to go.
Main Application Class:
@SpringBootApplication
public class StudentApplication {

public static void main(String[] args) {
    SpringApplication.run(StudentApplication.class, args);
}}

Controller Class: @Autowired is sufficient load your dependency, don't need to set, just see change you need to make in @Service notation where you need to name the interface name so dependency name can be locationService when you auto wired.
@RestController
public class LocationController {

@Autowired
private LocationService service;

@RequestMapping("/saveLoc")
public String saveLocation(@ModelAttribute("location") Location location, ModelMap modelMap) {
    Location locationSaved = getService().saveLocation(location);

    String msg = "Location save with id:" +locationSaved.getId();
    modelMap.addAttribute("msg", msg);
    return "createLocation";
}

Change in Service Class:
@Service("locationService)
public class LocationServiceImpl implements LocationService {


text:
Q: Unable to create Azure search service through terraform and AZ CLI with Standard3 High density SKU but getting the error I am trying to create an azure search service through terraform but it is not supported through standard3 High Density SKU. Subsequently, I am trying to create it with AZ CLI but getting the error as"ERROR: Unrecognized arguments: --hosting-mode highDensity". How to resolve this error and create a search service with S3HD SKU?
I Passed the AZ CLI command to create an Azure Search Service with S3HD Sku but it failed saying hosting mode is an unsupported argument, Also terraform does not support High Density SKU.

A: I Tried to reproduce the same in my environment to create an Azure Search Service with S3HD SKU Azure CLI:
Follow the below steps to create Azure Search Service using CLI.
If you select Azure Search Service SKU S3HD, it will show as Standard3 High density as below.

Azure CLI Commands
#Sing into Azure Subscription

az login

#Create Azure Search service with SKU S3HD

az search service create --name  venkatsearch --resource-group myResourceGroup --sku Standard3 --hosting-mode highDensity

Result:

az search service list --resource-group myResourceGroup

Result:

Once ran the above commands Azure Search Service with S3HD SKU are created successfully as below.

Refer the Ms Doc more about Azure Search Service using CLI.


text:
Q: Arduino String concatenation Serial.println() doesn't work I'm trying to read pass data of some text to server by first sending whole text to a function which finds its length and uses AT+CIPSEND=length comes here to open a TCP port later on. Everything was working fine before I add some additional info to my response data. I'm suspecting of char limits but couldn't find a reason even though debugging few hours.
Serial.println() doesn't show any output and string concatenation isn't healthy as it seems. The problem is that text is not being passed therefore CIPSEND doesn't work. Corresponding code section and its output shown below.
void sendHTTPResponse(int connectionId, String content) {
  Serial.println("SENDHTTPRESPONSE1: " + content);

  // build HTTP response
  String httpResponse;
  String httpHeader;
  // HTTP Header
  httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
  httpHeader += "Content-Length: ";
  httpHeader += content.length();
  httpHeader += "\r\n";
  httpHeader += "Connection: close\r\n\r\n";
  Serial.println("SENDHTTPRESPONSE2: " + httpHeader);
  httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
  Serial.println("HTTPRESPONSE3: " + httpResponse);
  sendCIPData(connectionId, httpResponse);
}

And serial monitor output. HTTPRESPONSE3 seems to be somehow empty?
SENDHTTPRESPONSE1: {"data":[{"id":"100"}]}{"data":[{"id":"100"}]}{"data":[{"id":"100"}]}{"data":[{"id":"100"}]}
SENDHTTPRESPONSE2: HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 92
Connection: close

DATA LENGTH:

======================================================
Executing command: AT+CIPSEND=0,0

HTTP/1.1
CoAT+CIPSEND=0,0

Thanks in advance.

A: This answer doesn't actually solve your problem.
To my excuse, I don't have the Arduino with me, so I can't reproduce your issue. :)
However, since you are into "string concatenation" style, I think you might benefit from using the source code posted here (provided that your project has room for it).
It's a small c++-style wrapper around the print library that I wrote two years ago. It will let you write stuff like this:
io::cout << "This is a beautiful message!\n"
         << io::setprecision(3) << some_float << "\n"
         << io::setbase(BIN) << some_int << io::endl;

By default the library provides io::cout which prints through usual Serial. You can hook this library up with any object implementing the Print interface, e.g. Serial and Software Serial.
The difference with what you are doing now is that by using the "<<" you'll get the same clean code-style as with "+", but you won't need to create a temporary String. Everything is immediately laid off to the output buffer to be printed out. As a result, you shouldn't incur in the same issue that you are experiencing right now. In other words, this does what @Olaf suggested in the comments, but in a fancy way. ;)
Note: You probably need to fix the includes in the test-iocout.ino file to fit your project.

*

*cout.h
#ifndef __COUT_H__
#define __COUT_H__

#include <Arduino.h>

namespace io {

/**
 * marker to end a message
 * (prints newline)
 */
struct Endl {};
const Endl endl = Endl();

/**
 * marker to modify way in which numbers are
 * printed on output stream
 */
struct setbase {
    uint8_t base;
    setbase(uint8_t v = DEC): base(v) {}
};

/**
 * marker to modify number of digits of doubles
 * printed on output stream
 */
struct setprecision {
    uint8_t precision;
    setprecision(uint8_t v = 2): precision(v) {}
};

/**
 * class out
 *
 * Provides a C++-like interface for printing stuff on
 * an output Stream, e.g. Serial, SoftwareSerial objects
 * Assumes a separated Stream initialization handling
 */
class out {
public:

    out(Print& print = Serial, uint8_t fmt = DEC, uint8_t dgt = 2);
    out(const out& other);
    out& operator =(const out& other);
    virtual ~out();

    inline out& operator<<(const String& msg)
    {
        __print.print(msg);
        return *this;
    };

    inline out& operator<<(const char msg[])
    {
        __print.print(msg);
        return *this;
    };

    inline out& operator<<(char c)
    {
        __print.print(c);
        return *this;
    };

    inline out& operator<<(unsigned char uc)
    {
        __print.print(uc, __base);
        return *this;
    };

    inline out& operator<<(int n)
    {
        __print.print(n, __base);
        return *this;
    };

    inline out& operator<<(unsigned int un)
    {
        __print.print(un, __base);
        return *this;
    };

    inline out& operator<<(long l)
    {
        __print.print(l, __base);
        return *this;
    };

    inline out& operator<<(unsigned long ul)
    {
        __print.print(ul, __base);
        return *this;
    };

    inline out& operator<<(double d)
    {
        __print.print(d, __precision);
        return *this;
    };

    inline out& operator<<(const __FlashStringHelper *fsh)
    {
        __print.print(fsh);
        return *this;
    };

    inline out& operator<<(const Printable& pr)
    {
        __print.print(pr);
        return *this;
    };

    inline out& operator<<(const Endl& el)
    {
        __print.println("");
        __base = DEC;
        __precision = 2;
        return *this;
    };

    inline out& operator<<(const setbase& p)
    {
        __base = p.base;
        return *this;
    };

    inline out& operator<<(const setprecision& p)
    {
        __precision = p.precision;
        return *this;
    };

    inline int getWriteError()
    {
        return __print.getWriteError();
    };

    inline void clearWriteError()
    {
        __print.clearWriteError();
    };

private:
    Print& __print;
    ///< output stream, must be separately initalized
    uint8_t __base;
    ///< base with which print numerical data
    uint8_t __precision;
    ///< number of fractional digits of float/double values
};

/**
 * Global io::cout object
 */
extern out cout;

} /* namespace io */

#endif

*cout.cpp
#include "cout.h"

namespace io {

out cout;

out::out(Print& print, uint8_t fmt, uint8_t dgt):
    __print(print), __base(fmt),
    __precision(dgt)
{
    // nothing to do
};

out::out(const out& other):
    __print(other.__print),
    __base(other.__base),
    __precision(other.__precision)
{
    // nothing to do
};

out& out::operator =(const out& other)
{
    if (this != &other) {
        __print = other.__print;
        __base = other.__base;
        __precision = other.__precision;
    }
    return *this;
};

out::~out()
{
    // nothing to do
};

} /* namespace io */

*test-iocout.ino
#include <Arduino.h>
#include "src/cout.h"

/******************************************************************************/
/*** PINS & GLOBALS                                                         ***/
/******************************************************************************/

const uint32_t SERIAL_BAUDRATE = 4800;

/******************************************************************************/
/*** RESOURCES                                                              ***/
/******************************************************************************/

/******************************************************************************/
/*** MAIN                                                                   ***/
/******************************************************************************/

/**
 * setup:
 * sets up the resources used within the arduino
 */
void setup()
{
    /* Initialize serial */
    Serial.begin(SERIAL_BAUDRATE);
    while (!Serial)
    {
        /* Needed by Arduino Leonardo */
    }

    /* new c++-like access to serial! */
    io::cout << "##### Arduino Station #####\n\n"
            << "- io::cout test 1.0" << io::endl;
}

/**
 * loop:
 *
 */
void loop()
{
    /* compute deltaTime */
    uint32_t curr_time = millis();
    static uint32_t start_time = curr_time; // note: initialized once!
    uint32_t deltaTime = curr_time - start_time;
    start_time = curr_time;

    io::cout << "\n> Last loop duration was: ";

    io::cout << io::setprecision(3)
            << deltaTime/1000.0f
            << " s." << io::endl;

    io::cout << "> 1025 in binary is: "
            << io::setbase(BIN)
            << 1025 << io::endl;

    delay(10000);
}


text:
Q: Run commands on python I'm trying to create a script to automatically compile apache. Sadly on my work I need to compile each an every apache I install.
So, I came up with this little code to run a command:
print("Source location %s" % source_location)
print("Configure command %s" % configure_command)
config = subprocess.Popen(configure_command, stdout=subprocess.PIPE, shell=True)
(output, err) = config.communicate()
config_status = config.wait()
print("Return configure status = %s" % config_status)

At the moment I'm stuck on the configure part.
Basically the configure line is like this:

/Volumes/nirvash/script/workarea/httpd-2.2.31/configure --prefix=/tmp/apache-2.2.31-instance1 --enable-mods-shared=all --enable-proxy --enable-proxy-connect --enable-proxy-ftp --enable-proxy-http --enable-deflate --enable-cache --enable-disk-cache --enable-mem-cache --enable-file-cache --with-included-apr  --with-mpm=worker

The problem is that when the apache is compiling, it creates (mkdir) an "include" directory inside the httpd-2.2.31. But in this case the directory is created on the bin directory of my script.
So the directory is created were the script is running.
Is it possible to fix this? Is there any way to run the configure in the directory that is compiling?

A: You can use os.chdir to change the current directory of your script to be the same as the directory which contains the source code.
os.chdir(source_location)

Alternately, you could change configure_command to first change directories using cd prior to running configure.
configure_command = 'cd "%s" && %s' % (source_location, configure_command)


text:
Q: How to change the background of a parent DIV based on the checked state of an INPUT I'm using checkboxes based on Brad Bodine's examples here.  I'm thrilled with the abilities his examples gave me, but I do have one question.
I'm using slideThree (see the CSS below).  It works like a charm, but I would like to change the background color of the parent DIV based on the position of the slider.  I thought that maybe one of the two examples below would do it:
.slideThree input[type=checkbox]:checked { background: green; }
.slideThree input[type=checkbox]:checked + div { background: green; }

But neither one worked.  Is it possible to change the background based on the selected state of the INPUT?
HTML

<input type="checkbox" value="None" id="test" name="check" checked />

CSS
/* .slideThree */
.slideThree {
  width: 80px;
  height: 26px;
  background: #333;
  margin: 20px auto;
  position: relative;
  border-radius: 50px;
  box-shadow: inset 0px 1px 1px rgba(0, 0, 0, 0.5), 0px 1px 0px rgba(255, 255, 255, 0.2);
}
.slideThree:after {
  content: 'OFF';
  color: #000;
  position: absolute;
  right: 10px;
  z-index: 0;
  font: 12px/26px Arial, sans-serif;
  font-weight: bold;
  text-shadow: 1px 1px 0px rgba(255, 255, 255, 0.15);
}
.slideThree:before {
  content: 'ON';
  color: #27ae60;
  position: absolute;
  left: 10px;
  z-index: 0;
  font: 12px/26px Arial, sans-serif;
  font-weight: bold;
}
.slideThree label {
  display: block;
  width: 34px;
  height: 20px;
  cursor: pointer;
  position: absolute;
  top: 3px;
  left: 3px;
  z-index: 1;
  background: #fcfff4;
  background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
  background: linear-gradient(to bottom, #fcfff4 0%, #dfe5d7 40%, #b3bead  100%);
  border-radius: 50px;
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;
  box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.3);
}
.slideThree input[type=checkbox] {
  visibility: hidden;
}
.slideThree input[type=checkbox]:checked + label {
  left: 43px;
}

/* end .slideThree */

A: My thanks to @LGSon.  His solution was perfect.  Here's the working modification to the HTML and addition to the CSS.  I had to add the border and box-shadow elements because Firefox didn't like my pushing the SPAN behind everything, so the SPAN was coming up square, etc.

<input type="checkbox" value="None" id="test" name="check" checked />

And the CSS...
.slideThree span{
    display: block;
    position: absolute;
    width: 50px;
    height: 16px;
    background: red;
    z-index: 0;
    top: 0px;
    left: 0px;
    border-radius: 8px;
    box-shadow: inset 0px 1px 1px rgba(0, 0, 0, 0.5), 0px 1px 0px rgba(255, 255, 255, 0.2);
}
.slideThree input[type=checkbox]:checked ~ span { background: green; }


text:
Q: Extract Image from RSS Feed in XML I am trying to display my Wordpress feed directly into my external magento site. I am using feedburner to achieve this result. So far i have been able to display the blog title & link. To improve the look I also want to display the Blog right next to the title.
Here is the php code i am using to parse the XML Feed for displaying the blog titles with link
<?php $channel = new Zend_Feed_Rss('http://feeds.feedburner.com/golfoy/pxce'); ?>

                    <?php foreach ($channel as $item): ?>

<a href="<?php echo $item->link; ?>"><?php echo $item->description; ?>

                    <?php endforeach; ?>

Below mentioned is the XML code for a single feed item. You can find the complete feed at this URL
 <item>
    <title>The grey-haired major winners.</title>
    <link>http://blog.golfoy.com/the-grey-haired-major-winners/</link>
    <pubDate>Mon, 29 Aug 2016 08:24:53 +0000</pubDate>
    <guid isPermaLink="false">http://blog.golfoy.com/?p=980</guid>

    <description>
        <![CDATA[
You are never too old to hit the greens and play a round of golf. In the history of men’s major championships, no golfer older than 48 (and just one golfer older than 46) has won. Have a look at the list of oldest men to have won a major: 1.Ben Hogan: The legend won […]]]>
    </description>
    <content:encoded>
    ....
    </content:encoded>
    </item>

I am trying to catch the entire img tag or just the "src" which is inside the description tag of a Feed Item. What would be the best practice to do this?

A: you select description in xml
ande send to get_images .

step 1

include simple_html_dom.php
download
and change define ( URL_IMAGE , PATH_UPLOAD ) in function .

step 2

function get_images($html)
require_once('simple_html_dom.php');

function get_images($html)
    {
        if (!empty($html))
        {

            $post_dom   = str_get_html($html);
            $first_img  = $post_dom->find('img');

            $image_list = array();
            foreach ($first_img as $image)
            {
                if(isset($image->src) AND $image->src != '')
                {
                    $image = $image->src;

                    $filetype = strtolower(substr(strrchr($image,'.'),1));
                    if (in_array($filetype,array('jpg','jpeg','png','gif')))
                    {
                        $filename = 'image_'.time().'_'.rand(0000000,99999999).'.'.$filetype;
                        $up = file_put_contents(PATH_UPLOAD.$filename,file_get_contents($image));
                        $size = filesize(PATH_UPLOAD.$filename);
                        list($width) = getimagesize(PATH_UPLOAD.$filename);

                        if(intval($size) >= 1024 AND $width >= 40)
                        {
                            $filename = URL_IMAGE.$filename;
                        }
                        else
                        {
                            unlink(PATH_UPLOAD.$filename);
                            $filename = '';
                        }

                        array_push($image_list, "$image|$filename");
                    }
                }
            }

            return $image_list;
        }
        else
        {
            return array();
        }
    }

step 3

select description
$html = $feed->item->description;
print_r(get_images($html));


text:
Q: Flutter SVG rendering I tried adding an image with a SVG source to my flutter application.
new AssetImage("assets/images/candle.svg"))
But I didn't get any visual feedback.
How can I render an SVG picture in Flutter?

A: Flutter does not currently support SVG. Follow issue 1831 for updates.
If you absolutely need vector drawing you can see the Flutter Logo widget as an example of how to draw using the Canvas API, or rasterize your image on the native side and pass it to Flutter as a bitmap, but for now your best bet is probably to embed high-resolution rasterized asset images.

A: step 1. add dependency in your pubspec.yaml
dependencies:
     flutter_svg: any

the Advantage of version any is you can use in any SDK version
but dependencies version is most important so add suitable version for your dependency.
step 2. import the flutter svg package in your app
 import 'package:flutter_svg/flutter_svg.dart';

step 3. just use like below
 SvgPicture.asset(
    'assets/images/bm-icon1.svg',
     width: 18.0,
     height: 18.0,
  ),

A: You can use this library for rendering SVG Images - https://pub.dev/packages/flutter_svg
Example -
Container(
    child: SvgPicture.asset("assets/images/yourImage.svg")
)

A: Of possible interest:  There's a newer Flutter SVG library called jovial_svg.  I wrote it to handle a more robust subset of SVG than what I was able to find on pub.dev at the time.  While I was at it, I also made a binary format that SVG assets can be compiled to.  It's a little more compact, and about 10x faster to read, so it's a good choice for assets you package with your application.
The library is at https://pub.dev/packages/jovial_svg

A: I solved similar problem by converting the svg images to ttf at fluttericon.com.
These are the steps involved.
Keep all your svg files in a folder.
Upload all of them to fluttericon by using the uploader there.
You can select all of them and drag and drop at the spot.
Give your icons a dart class name at the top: like, Svgicons
Select all your icons and press Download.
It will download a zip file with a dart file and fonts folder which contains Svgicons.ttf.
copy the fonts folder to your project folder and refer to it as an asset in pubspec.yaml.
fonts:
  - family: Svgicons
    fonts:
      - asset: fonts/Svgicons.ttf

import the svgicons_icons.dart where you are going to use the images.
Sample:
import '../svgicons_icons.dart';

import 'social_media.dart';

class SocialMediaRepository {
  List<SocialMedia> getSocialMedia = [
    SocialMedia(id: 1, title: "Facebook", iconAsset:Svgicons.facebook, isFavorite: false),
    SocialMedia(id: 2, title: "Instagram", iconAsset: Svgicons.instagram, isFavorite: false),
    SocialMedia(id: 3, title: "LinkedIn", iconAsset: Svgicons.linkedin, isFavorite: false),
    ....

Here iconAsset is of type IconData which used to be a String referring to the svg image originally.
Display the ttf by using
    ...
    Icon(item.iconAsset),
    SizedBox(width: 10),
    Text(item.title),
  ],
),

where item is the object containing IconData.
Now you can remove the reference to svg images from the project.

A: Developers from the Flutter community created a lib to handle svg files. We can use it as
new SvgPicture.asset(
  'assets/images/candle.svg',
  height: 20.0,
  width: 20.0,
  allowDrawingOutsideViewBox: true,
),

I found a small example of SVG implementation here.

A: You can use flare to create animations and just import .flr as an asset
import 'package:flare_flutter/flare_actor.dart';
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new FlareActor("assets/Filip.flr", alignment:Alignment.center, fit:BoxFit.contain, animation:"idle");
  }
}

visit flare_flutter https://pub.dev/packages/flare_flutter

A:
flutter support special type of svg
if have style tag then not load svg image in flutter
flutter support inline styling  in svg

A: The work around for now is use fonts
https://icomoon.io/
  fonts:
   - family: icomoon
     fonts:
       - asset: assets/fonts/icomoon.ttf

Useage
  static const IconData TabBarHome= const IconData(0xe906, fontFamily: 'icomoon');
  static const IconData TabBarExplore= const IconData(0xe902, fontFamily: 'icomoon');

Replace the ### eg (906)

A: You can follow the below steps
 - visit http://fluttericon.com
 - upload your SVG icons
 - click on download button
 - you will get two files
 1. iconname.dart 2. iconname.ttf font file
- use this file in flutter & import iconname.dart

A: Fonts are a great option for a lot of cases.
I've been working on a library to render SVGs on a canvas, available here:
https://github.com/dnfield/flutter_svg
The API as of right now would look something like
new SvgPicture.asset('asset_name.svg')

to render asset_name.svg (sized to its parent, e.g. a SizedBox).  You can also specify a color and blendMode for tinting the asset..
It's now available on pub and works with a minimum of Flutter version 0.3.6.  It handles a bunch of cases but not everything - see the GitHub repo for updates and to file issues.
The original GitHub issue referenced by Colin Jackson is really not meant to be primarily focused on SVG in Flutter.  I opened another issue here for that: https://github.com/flutter/flutter/issues/15501

A: Svg in flutter https://pub.dev/packages/flutter_svg

*

*add package in pubspec.yaml
dependencies:
flutter_svg: any
assets:
-assets/images/

*to insert svg.
SvgPicture.asset('assets/images/password-icon.svg',
width: 24, height: 29.2),