text:
Q: How can I sort List[Int] objects? What I want to do is sort List objects in Scala, not sort the elements in the list. For example If I have two lists of Ints:
val l1 = List(1, 2, 3, 7)
val l2 = List(1, 2, 3, 4, 10)

I want to be able to put them in order where l1 > l2.
I have created a case class that does what I need it to but the problem is that when I use it none of my other methods work. Do I need to implement all the other methods in the class i.e. flatten, sortWith etc.?
My class code looks like this:
class ItemSet(itemSet: List[Int]) extends Ordered[ItemSet] {

  val iSet: List[Int] = itemSet

  def compare(that: ItemSet) = {

    val thisSize = this.iSet.size
    val thatSize = that.iSet.size
    val hint = List(thisSize, thatSize).min
    var result = 0
    var loop = 0

    val ths = this.iSet.toArray
    val tht = that.iSet.toArray

    while (loop < hint && result == 0) {
      result = ths(loop).compare(tht(loop))
      loop += 1
    }
    if (loop == hint && result == 0 && thisSize != thatSize) {
      thisSize.compare(thatSize)
    } else
      result
  }

}

Now if I create an Array of ItemSets I can sort it:
val is1 = new ItemSet(List(1, 2, 5, 8))
val is2 = new ItemSet(List(1, 2, 5, 6))
val is3 = new ItemSet(List(1, 2, 3, 7, 10))

Array(is1, is2, is3).sorted.foreach(i => println(i.iSet))

scala> List(1, 2, 3, 7, 10)
List(1, 2, 5, 6)
List(1, 2, 5, 8)

The two methods that are giving me problems are:
def itemFrequencies(transDB: Array[ItemSet]): Map[Int, Int] = transDB.flatten.groupBy(x => x).mapValues(_.size)

The error I get is:

Expression of type Map[Nothing, Int] doesn't conform to expected type Map[Int, Int]

And for this one:
def sortListAscFreq(transDB: Array[ItemSet], itemFreq: Map[Int, Int]): Array[List[Int]] = {
  for (l <- transDB) yield
    l.sortWith(itemFreq(_) < itemFreq(_))
}

I get:

Cannot resolve symbol sortWith.

Is there a way I can just extend List[Int] so that I can sort a collection of lists without loosing the functionality of other methods?

A: The standard library provides a lexicographic ordering for collections of ordered things. You can put it into scope and you're done:
scala> import scala.math.Ordering.Implicits._
import scala.math.Ordering.Implicits._

scala> val is1 = List(1, 2, 5, 8)
is1: List[Int] = List(1, 2, 5, 8)

scala> val is2 = List(1, 2, 5, 6)
is2: List[Int] = List(1, 2, 5, 6)

scala> val is3 = List(1, 2, 3, 7, 10)
is3: List[Int] = List(1, 2, 3, 7, 10)

scala> Array(is1, is2, is3).sorted foreach println
List(1, 2, 3, 7, 10)
List(1, 2, 5, 6)
List(1, 2, 5, 8)

The Ordering type class is often more convenient than Ordered in Scala—it allows you to specify how some existing type should be ordered without having to change its code or create a proxy class that extends Ordered[Whatever], which as you've seen can get messy very quickly.


text:
Q: how to import a react 3rd party library into the project (the library uses module.exports but in react we use import syntax) how to import a react 3rd party library into the project (the library uses module.exports but in react we use import syntax)
Library which i want to use inside my react project is mentioned below : -

*

*https://www.npmjs.com/package/systeminformation

*https://www.npmjs.com/package/os
Can i please get some help !!

A: Libraries are transpiled so you can easily use them.
just install them with npm install
and then import/require it
const si = require('systeminformation');

// promises style - new since version 3
si.cpu()
  .then(data => console.log(data))
  .catch(error => console.error(error));

all is here in readme https://github.com/sebhildebrandt/systeminformation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert a string array with numpy I am scraping some data from a website. I have names, and prices lists from different pages. I want to stack two lists first, then an array contains all data in rows for each page. However, np.insert gives the following error:

'ValueError: could not convert string to float'.

Here is the code
import numpy as np

finallist = []
...
for c in range(0, 10)
    narr = np.array(names)
    parr = np.array(prices)

    nparr = np.array(np.column_stack((narr, parr)))

    finallist = np.insert(finallist, c, nparr)

What I want to accomplish is the following.
finallist =  [[[name1, price1], [name2, price3], ...] # from page one
               [name1, price1], [name2, price3], ...] # from page two
               ...                                  ] # from page x

So that I will be able reach all data.


text:
Q: Updating size of fancybox with iFrame content everytime the content changes I'm using fancybox 1.3.1. Now I load an iFrame into the Fancybox which works fine. In the iFrame the user goes from step to step. At some step the height of the content changes. How can I update the height of the iFrame?
I tried jQuery postMessage:
<script type="text/javascript" src="fileadmin/templates/lib/jquery.ba-postmessage.min.js"></script>
<script type="text/javascript">
    $("#fancylink").fancybox({
        'type'    :    'iframe',
        'width' : 700,
        'height' : 450,
        'autoScale' : false
    });
</script>

<script type="text/javascript">
// set inital height
var if_height = 450;

$(document).ready(function() {
    if($.receiveMessage){
        $.receiveMessage(function(e){

            // Get the height from the passsed data.
            var h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ));
            if ( !isNaN( h ) && h > 0 && h !== if_height ) {
                // Height has changed, update the iframe.
                // checking min and max height
                h=(h<450)?450:h;
                $("#fancybox-frame").height( if_height = h );
            }
        });
    }
});
</script>

I get two height styles with overflow:hidden; as can be seen here:
<div id="fancybox-inner" style="top: 10px; left: 10px; width: 700px; height: 450px; overflow: hidden;">
<iframe id="fancybox-frame" scrolling="auto" frameborder="0" src="https://www.externaldomain.com#http://www.internaldomain.com/page" hspace="0" name="fancybox-frame1347984635401" style="height: 1180px;">

As result there is more content available but the user cannot scroll. So doing nothing is better than this.
I also tried it with
$('#element').fancybox({
    'onComplete' : function(){
        $.fancybox.resize();
    }
});

but here nothing happens (no resize). I think this resize is only at the first load of the fancybox. But also on the first time nothing happens.
Is there a solution to my problem or can I only use a fixed size?
Solution:
So I added the following code and it seems to work as desired:
$("#fancybox-inner").height( h );
$("#fancybox-wrap").height( h+20 );
$.fancybox.center();

I will test a little bit, but I think this can work. What happens if the fancybox is higher than the current page? Will the page increase in size?

A: You can do something like below.
 function updateMyFancyBox() {
    $.fancybox.wrap.height($.fancybox.inner.height() + $('div#yourContentDiv').height());//increase fancybox height by adding your div height.
    $.fancybox.update();//Fancybox will re-size according to new size, if it exceeds size limit, it will show scroll bar.
 }


text:
Q: If $S_1, S_2$, and $S_1 \cup S_2$ are $\sigma$-fields, then either $S_1 \subset S_2$ or $S_2 \subset S_1$ I wanted to show that

If $S_1, S_2$, and $S_1 \cup S_2$ are $\sigma$-fields, then either $S_1 \subset S_2$ or $S_2 \subset S_1$.

Here is what I've tried:
Assume the opposite: $S_1 \not\subset S_2$ and $S_2 \not\subset S_1$. Therefore $\exists A \in S_1: A \not\in S_2$ and $\exists B \in S_2: B \not\in S_1$. Consequently $A, B \in S_1 \cup S_2$ but $S_1 \cup S_2$ is a $\sigma$-field so $A \cup B \in S_1 \cup S_2$. Then either $A \cup B \in S_1$ or $A \cup B \in S_2$. Without loss of generality, assume the former. And at this point I wanted to show a contradiction by arriving at $B \in S_1$. Yet it doesn't seem to work.
Any hints are hugely appreciated.

A: Note that because both $A$ and $B$ belongs to $S_1\cup S_2$, then $A\cup B, A\cap B$ and $A\bigtriangleup B=(A\setminus B)\cup (B\setminus A)$ are all in $S_1\cup S_2$ (by properties of a $\sigma$-field.
Then, by the Pigeonhole principle, at least two of these sets should belong to either $S_1$ or $S_2$. Without loss of generality, assume they belong to $S_1$ and note that
$$
A\cup B= (A\bigtriangleup B)\cup (A\cap B)\\
A\bigtriangleup B= (A\cup B) \setminus (A\cap B)\\
A\cap B= (A\cup B)\setminus (A\bigtriangleup B)
$$
Then, we have that the three sets belong to $S_1$.
Finally, note that $B\setminus A= (A\cup B)\setminus A$ and that $B= (B\cap A)\cup (B\setminus A)$


text:
Q: Window.open opening tab instead of popup in Opera? I'm simply opening a popup from JavaScript with the settings you can see in the code. Works fine in Firefox. In Opera it's opening it in a new tab instead. Why?
Here's a JSFiddle:
http://jsfiddle.net/hafWs/3/
The number of parameters doesn't seem to make a difference. Either work in Firefox and IE8. (Don't have IE9 or Chrome to test right now.)
I tried googling... can't find anything. I don't even see anything here that mentions it, yet it's clearly working in their examples: http://www.quirksmode.org/js/popup.html
Thank you for any help.

A: This is controlled by the browser itself (preferences) and cannot be changed from JavaScript.
NOTE: I've seen some posts that say you can determine whether the window opens in a tab or as a new window based on the parameters that you pass the window.open function. I have never seen this work consistently.

A: There is problem with spaces in options param:
window.showPopup = function(){
    window.open(
        'http://placekitten.com/600/500',
        'thePopup',
        'width=600,height=500' /* <------- Look, no spaces and works */
    );
}

It is still a tab, but with different dimensions. So, it looks kinda as popup.


text:
Q: using value of boolean to display information I have a bool that could either be true or false and display different messages depending on the bool value using the ? and :
I tried below
Message = if(isPGUID = true) "ParentGuide" else "Guid is not the parent Guid",

A: You probably mean:
Message = isPGUID ? "ParentGuide" : "Guid is not the parent Guid";

Though your question could use  a bit of clarification.


text:
Q: Asp.net : How to write a regular expression that validates strings of two lengths? I need to validate strings(only digits) that have the length of 7 OR 10 . ValidationExpression="^\d{10}$"
this piece of code accept strings with length of 10 digits, but i also want to include strings length of 7 digits.
if i use ValidationExpression="^\d{7,10}$" , i can enter digits with the length of 7 or 10,   but i also can enter 8 and 9 digits witch is not acceptable.

A: Use an OR: "^(\d{7}|\d{10})$"


text:
Q: What this Unique ID exactly represents? While executing the below mentioned powershell script, I will get the unique ID of the Azure Virtual Machine. I have a doubt with that. Even when I execute this script in the physical machine, I get an ID. I want to know,
what that ID exactly represents?
Is this ID unique for every machine?
Powershell Script:

$computerSystemProduct = Get-WmiObject -class
  Win32_ComputerSystemProduct -namespace root\CIMV2
'BIOS GUID: "{0}"' -f $computerSystemProduct.UUID

A: The ID represents the System Information as a GUID.
This GUID is unique - for every machine.
See for reference
https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-computersystemproduct

A: It's unique for every machine, and you can check the details here:

(Universally Unique ID) A 128-bit unique number generated by various
  algorithms to identify hardware or software. Because the number is so
  large, for all intents and purposes no two UUIDs can be the same. The
  reason for UUIDs is that they can be combined from disparate sources
  into one database without fear of duplication.


text:
Q: How to use a where query to check a value inside a JSON field in rails I have a model named Notification with a JSON field along with other fields.
I am listing all notifications using @notification
@notifications = current_user.notifications

@notifications carry an array of notifications of that user.
I'm now implementing a search feature in notification. We have
params[:search] = abc@gmail.com

In our method we have a params of searched email id
notification_user_id = User.find_by(email: params[:search]).id

Here we are finding the corresponding user with the email id and taking its id to notification_user_id which is used to find the notifications
Now I want to refactor the @notifications with a 'where query' like
@notifications = current_user.notifications.where(user_id: notification_user_id)

For reference, fields in notification table:
current_user.notification.last

Here taking last notification of current_user for reference purpose
#<Notification:0x00007f3a9488b4b0
 id: 6,
 recipient_type: "User",
 recipient_id: 1,
 type: "TicketNotification",
 params:
  {:ticket=>
    #<Ticket:0x00007f3a94898bb0
     id: 11,
     user_id: 2,
     complaint: "complaint 1",
     complaint_type: "suggestion",
     created_at: Mon, 17 Oct 2022 12:30:20.755854000 UTC +00:00,
     updated_at: Mon, 17 Oct 2022 12:30:20.755854000 UTC +00:00,
     status: "pending",
     deleted_at: nil>}

Requirement:
I need a where query which return all notifications where user_id: notification_user_id. Remember that field params is a JSON field, inside that JSON field we have user id.
So how to get all data by checking a field inside a JSON field?

A: You will have to use LIKE query
@notifications = current_user.notifications.where("params LIKE ?", "%user\_id: #{notification_user_id}%")


text:
Q: Seaborn and plotly violin plots in Jupyter Notebook kill kernel I am trying to generate a violin plot using seaborn 0.7.1 in a Jupyter notebook. Boxplot works fine for the same data, but violinplot causes the kernel to "die unexpectedly."
I have also tried using plotly 1.12.9 to do a violin plot (following the example on the plotly website), but that also kills the kernel.
Does anyone have any idea about what the error might be or how I should go about debugging this?
This is the code I used for seaborn:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

fig2, ax2 = plt.subplots()
sns.violinplot(x="Group", y="Data", data=df, ax=ax2)
ax2.set_ylim([0., 1.])
fig2.title = "Data by Group"
fig2.show()

and this is the code I use for plotly:
import plotly.plotly as py
from plotly.tools import FigureFactory as FF
from plotly.graph_objs import graph_objs
from scipy import stats

fig = FF.create_violin(bs_df, data_header="Data", group_header="Group",
                           height=500, width=800)
fig.show()

The error that Jupyter Notebook wasn't showing was:
Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so.

A: Given the error message below:
Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so.

I was able to resolve it by updating numpy to 1.11.1 and scipy to 0.17.1.


text:
Q: How to use angular services with controllers I'm new to angular and I've been told that it's better to make services do the heavy lifting for the controllers, but I'm finding it diffcult to make use of the services I've created. I've seen several questions on this but I can't find solutions.
Here's my service
(function () {
  'use strict';

var office = angular.module('Office', []);

office.factory('auth', ['$http', '$localForage', '$scope', function ($http, $localForage, $scope) {

    var auth = {}

    auth.login = function (credentials) {
        $http.post('/auth_api/login', credentials)
            .then(function (data) {
                    $localForage.setItem('user', data.data)
                },
                function () {
                    $scope.login_error = 'Invalid Username/password'
                })
    }

    $localForage.getItem('user').then(function (data) {
        auth.isAuthenticated = !!data.id
    })

    return auth
}])

And here's my controller
office.controller('LoginController', ['$scope', 'auth', function ($scope, auth) {

    $scope.login = auth.login($scope.user)
}])

A: I have created a simpler version from your code.. and its working here . check the link - fiddle
app.factory('auth', ['$http', function ($http) {
    var auth = {};
    auth.login = function (credentials) {
      return "success";
    }
    return auth;
}]);

replace login function with your implemenation

A: Your code is correct but as you are not returning anything from the "auth" factory, you are not getting any update in the controller. Change your code as shown below to return the data from factory or any message acknowledging the login.
Factory :
 (function () {
  'use strict';

   var office = angular.module('Office', []);

   office.factory('auth', ['$http', '$localForage', '$scope', function ($http, $localForage, $scope) {

   var auth = {}

   auth.login = function (credentials) {
    return $http.post('/auth_api/login', credentials)
        .then(function (data) {
                $localForage.setItem('user', data.data);
                setAuthentication(true);
                return data.data;
            },
            function (err) {
                return err;
            });
   }

   auth.setAuthentication = function (isLoggedIn){
     this.isAuthenticated = isLoggedIn;
   }

   return auth;
 }]);

Controller :
office.controller('LoginController', ['$scope', 'auth', function ($scope, auth) {
      $scope.login = function (){
       auth.login($scope.user).then(function (data){
         $scope.userDetails = data;
       }, function (err){
         $scope.loginError = 'Invalid Username/password';
       });
      }
}]);


text:
Q: How to remove or reduce the white space between the header and the page title Astra WP theme Never used CSS before and was pleased to find how to change the header color, it worked great.
Now trying to remove or at least reduce the white space between the page title and the header(?) where my logo is.
Read the similar question but the suggestions didn't work for me.
I also want to make the PAGE TITLE itself smaller as it looks too big on a mobile phone, have tried pasting various bits of code that I've found in searches but nothing has worked.
I'm in my 60s and am not very techy so please be gentle :)
Many thanks in advance,
My site is: www.andypiggott.com (Astra theme)

A: First, you need to head over to the Appearance » Customize page from your WordPress dashboard, The tab will slide to show you a simple box where you can add your custom CSS, now add this code:
.ast-plain-container.ast-no-sidebar #primary {
  margin-top: 0 !important;
}

For page title you can paste this code :
@media only screen and (max-width: 600px) {
  .entry-title {
   font-size:20px;
//or what ever the font size you want to be on mobile
  }
}


text:
Q: terraform - load json file from external source (S3) and inject variables into it Consider this:
// fruits.json
{
   "fruits" :
      {
          "apples": 3,
          "bananas": 4,
          "pears": "${pears}"
      }
}

In terraform I can do this:
# main.tf

variable "pears" {
    type    = number
    default = 2
}

locals {
      fruits = templatefile("fruits.json", { pears = "${var.pears}" })
}

However, I want to put that json file on S3. I can fetch its content like this:
data "aws_s3_bucket_object" "fruits" {
    bucket = "fruits"
    key    = "subdir/fruits.json"
}

locals {
    data = jsondecode(data.aws_s3_bucket_object.fruits.body)
}

But then I'm not actually injecting my variable like when using templatefile. It just fetches it as a literal string {pears} (replacing it with a direct {var.pears} doesn't work either).
How do I work around this? Seems like terraform doesn't have a built in "parsing" functionality I can just manually call. templatefile doesn't accept strings and the old data source that could transform a string to an IO file object was deprecated. It's unclear to me whether what I'm asking for is even possible.


text:
Q: How to replace a archived root site to root site So I have replaced my classic root site with a new modern root site. And now I need to replace the archived root site again as few WebJobs were running and used the old URL. According to our dev team, they can't change the URL in the jobs, and I need to make the archived root site our main root site again.
Would you please help me with this?
Kind Regards

A: I am afraid you might not be able to swap your classic team site back.
Quote:

If the target is the root site at https://tenant-name.sharepoint.com then the source site must be either a Modern Team Site (STS#3) or a Communication Site (SITEPAGEPUBLISHING#0) and the publishing feature can never have been activated on the source site.

You can't push (swap) a classic site to a root site since it's not supported.


text:
Q: Apollo Client useQuery making un-necessary refetches upon Next.js router.push I'm dealing with an issue in which a query inside a useQuery Apollo Client hook is getting un-necessarily re-run whenever Next.js's router.push (docs here) is called.
The abbreviated code is:
const Parent = () => {
  useQuery(QUERY_HERE, {
    onCompleted: () => {
      console.log("just completed apollo query");
    }
  });

  return <Child />;
}

const Child = () => {
  const router = useRouter();
  const currentArg = router.query?.currentArg;

  return (
    <div>
      <button
        onClick={() => {
          if (currentArg === "on") {
            router.push("/?currentArg=off");
          } else {
            router.push("/?currentArg=on");
          }
        }}
      >
        Click me!
      </button>
    </div>
  );
};

You can see a reproduction on CodeSandbox here.
My expectation is that whenever the button is clicked (and thus router.push is called), the query shouldn't be re-run. However, it's re-run any time the button is clicked. This is surprising because my understanding is that an Apollo query should only be re-run when one of its variables change.
Does anyone know of a way to ensure that the Apollo query is not re-run?

A: Next.js re-renders pages when navigation occurs and in your example you recreate Apollo Client every time it happens. Then your useQuery component renders again, checks if cache contains data for given query (it doesn't as new client is empty) and sends query again.
To fix this, create your ApolloClient in global scope. This way it'll stay stable and can be reused between multiple queries and renders.


text:
Q: CakeDC/Users - Tipos de usuários Implantei o plugin de autenticação CakeDC/Users e quero adicionar outros tipos de usuários ao meu sistema.
Atualmente tenho somente as duas permissões padrão: superuser e user.
Estou fazendo o controle de permissões através do arquivo permissions.php.
Estou também sobreescrevendo os arquivos de layout, tentei inicialmente forçar o campo role no formulário, mas ele força o tipo de usuário diretamente no controller do plugin.

A: Como o steinkel passou nesse issue: https://github.com/CakeDC/users/issues/513
Basta adicionar essa linha após o pathEntity em /vendor/cakedc/user/src/Controller/Traits/SimpleCrudTrait.php
$entity->role = $this->request->data('role');

E então configurar seu formulário para passar o campo role. No meu caso, passei essa informação através de um select.


text:
Q: cyclic dependency node js Node JS documention on Cyclic module dependencies

When main.js loads a.js, then a.js in turn loads b.js. At that point,
  b.js tries to load a.js. In order to prevent an infinite loop, an
  unfinished copy of the a.js exports object is returned to the b.js
  module. b.js then finishes loading, and its exports object is provided
  to the a.js module.

I don't understand the above statement, specially returning the unfinished copy which mean that at times it can result in undefined behavior.
Does this mean that we should always avoid cyclic dependency in Node to avoid undefined behavior? Is there a way to handle this scenario?


text:
Q: Is the default .gitignore that comes with each new Android Studio project good enough? I'm just wondering if the two .gitignores that are automatically generated with each Android Studio project ignore all the truly unnecessary files?
When I pushed the project to GitHub, there still seems to be a lot of clutter, but I don't know if it is necessary clutter?
For example, I'm not sure if all the gradle files are necessary: gradlew, settings.grade, the gradle/wrapper directory, etc.
Here are the default .gitignore files:
The one in the Project folder:
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
.idea/
app/app.iml
*.iml

And the one in the app folder:
/build

And here's my GitHub repository for a visual of what else got pushed:
https://github.com/quinteroheg2/AndroidWorkspace

A: Actually, I doubt that you need to ignore IDE-specific files on repository basis, not just in .git/info/exclude. Most of the aforementioned files are Idea-specific files which indeed shouldn't be committed into the repo. But your co-workers could use other IDEs so technically you should ignore other IDE-specific files as well. Or just make an informal agreement that people in your project(s) don't commit IDE-specific settings and set up .git/info/exclude themselves.


text:
Q: Weird font displaying problem -- Maybe index out of bounds? Screenshot of the rendering system attempting to display "ABCD1234!\n":

(text size is very small, so I had to crop in quite a bit so it's visible)
The characters displayed are not in the font array, so it seems to me like I've indexed something out of bounds somewhere. Here's the relevant code:
// I've left out a bit of initilization code, the rest of the code is in the Github repository
// linked, at bootloader/include/bootloader_tty.h

size_t strlen(const char * _str)
{
    size_t i = 0;
    while(_str[i++]);
    return i - 1;
}

// Prints character 'c' at X, Y
void terminal_putc(char c, unsigned int x, unsigned int y, uint32_t fgcolor)
{
    for (unsigned int Y = 0; Y < 8; Y++)
    {
        for (unsigned int X = 0; X < 8; X++)
        {
            if ((font[(c * 8) + Y] & (1 << X)))
            {
                *((uint32_t*)(framebuffer_addr + 4 * pitch * Y + y + 4 * X + x)) = fgcolor;
            }
        }
    }
}

// Writes the string `data` of length `length` to the "terminal"
void terminal_write(const char* data, size_t length)
{
    for (size_t i = 0; i < length; i++)
    {
        char c = data[i];

        if (c == '\n')
        {
            cursorY++;
            break;
        }

        terminal_putc(c, cursorX * 8, cursorY * 8, 0xFFFFFFFF);

        cursorX++;

        if (cursorX > consoleWidth)
        {
            cursorX = 0;
            cursorY++;
        }
    }

}

// Writes the string `data` to the "terminal"
void terminal_writestring(const char* data)
{
    terminal_write(data, strlen(data));
}

The way I'm calling terminal_writestring() is:
terminal_writestring("ABCD1234!\n");

Github repository: link

A: The distortion exists for a couple of reasons

*

*The leftmost pixel for any character resides in bit 7 of the concerned font byte. Your code currently fetches it from bit 0, thereby mirroring the output of the character.
Change if ((font[(c * 8) + Y] & (1 << X))) into either

*

*
if ((font[(c * 8) + Y] & (1 << (7 - X))))

or

*

*
if ((font[(c * 8) + Y] & (0b10000000 >> X)))

*The offset address calculation only scales the character-internal (X,Y) offsets, but forgets to also scale the (x,y) screen coordinates.
Change *((uint32_t*)(framebuffer_addr + 4 * pitch * Y + y + 4 * X + x)) = fgcolor; into

*

*
*((uint32_t*)(framebuffer_addr + 4 * pitch * (Y + y) + 4 * (X + x))) = fgcolor;


text:
Q: SQLalchemy update data in SQlite using wtforms Hello everyone,
I have a problem to edit my data using a wtforms, SQLAlchemy and SQlite3. I have generated a form and can query the data filtered by ID. The form is perfectly filled with corresponding data. But when I change the data and press submit it won't update the data. There are actually two problems. First the forms don't pass the new typed data back to python and variables, and second i can't figure how to update the current selected row of data.
Here's is my code:
@app.route('/sensorlist_edit/<string:id>', methods=['GET', 'POST'])
@is_logged_in
def sensorlist_edit(id):
    sensor = Sensor.query.filter_by(id=id).first()
    form = SensorListForm(request.form)
    form.name.data = sensor.name
    form.sensor_type.data = str(sensor.sensor_type)
    form.pin.data = sensor.pin
    form.limit_temp_up.data = sensor.limit_temp_up
    form.limit_temp_down.data = sensor.limit_temp_down
    form.limit_hum_up.data = sensor.limit_hum_up
    form.limit_hum_down.data = sensor.limit_hum_down
    form.limit_aqua_temp_up.data = sensor.limit_aqua_temp_up
    form.limit_aqua_temp_down.data = sensor.limit_aqua_temp_down

    if request.method == 'POST' and form.validate():
        name = form.name.data
        sensor_type = int(form.sensor_type.data)
        pin = form.pin.data
        limit_temp_up = form.limit_temp_up.data
        limit_temp_down = form.limit_temp_down.data
        limit_hum_up = form.limit_hum_up.data
        limit_hum_down = form.limit_hum_down.data
        limit_aqua_temp_up = form.limit_aqua_temp_up.data
        limit_aqua_temp_down = form.limit_aqua_temp_down.data

        db.session.commit()

        flash('You updated a sensor', 'success')

        return redirect(url_for('sensorlist_CRUD'))
    return render_template('sensorlist_edit.html', form=form)

The model class is generated with this code:
class Sensor(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    sensor_type = db.Column(db.Integer)
    pin = db.Column(db.Integer)
    limit_temp_up = db.Column(db.Float)
    limit_temp_down = db.Column(db.Float)
    limit_hum_up = db.Column(db.Float)
    limit_hum_down = db.Column(db.Float)
    limit_aqua_temp_up = db.Column(db.Float)
    limit_aqua_temp_down = db.Column(db.Float)

And here is the Jinja template form the wtforms:
{% extends 'layout.html' %}

{% block body %}

Edit Sensor

  {% from "includes/_formhelpers.html" import render_field %}
  <form method="POST" action="">

      {{render_field(form.name, class_="form-control")}}

      {{render_field(form.sensor_type, class_="form-control")}}

      {{render_field(form.pin, class_="form-control")}}

      {{render_field(form.limit_temp_up, class_="form-control")}}

      {{render_field(form.limit_temp_down, class_="form-control")}}

      {{render_field(form.limit_hum_up, class_="form-control")}}

      {{render_field(form.limit_hum_down, class_="form-control")}}

      {{render_field(form.limit_aqua_temp_up, class_="form-control")}}

      {{render_field(form.limit_aqua_temp_down, class_="form-control")}}

<input type="submit" class="btn btn-primary" value="Submit">

  </form>
{% endblock %}

I use exactly the same form, model, python-code and template (with other .html) for the adding of data to the database, and that works perfectly.
I hope someone could help me with what i'm missing, or could give me a link of short description of what i'm doing wrong. I searched already multiple threads and other posts, but can't find the solution.
Thanks in advance for every help you give.

A: You are really close, in your code under the POST block you need to update the actual model... right now you are just setting a bunch of variables with the form data but it isn't getting applied to the model. Like this:
@app.route('/sensorlist_edit/<string:id>', methods=['GET', 'POST'])
@is_logged_in
def sensorlist_edit(id):
    sensor = Sensor.query.filter_by(id=id).first()
    form = SensorListForm(request.form)

    if request.method == 'POST' and form.validate():
        sensor.name = form.name.data
        sensor.sensor_type = int(form.sensor_type.data)
        sensor.pin = form.pin.data
        sensor.limit_temp_up = form.limit_temp_up.data
        sensor.limit_temp_down = form.limit_temp_down.data
        sensor.limit_hum_up = form.limit_hum_up.data
        sensor.limit_hum_down = form.limit_hum_down.data
        sensor.limit_aqua_temp_up = form.limit_aqua_temp_up.data
        sensor.limit_aqua_temp_down = form.limit_aqua_temp_down.data

        db.session.commit()

        flash('You updated a sensor', 'success')

        return redirect(url_for('sensorlist_CRUD'))

    form.name.data = sensor.name
    form.sensor_type.data = str(sensor.sensor_type)
    form.pin.data = sensor.pin
    form.limit_temp_up.data = sensor.limit_temp_up
    form.limit_temp_down.data = sensor.limit_temp_down
    form.limit_hum_up.data = sensor.limit_hum_up
    form.limit_hum_down.data = sensor.limit_hum_down
    form.limit_aqua_temp_up.data = sensor.limit_aqua_temp_up
    form.limit_aqua_temp_down.data = sensor.limit_aqua_temp_down

    return render_template('sensorlist_edit.html', form=form)

Update:
I moved the form assignments below the POST section as I think they were overwriting the submitted form data with the old information... sorry I missed that the first time through!!


text:
Q: QGIS - Create equal length polygon along polyline How can I create a series of polygons along a line? I need to assess the density of a number of targets along a line within a corridor.

I have tried the following:

*

*creating a buffer,

*using the plugin station lines to create perpendicular lines,

*Using the Digitizing Tools Plugin to split the buffer with the
station lines

This only splits the polygon one line at a time, the lines is 20+km long and I would like 25m sections making manual repetitions impractical.The line also has complex curves.
Is there a way to create such a grid?

A: I realised that I was looking at the problem the wrong way round. Rather than create polygons along a line to be able to used the points in polygon methods, I realised that I was looking for a Linear Reference solution and therefore the LRS Plugin would produce the information I required.
Thanks for helping anyway.

A: You could Union (Vector -> Geoprocessing -> Union) your Station Lines with your Buffer layer.  Input vector layer = Station lines, Union Layer = Buffer
This will create a line output with the edge of the buffer, and the station lines.
Then you can use the Polygonize plugin (see here and here).


text:
Q: Exclude object property on JSON output I am trying to create a user model with username and password.
I dont want the password to be displayed in the api response, but it is required on signup. So [JsonIgnore] wont work.
Any suggestions?
public class User {
    [Required]
    public string Username { get; set; }

    [Required]
    public string Password { get; set; }
}

A: That's why you should separate your actual entity and model. You should create a model / viewmodel and send that as response from your API / MVC controller like
public class UserModel
{
  public string Username { get; set; }
}

Another piece of advice, never include any data validation in your actual entity, rather you should have those validation [Required] in your model / viewmodel; and should keep the entity away from this clutter.


text:
Q: Composition of function $f (x) = \sqrt{2x^2+17}-3$ a total of $10$ times
So I have this question here. Obviously, I don't think I am expected to take a composition of a function 10 times. That would be crazy. My idea is that f(x) repeats 10 times and that $\sqrt{2}$ repeats 10 times too so I was thinking I could write $f(x)$ as:
$$f(x)=\sqrt{2^{(1/2)^{10}}(f(x))^{10}+17}-3.$$ I could then go from there or something. Anything to add? Am I completely off or am I doing something totally wrong?

A: Note that $f(2)=2$ and $f(4)=4$. Moreover $f$ is a continuous and strictly increasing function in $[2,4]$. These properties hold also for the composition $g$. Therefore $g((2,4))=(2,4)$ and by  the Intermediate Value Theorem there is $c\in (2,4)$ such that $g(c)=3$.
Note that since $g$ is strictly increasing the point $c$ is unique.


text:
Q: How to solve UnknownHostException error in google spreadsheet using the API? To develope a client applications, I need to read and modify worksheets and data in Google Sheets. I am facing with below issue:
SpreadsheetService service = new SpreadsheetService("sheet1");
String sheetUrl = "https://spreadsheets.google.com/feeds/list/1XP3KQTboWCArbvH99XYEGsVOldc97NqFzKD MiEepXRA/default/public/values"; //Sheet url
URL url = new URL(sheetUrl); // Get Feed of Spreadsheet url
ListFeed lf = service.getFeed(url, ListFeed.class); //Error statement

Issue:

java.net.UnknownHostException: spreadsheets.google.com    at
  java.net.AbstractPlainSocketImpl.connect(Unknown Source)  at
  java.net.PlainSocketImpl.connect(Unknown Source)  at
  java.net.SocksSocketImpl.connect(Unknown Source)  at
  java.net.Socket.connect(Unknown Source)   at
  sun.security.ssl.SSLSocketImpl.connect(Unknown Source)    at
  sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)    at
  sun.net.NetworkClient.doConnect(Unknown Source)   at
  sun.net.www.http.HttpClient.openServer(Unknown Source)    at
  sun.net.www.http.HttpClient.openServer(Unknown Source)    at
  sun.net.www.protocol.https.HttpsClient.(Unknown Source)     at
  sun.net.www.protocol.https.HttpsClient.New(Unknown Source)    at
  sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown
  Source)   at
  sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown
  Source)   at
  sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown
  Source)   at
  sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown
  Source)   at
  com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:503)
    at
  com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
    at com.google.gdata.client.Service.getFeed(Service.java:1135)   at
  com.google.gdata.client.Service.getFeed(Service.java:998)     at
  com.google.gdata.client.GoogleService.getFeed(GoogleService.java:631)
    at com.google.gdata.client.Service.getFeed(Service.java:1017)   at
  test_project.test_demo.main(test_demo.java:35)

A: As stated here, UnknownHostException means that your device was not able to resolve the host name. It emerges when you are trying to connect to a remote host using its host name, but the IP address of that host cannot be resolved. From this blog, you should check the input of Socket (or any other method that throws an UnknownHostException), and validate that it is the intended one. If you are not sure whether you have the correct host name, you can launch a terminal and use the nslookup command to see if your DNS server can resolve the host name to an IP address successfully.
If that doesn't work, you should check if the host name you have is correct and then try to refresh your DNS cache. If that doesn't work either, try to use a different DNS server, eg Google Public DNS is a very good alternative.
You can also check on this link. Hope this helps!


text:
Q: Aviation signals probability I'm trying to solve this exercise but i don't know where to start. The exercise is:
I have two types of signals with codes $111$ or $000$ with probabilities of $0.65$ and $0.35$ respectively. These signals are distorted by noise, which provocates that a $1$ (sent) can be receipt as $0$ with a probability of $0.2$ and the converse with $0.8$. Suppose that the symbols suffers these noises independently.
Which is the probability of get in the output we receive the signals $111$, $000$ and $010$ ?

A: $111$ sent and received correctly $(0.65\cdot0.80^3)$
$000$ sent and received as $111$ $(0.35\cdot0.20^3)$
P(111) received $(0.65\cdot0.80^3) + (0.35\cdot0.20^3)$
$111$ sent and received as 010 $=(0.65\cdot0.80\cdot 0.2^2)$
$000$ sent and received as 010 $=(0.35\cdot0.80^2\cdot 0.2)$
etc.


text:
Q: What is the equivalent way to set post parameters in .net? I have to integrate with a third party API. To use the service, I have to "POST" to a specific url with certain parameters.
The example code provided by the service is in php and is as follows
$data = array('From' => '0999999', 'To' => '08888888');
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  <--- Ignore SSL warnings
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

I am trying to use the WebRequest class to achieve the same in .net. However, I am a bit confused about how to set the post parameter data. I figured $data above is nothing but a Dictionary. So I created a equivalent dictionary. However, how do I set the post parameters with the dictionary values?
In http://msdn.microsoft.com/en-us/library/debx8sh9.aspx, they have serialized a string to a byte array and then set is as the post parameter in the dataStream. How do I do the same for a Dictionary?
Or is my approach incorrect? Is there a better way to do this?

A: Generally, WebClient.UploadValues is going to be the easiest approach here; see MSDN for a full example. Note, however, that this only covers CURLOPT_POSTFIELDS and CURLOPT_POST. Fail on error is automatic and implicit, and the response is already included as a byte[].
i.e.
using(var client = new WebClient()) {
    var data = new NameValueCollection();
    data.Add("From", "0999999");
    data.Add("To", "08888888");
    var result = client.UploadValues(url, data);
}

note POST is implicit here; if you need a different http method, use the overload:
var result = client.UploadValues(url, "PUT", data); // for example

A: If you are using url encoded post data you can url encode each key/value pair of your dictionary using HttpServerUtility.UrlEncode Method (String)
// Build postData
StringBuilder post = new StringBuilder();
foreach(item in dictionary) {
  post.AppendFormat("&{0}={1}", item.key, HttpUtility.UrlEncode(item.value));
}
string postData = post.ToString();

// HTTP POST
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
  UTF8Encoding encoding = new UTF8Encoding();
  byte[] bytes = encoding.GetBytes(postData);
  writeStream.Write(bytes, 0, bytes.Length);
}

A: Just in case you have to use HttpWebRequest, the code below converts a Dictionary<String,String> named formVars to a byte[] named toPost:
byte[] toPost = System.Text.Encoding.UTF8.GetBytes(
    String.Join("&", formVars.Select(x =>
        HttpUtility.UrlEncode(x.Key) + "=" +
        HttpUtility.UrlEncode(x.Value)));
);

Play with a working copy at https://dotnetfiddle.net/IOzIE6

A: You probably want to use the
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://url");
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
string post = "From=0999999&To=08888888";
request.ContentLength = post.Length;
request.ContentType = "application/x-www-form-urlencoded";

StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(post);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();


text:
Q: Is weak convergence only defined for probability measures on metric spaces with Borel sigma algebra? When searching for a definition of weak convergence for probability measures I find only definitions with them being defined on metric spaces with Borel sigma algebra. Is it really only defined on those spaces?
Can we not define it for general topological spaces with Borel sigma algebra?


text:
Q: starting Activities from an expandable list dynamically I am attempting to start an activity from the children of my expandable list This framework is taken from the sample in the Android SDK, and is the core for my application.  Here is teh code and I will identify which areas are not working.
package com.soraingraven.suprRef;

import android.app.ExpandableListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

public class SuperReferenceActivity extends ExpandableListActivity {
    ExpandableListAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set up our adapter
        mAdapter = new MyExpandableListAdapter();
        setListAdapter(mAdapter);
        //registerForContextMenu(getExpandableListView());
        getExpandableListView().setOnChildClickListener(this);
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        super.onListItemClick(parent, v, groupPosition, childPosition, id);
        String testName[][] = children[groupPosition][childPosition];
        try {
            Class clazz = Class.forName("com.soraingraven.suprRef." + testName);
            Intent intent = new Intent(this, clazz);
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // use groupPosition and childPosition to locate the current item in the adapter
        return true;
    }

    /*@Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Sample menu");
        menu.add(0, 0, 0, "Sample action");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
        String title = ((TextView) info.targetView).getText().toString();

        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
            int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
            Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
                    Toast.LENGTH_SHORT).show();
            return true;
        } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
            Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
            return true;
        }

        return false;
    }*/ //Context Menu Stuff May or may not use

    //Indexes for all the options
    public class MyExpandableListAdapter extends BaseExpandableListAdapter {
        private String[] groups = {"Math Formulas and Equations"};                                  //Main Menu

        private String[][] children = {                                                             //Sub Menus
                { "PerfectGasLaw" }                                                             //Math Equations Sub Menu
        };

        public Object getChild(int groupPosition, int childPosition) {
            return children[groupPosition][childPosition];
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            return children[groupPosition].length;
        }

        public TextView getGenericView() {
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT, 128);
            TextView textView = new TextView(SuperReferenceActivity.this);
            textView.setLayoutParams(lp);
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            textView.setPadding(128, 0, 0, 0);
            return textView;
        }

        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getChild(groupPosition, childPosition).toString());
            return textView;
        }

        public Object getGroup(int groupPosition) {
            return groups[groupPosition];
        }

        public int getGroupCount() {
            return groups.length;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }
    }
}

Line 31 I cannot figure out how to get the super reference class to accept the children array, as it is listed as private to another class.  Please help.  Im not sure if i need to create a 2D array inside the activity class and pass it the data contained in children or what exactly needs to be done. Thanks.

A: You're trying to concatenate a 2d String array to a String! Remove the [][]
    String testName = children[groupPosition][childPosition];
    try {
        Class clazz = Class.forName("com.soraingraven.suprRef." + testName);


text:
Q: Lifo Typeahead on new dom elements I am building a Symfony2 app, and have a form with repeated form elements, where I am using Lifo's Typeahead extension.
https://github.com/lifo101/typeahead-bundle
It works great on form elements that exist on load, but when I add new form elements using JQuery, the the Typeahead isn't working. I'm not very good with Javascript, so I'm struggling to understand how to make the script work with the new fields. Does anyone have any suggestions? I think I need to re-initialise the script but I don't know how to do this.

A: Thank you for trying the bundle.
The problem is I never considered dynamic insertion of DOM elements for my typeahead widget so the current version isn't going to work with inputs that are dynamically inserted into the DOM.
However, I've now updated my code to properly trigger for any existing or newly inserted elements into the DOM. As long as the inserted HTML is in the proper format that my typeahead bundle expects it should just automatically work as soon as you insert your HTML.


text:
Q: Adding data to state in Ngrx reducer function I am learning front-end and trying making an Angular app using NgRx for state management.
I have a table of Messages. I want to remove and add messages to store.
I am able to remove rows using a reducer function as shown below.
function RemoveHandler(state: StoreMessages, action) {
    return {
        ...state,
        selections: state.selections.filter(messageId => messageId !== action.messageId),
        messages: state.messages.filter(item => item.messageId !== action.messageId),
        all: state.all.filter(item => item.messageId !== action.messageId)
    };
}

This works fine, but my logic for add message functionality is not working.
function AddHandler(state: StoreMessages, action) {
        return {
            ...state,
            messages: state.messages.push(action.newMessage),
            all: state.all.push(action.newMessage)
        };
    }

The problem is that pop method return length of array and hence length is assigned to 'messages' and 'all' properties of my state. How can I add new messages to my state. Any help is appreciated.

A: you don't need the array.push method in the reducer. the first code work, because you are filtering an array that is in the state. to add data to the state simply assign it like
function AddHandler(state: StoreMessages, action) {
    return {
        ...state,
        messages: action.newMessage,
        all: action.newMessage
    };
}

or if you are insert an array
function AddHandler(state: StoreMessages, action) {
    return {
        ...state,
        messages: [...action.newMessage],
        all: [...action.newMessage]
    };
}


text:
Q: Include Value from Dictionary in New Dictionary Only if Number How can I create a new dictionary from an existing dictionary to include only key and values where values are numeric?
Example dictionary:
simple_dict = {
  'a': 1,
  'b': 2,
  'c': 3,
  'd': 'John',
  'e': 4,
  'f': 'Sandra'
}

What I have so far:
new_dict = {key: value for key, value in simple_dict.items() if }

I've tried using something like isdigit() or isnumeric() but keep receiving errors.

A: import numbers
...
new_dict = {
    key:value for key, value in simple_dict.items()
    if isinstance(value, numbers.Number)
}


text:
Q: Generating a dropdown list with database first In my mvc3 application i want to populate the dropdownlist for the data which is coming from database here am using entityframework with database first approach so please help me to do this

A: You did not provide any code of what you have done so far so I know nothing about the data that you have been working with. I will post some code and all that you will have to do is to modify it to fit in with your scenario.
Lets work with a simple solution of loan applications.  A client needs to apply for a loan and he needs to supply banking details. He will have to select a bank from a drop down list.
Lets start with the domain model called Bank. This represents your data coming from your database table. Lets call the table Banks.
public class Bank
{
     public int Id { get; set; }

     public string Name { get; set; }
}

Your table called Banks will look like this:
Id | int | not null | primary key
Name | varchar(50) | not null

Depeneding on you what you need to do I normally have a service layer that calls my bank repository to bring back the data. But seeing that you only need to bring back data and nothing else we can skip the service layer.
public class BankRepository : RepositoryBase<Bank>, IBankRepository
{
     public IEnumerable<Bank> FindAll()
     {
          return DatabaseContext.Banks;
     }
}

You database context will look like this:
public class DatabaseContext : DbContext
{
     public DbSet<Bank> Banks { get; set; }
}

This is how your data retrieval methods could look like. It might not be the full solution but there are many samples online. Just go and Google.
Lets move onto the web application.
Your view/page will work with a view model and not your domain model. You use view models to represent your data on the view/page. So on your create view you will pass in a create application view model with a list of your banks. An instance of IBankRepository will be supplied through a technique called dependency injection. I use Autofac for this.
public class ApplicationViewModel
{
     public int BankId { get; set; }

     public IEnumerable<Bank> Banks { get; set; }
}

Your controller's action method will populate the view model and send it to your view.
public class ApplicationController : Controller
{
     private readonly IBankRepository bankRepository;

     public ApplicationController(IBankRepository bankRepository)
     {
          this.bankRepository = bankRepository;
     }

     public ActionResult Create()
     {
          ApplicationViewModel viewModel = new ApplicationViewModel
          {
               Banks = bankRepository.FindAll()
          };

          return View(viewModel);
     }
}

Your view will then receive this view model and do with it what it needs to do. In this case it will populate your bank drop down.
@model YourProject.ViewModels.Applications.ApplicationViewModel

@using (Html.BeginForm())
{

          Bank: **

               @Html.DropDownListFor(
                    x => x.BankId,
                    new SelectList(Model.Banks, "Id", "Name", Model.BankId),
                    "-- Select --"
               )
               @Html.ValidationMessageFor(x => x.BankId)

}

I don't what your experience is but judging from your question it seems like you still need to do a lot of research. There are tonnes of examples online. You will need to work through samples of Entity Framework code first and ASP.NET MVC. Invest some time and you will reap the rewards later.
I hope this works and best of luck. The solution might not be what you want but it can help guide you in the right direction.

A: Let assume you have a class like so
public class ProductBrand
    {
        //Eg. Nokia, Hp, Dell
        ///
        /// Second Level to Category
        /// Has Foreign Key to category table
        ///
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ProductBrandId { get; set; }

        [Display(Name = "Category")]
        public int ProductCategoryId { get; set; }
        public virtual ProductCategory ProductCategory { get; set; }

        [Required(ErrorMessage = "This field is required")]
        [StringLength(300, ErrorMessage = "This field must not be greater than 300 xters long")]
        [Display(Name="Name")]
        public string BrandName { get; set; }

        public IList<Product> Products { get; set; }

        [Display(Name = "Status")]
        public bool ActiveStatus { get; set; }

    }

Which means this model has a foreign key name ProductCategoryId then in your create Product brand view you will need a dropdownlist containing All productcategory to choose from.
Just create an actionresult like so
  public ActionResult CreateProductBrand() {

            ViewBag.ProductCategoryId = new SelectList(context.ProductCategories, "ProductCategoryId", "CategoryName");
            return View();
        }

Then call the viewbag in you corrensponding view like so:
  @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

                    Category

                            @Html.DropDownList("ProductCategoryId", String.Empty)
                            @Html.ValidationMessageFor(model => model.ProductCategoryId)

                    Brand

                            @Html.EditorFor(model => model.BrandName)
                            @Html.ValidationMessageFor(model => model.BrandName)

                    Status

                            @Html.EditorFor(model => model.ActiveStatus)
                            @Html.ValidationMessageFor(model => model.ActiveStatus)

                        <input type="submit" class="button blue" value="Save" />
                        Cancel

    }

A: ViewModel:
    public List<Item> _Items { get; set; }
    public int_newID { get; set; }

Model Item
    public int_id { get; set; }
    public string _name { get; set; }

Controller:
Populate _Items with data and send that list to your view
View:
    @Html.DropDownListFor(c => c._newID, new SelectList(Model._Items , "_id", "_name"),--Select Item--")


text:
Q: How to use enum with bitwise operator when the items already have values I've the following enum:
[Flags]
public enum MouseMessage
{
    WM_LBUTTONUP = 0x0202,
    WM_RBUTTONUP = 0x0205,
    WM_WHEELBUTTONUP = 0x208,
    WM_XBUTTONUP = 0x020C
}

And what i want to do is something like this (e.Message contains an item from the MouseMessage enum):
switch (e.Message)
{
      case MouseMessage.WM_LBUTTONUP
           | MouseMessage.WM_RBUTTONUP
           | MouseMessage.WM_XBUTTONUP
           | MouseMessage.WM_WHEELBUTTONUP:
                // Do something...
                break;
}

This does not work for me because the items in the enum already have values so I cannot benefit from the Flags attribute (i.e. 0,1,2,4 as values for the items).
I tried something but it didn't work either:
[Flags]
public enum MouseMessage
{
     WM_LBUTTONUP = 0x0202 | 0,
     WM_RBUTTONUP = 0x0205 | 1,
     WM_WHEELBUTTONUP = 0x208 | 2,
     WM_XBUTTONUP = 0x020C | 4
}

Any ideas?
UPDATE:
I want to use the enum like this (in a Dictionary)
Dictionary<MouseMessage, Action> dictionary = new Dictionary<MouseMessage, Action>()
{
{MouseMessage.WM_LBUTTONUP | MouseMessage.WM_RBUTTONUP | MouseMessage.WM_WHEELBUTTONUP |
MouseMessage.WM_XBUTTONUP, () => //...},
};
Note: this example is only to simplify my problem

A: If you want all the "button up" cases to have the same block of code in the switch statement, you can simply write the switch so that the cases all fall through to one code block:
switch (e.Message)
{
    case MouseMessage.WM_LBUTTONUP:
    case MouseMessage.WM_RBUTTONUP:
    case MouseMessage.WM_XBUTTONUP:
    case MouseMessage.WM_WHEELBUTTONUP:
    {
        // Do something...
        break;
    }
}

A: If you want to do complex comparision on each combination of enum values to match to one case, there is pattern matching. It is quite literally designed for that. If you want to check that WM_LBUTTONUP || WM_XBUTTONUP is up, no longer requires complicated if/else constructs.
And this Enumeration should in no way have enough combination that repalcing the switch/case with a dictionary is worth it.
If you are truly dead set on your soltion, make your Own Enumeration and translate between the two.
The input would be:
[Flags]
public enum MouseMessage
{
    WM_LBUTTONUP = 0x0202,
    WM_RBUTTONUP = 0x0205,
    WM_WHEELBUTTONUP = 0x208,
    WM_XBUTTONUP = 0x020C
}

The output would be:
[Flags]
public enum CustomMouseMessage
{
     WM_LBUTTONUP = 0x0202 | 0,
     WM_RBUTTONUP = 0x0205 | 1,
     WM_WHEELBUTTONUP = 0x208 | 2,
     WM_XBUTTONUP = 0x020C | 4
}

Mostly pseudo code:
CustomMouseMessage result;

switch(e.Message){
    case MouseMessage.WM_LBUTTONUP:
        result += CustomMouseMessage.WM_LBUTTONUP;
        break;
   //
}

return result;


text:
Q: amc, aerospike are not recognized inside docker container I've docker ubuntu 16.04 image and I'm running aerospike server in it.
$ docker run -d -p 3000:3000 -p 3001:3001 -p 3002:3002 -p 3003:3003  -p 8081:8081  --name aerospike aerospike/aerospike-server

The docker container is running successfully.
$ docker ps
CONTAINER ID        IMAGE                        COMMAND
CREATED             STATUS              PORTS
NAMES
b0b4c63d7e22        aerospike/aerospike-server   "/entrypoint.sh asd"
36 seconds ago      Up 35 seconds       0.0.0.0:3000-3003->3000-3003/tcp, 0.0.0.0:8081->8081/tcp   aerospike

I've logged into the docker container
$ docker exec -it b0b4c63d7e22 bash
root@b0b4c63d7e22:/#

I have listed the directories -
root@b0b4c63d7e22:/# ls
bin  boot  core  dev  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt
proc  root  run  sbin  srv  sys  tmp  usr  var
root@b0b4c63d7e22:/#

I changed the directory to bin folder and listed the commands
root@b0b4c63d7e22:/# cd bin
root@b0b4c63d7e22:/bin# ls
bash   dnsdomainname  ip          mount          readlink    systemctl
touch         zegrep
cat    domainname     journalctl  mountpoint     rm          systemd
true          zfgrep
chgrp  echo           kill        mv             rmdir       systemd-ask-
password            umount        zforce
chmod  egrep          ln          netstat        run-parts   systemd-escape
uname         zgrep
chown  false          login       networkctl     sed         systemd-inhibit
uncompress    zless
cp     fgrep          loginctl    nisdomainname  sh          systemd-machine-
id-setup        vdir          zmore
dash   findmnt        ls          pidof          sh.distrib  systemd-notify
wdctl         znew
date   grep           lsblk       ping           sleep       systemd-tmpfiles
which
dd     gunzip         mkdir       ping6          ss          systemd-tty-ask-
password-agent  ypdomainname
df     gzexe          mknod       ps             stty        tailf
zcat
dir    gzip           mktemp      pwd            su          tar
zcmp
dmesg  hostname       more        rbash          sync        tempfile
zdiff

Then I want to check the service -
root@b0b4c63d7e22:/bin# service amc status
amc: unrecognized service

A: Aerospike's official docker container does not have Aerospike Server running as a daemon, but instead as a foreground process. You can see this in the official github DOCKERFILE.
AMC is not part of Aerospike's Docker Image. It is up to you to run AMC from the environment of your choosing.
Finally, since you have not created a custom aerospike.conf file, Aerospike Server will only respond to clients on the Docker internal network. The -p parameters are not sufficient in itself to expose Aerospike's ports to clients, you'd also need to configure access-address, if you'd want client access from outside of the docker environment. Read more about Aerospike's networking at: https://www.aerospike.com/docs/operations/configure/network/general

A: You can build your own Docker container for amc to connect to aerospike running on containers.
Here is a sample Dockerfile for AMC.
cat Dockerfile

FROM ubuntu:xenial

ENV AMC_VERSION 4.0.13

# Install AMC server

RUN \
  apt-get update -y \
  && apt-get install -y wget python python-argparse python-bcrypt python-openssl logrotate net-tools iproute2 iputils-ping \
  && wget "https://www.aerospike.com/artifacts/aerospike-amc-community/${AMC_VERSION}/aerospike-amc-community-${AMC_VERSION}_amd64.deb" -O aerospike-amc.deb \
  && dpkg -i aerospike-amc.deb \
  && apt-get purge -y

# Expose Aerospike ports
#
#   8081 – amc port
#
EXPOSE 8081

# Execute the run script in foreground mode
ENTRYPOINT ["/opt/amc/amc"]
CMD [" -config-file=/etc/amc/amc.conf -config-dir=/etc/amc"]

#/opt/amc/amc -config-file=/etc/amc/amc.conf -config-dir=/etc/amc

# Docker build sample:
# docker build -t amctest .

# Docker run sample for running amc on port 8081
# docker run -tid --name amc -p 8081:8081 amctest
# and access through http://127.0.0.1:8081

Then you can build the image:
docker build -t amctest .
Sending build context to Docker daemon  50.69kB
Step 1/6 : FROM ubuntu:xenial
 ---> 2fa927b5cdd3
Step 2/6 : ENV AMC_VERSION 4.0.13
 ---> Using cache
 ---> edd6bddfe7ad
Step 3/6 : RUN apt-get update -y   && apt-get install -y wget python python-argparse python-bcrypt python-openssl logrotate net-tools iproute2 iputils-ping   && wget "https://www.aerospike.com/artifacts/aerospike-amc-community/${AMC_VERSION}/aerospike-amc-community-${AMC_VERSION}_amd64.deb" -O aerospike-amc.deb   && dpkg -i aerospike-amc.deb   && apt-get purge -y
 ---> Using cache
 ---> f916199044d8
Step 4/6 : EXPOSE 8081
 ---> Using cache
 ---> 06f7888c1721
Step 5/6 : ENTRYPOINT /opt/amc/amc
 ---> Using cache
 ---> bc39346cd94f
Step 6/6 : CMD  -config-file=/etc/amc/amc.conf -config-dir=/etc/amc
 ---> Using cache
 ---> 8ae4300e7c7c
Successfully built 8ae4300e7c7c
Successfully tagged amctest:latest

and finally run it with port forwarding to port 8081:
docker run -tid --name amc -p 8081:8081 amctest
a07cdd8bf8cec6ba41ce068c01544920136a6905e7a05e9a2c315605f62edfce


text:
Q: matlab compiled program execute code on close I have a compiled matlab program that runs as a dos box basically (ie no GUI). Is there a way to get code to execute when someone closes the program? Specifically closing by clicking on the X?

A: I suggest to define a cleanup task. This will be executed whenever a function is terminated (by whatever means), so as long as closing the program is not done with a kill -9 command or similar, the code is being run.


text:
Q: Getting metadata from SHOUTcast using IcyStreamMeta I am writing an app for Android that grabs meta data from SHOUTcast mp3 streams. I am using a pretty nifty class I found online that I slightly modified, but I am still having 2 problems.
1) I have to continuously ping the server to update the metadata using a TimerTask. I am not fond of this approach but it was all I could think of.
2) There is a metric tonne of garbage collection while my app is running. Removing the TimerTask got rid of the garbage collection issue so I am not sure if I am just doing it wrong or if this is normal.
Here is the class I am using:
public class IcyStreamMeta {
    protected URL streamUrl;
    private Map<String, String> metadata;
    private boolean isError;

public IcyStreamMeta(URL streamUrl) {
    setStreamUrl(streamUrl);

    isError = false;
}

/**
 * Get artist using stream's title
 *
 * @return String
 * @throws IOException
 */
public String getArtist() throws IOException {
    Map<String, String> data = getMetadata();

    if (!data.containsKey("StreamTitle"))
        return "";

    try {
        String streamTitle = data.get("StreamTitle");
        String title = streamTitle.substring(0, streamTitle.indexOf("-"));
        return title.trim();
    }catch (StringIndexOutOfBoundsException e) {
        return "";
    }
}

/**
 * Get title using stream's title
 *
 * @return String
 * @throws IOException
 */
public String getTitle() throws IOException {
    Map<String, String> data = getMetadata();

    if (!data.containsKey("StreamTitle"))
        return "";

    try {
        String streamTitle = data.get("StreamTitle");
        String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
        return artist.trim();
    } catch (StringIndexOutOfBoundsException e) {
        return "";
    }
}

public Map<String, String> getMetadata() throws IOException {
    if (metadata == null) {
        refreshMeta();
    }

    return metadata;
}

public void refreshMeta() throws IOException {
    retreiveMetadata();
}

private void retreiveMetadata() throws IOException {
    URLConnection con = streamUrl.openConnection();
    con.setRequestProperty("Icy-MetaData", "1");
    con.setRequestProperty("Connection", "close");
    //con.setRequestProperty("Accept", null);
    con.connect();

    int metaDataOffset = 0;
    Map<String, List<String>> headers = con.getHeaderFields();
    InputStream stream = con.getInputStream();

    if (headers.containsKey("icy-metaint")) {
        // Headers are sent via HTTP
        metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
    } else {
        // Headers are sent within a stream
        StringBuilder strHeaders = new StringBuilder();
        char c;
        while ((c = (char)stream.read()) != -1) {
            strHeaders.append(c);
            if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
                // end of headers
                break;
            }
        }

        // Match headers to get metadata offset within a stream
        Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
        Matcher m = p.matcher(strHeaders.toString());
        if (m.find()) {
            metaDataOffset = Integer.parseInt(m.group(2));
        }
    }

    // In case no data was sent
    if (metaDataOffset == 0) {
        isError = true;
        return;
    }

    // Read metadata
    int b;
    int count = 0;
    int metaDataLength = 4080; // 4080 is the max length
    boolean inData = false;
    StringBuilder metaData = new StringBuilder();
    // Stream position should be either at the beginning or right after headers
    while ((b = stream.read()) != -1) {
        count++;

        // Length of the metadata
        if (count == metaDataOffset + 1) {
            metaDataLength = b * 16;
        }

        if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
            inData = true;
        } else {
            inData = false;
        }
        if (inData) {
            if (b != 0) {
                metaData.append((char)b);
            }
        }
        if (count > (metaDataOffset + metaDataLength)) {
            break;
        }

    }

    // Set the data
    metadata = IcyStreamMeta.parseMetadata(metaData.toString());

    // Close
    stream.close();
}

public boolean isError() {
    return isError;
}

public URL getStreamUrl() {
    return streamUrl;
}

public void setStreamUrl(URL streamUrl) {
    this.metadata = null;
    this.streamUrl = streamUrl;
    this.isError = false;
}

public static Map<String, String> parseMetadata(String metaString) {
    Map<String, String> metadata = new HashMap<String, String>();
    String[] metaParts = metaString.split(";");
    Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
    Matcher m;
    for (int i = 0; i < metaParts.length; i++) {
        m = p.matcher(metaParts[i]);
        if (m.find()) {
            metadata.put((String)m.group(1), (String)m.group(2));
        }
    }

    return metadata;
}

}
And here is my timer:
private void getMeta() {
    timer.schedule(new TimerTask() {
        public void run() {
            try {
                icy = new IcyStreamMeta(new URL(stationUrl));

                runOnUiThread(new Runnable() {
                     public void run() {
                         try {
                             artist.setText(icy.getArtist());
                             title.setText(icy.getTitle());
                         } catch (IOException e) {
                             e.printStackTrace();
                         } catch (StringIndexOutOfBoundsException e) {
                             e.printStackTrace();
                         }
                     }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

        }
    },0,5000);

}

Much appreciation for any assistance!

A: I've replaced the IcyStreamMeta class in my program and am getting the meta data from the 7.html file that is a part of the SHOUTcast spec. Far less data usage and all that so I feel it is a better option.
I am still using the TimerTask, which is acceptable. There is practically no GC any more and I am happy with using 7.html and a little regex. :)


text:
Q: Build an URL with parameters in R What is the best way to build a request URL with parameters in R?
Thus far I came up with this:
library(magrittr)
library(httr)
library(data.table)
url <- list(hostname = "geo.stat.fi/geoserver/vaestoalue/wfs",
            scheme = "https",
            query = list(service = "WFS",
                         version = "2.0.0",
                         request = "GetFeature",
                         typename = "vaestoalue:kunta_vaki2017",
                         outputFormat = "application/json")) %>%
       setattr("class","url")
request <- build_url(url)

What I like about the code that I have now, is that I can easily change parameter values and rebuild the URL.
Also, the resulting url is properly html encoded:
https://geo.stat.fi/geoserver/vaestoalue/wfs/?service=WFS&version=2.0.0&request=GetFeature&typename=vaestoalue%3Akunta_vaki2017&outputFormat=application%2Fjson

But loading the data.table library, only to build an url, just doesn't feel right. Is there a better to do this?

A: You absolutely don't need data.table to build URLs. As José noted, it was loaded to use a single convenience function you can just mimic with:
set_class <- function(o, v) { class(o) <- v ; invisible(o) }

Also, unless the goal is to have a URL vs just read data from a site, you can also just use httr verbs:
httr::GET(
  url = "https://geo.stat.fi/geoserver/vaestoalue/wfs",
  query = list(
    service = "WFS",
    version = "2.0.0",
    request = "GetFeature",
    typename = "vaestoalue:kunta_vaki2017",
    outputFormat = "application/json"
  )
) -> res

dat <- httr::content(res)

str(dat, 1)
## List of 5
##  $ type         : chr "FeatureCollection"
##  $ totalFeatures: int 311
##  $ features     :List of 311
##  $ crs          :List of 2
##  $ bbox         :List of 4


text:
Q: Let display:none elem slideRight(); I'm trying to make a menu in CSS where only icons are visible as buttons, but when you hover over them, the text next to the icon must be shown. The thing is that I want to animate the effect of showing the text with a slideDown() like effect, only then to the right.
The HTML (which includes fontawesome for the icons):

Home

Team

Management

Settings

Mail Jobs

The CSS:
nav {
    position:fixed;
    top:20px;
    background:#701313;
    border-radius:0 30px 30px 0;
    font-family:'Open Sans', sans-serif;
}
nav ul {
    margin:0px;
    padding:0px 20px;
    width:56px;
}
nav ul li {
    font-size:23px;
    display:block;
    width:3000px;
    margin:40px 0;
}
nav ul li a {
    background:#2e2e2e;
    border-radius: 30px;
    padding:15px 17px;
    color:#FFF;
    text-decoration: none;
}
nav ul li a:hover span {
    display:inline;
}
nav ul li i {
    font-size:28px !important;
}
nav ul li span {
    display:none;
    padding:0 20px;
}

I also included a JSFiddle.
The ideal solution would be pure CSS, but I'm not sure if that's possible. So if it's not possible, a solution with jQuery would be a good outcome.

A: You can do that with CSS3 animation but you have to specify fixed width to the a elements. That will make it less dynamic.
jQuery can be used to update the width value and the CSS3 animation will be triggered by that. I have modified your CSS and added simple JS function to update the width value.
    nav ul li a {
        background:#2e2e2e;
        border-radius: 30px;
        padding:15px 0;
        color:#FFF;
        text-decoration: none;
        overflow:hidden;
        width:60px;
        display:inline-block;
        -webkit-transition: width 0.5s; /* For Safari 3.1 to 6.0 */
        transition: width 0.5s;
    }
    nav ul li a:hover {
    }

    nav ul li a:hover span {
        opacity: 1;
    }
    nav ul li i {
        margin-left:16px;
        font-size:28px !important;
    }
    nav ul li span {
       position:absolute;
        padding:0 20px;
        opacity: 0;
        -webkit-transition: opacity 0.9s; /* For Safari 3.1 to 6.0 */
        transition: opacity 0.9s;
    }

And the Javascript code:
$(function(){
    $("nav ul li a").hover(function(){
        $(this).css("width", $(this).find("span").innerWidth() + 50);
    }, function(){
        $(this).css("width", 60);
    });
});

*

*You need to include the jQuery lib.

*You can change the animation in your CSS.


text:
Q: How to fill a linked list with elements I already have? I am trying to create a linked list with elements I have, but I need 24 nodes for this and I don't want to end up like this:
head->next->next->next->next->next->next->next->id = 1;

How can I prevent this?
I tried creating something likes but all nodes(obviously) are pointing the same data.
void init_board(block **head)
{
    block temp;

    temp.id=0;
    temp.name="Start";
    temp.price=0;
    temp.rent=0;
    temp.next = NULL;

    *head = &temp;
    (*head)->next = NULL;
    (*head)->next = (block*) malloc(sizeof(block*));
    temp = head->next;

    temp.id=1;
    temp.name="End";
    temp.price=16000;
    temp.rent=800;
    temp.next = NULL;
}

A:
I am trying to create a linked list with elements I have, but I need 24 nodes for this and I don't want to end up like this:
head->next->next->next->next->next->next->next->id = 1;
How can I prevent this?

updating head (not only *head)

 block temp;
 ...
 temp = head->next;

you cannot do that, because temp is s struct but next a pointer

I tried creating something likes but all nodes(obviously) are pointing the same data.

you need to allocate a new cell for all the new element, including for the first you currently put in the stack (never return the address of something saved in the stack)

(head)->next = (block) malloc(sizeof(block*));

this is not what you want, you need to alloc for a block, not for a block *
Example initializing with two cells :
void init_board(block **plast)
{
  *plast = malloc(sizeof(block));
  (*plast)->id=0;
  (*plast)->name="Start";
  (*plast)->price=0;
  (*plast)->rent=0;
  (*plast)->next = malloc(sizeof(block));
  plast = &(*plast)->next;
  (*plast)->id=1;
  (*plast)->name="End";
  (*plast)->price=16000;
  (*plast)->rent=800;
  (*plast)->next = NULL;
}

int main()
{
   block * l;

   init_board(&l);
}

Of course if you have 20 block to initialize to expanse each case is not practical, may be the values come from a file or an array like that :
#include <stdio.h>
#include <stdlib.h>

typedef struct block {
  int id;
  const char * name;
  int price;
  int rent;
  struct block * next;
} block;

const block Boards[] = {
  { 0, "Start", 0, 0, NULL },
  { 2, "Intermediate", 123, 456, NULL },
  { 1, "End", 16000, 800, NULL }
};

void init_board(block **plast)
{
  for (const block * b = Boards; b != Boards + sizeof(Boards)/sizeof(Boards[0]); ++b) {
    *plast = malloc(sizeof(block));

    (*plast)->id = b->id;
    (*plast)->name = b->name;
    (*plast)->price = b->price;
    (*plast)->rent = b->rent;
    (*plast)->next = NULL;
    plast = &(*plast)->next;
  }
}

int main()
{
  block * blocks;

  init_board(&blocks);

  /* debug */
  for (block * b = blocks; b != NULL; b = b->next)
    printf("%d %s %d %d\n", b->id, b->name, b->price, b->rent);

  /* free resources */
  while (blocks != NULL) {
    block * b = blocks;

    blocks = blocks->next;
    free(b);
  }

  return 0;
}

Compilation and execution :
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall l.c
pi@raspberrypi:/tmp $ ./a.out
0 Start 0 0
2 Intermediate 123 456
1 End 16000 800

Execution under valgrind :
pi@raspberrypi:/tmp $ valgrind ./a.out
==6819== Memcheck, a memory error detector
==6819== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6819== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==6819== Command: ./a.out
==6819==
0 Start 0 0
2 Intermediate 123 456
1 End 16000 800
==6819==
==6819== HEAP SUMMARY:
==6819==     in use at exit: 0 bytes in 0 blocks
==6819==   total heap usage: 4 allocs, 4 frees, 1,084 bytes allocated
==6819==
==6819== All heap blocks were freed -- no leaks are possible
==6819==
==6819== For counts of detected and suppressed errors, rerun with: -v
==6819== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $

A: struct link
{
  int data;
  int dataOne;
  // data n....
   struct link* link;
};
// HeadNode
struct link* pHeadLink = NULL;
//add the link and return the current.
struct link* appendLink()
{
   if(pHeadLink == NULL)
   {
     pHeadLink = (struct link*) malloc(sizeof(struct link));
     pHeadLink->link = NULL;
     return pHeadLink;
  }
  struct link *pTempLink = pHeadLink;
  while(pTempLink->link != NULL)
  {
     pTempLink = pTempLink->link;
  }
  pTempLink->link = (struct link*) malloc(sizeof(struct link));
  pTempLink->link->link = NULL;
  return pTempLink;
}
// calling function:
int fun()
{

 loop() // loop for 24 times.
{
  struct link* pFillDataLink = appendLink();
   // here you can fill rest the items like below.
   pFillDataLink->data = 34;
   pFillDataLink->dataOne = 334;
   // etc....
}
}


text:
Q: inserting values to an array of pointers to linked lists, the array is in a struct | C i have been trying to figure out the problem for 7-8h,
the thing that i must build a matrix multiplication func, using a given structs and an array of pointers to linked lists(The Matrix)
everything must be allocated by malloc,
Here is the given structs:
typedef struct cellNode
    {
        int cell;
        struct cellNode* next;
    } Node;
typedef struct matrix
    {
        int numRows;
        int numColumns;
        Node** rows;
    } Matrix;

and here is the function to build the matrix and to allocate it:
Matrix* MatrixBuilder(Matrix* A, int rows, int cols)
{
    int i=0;
    A->numColumns=cols;
    A->numRows=rows;

    A->rows = (Node**)malloc(rows * sizeof(Node*));
    if (A->rows == NULL)
    {
        printf("memory error!");
        exit(1);
    }

    for (i=0; i<rows; i++)
    {
    A->rows[i] = (Node*)malloc(rows * sizeof(Node));
    if (A->rows[i] == NULL)
    {
        printf("memory error!");
        exit(1);
    }
    }
    for (i=0; i<rows; i++)
    {
        A->rows[i] = NULL;
    }
    return A;

}

and here is the function to build the node, with a given data and link it to the list:
Matrix* MatrixBuilder(Matrix* A, int rows, int cols)
{
    int i=0;
    A->numColumns=cols;
    A->numRows=rows;

    A->rows = (Node**)malloc(rows * sizeof(Node*));
    if (A->rows == NULL)
    {
        printf("memory error!");
        exit(1);
    }

    for (i=0; i<rows; i++)
    {
    A->rows[i] = (Node*)malloc(rows * sizeof(Node));
    if (A->rows[i] == NULL)
    {
        printf("memory error!");
        exit(1);
    }
    }
    for (i=0; i<rows; i++)
    {
        A->rows[i] = NULL;
    }
    return A;

}

and this is my main function:
int main()
{
    int n,m,k,i,x,j=0; /* x to help me insert integers into the list */
    Matrix* A = (Matrix*)malloc(sizeof(Matrix));
    Matrix* B = (Matrix*)malloc(sizeof(Matrix));
    Matrix* C = (Matrix*)malloc(sizeof(Matrix));

    printf("please enter n:");
    scanf("%d",&n);

    printf("please enter m:");
    scanf("%d",&m);

    printf("please enter k:");
    scanf("%d",&k);

    A = MatrixBuilder(A, n, m);
    B = MatrixBuilder(B, m, k);
    C = MatrixBuilder(C, n, k);

    for (i=0; i<n; i++)
    {
        printf("Enter row %d data\n",i);
        for (j=0; j<m; j++)
        {
            scanf("%d", &x);
            NodeBuilder_Insert(A->rows[j], x);
        }
    }

    return 0;
}

when i run it, it stops right when i enter the first element in first row, so i quess the problem is in the NodeBuilder function, but i cant find it,
and i am not sure if i allocated everything properly...


text:
Q: I had created a package npm for test and i can't retrieve the params of my function after install it [enter image description here][1]
import {addTwo} from 'testrol';
console.log(addTwo('2'));
addTwo(2);

**i publish a npm package for test before publish our packages. When i install it (testrol), i can't see the params of my function when my mouse over**

A: Welcome, calsuoile !
Did you export the types of your lib?
You can find more information about how to do it on typescript publishing docs


text:
Q: Is it possible to create a macro to hide/show rows 5 to 28, assigned to a button that will translate to iOS/android? I've created a spreadsheet to help calculate drug doses in pediatrics. My hospital would like to make it look like more of a form: Input weight + age, click "go" and the doses appear below in the table. The idea is anyone can download the file from the trust when they need it, to a computer or more likely; their mobile phone.
So far I've been able to create a macro and assign it to the button to achieve this on a computer, however it doesn't translate to iOS or Android.
Is there a way around this?
Would it be simpler to create a hyperlink to another sheet showing the table of doses?

A: Here's an interesting looking age/weight dosage calculator from Medscape.com


text:
Q: PHP, how to check for uppercase/lowercase/numbers/special in regex I'm trying to create a class which validates parameters passed into a function, only primitive values though. I've so far done integer, boolean and float. However with my string function, I also want to be able to pass in a parameters about allowed character sets.
Like:

*

*Allowed upper case

*Allowed lower case

*Allowed numbers

*Allowed special characters

However, I can't figure out how to test this. I've tried doing it with regex, but my best trials aren't working too well.
Any nudge in the right direction would be a great help.
Please note, I'm using an old version for PHP - 5.1.2

A: Depends on what specials. Can try this and use with preg_match.
preg_match('/^[[:alnum:][:punct:]]+$/', $str)

Check out demo at regex101

*

*[:alnum:] matches [a-zA-Z0-9]

*[:punct:] matches [!"#$%&'()*+,\-./:;<=>?@[\\\]^_{|}~] and backtick.

*+ one ore more from ^ start to $ end

See more posix classes

A: Try this:
if(!preg_match('/[.\s]/', $string))
{
  // it contains any single character except dot and white space
  // you can change not permitted list on your demand
}


text:
Q: Can I use comma after "because" in the middle of the sentence? Is the following comma after "because" correct or not?

I don't like flowers because, they smell bad.

If not, why?

For reference, my full sentence:

An effective leader is who connects skills and personalities which are shaped by experience, and not always realistic to leadership expectations without sex difference because, accomplishment oriented development efforts in American culture and are often effective whether qualities of traits are masculine or feminine as long as has empathetic influence towards tasks.

A: No, you can't, but you can say this instead:

I don't like flowers, because they smell bad.

Anyway it doesn't sound natural, but it's correct. It's better if you say

I don't like flowers because they smell bad.


text:
Q: Is there a relationship between germs and Taylor coefficients? For the definition of germ, please see below.
I am having some difficulty internalizing the  concept of germ due to an inability to think of concrete examples, which led to me having the following questions:

1. Are the germs of holomorphic functions (at a point $p$) simply single-element equivalence classes, because the Identity theorem implies that any two holomorphic functions which agree identically on a neighborhood are identical on their entire domains of definition?
2. Can one describe the members of the equivalence class of a smooth germ explicitly for simple enough examples? E.g. Let $M=\mathbb{R}$, and let $f(x)=x$, then is the germ of $x$ at $0$ just $$[x]_p=\{g\in C^{\infty}: g(0)=0, g'(0)=1,g^{(r)}(0)=0\ \forall\ r \ge 1  \}? $$
3. Do similar results hold for the members of the equivalence class of a $C^k$ germ, e.g. $$[x]_p = \{ g \in C^k: g(0)=0, g'(0)=1, g^{(r)}(0)=0\ \forall\ 1 \le r \le k \}? $$
4. Two distinct (real or complex) analytic functions cannot coincide on a neighborhood of a point -- is this the smallest class of functions for which this holds? (I.e. are germs non-trivial precisely for classes of functions which do not always coincide with their Taylor series, and are the equivalence classes simply the functions with the same Taylor series up to a certain order?)

My conjectures are motivated by the idea of derivatives being "infinitesimal" or local approximations of functions, as well as the fact that the standard example of a non-analytic smooth function is the only function I can think of which belongs to the germ of another function, but other than this intuition I have no reason to think that the germs of analytic, smooth, or differentiable functions can be described in the manner above.
That and this comment in Lee (on p.72):

The germ definition has a number of advantages. One of the most significant is that it makes the local nature of the tangent space clearer, without requiring the use of bump functions. Because there do not exist analytic bump functions, the germ definition of tangent vectors is the only one available on real-analytic or complex-analytic manifolds.

The only reason I might suspect that these are false is that they would lead to a much simpler definition (in my opinion) then the one given in the book. On the other hand, a definition of germs based on equality of Taylor coefficients would not generalize very well to classes of continuous functions and the like, which is perhaps the intent.

Definition: (taken from p.71 of Introduction to Smooth Manifolds by John Lee):

A smooth function element on [a smooth manifold] $M$ is an ordered pair $(f,U)$, where $U$ is an open subset of $M$ and $f: U \to \mathbb{R}$ is a smooth function. Given a point $p \in M$, let us define an equivalence relation on the set of all smooth function elements whose domains contain $p$ by setting $(f,U) \sim (g,V)$ if $f \equiv g$ on some neighborhood of $p$. The equivalence class of a function element $(f,U)$ is called the germ of $f$ at $p$. The set of all germs of smooth functions at $p$ is denoted by $C_p^{\infty}(M)$... Let us denote the germ at $p$ of the function element $(f,U)$ simply by $[f]_p$; there is no need to include the domain of $U$ in the notation, because the same germ is represented by the restriction of $f$ to any neighborhood of $p$. To say that two germs $[f]_p$ and $[g]_p$ are equal is simply to say that $f \equiv g$ on some neighborhood of $p$, however small.

Related questions (in which I could not find the answer): (1) (2) (3) (4) (5) (6) (7) (8) (9)

A: *

*The equivalence class of a function element $(f,U)$ around $p \in M$ will never consist of a single element unless the topology of $M$ is such that you can find an open neighborhood $V$ of $p$ which is "minimal" in the sense that any other open neighborhood $V$ of $p$ must contain it. Otherwise, you can take some open neighborhood $p \in V \subsetneq U$ and consider the different (but equivalent) function element $(f|_{V}, V)$.
The identity theorem implies that if $(f, U)$ and $(g,V)$ are holomorphic equivalent function elements around $p$ and if $U \cap V$ is connected, then $f|_{U \cap V} = g|_{U \cap V}$ which won't necessarily be the case if you will work with smooth or continuous functions. However, a different version of the identity theorem states that if $f \colon U \rightarrow \mathbb{C}$ and $g \colon V \rightarrow \mathbb{C}$ are holomorphic functions with $p \in U \cap V$ and $f^{(i)}(p) = g^{(i)}(p)$ for all $i \geq 0$ then $f$ and $g$ will agree on an open neighborhood of $p$ and so they will define the same germ. Hence, you can describe a germ $[f]$ of holomorphic functions at $p$ by providing a list of all derivatives of $f$ (or any other $g$ with $[g] = [f]$) at $p$. In fact, it is more convenient to provide the list $(a_0, \dots, a_n, \dots)$ of the coefficients of the local power series expansion $f(z) = \sum_{n=0}^{\infty} a_n (z - p)^n$ which are given by $a_n = \frac{f^{(n)}(p)}{n!}$. This way, you can see that not all possible sequences arise as a germ of some function elements - only those sequences for which the power series defined by $\sum_{n=0}^{\infty} a_n (z - p)^n$ converges in a neighborhood of $p$. Thus, the set of germs of a holomorphic function at $p$ is in bijection with the set
$$ \left \{ (a_0, \dots, a_n, \dots) \, \big| \, a_i \in \mathbb{C}, \limsup_{n \to \infty} |a_n|^{\frac{1}{n}} < \infty \right \}. $$

*You can't describe nicely the germ of a smooth/$C^k$/continuous function around $p \in M$ unless $M$ is zero dimensional. If $f \colon \mathbb{R} \rightarrow \mathbb{R}$ and $g \colon \mathbb{R} \rightarrow \mathbb{R}$ are smooth and define the same germ around $x = 0$ then $f^{(i)}(x) = g^{(i)}(x)$ for all $i \geq 0$ but this list is not enough to characterize explicitly the germ. For example, the zero function and the function $e^{-\frac{1}{x^2}}$ (a standard example for a function whose taylor series converges, but not to the function) share the derivatives of all orders at $x = 0$ but do not define the same germ. Characterizing the germ of a function in some category is the same as characterizing all possible local behaviors of functions and this is hopeless unless the category is rigid in some sense (for example, if you work with holomorphic/analytic/polynomial functions).


text:
Q: How to Improve GWT XML parsing? How to Improve xml parsing in GWT ?
My xml is as follows with 1 record
To parse 100 Record GWT takes 8 sec
Is there any way to improve performance ? Plz see my gwt code to parse xml
< Record productid="0" productidext="0" productkeyid="16000" productversion="1" isFEDRecord="false" validationstatus="" selected="false" accessmode="modify" isedited="false">
< RecordAttribute name="CINTEGERATTR" edited="false">
< Value>12345678< /Value>
< OldValue>12345678< /OldValue>
< /RecordAttribute>
< /Record>
My GWT parsing code is as follows:

private static List parseRecords(Document mainDOM,
              List records) {
          NodeList  recordNodeList = mainDOM.getElementsByTagName("Record"); //Record node
          RecordInfo recordInfo= null;

    for(int i=0;i<recordNodeList.getLength();i++){ //iteration over record node

        recordInfo = new RecordInfo();
        recordInfo.setColumnCount(columnInfoList.size());
        recordInfo.setColumnInfoList(columnInfoList);
        HashMap<String, String> recordsColumnValueHashMap = new HashMap<String, String>();

        Element element = ((Element)recordNodeList.item(i));  //Record node

        NamedNodeMap recNodeMap = recordNodeList.item(i).getAttributes();
        if(i==0){

        }else{

            recordInfo.setProductid(recNodeMap.getNamedItem("productid").getNodeValue());
            recordInfo.setProductidext(recNodeMap.getNamedItem("productidext").getNodeValue());
            recordInfo.setProductkeyid(recNodeMap.getNamedItem("productkeyid").getNodeValue());
            recordInfo.setProductversion(Integer.parseInt(recNodeMap.getNamedItem("productversion").getNodeValue()));
            recordInfo.setFEDRecord(Boolean.parseBoolean(recNodeMap.getNamedItem("isFEDRecord").getNodeValue()));
            recordInfo.setValidationstatus(recNodeMap.getNamedItem("validationstatus").getNodeValue());
            recordInfo.setSelected(Boolean.parseBoolean(recNodeMap.getNamedItem("selected").getNodeValue()));
            recordInfo.setAccessmode(recNodeMap.getNamedItem("accessmode").getNodeValue());
            recordInfo.setIsedited(recNodeMap.getNamedItem("isedited").getNodeValue());
        NodeList recList = element.getElementsByTagName("RecordAttribute");

        for(int j=0;j<recList.getLength();j++){ //iterating all record attributes
            NodeList  child = recList.item(j).getChildNodes();

recordInfo.setColumnNameInRecord(recList.item(j).getAttributes().getNamedItem("name").getNodeValue());
                recordInfo.setColumnInRecordEdited(Boolean.parseBoolean(recList.item(j).getAttributes().getNamedItem("edited").getNodeValue()));
                for(int k=0;k

                if("Value".equalsIgnoreCase(child.item(k).getNodeName())){
                    if(child.item(k).getFirstChild()!=null){
                        String value = child.item(k).getFirstChild().getNodeValue();
                    //System.out.println("Value =  "+child.item(k).getFirstChild().getNodeValue());
                    recordInfo.setValue(value);
                    String columnName = recList.item(j).getAttributes().getNamedItem("name").getNodeValue();
                    recordsColumnValueHashMap.put(columnName, value);
                }
                }
                if("OldValue".equalsIgnoreCase(child.item(k).getNodeName())){
                    if(child.item(k).getFirstChild()!=null){
                        String oldValue = child.item(k).getFirstChild().getNodeValue();
                    //System.out.println("oldValue  ="+child.item(k).getFirstChild().getNodeValue());
                    recordInfo.setOldValue(oldValue);
                    }
                }
            }

        }
         recordInfo.setRecordHashMap(recordsColumnValueHashMap);
        }

        records.add(recordInfo);
    }
    return records;
}

A: are your running in development mode or have you compilded it to actuall JavaScript code. In my experince development mode runds 10 times slower then when it is cross compiled to JavaScript. Still 8s is alot! Have you used Speedtrace to see where most of the time is lost?

A: It seems highly unlikely that the 8sec is being spent parsing - my guess is that it is spent trying to find resources on the network such as a DTD access.