text:
Q: SSMS stuck scripting database objects SQL Server Management Studio sits stuck, after scripting all objects in a database. Except it didn't script all objects in a database.
i scripted all the objects in an SQL Server 2008 database from SQL Server Management Studio (three times):

And it says it scripted all the objects, except it never actually completes - sitting there stuck:

It does manage to script three objects:

But not all the objects.
You'll notice:

*

*the UI says it sucessfully scripted all 189 objects

*the UI is stuck; the Close button is disabled

*the folder that contains the "successfully" scripted database objects doesn't contain all the successfully scripted database objects.

Which begs the question:

How do i script the objects of an SQL Server 2008 databasein SSMS?

Update: It can script any VIEW, STORED PROCEDURE, or FUNCTION, without issue. But if i choose to script just the first table, it fails:

It also fails if i script tables:

*

*A - M

*O - Z

*A - G
This never-ending bug was the reason we bought SQL Compare four years ago; you couldn't trust Microsoft's tool to script a database correctly (silently omitting tables).
Update: Scripting options
Here's the set of scripting options in use

*

*ANSI Padding: True

*Append to File: False

*Continue scripting on Error: False

*Convert UDDTs to Base Types: False

*Generate Script for Dependent Objects: False

*Include Descriptive Headers: True

*Include If NOT EXISTS: False

*Include system constraint names: False

*Schema qualify object names.: True

*Script Bindings: False

*Script Collation: True

*Script Create: True

*Script Defaults: True

*Script Drop: False

*Script Extended Properties: True

*Script for Server Version: SQL Server 2008

*Script Logins: False

*Script Object-Level Permissions: False

*Script Statistics: Script statistics

*Script USE DATABASE: True

*Script Change Tracking: False

*Script Check Contraints: True

*Script Data: False

*Script Data Compression Options: False

*Script Foreign Keys: True

*Script Full-Text Indexes: True

*Script Indexes: True

*Script Primary Keys: True

*Script Triggers: True

*Script Unique Keys: True

*

*My related question from 4 years ago: SQL Server Management Studio not scripting all objects


text:
Q: AVG Scan Results I'm new in Ubuntu World.I have installed Avg 2013 on my Ubuntu LTS 12.04.
I'm using only the command line scanner. I would like to access the results summary (scan profile), after scanning the disk, and copy them in a txt.
Having tried access avgvlog file but doesn't display the summary...
Any ideas??

A: You can use -r option with avgscan to save your report into a text file.
For example
 avgscan /directory/to/scan -r report.txt

It will store your scan summery in the report.txt file with all relevant details.
From man avgscan
   -r FILE, --report FILE
          Save scan report to specified file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to clear screen in C without any system function or library? Clear Screen in the C programming language without use of the system function or any library?
#include<stdio.h>
void main()
{
    char name[11]="abhinay";
    // The ANSI character to print the "name value"  in the colorful form.
    printf("%c[36m%s\n\n", (char) 27,name);
    printf("\n Hellow world\n");
    printf("[36m %s \n\n", name);

}

A: There is no standard or portable way, it depends on your terminal emulator.
You can do it with ANSI escape sequences, which seems to be what you're using.
This Wikipedia page indicates that ED (erase display) is the right command, with code 2, i.e. printf("%c2J", 27);.


text:
Q: Implementing map function I am creating a 'SpecialList' and am require to implement the map function. The list should be lazy, and will only produce values when evaluated.
toString() returns "?" if the value is not yet available; returns the string representation of the value otherwise.
get() called when the contents is needed. If the value is already available, return that value; otherwise, compute the value and return it. The computation should only be done once for the same value.
Here's what I have:
public <U> SpecialList<U> map(Function<T, U> mapper) {
    if (!this.isAvailable) {
        return new SpecialList<U>(this.supplier);
    }
    return new SpecialList<U>(mapper, value);
}

// private constructor
private SpecialList(CachedSupplier<T> s) {
    this.supplier = s;
    this.isAvailable = false;
}

However, it is telling me that there's no valid constuctor because T cannot be converted to U.
SpecialList.java:65: error: no suitable constructor found for SpecialList(SpecialList<T>.CachedSupplier<T>)
            return new SpecialList<U>(this.supplier);
                   ^
    constructor SpecialList.SpecialList(U) is not applicable
      (argument mismatch; SpecialList<T>.CachedSupplier<T> cannot be converted to U)
    constructor SpecialList.SpecialList(Supplier<U>) is not applicable
      (argument mismatch; SpecialList<T>.CachedSupplier<T> cannot be converted to Supplier<U>)

Doesn't the 'U' become a T when returned?
How do I go about solving this? I am still a little unclear about the method level generic types. But I was told that I need to add the < U > for my map method.
Below is my code in full:
class SpecialList<T> {
    class CachedSupplier<T> {
        private Supplier<? extends T> supplier;
        private T value;
        boolean isAvailable;

        public CachedSupplier(Supplier<? extends T> supplier) {
            this.supplier = supplier;
        }

        public T get() {
            if (!isAvailable) {
                value = supplier.get();
                isAvailable = true;
            }
            return value;
        }
    }

    private CachedSupplier<T> supplier;
    private T value;
    boolean isAvailable;

    private SpecialList(T value) {
        this.value = value;
        this.isAvailable = true;
    }

    private SpecialList(Supplier<T> s) {
        this.supplier = new CachedSupplier<T>(s);
        this.isAvailable = false;
    }

    private SpecialList(CachedSupplier<T> s) {
        this.supplier = s;
        this.isAvailable = false;
    }

    private <R> SpecialList(Function<T, R> mapper, T v) {
        this.supplier = new CachedSupplier<T>(() -> mapper.apply(v));
        this.isAvailable = false;
    }

    public static <T> SpecialList<T> of(T value) {
        return new SpecialList<>(value);
    }

    public static <T> SpecialList<T> of(Supplier<T> supplier) {
        return new SpecialList<>(supplier);
    }

    public <R> SpecialList<R> map(Function<? super T,? extends R> mapper) {
        if (!this.isAvailable) {
            return new SpecialList<>(this.supplier);
        }
        return new SpecialList<R>(mapper, value);
    }

    public T get() {
        if(this.isAvailable) {
            return this.value;
        } else {
            this.value = this.supplier.get();
            this.isAvailable = true;
            return this.value;
        }
    }
}

I am still a little confused with Generic Types etc. so please let me know if there's anything odd/I can improve!
Thanks

A: According to the code you posted, there is a compile-time error in one of the constructors for class SpecialList...
private <R> SpecialList(Function<T, R> mapper, T v) {
    this.supplier = new CachedSupplier<T>(() -> mapper.apply(v));
    this.isAvailable = false;
}

Firstly, in the code you posted, there is no constructor in inner class CachedSupplier that takes a Function parameter, so you need to add one with this signature:
public <R> CachedSupplier(Function<T, R> mapper)

And the second problem with the SpecialList constructor is the lambda expression. Abstract method apply in interface Function has a parameter, which your lambda expression is missing. So the constructor code should be:
private <R> SpecialList(Function<T, R> mapper, T v) {
    this.supplier = new CachedSupplier<T>((v) -> mapper.apply(v));
    this.isAvailable = false;
}

A: I think you're doing an overkill by checking isAvailable in both, the SpecialList and the CachedSupplier. It seems enough to me to do so in the CachedSupplier and reduce the members of SpecialList to just the supplier (which is, when the value is available, simply a value-getter without additional costly evaluations). And in the constructors you make sure that the supplier is a cached one, when needed (i.e. when you don't have the value yet).
So here's my suggestion. Further comments are directly in the source code (which compiles now without errors or warnings):
class SpecialList<T> {
static class CachedSupplier<R> implements Supplier<R> {
    /* R is a priori an idependent parameter. If you call it T again, then you get a warning
     * that the original T is hidden within the new nested class (though it wouldn't really matter here),
     * as one doesn't need to refer to it. I made it static, as you don't need an instance to define it. */
    private Supplier<? extends R> supplier;
    private R value;
    boolean isAvailable;

    public CachedSupplier(Supplier<? extends R> supplier) {
        this.supplier = supplier;
        this.isAvailable = false;
    }

    @Override
    public R get() {
        if (!isAvailable) {
            value = supplier.get();
            isAvailable = true;
        }
        return value;
    }
}

private Supplier<T> supplier;

private SpecialList(T value) {
    /* in this case no lazy evaluation and no caching needed */
    this.supplier = () -> value;
}

private SpecialList(Supplier<T> s) {
    this.supplier = new CachedSupplier<T>(s);
}

private SpecialList(CachedSupplier<T> s) {
    this.supplier = s;
}

private <R> SpecialList(Function<R, T> mapper, R v) {
    /* This constructor is not needed anymore in my suggested code.
     * I left it simply, in order to show how to fix the type errors related to it.
     * if I understood correctly the intentions of this constructor,
     * R and T have to be swapped w.r.t the original post.
     * This is a constructor that uses an R-value and a mapper R->T to create a SpecialList<T> */
    this.supplier = new CachedSupplier<T>(() -> mapper.apply(v));
}

public static <T> SpecialList<T> of(T value) {
    return new SpecialList<>(value);
}

public static <T> SpecialList<T> of(Supplier<T> supplier) {
    return new SpecialList<>(supplier);
}

public <R> SpecialList<R> map(Function<T, R> mapper) {
    /* mapper is here different (opposite direction) than in the last of the constructors.
     * Here we have an existing SpecialList containing a value of Type T which will be turned into a
     * SpecialList containing a value of type R by applying a mapper T->R after getting the value from
     * the original SpecialList */

    return new SpecialList<R>(() -> mapper.apply(get()));
}

public T get() {

    return this.supplier.get();
}
}

This solution doesn't yet take care of the toString() implementation. When you want to implement also the latter, it might be more natural to make SpecialList a subclass of CachedSupplier (with the additional map- and toString- methods and direct access to isAvailable)

A: The problem is your map function is changing the SpecialList type parameter from T to R. But in the fragment highlited by compiler you return still SpecialList.
Things you can do:

*

*If you are not planning to change the type of elements with your map() function, get rid of R, and replace Function<? super T,? extends R> mapper with Function<? super T,? extends T> mapper. However, this way the mapper would be totaly omited, which might not be the desired behaviuor.

*Otherwise, you should pass into your SpecialList constructor a combination of the original supplier and new mapper like so:

    return new SpecialList<R>(() -> {
        T originalValue = this.supplier.get();
        return mapper.apply(originalValue);
    };


text:
Q: malloc function crash I have a problem with memory allocation using malloc.
Here is a fragment from my code:
    printf("DEBUG %d\n",L);
    char *s=(char*)malloc(L+2);
    if(s==0)
    {
      printf("DEBUGO1");
    }
    printf("DEBUGO2\n");

It outputs "DEBUG 3",and then a error msgbox appears with this message:

The instruction at 0x7c9369aa referenced memory at "0x0000000".   The
  memory could not be read

For me such behavior is very strange.
What can be wrong here?
The application is single threaded.
I'm using mingw C compiler that is built in code::blocks 10.05
I can provide all the code if it is needed.
Thanks.
UPD1:
There is more code:
char *concat3(char *str1,char *str2,char *str3)
{
    /*concatenate three strings and frees the memory allocated for substrings before*/
    /* returns a pointer to the new string*/

    int L=strlen(str1)+strlen(str2)+strlen(str3);
    printf("DEBUG %d\n",L);
    char *s=(char*)malloc(L+2);
    if(s==0)
    {
      printf("DEBUGO1");
    }
    printf("DEBUGO2\n");
    sprintf(s,"%s%s%s",str1,str2,str3);
    free(str1);
    free(str2);
    free(str3);
    return s;
}

UPD2:
It seems the problem is more complicated than i thought. Just if somebody has enough time for helping me out:
Here is all the code
Proj
(it is code::blocks 10.05 project,but you may compile the sources without an ide ,it is pure C without any libraries):
call the program as
"cbproj.exe s.pl" (the s.pl file is in the root of the arhive)
and you may see it crashes when it calls  the function "malloc" that is on the 113th line of "parser.tab.c"(where the function concat3 is written).
I do the project in educational purpouses,you may use the source code without any restrictions.
UPD3:
The problem was that it was allocated not enough memory for one of the strings in program ,but the it seemed to work until the next malloc.. Oh,I hate C now:)
I agree with the comments about bad coding style,need to improve myself in this.

A: From the error message it actually looks like your if statement is not quite what you have posted here. It suggests that your if statement might be something like this:
if(s=0) {
}

Note the single = (assignment) instead of == (equality).

A: The problem with this exact code is that when malloc fails, you don't return from the function but use this NULL-pointer further in sprintf call as a buffer.
I'd also suggest you to free memory allocated for str1, str2 and str3 outside this function, or else you might put yourself into trouble somewhere else.

EDIT: after running your program under valgrind, two real problems revealed (in parser.tab.c):
In yyuserAction,
char *applR=(char*)malloc(strlen(ruleName)+7);
sprintf(applR,"appl(%s).",ruleName);

+7 is insufficient since you also need space for \0 char at the end of string. Making it +8 helped.
In SplitList,
char *curstr=(char*)malloc(leng);

there's a possibility of allocating zero bytes. leng + 1 helps.
After aforementioned changes, everything runs fine (if one could say so, since I'm not going to count memory leaks).

A: You cannot use free on pointers that were not created by malloc, calloc or realloc.  From the Manpage:

free()  frees  the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc().  Otherwise,  or if free(ptr) has already been called before, undefined behavior occurs.  If ptr is NULL, no operation is performed.


text:
Q: Segmentation fault when passing array of pointers to function I am currently working on a homeworking question and I have been trying to figure out why I keep getting a segmentation fault (core dump). I have narrowed it down to accessing an array within a function. The goal of the program is to store words from a book in a separate chaining hash table. And we can't use STL.
The array in question (Table size is 30000):
Node* hashTable = new Node[TABLE_SIZE];

The Node:
struct Node {
  unsigned int hash = 0;
  string word;
  int count;
  Node* next;
};

the function prototype that I am using:
int insert(unsigned int hash, string word, Node* table[]);

How I am calling the function:
int result = insert(hashIndex, word, &hashTable);

The function itself (yes I know its not pretty):
int insert(unsigned int hash, string word, Node* table[])
{
  unsigned int hashIndex = hash;

  Node* newNode;
  newNode->hash = hashIndex;
  newNode->count = 1;
  newNode->word = word;
  newNode->next = nullptr;

  if(table[hashIndex % TABLE_SIZE] == nullptr) {
    table[hashIndex % TABLE_SIZE] = newNode;
    return 0;
  }
  else {
    if(table[hashIndex % TABLE_SIZE]->hash == hash) {
      table[hashIndex % TABLE_SIZE]->count++;
      return 2;
    }

    Node* indexPtr = table[hashIndex % TABLE_SIZE]->next;
    while(indexPtr) {
      if(indexPtr->hash == hash) {
        indexPtr->count++;
        return 2;
      }
      indexPtr = indexPtr->next;
    }

    indexPtr->next = newNode;
  }

  return 1;
}

Whenever I try to access anything within hashTable I get a segmentation fault. Any help and criticism would be appreciated.
MINIMUM REPRODUCIBLE EXAMPLE:
#include <iostream>
#include <cctype>
using namespace std;

struct Node {
  unsigned int hash = 0;
  string word;
  int count;
  Node* next;
};

const string FILENAME = "C:/Users/Matthew/CLionProjects/p5/ulyss12.txt";
const int TABLE_SIZE = 30011;

string processWord(string word);
string removePunctuation(string word);
unsigned int hashFunc(string value);
int insert(unsigned int hash, string word, Node* table[]);
void displayHash(Node* table[]);

int main()
{
  Node* hashTable = new Node[TABLE_SIZE];
  string word = "HelloWorld";
  unsigned int hash = hashFunc(word);
  insert(hash, word, &hashTable);

  return 0;
}

string processWord(string word)
{
  if(word.length() >= 5) {
    word = removePunctuation(word);
  }
  else {
    return "";
  }

  return word;
}

string removePunctuation(string word)
{
  int i = 0;
  while(ispunct(word[i])) {
    word.erase(i, 1);
    i++;
  }

  i = word.length()-1;
  while(ispunct(word[i])) {
    word.erase(i, 1);
    i--;
  }

  return word;
}

int insert(unsigned int hash, string word, Node* table[])
{
  unsigned int hashIndex = hash;

  Node* newNode = new Node();
  newNode->hash = hashIndex;
  newNode->count = 1;
  newNode->word = word;
  newNode->next = nullptr;

  if(table[hashIndex % TABLE_SIZE] == nullptr) {
    table[hashIndex % TABLE_SIZE] = newNode;
    return 0;
  }
  else {
    if(table[hashIndex % TABLE_SIZE]->hash == hash) {
      table[hashIndex % TABLE_SIZE]->count++;
      return 2;
    }

    Node* indexPtr = table[hashIndex % TABLE_SIZE]->next;
    while(indexPtr) {
      if(indexPtr->hash == hash) {
        indexPtr->count++;
        return 2;
      }
      indexPtr = indexPtr->next;
    }

    indexPtr->next = newNode;
  }

  return 1;
}

unsigned int hashFunc(string value)
{
  const char* str = value.c_str();
  int length = value.length();

  unsigned int hash = 5381;
  int i    = 0;

  for (i = 0; i < length; ++str, ++i)
  {
    hash = ((hash << 5) + hash) + (*str);
  }

  return hash;
}

A: Thanks to both @AlanBirtles, @user4581301, and @tadman for the answers that they provided. It turns out that I had not initialized the nodes within the array to anything, so a simple for loop going through the hashTable array and setting everything to nullptr, along with the suggestions from the aforementioned users fixed the problem I was having.
SOLUTION
  Node** hashTable = new Node*[TABLE_SIZE]{};

Credit it @Eljay for the suggestion to use the curly brackets instead of a for loop.
If there is any further issues that any of you have noticed. Please comment. Or something.


text:
Q: Self join to compare quarterly data from same table? I'm helping a small rural health system add some databanking to their operations. They currently keep track of some operational statistics that they report each quarter.
I'd like to put the meat of these responses in one table and do historical comparisons from it. I'll have some additional tables for normalization, but here's the main one.
+-------+----------+-------------+----------+
| year  | quarter  | question_id | response |
+-------+----------+-------------+----------+
| 2000  | 1        | 100         | 50       |
+-------+----------+-------------+----------+
| 2000  | 2        | 100         | 100      |
+-------+----------+-------------+----------+
| 2000  | 1        | 200         | 75       |
+-------+----------+-------------+----------+
| 2000  | 2        | 200         | 25       |
+-------+----------+-------------+----------+

The output I'm looking for is to put those quarterly responses for each question side-by-side so I can calculate changes better and easy up my PHP processing. Below is the desired output:
+-------------+----------------------+----------------------+
| question_id | 1st quarter response | 2nd quarter response |
+-------------+----------------------+----------------------+
| 100         | 50                   | 100                  |
+-------------+----------------------+----------------------+
| 200         | 75                   | 25                   |
+-------------+----------------------+----------------------+

I'm new to SQL (using MySQL 5) and the only thing I can think of is I need a self join. I've tried but can't seem to get it. Am I approaching the table structure the correct way for this kind of historical analysis?
Any pointers would be a big help and a help to our project!
Thanks!

A: You could group by question, and then use a combination of case and max to select the answer for that quarter.
select  question_id
,       max(case when quarter = 1 then question_responses end) as Q1
,       max(case when quarter = 2 then question_responses end) as Q2
,       max(case when quarter = 3 then question_responses end) as Q3
,       max(case when quarter = 4 then question_responses end) as Q4
from    question_responses
where   year = 2000
group by
        question_id

In this example the max doesn't actually max anything, it ends up selecting the only quarter for which the case returns a value.

A: Well assuming you want to get that output for a specific year, eg. 2000:
SELECT
    question_id,
    (SELECT response FROM question_responses WHERE year = qr.year AND question_id = qr.question_id AND quarter = 1) AS qrt_resp_1,
    (SELECT response FROM question_responses WHERE year = qr.year AND question_id = qr.question_id AND quarter = 2) AS qrt_resp_2
    FROM question_responses AS qr
    WHERE year = 2000
    GROUP BY question_id


text:
Q: AWS HTTPS dropping HTTP_REFERER I have an application that is running in PHP. I have a ELB classic load balancer in AWS routing HTTPS requests.
I am trying to get the referer URL (understanding this isn't always present) but when I first load the page I can see it appear but then it immediately disappears. I'm guessing this is because ELB is routing HTTPS to HTTP and the page immediately assumes the current domain is the referer. Buuut, I don't know if this is correct and if it is, how can I fix it?
I've Googled but it hasn't come up with any solutions.
Thanks

A: REF: https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
Check your headers. If you use the X-Forwarded-Proto header is should pass along the referring protocol (HTTP/HTTPS) with the request. Give that a shot, let us know.
One note, ALB's strip this header out by design to prevent forgery. A NLB doesn't perform header manipulation.


text:
Q: "Cannot find module" error when using TypeScript 3 Project References I'm trying to get TypeScript 3's project references working but struggling to import a function from a referenced project.
I have a ProjectA that references Shared. Here's the file structure:
ProjectA
|_ src
|     |_person.ts
|_ tsconfig.json
|
Shared
|_ src
      |_utils.ts
|_ tsconfig.json

Here's utils.ts:
export function guid() {
  return "a guid";
}

Here's Shared/tsconfig.json:
{
  "compilerOptions": {
    "composite": true,
    "declaration": true,

    "target": "es5",
    "outDir": "dist",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitReturns": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*"]
}

Here's ProjectA/tsconfig.json:
{
  "compilerOptions": {
    "composite": true,
    "declaration": true,

    "target": "es5",
    "outDir": "dist",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitReturns": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*"],
  "references": [{ "path": "../shared" }]
}

Here's the problem file - person.ts:
import { guid } from "../../Shared";

class Person {
  id: string;
  name: string;
  constructor() {
    this.id = guid();
  }
}

The TS compiler errors with "Cannot find module '../../Shared'"

What am I doing wrong when trying to import the guid function? Any help would be appreciated

A: You need to use the full relative path to the file you are importing from, just as you would if the file were in the same project:
import { guid } from "../../Shared/src/utils";


text:
Q: Dynamically identify/locate HTML tables within a page? Admin users can add HTML content to a website via a CMS textbox control.
When this content is displayed to a website visitor, I'd like to identify the presence of a HTML table (added by a Admin user using the CMS) and display an option for visitors to export that table.
I can handle the exporting, but identifying the HTML tables has me stumped.
Can anyone provide me with some direction?  This website is using ASP.NET 2.0/VB.NET.

A: Give them a specific ID and target this id using Javascript acting on the DOM.
http://www.w3schools.com/htmldom/dom_obj_table.asp

A: If you want to do this work client side you can do so with JavaScript using getElementsByTagName('table').
http://www.w3schools.com/HTMLDOM/met_doc_getelementsbytagname.asp


text:
Q: How to replace character in nginx variable? I have a variable that has in it
first_name_domain
And I want to transform it in
first.name.domain
I have tried something like
if ($subdomain ~ ^(.+&|)(LAYERS=[^&]+)_(.*)$) {
    set $subdomain2 $1$2.$3;
}

Thank you.

A: I don't think there is a way to replace some character multiply times like you want to (except of using third party modules). As a workaround, to replace limited quantity of characters, you can try a chain of the map blocks:
map $layers $first_replacement {
    ~^(?<first_prefix>.*?)_(?<first_suffix>.*)$  $first_prefix.$second_replacement;
    default  $layers;
}
map $first_suffix $second_replacement {
    ~^(?<second_prefix>.*?)_(?<second_suffix>.*)$  $second_prefix.$third_replacement;
    default  $first_suffix;
}
map $second_suffix $third_replacement {
    ~^(?<third_prefix>.*?)_(?<third_suffix>.*)$  $third_prefix.$third_suffix;
    default  $second_suffix;
}

server {
    ...
    if ($subdomain ~ ^(?<prefix>.+&|)(?<fixed>LAYERS=[^&]*?)_(?<layers>[^&]*)(?<suffix>&.*|$) {
        set $subdomain2 $prefix$fixed.$first_replacement$suffix;
    }
    ...
}

This example will replace maximum of four underscores, but you can increase the number of map blocks if you need.


text:
Q: android timepicker frag.show error Having massive issues implementing a time picker in my android app.Everything works except the timepicker.I have the following code;
TimePickerFragment.java
    package com.deano.dfw;

    import java.util.Calendar;

    import android.app.Dialog;
    import android.app.TimePickerDialog;
    import android.content.Context;
    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.widget.TimePicker;

    import com.deano.dfwcomputer.BookNowFragment.TimePickerFragmentListener;

    public class TimePickerFragment extends DialogFragment {

        public static String TAG1 = "TimePickerFragment";
        static Context tContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
        static int tHour;
        static int tMinute;

        static TimePickerFragmentListener tListener;

        public static TimePickerFragment newInstance(Context context, TimePickerFragmentListener listener, Calendar now) {
            TimePickerFragment dialog = new TimePickerFragment();
            tContext = context;
            tListener = listener;

            tHour = now.get(Calendar.HOUR_OF_DAY);
            tMinute = now.get(Calendar.MINUTE);

            /*I dont really see the purpose of the below*/
            Bundle args = new Bundle();
            args.putString("title", "Set Time");
            dialog.setArguments(args);//setArguments can only be called before fragment is attached to an activity, so right after the fragment is created

            return dialog;
        }

        public Dialog onCreateDialog(Bundle savedInstanceState) {
            //return new DatePickerDialog(tContext, mDateSetListener, tHour, tMinute);
            return new TimePickerDialog(tContext,
                    tTimeSetListener, tHour, tMinute, false);
        }

        private TimePickerDialog.OnTimeSetListener tTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                tHour = hourOfDay;
                tMinute = minute;

                tListener.updateChangedTime(hourOfDay, minute);
            }
        };
}

BookNowFragment.java
package com.deano.dfwcomputer;

import java.util.Calendar;
import java.util.regex.Pattern;

import android.support.v4.app.DialogFragment;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class BookNowFragment extends Fragment implements OnClickListener {
    DateDialogFragment frag;
    TimePickerFragment fragTime;
    Button button;
    Button buttonTime;
    Button buttonSubmit;
    Calendar now;
    EditText edittextName;
    EditText edittextPhone;
    EditText editTextProblem;
    private Drawable error_indicator;
    static final int DATE_DIALOG_ID = 0;
    static final int TIME_DIALOG_ID = 2;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // final View rootView = inflater.inflate(R.layout.fragment_booknow,
        // container, false);
        LayoutInflater lf = getActivity().getLayoutInflater();
        final View rootView = lf.inflate(R.layout.fragment_booknow, container,
                false);

        // Setting custom drawable instead of red error indicator,
        error_indicator = getResources().getDrawable(R.drawable.icon);

        int left = 0;
        int top = 0;

        int right = error_indicator.getIntrinsicHeight();
        int bottom = error_indicator.getIntrinsicWidth();

        error_indicator.setBounds(new Rect(left, top, right, bottom));

        edittextName = (EditText) rootView.findViewById(R.id.edittextName);
        edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
        editTextProblem = (EditText) rootView
                .findViewById(R.id.editTextProblem);

        // Called when user type in EditText
        edittextName.addTextChangedListener(new InputValidator(edittextName));
        edittextPhone.addTextChangedListener(new InputValidator(edittextPhone));
        editTextProblem.addTextChangedListener(new InputValidator(
                editTextProblem));

        // Called when an action is performed on the EditText
        edittextName.setOnEditorActionListener(new EmptyTextListener(
                edittextName));
        edittextPhone.setOnEditorActionListener(new EmptyTextListener(
                edittextPhone));
        editTextProblem.setOnEditorActionListener(new EmptyTextListener(
                editTextProblem));

        now = Calendar.getInstance();
        button = (Button) rootView.findViewById(R.id.date_button);
        button.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)) + "-"
                + String.valueOf(now.get(Calendar.MONTH) + 1) + "-"
                + String.valueOf(now.get(Calendar.YEAR)));
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        buttonTime = (Button) rootView.findViewById(R.id.time_button);
        buttonTime.setText(String.valueOf(now.get(Calendar.HOUR_OF_DAY)) + ":"
                + String.valueOf(now.get(Calendar.MINUTE)));
        buttonTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strPhoneNo = "0417538062";
                TextView txtName = (TextView) rootView
                        .findViewById(R.id.edittextName);
                TextView txtPhone = (TextView) rootView
                        .findViewById(R.id.edittextPhone);
                TextView txtDate = (TextView) rootView
                        .findViewById(R.id.date_button);
                TextView txtTime = (TextView) rootView
                        .findViewById(R.id.time_button);

                TextView txtProblem = (TextView) rootView
                        .findViewById(R.id.editTextProblem);
                String strName = "Name: " + txtName.getText().toString();
                String strPhone = "Phone: " + txtPhone.getText().toString();
                String strDate = "Date: " + txtDate.getText().toString();
                String strTime = "Time: " + txtTime.getText().toString();

                String strProblem = "Problem: "
                        + txtProblem.getText().toString();
                String strMessage = strName + "\n" + strPhone + "\n" + strDate
                        + "\n" + strTime + "\n" + strProblem;

                BookNowSMS(strPhoneNo, strMessage);

            }
        });

        return rootView;
    }

    // ---sends a SMS message to another device---
    private void BookNowSMS(String phoneNumber, String message) {

        /*
         * PendingIntent pi = PendingIntent.getActivity(this, 0, new
         * Intent(this, test.class), 0); SmsManager sms =
         * SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
         * message, pi, null);
         */

        String SENT = "SMS_SENT";
        // String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
                new Intent(SENT), 0);

        /*
         * PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
         * Intent(DELIVERED), 0);
         */

        // ---when the SMS has been sent---
        getActivity().registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getActivity(), "Message Sent",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getActivity(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getActivity(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getActivity(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getActivity(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));

        SmsManager sms = SmsManager.getDefault();
        Toast.makeText(getActivity(), "Sending Please Wait", Toast.LENGTH_SHORT)
                .show();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
        // rootView.findViewById(R.id.edittextName);
        TextView text = (TextView) getActivity()
                .findViewById(R.id.edittextName);
        text.setText(null);
        TextView text1 = (TextView) getActivity().findViewById(
                R.id.edittextPhone);
        text1.setText(null);
        TextView text2 = (TextView) getActivity().findViewById(
                R.id.editTextProblem);
        text2.setText(null);
        resetDate();

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }

    public void showDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            FragmentActivity activity = (FragmentActivity) getActivity();
            // FragmentTransaction ft = getFragmentManager().beginTransaction();
            // //get the fragment
            FragmentTransaction ft = activity.getFragmentManager()
                    .beginTransaction();
            frag = DateDialogFragment.newInstance(getActivity(),
                    new DateDialogFragmentListener() {
                        public void updateChangedDate(int year, int month,
                                int day) {
                            button.setText(String.valueOf(day) + "-"
                                    + String.valueOf(month + 1) + "-"
                                    + String.valueOf(year));
                            now.set(year, month, day);
                        }
                    }, now);

            frag.show(ft, "DateDialogFragment");

        case TIME_DIALOG_ID:
            // return new TimePickerFragment(getActivity(), tListener, hours,
            // min, false);
            FragmentActivity activityTime = (FragmentActivity) getActivity();
            // FragmentTransaction ft = getFragmentManager().beginTransaction();
            // //get the fragment
            FragmentTransaction ftime = activityTime.getFragmentManager()
                    .beginTransaction();
            fragTime = TimePickerFragment.newInstance(getActivity(),
                    new TimePickerFragmentListener() {
                        public void updateChangedTime(int hour, int minute) {
                            buttonTime.setText(String.valueOf(hour) + ":"
                                    + String.valueOf(minute));
                            now.set(hour, minute);
                        }
                    }, now);

            fragTime.show(ftime, "TimePickerFragment");
        }
        return;

    }

    public interface DateDialogFragmentListener {
        // this interface is a listener between the Date Dialog fragment and the
        // activity to update the buttons date
        public void updateChangedDate(int year, int month, int day);
    }

    public interface TimePickerFragmentListener {
        // this interface is a listener between the Time Dialog fragment and the
        // activity to update the buttons time
        public void updateChangedTime(int hour, int minute);
    }

    public void resetDate() {
        now = Calendar.getInstance();
        button = (Button) getActivity().findViewById(R.id.date_button);
        button.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)) + "-"
                + String.valueOf(now.get(Calendar.MONTH) + 1) + "-"
                + String.valueOf(now.get(Calendar.YEAR)));
    }

    private class InputValidator implements TextWatcher {
        private EditText et;

        private InputValidator(EditText editText) {
            this.et = editText;
        }

        public void afterTextChanged(Editable s) {

        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (s.length() != 0) {
                switch (et.getId()) {
                case R.id.edittextName: {
                    if (!Pattern.matches("^[\\sa-zA-Z]{1,25}$", s)) {
                        et.setError("Name must have only a-z or A-Z E.g. John Doe");
                    }
                }
                    break;

                case R.id.edittextPhone: {
                    if (!Pattern.matches("^[0-9]{1,10}$", s)) {
                        et.setError("Phone Number must be 10 numbers only with no spaces E.g. 0417538062");
                    }
                }
                    break;
                case R.id.editTextProblem: {

                    if (!Pattern.matches("^[\\w\\sa-zA-Z0-9.']{1,65}$", s)) {
                        et.setError("Text must only contain a-z and A-Z and numbers.");
                    }
                }
                    break;

                }
            }
        }
    }

    private class EmptyTextListener implements OnEditorActionListener {
        private EditText et;

        public EmptyTextListener(EditText editText) {
            this.et = editText;
        }

        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                // Called when user press Next button on the soft keyboard

                if (et.getText().toString().equals(""))
                    et.setError("Oops! empty.", error_indicator);
            }
            return false;
        }
    }

}

fragment_booknow.xml
<?xml version="1.0" encoding="utf-8"?>

    <TableLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:stretchColumns="1"
        android:orientation="vertical" >

        <TableRow>

            <TextView
                android:layout_gravity="center_horizontal"
                android:layout_span="3"
                android:padding="10sp"
                android:text="@string/textBookService"
                android:textSize="22sp" />
        </TableRow>

        <TableRow>

            <EditText
                android:id="@+id/edittextName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5px"
                android:layout_span="2"
                android:hint="@string/hintYourName" >
            </EditText>
        </TableRow>

        <TableRow>

            <EditText
                android:id="@+id/edittextPhone"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5px"
                android:layout_span="2"
                android:hint="@string/hintPhone"
                android:saveEnabled="false" >
            </EditText>
        </TableRow>

        <TableRow>

            <TextView android:text="@string/SelectDate" />
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/date_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="clickMe"
                android:text="03-18-2012" />
        </TableRow>

        <TableRow>

            <TextView android:text="@string/SelectTime" />
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/time_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="clickMe"
                android:text="03-18-2012" />
        </TableRow>

        <TableRow>

            <EditText
                android:id="@+id/editTextProblem"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_span="2"
                android:hint="@string/hintProblem"
                android:minLines="3" >
            </EditText>
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/buttonSubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_margin="5px"
                android:layout_span="2"
                android:text="@string/buttonSubmit" >
            </Button>
        </TableRow>
    </TableLayout>

The error I'm getting is in BookNowFragment.java
The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentTransaction, String)

and is from this part of the code;
fragTime.show(ftime, "TimePickerFragment");

strange part is the date dialog above is similar and works perfectly.Any ideas how to resolve this.
UPDATE 2
Fixed timepicker as follows;
Changed;
return new TimePickerDialog(tContext, tTimeSetListener, tHour, tMinute, false);
To;
return new TimePickerDialog(getActivity(), tTimeSetListener, tHour, tMinute, false);
But still have error The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentTransaction, String)
in the following frag.show;
case DATE_DIALOG_ID:
            FragmentActivity activity = (FragmentActivity) getActivity();
            // FragmentTransaction ft = getFragmentManager().beginTransaction();
            // //get the fragment
            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
            frag = DateDialogFragment.newInstance(getActivity(),
                    new DateDialogFragmentListener() {
                        public void updateChangedDate(int year, int month,
                                int day) {
                            button.setText(String.valueOf(day) + "-"
                                    + String.valueOf(month + 1) + "-"
                                    + String.valueOf(year));
                            now.set(year, month, day);
                        }
                    }, now);

            frag.show(ft, "DateDialogFragment");

A: You should use android.support.v4.app.FragmentManager instead of android.app.FragmentManager.
call like this it will help
call getSupportFragmentManager() but not getFragmentManager()
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();

refer this doc :  Document


text:
Q: Plotting custom periodic function I want to plot a periodic function with following commands:
x[t_] := 1 + t /; -Pi < t <  Pi
x1[t_] := x[Mod[t, 2 Pi]]
Plot[x1[t],{t, -2 Pi, 2 Pi}]

but in the figure, the function has not been plotted in [-Pi, 0].

A: x[t_] := 1 + t /; -Pi < t < Pi
x1[t_] := x[Mod[t + Pi, 2 Pi] - Pi]
Plot[x1[t], {t, -4 Pi, 4 Pi},
 GridLines -> {Range[-4, 4]*Pi, Automatic}, ImageSize -> 400,
 Ticks -> {Pi Range[-4, 4], Automatic}, Exclusions -> True,
 ExclusionsStyle -> Directive[Thin, Black, Dashed]]

Edit
As @march suggested in the comment below, a third, Offset argument can be supplied to Mod which will give the same effect.
x1[t_]:= x[Mod[t,2Pi,Pi]]


text:
Q: CollectionViewCell's container view doesn't fill cell I have a collectionView who's height and width I set with constraints using autolayout.
In my
func collectionView(_ collectionView: ...., sizeForItemAt indexPath: IndexPath) I return CGSize(width: self.collectionView.frame.width-20, height: self.collectionView.frame.height) and as seen on the image linked below it lines up perfectly fine.
The problem is that the container view (white space) of that cell doesn't fill up the green space (that is the cell's background) at all even though I have set constraints of the containerView to hug left/right/bottom/up with 0 margin.
What I have tried so far:

*

*Make a height constraint for the container view that I assign the collection view's height

*updateConstraints() in cellForItemAt and inside the cell's class in ```layoutSubview()````

*Set the container view's frame to the collectionView's frame

*cell.layoutIfNeeded()in cellForItemAt
None of these have solved my problem.
https://i.stack.imgur.com/mD2iC.jpg

A: Here issue related to inset I think. Please use collection delegate method
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    return UIEdgeInsetsMake(top, left, bottom, right);

}

or
UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];

[aFlowLayout setSectionInset:UIEdgeInsetsMake(top, left, bottom, right)];

Swift 5.1
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 15.0
}


text:
Q: ng-model in numeric input does not affect scope ng-model does not affect the scope and I can't understand why.
Here is most of my HTML:
<ion-view view-title="{{ inputType | uppercase | translate }}">

  <ion-content class="padding">

    <div class="list">
      <label class="item item-input">
        <input ng-model="amount" class="text-align-center" type="number" placeholder="{{ 'AMOUNT' | translate }}">
      </label>
    </div>

    <button class="button button-block button-stable" ng-click="okAmount()">{{ 'SAVE' | translate }}</button>

  </ion-content>
</ion-view>

Here is most of my controller:
(function(){
  angular.module('mb')
    .controller('EnterAmountCtrl', ['$scope', '$state', '$filter', '$translate',
      function($scope, $state, $filter, $translate) {

        $scope.amount = '';

        $scope.okAmount = function() {
          console.log($scope.amount);
        };

      }]);
})();

I don't think that this can be a scoping issue. There are no nested controllers. Routing is handled like this:
    $stateProvider.state('enter-amount', {
      url: '/enter-amount/:inputType',
      templateUrl: 'templates/enter-amount.html',
      controller: 'EnterAmountCtrl'
    });

Regardless of what I write in the text box, $scope.amount remains undefined. What might be causing this?

A: Updated answer:
Following up on Sunil D and Dayan Moreno's comments to the question, throwing the primitive value inside an object is the best approach, and avoids having to use $parent in your code:
ng-model='object.amount'

As long as object doesn't exist in the child scope, it will refer to the object variable found in the parent scope and set the amount value appropriately.
Original answer:
Having not used ion yet, I would assume that either ionView or ionContent is a directive which creates its own scope.
You're setting the value property of a child scope, then trying to access the value property of the parent scope. Accessing the parent scope's amount value might solve the issue for you:
ng-model='$parent.amount'


text:
Q: How to show observable collection items on WPF canvas I have an observable collection which is binded to datagrid.
I can create wpf controls such as label,textbox etc into datagrid cells dynamically which in turn updates observable collection.
Now, I would like to show this collection of items on canvas in rows and columns as in datagrid.
Please help me to get that.
I am using the code as below.
ObservableCollection<Data> Items= this.Items as ObservableCollection<Data>;

              if (this.Items != null)
                    {
                        foreach (var element in this.Items)
                        {
                            if (element != null)
                            {
                                UIElement getitem = (UIElement)element.InputField;

             //where inputfield is a property which holds the control.
             // It eturns the control that has created.
                                canvas.Children.Add(getitem);//adding the control to canvas
                            }
                        }
                    }

But it throwing the exception(on adding the control to canvas) as below.
Specified Visual is already a child of another Visual or the root of a CompositionTarget.
Thank you for your response.
Where Data is a class defined as below.
public class Data : INotifyPropertyChanged
    {
    private UIElement _uIElement;
    public UIElement UIElement
    {
        get { return _uIElement; }
        set
        {
            if (value != _uIElement)
            {
                _uIElement = value;
                this.OnPropertyChanged("UIElement");
            }
        }
    }

    private UIElement _inputField;
    public UIElement InputField
    {
        get { return _inputField; }
        set
        {
            if (value != _inputField)
            {
                _inputField = value;
                this.OnPropertyChanged("InputField");
            }
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string name)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

}
}
Inputfield and UIelement properties are the 2 columns of datagrid which holds the dynamic created controls information.

A: A Visual can only have one parent so you would have to remove it from the ObservableCollection (which presumably your DataGrid is bound to) first....but then you would have it on your Canvas but not on your DataGrid.
So if you're trying to have 2 "views" of your collection of UIElements at the same time, then you'd have to clone the elements so they could go into the Canvas.
What is the "Data" type...can you elaborate on it?
The preferred way to do things is keep your Model/View Models in the collection (not UIElements), then define DataTemplates which define the visuals for those data types. Then you can have the DataGrid and the Canvas both bind to the same collection of data, but they will each have their own inflated Visuals when the DataTemplates are applied.
See these links:

*

*http://social.msdn.microsoft.com/forums/en-US/wpf/thread/0df6181d-938f-4f45-9463-5b5035b57000/

*How to copyclone a UIElement and keep the layout/render information?

*Cloning WPF controls and object hierarchies


text:
Q: Chrome Native Messaging Host VB.Net I have had a hard time finding any support for Chrome Native Messaging Hosts in VB.Net, after much trial and error I have put together something that works for a single message at a time. However I have not been able to get the
While OpenStandardStreamIn() IsNot Nothing

part to work. If anyone has any suggestions...
OTHERWISE THIS CODE WORKS GREAT, for anyone else like me looking for a VB.Net Native Message Host:
Also, this uses Newtonsoft.Json Lib for JSON serializing...
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.Runtime.InteropServices

Module Module1

Public Sub Main(ByVal args As String())

    'create response as an array so it can be easily converted JSON
    Dim ResponseString() As String = {""}

    ' get input from chrome extension
    Dim InputString As String = OpenStandardStreamIn()

    ' Do whatever you want with Input, then prepare Response
    ResponseString(0) = DO_SOMETHING(InputString)

    ' Send Response to Chrome
    OpenStandardStreamOut(ResponseString)

End Sub

Public Function OpenStandardStreamIn() As String
    Dim MsgLength As Integer = 0
    Dim InputData As String = ""
    Dim LenBytes As Byte() = New Byte(3) {} 'first 4 bytes are length

    Dim StdIn As System.IO.Stream = Console.OpenStandardInput() 'open the stream
    StdIn.Read(LenBytes, 0, 4) 'length
    MsgLength = System.BitConverter.ToInt32(LenBytes, 0) 'convert length to Int

    Dim Buffer As Char() = New Char(MsgLength - 1) {} 'create Char array for remaining bytes

    Using Reader As System.IO.StreamReader = New System.IO.StreamReader(StdIn) 'Using to auto dispose of stream reader
        While Reader.Peek() >= 0 'while the next byte is not Null
            Reader.Read(Buffer, 0, Buffer.Length) 'add to the buffer

        End While
    End Using

    InputData = New String(Buffer) 'convert buffer to string

    Return InputData
End Function

Private Sub OpenStandardStreamOut(ByVal ResponseData() As String) 'fit the response in an array so it can be JSON'd

    Dim OutputData As String = ""
    Dim LenBytes As Byte() = New Byte(3) {} 'byte array for length
    Dim Buffer As Byte() 'byte array for msg

    OutputData = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseData) 'convert the array to JSON

    Buffer = System.Text.Encoding.UTF8.GetBytes(OutputData) 'convert the response to byte array
    LenBytes = System.BitConverter.GetBytes(Buffer.Length) 'convert the length of response to byte array

    Using StdOut As System.IO.Stream = Console.OpenStandardOutput() 'Using for easy disposal

        StdOut.WriteByte(LenBytes(0)) 'send the length 1 byte at a time
        StdOut.WriteByte(LenBytes(1))
        StdOut.WriteByte(LenBytes(2))
        StdOut.WriteByte(LenBytes(3))

        For i As Integer = 0 To Buffer.Length - 1 'loop the response out byte at a time
            StdOut.WriteByte(Buffer(i))
        Next

    End Using
End Sub
End Module

From the Chrome Extension, open a connection, send a message, and once a response is received the host will close. Check our Chrome's Dev page for a sample app/extension: https://developer.chrome.com/apps/nativeMessaging
I hope this helps somebody, and please let me know if you make any improvements!

A:  Sub Main() ' Recursive Version
    Try
        Dim stdin As Stream = Console.OpenStandardInput()
        Dim stdout As Stream = Console.OpenStandardOutput()

        Dim MsgLength As Integer = 0
        Dim InputData As String = ""
        Dim LenBytes As Byte() = New Byte(3) {}
        stdin.Read(LenBytes, 0, 4)
        MsgLength = BitConverter.ToInt32(LenBytes, 0)
        Dim Buffer As Byte() = New Byte(MsgLength - 1) {}
        stdin.Read(Buffer, 0, Buffer.Length)
        InputData = Encoding.UTF8.GetString(Buffer)

        Dim Str As String = Newtonsoft.Json.JsonConvert.SerializeObject("[" & Now & "] Arrrr!")
        Dim buff() As Byte = Encoding.UTF8.GetBytes(Str)
        stdout.Write(BitConverter.GetBytes(buff.Length), 0, 4)
        stdout.Write(buff, 0, buff.Length)
        Main()
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Oh, Snap!")
    End Try
End Sub


text:
Q: Basic table structure Display table with 600px width having three rows. First row should have full width. second row with two td having 50% width each and third row with three td with equal length.
What I have done so far:

Hey I am first row

Hey I am second row

Hey I am second row

Hey I am third row

Hey I am third row

Hey I am third row

A: Yes, this is tricky... You need to keep 6 as your base and work on it, so that you don't need to use nested tables. May be you can do like this:

table {width: 600px; text-align: center;}
table td {border: 1px solid #999; padding: 5px;}

    Full Width

    ½
    ½

    ⅓
    ⅓
    ⅓

Hope this helps?


text:
Q: Efficiently displaying Top N in Excel PivotTable from SSAS Tabular Model I have a simple tabular model consisting of a fact table with approx. 20 mio. records (sales transactions) and a dimension table with approx 600.000 records (customers).
A typical reporting scenario is to get the top 10 customers over some measure in the fact table, possibly filtered by some other criteria (typically a time period, a product, etc.).
In Excel, aggregating all of the 20 mio. records to return a total sales amount is instant. However, once I try to group by customers, it takes some time (15-20 seconds) to retrieve all the data, which makes sense since there is quite a lot of customers (600.000) that needs to be displayed.
Now, if I apply a value filter in Excel, to get only the top 10 customers, it still takes around 15-20 seconds to return the result, which is unacceptable to my users (as they would like to instantly see the top 10 customers while slicing on other attributes such as product, time, etc).
Internally, Excel uses the TOPCOUNT MDX-function when querying the tabular model with a value filter.
Is there anything I can do in the tabular model, to speed up these kinds of queries?
I've tried:

*

*Creating a calculated column on the dimension table, containing the total sales amount for each customer. While the performance is better, this is not the way to go because the values in this column can not be sliced by other attributes from the facts, and the column obviously ends up containing many distinct values (which is a bad thing in tabular).

*Creating a calculated measure on the fact table, using the DAX RANKX function as suggested here. This caused my Tabular instance to crash (too many records in the dimension table?)

*Executing a simple DAX statement directly on the tabular model using the DAX TOPN function. This was even slower than the TOPCOUNT MDX-approach, by a factor of 3-4.

A: After searching the web some more and performing additional tests, I have come to the conclusion that SSAS Tabular is inherently bad at answering TOPCOUNT/RANK-kind queries in an unfiltered context. The reason seems to be quite simple:
If I have a dimension containing 600.000 customers, and I ask for the top 10 by Sales Amount in an unfiltered context, the tabular engine needs to compute the sum of Sales Amount for each individual customer, before being able to sort and return the top 10 or the rank of each customer.
In multidimensional OLAP, data is typically preaggregated on a pr. customer level, meaning the multidimensional cube can answer these kinds of queries much faster.
When applying one or more filters in SSAS tabular (for example current month, a specific product, etc.), I saw a significant performance increase. The solution, in my case, is then to educate my users to always filter their data before including the customer dimension in their PivotTables.


text:
Q: Как переименовать столбец в таблице Пытался сделать так, но ничего не происходит ( не нашел решения в инете по этому вопросу.
MySqlCommand deletedStudentCommand = new MySqlCommand("UPDATE Students CHANGE COLUMN `" + selectedd + "` `" + textBox1.Text + "`", sqlConnection);

A: MySqlCommand deletedStudentCommand = new MySqlCommand("ALTER TABLE Students CHANGE `" + selectedd + "` `" + textBox1.Text + "` TEXT", sqlConnection);


text:
Q: LWC lightning-datatable Infinite Scrolling Not Working I am trying to use the built-in infinite loading capabilities of the lightning-datatable. But whenever enable-infinite-loading is set to true, the component repeatedly spams the onloadmore action, even if the user has not scrolled to the bottom of the table.
<template>
    <lightning-datatable
        key-field="Id"
        columns={tableColumns}
        data={data}
        enable-infinite-loading={isLoaded}
        onloadmore={onLoadMoreHandler}>
    </lightning-datatable>
</template>

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {
    tableColumns = [
        {label: 'Number', fieldName: 'Id', type: 'number'},
        {label: 'Name', fieldName: 'Name'}
    ];

    @track data = [];
    @track isLoaded = false;

    addMoreDataCounter = 0;

    connectedCallback() {
        this.addMoreData();
        this.isLoaded = true;
    }

    addMoreData() {
        const offset = this.data.length;
        let newData = [];

        for(let i=offset + 1;i<=offset + 100; i++) {
            newData.push({
                Id: i,
                Name: 'Test Row #' + i
            });
        }

        this.data = [...this.data, ...newData];

        this.addMoreDataCounter++;
    }

    onLoadMoreHandler() {
        console.log('load more');
        this.addMoreData();

        if(this.addMoreDataCounter === 4) {
            this.isLoaded = false;
        }
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>46.0</apiVersion>
    <description>Scroll Issue</description>
    <isExposed>true</isExposed>
    <masterLabel>Scroll Issue</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

*

*In this example, enable-infinite-loading is turned off after the fourth call to addMoreData() to prevent the application from crashing.

*This component is being used in a single column Lightning App Builder page, where it is the only component.

*This example is intentionally simplified to generate data on the client side, in order to reproduce the issue in a way that is easy to share.

A: If you carefully observe the definition of when datatable fired loadmore event in documentation

Determines when to trigger infinite loading based on how many pixels
  the table's scroll position is from the bottom of the table. The
  default is 20.

As you are not restricting the height, it is firing the events as long as it reaches enable-infinite-loading to be false. As the scroll is internally implemented in datatable, If you are not restricting height, the page height is considered full view and thinks that user has reached the end of scroll. Try below:
    <div style="height: 15rem;">
        <lightning-datatable key-field="Id"
                             columns={tableColumns}
                             data={data}
                             enable-infinite-loading={isLoaded}
                             onloadmore={onLoadMoreHandler}>
        </lightning-datatable>
    </div>

style="height: 15rem;" restricts the height to 15rem.


text:
Q: Problems saving to the database Good morning everyone, I'm learning to use asp.net core in version 6 and I'm having problems saving a record to the database it shows the following error:

SqlException: Invalid object name 'VehiclePerson'.

From what I know, it is actually because it does not find the table in "VehiclePerson" although the connection is made, so I used Scaffolding to obtain the DB from Microsoft SSMS and I created the models and the Context file, so I don't think there are problems with the connection.
This is my VehiclePerson.cs file
using System.Collections.Generic;

namespace APITDCON.Models.QQGUAR01;

public partial class VehiclePerson
{
    public string? EmpNumber { get; set; }
    public string? Lastname { get; set; }
    public string? Firstname { get; set; }
    public string? Costcenter { get; set; }
    public string? Department { get; set; }
    public string? CredentNumber { get; set; }
    public string? FromDate { get; set; }
    public string? ToDate { get; set; }
    public string? Rights { get; set; }
    public int Id { get; set; }
}

This is my VehiclePerson.cs file
using Microsoft.EntityFrameworkCore;
using APITDCON.Models.QQGUAR01;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace APITDCON.Data
{
    public class APITDCONContext : DbContext
    {
        public APITDCONContext(DbContextOptions<APITDCONContext> options) : base(options)
        {

        }
        public DbSet<VehiclePerson> VehiclePerson { get; set; }
    }
}

This is my VehiclePerson.cs file
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using APITDCON.Models.TANKFARM;
using APITDCON.Models;
using APITDCON.Data;
using System.Collections;

namespace APITDCON.Controllers
{

    public class VehiclePersonController1 : Controller
    {
        private readonly APITDCONContext _apiTDCONContext;
        public VehiclePersonController1(APITDCONContext apiTDCONContext)
        {
            _apiTDCONContext = apiTDCONContext;
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            List<VehiclePerson> lista = new List<VehiclePerson>();
            lista = GetAllDataDrivers();
            return View(lista);
        }

        [HttpGet]
        public IActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Add(VehiclePerson vehiclePersonRequest)
        {
            string mensaje = "";
            var vehicleperson = new VehiclePerson()
            {
                EmpNumber = vehiclePersonRequest.EmpNumber,
                Lastname = vehiclePersonRequest.Lastname,
                Firstname = vehiclePersonRequest.Firstname,
                Costcenter = vehiclePersonRequest.Costcenter,
                Department = vehiclePersonRequest.Department,
                CredentNumber = vehiclePersonRequest.CredentNumber,
                FromDate = vehiclePersonRequest.FromDate,
                ToDate = vehiclePersonRequest.ToDate,
                Rights = vehiclePersonRequest.Rights
            };

            using (var db = new Models.QQGUAR01.Qqguar01Context())
            {
                var result = new List<VehiclePerson>();
                result = (from data in db.VehiclePerson
                          select new VehiclePerson
                         {
                             EmpNumber = data.EmpNumber,
                             Lastname = data.Lastname,
                             Firstname = data.Firstname
                         }).ToList();
            }

            _apiTDCONContext.VehiclePerson.Add(vehicleperson);
            _apiTDCONContext.SaveChanges();
            return RedirectToAction("Add");
        }
    }
}

Database and table

Error

A: By default EF will use entity name as table name so you can override it in multiple ways, for example using Table attribute:
[Table("VEHICLE_PERSON")]
public partial class VehiclePerson
{
}

A: The table name defined in your database context is VehiclePerson, but your table name in the database is VEHICLE_PERSON, the two names do not match.
The easiest way is to change the name of the table VEHICLE_PERSON in the database to VehiclePerson, or change public DbSet<VehiclePerson> VehiclePerson { get; set; } to public DbSet<VehiclePerson> VEHICLE_PERSON { get; set; } in your context.
If you want to avoid similar situations in the future, you can use the following commands to migrate and update the database after adding Scaffolding:
Add-Migration InitialCreate
Update-Database

For more details on scaffolding and connecting to the database, you can refer to this official document.


text:
Q: Visual Studio stop running the application once I start I'm using MVC5 with C# application but what my problem is VS 2013 and VS 2015 immediately stops whenever I try to run the application. Output window is showing the below message:
The program '[8916] iisexpress.exe: Program Trace' has exited with code 0 (0x0). The program '[8916] iisexpress.exe' has exited with code 0 (0x0).


text:
Q: Importing a python file from another python file in VSCode I've seen many attempts at a fix for this question, but not have gotten it right for me. I love VSCode - it's good looking, lightweight, and fast. But I cannot understand how they made import statements so absolutely confusing. For context, I'm coming from Pycharm where everything just worked (after 10 minutes of waiting for the program to startup).
So, I have a folder structure that looks something like this:

How the interactions work currently:

*

*a.py and b.py can import with each other just fine with: import (a|b).py

*a.py and b.py can import with c.py and d.py just fine with: from folder(1|2) import (c|d).py

*c.py and d.py cannot import with a.py or d.py with: from . import (a|b).py (which has been a recommended solution on other questions of a similar nature as this one)

*c.py and d.py cannot import with each other with: from .folder(1|2) import (c|d).py  (I'm pretty sure the syntax is wrong here anyway)

My current settings.json is:
"python.pythonPath": "c:\\dev\\workspace-vscode\\Python\\Personal\\importTesting\\venv\\Scripts\\python.exe"
and my launch.json is:
{
"version": "0.2.0",
"configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
        "cwd": "${workspaceFolder}"
    }
]}

I've seen solutions involving a .env file, but they never explain where to put the file. Also, what is the workspace folder? Where does that resolve to? Is it considered the root folder?
Something else to note is that the actual import statement that I'm using is: from Code.WordAnalysis.wordsAndLetters import word_count, which I understand will mean nothing to you unless you look at my code (which I've linked to below). But the goofy thing about that is that it works in Pycharm without breaking a sweat. This behavior makes me think it's some referencing issue - could be wrong.
The above import statement spits out this error:

Traceback (most recent call last): File "c:\dev\workspace-vscode\Python\WorkRelated\ITTechTalk\Code\PasswordStrengthCalculators\passwordstrengthreal.py", line 1, in <module> from Code.WordAnalysis.wordsAndLetters import word_count ModuleNotFoundError: No module named 'Code'

In case you want to look at my repository, it can be found here: https://github.com/TJMcButters/workspace-vscode/tree/master/Python/WorkRelated/ITTechTalk
Any help with this would be very much appreciated! It's driving me crazy.

A: Response to cases number 3 and 4:
When running a script directly, it is impossible to import anything from its parent directory.
My approach is to avoid writing scripts that have to import from the parent directory. In cases where this must happen, the preferred workaround is to modify sys.path.
You can add directories from which you want to import modules in a runtime, by doing something like this:
import sys
sys.path.append("dir_from_which_to_import")

I would recommend you to have a look on this material - https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html.


text: Q: iphone 6 size not recognized by website. css code need to be added I have a problem. Recently I noticed that  my website has a problem showing the text with iPhone 6 and 6+. the text is little bit out of margin in right. with the other phones it automatically resizes the screen and I am able to see the text fully. But in iPhone 6 I need to add some sort of code to the css file of my html5 website.can any one help me with this issue?


text:
Q: need query syntax to fetch latest by PKID after joining multiple tables I have 3 tables:
select * from company
select * from emp_profile
select * from emp_salary_upgrade_tracker

table 1, company_pkid, company_code, company_name

table 2,  emp_profile_pkid,company_fk_id, emp_number, emp_name, salary

table 3, salary_pk_id,emp_profile_fk_id,emp_number, old_salary, current salary

whenever an employee's salary is changed, its tracked in emp_salary_upgrade_tracker.
I need to write a query to fetch
company_code, emp_number, emp_name, old_salary, current salary
Here the result should have the latest entry ,ie latest salary change from emp_salary_upgrade_tracker.
After joining the tables, i need to fetch the latest from emp_salary_upgrade_tracker(order by pkid may be).
But am clueless of the query syntax. Please help

A: Use a subquery to get lates ids:
select c.company_code,
       e.emp_number,
       e.emp_name,
       t.old_salary,
       t.current_salary
from(select emp_profile_fk_id, max(salary_pk_id) as salary_pk_id
     from emp_salary_upgrade_tracker group by emp_profile_fk_id) m
join emp_salary_upgrade_tracker t on m.salary_pk_id = t.salary_pk_id
join emp_profile e on t.emp_profile_fk_id = e.emp_profile_pk_id
join company c on e.company_fk_id = c.company_pkid

A: Here's a way using row_number to select the row containing the latest value in the emp_salary_upgrade_tracker table when ordered by its primary key.
select * from (
    select *,
        row_number() over (partition by esut.emp_number order by esut.salary_pk_id desc) rn
    from emp_salary_upgrade_tracker esut
    join emp_profile ep on ep.emp_profile_pk_id = esut.emp_profile_fk_id
    join company c on c.company_pk_id = ep.company_fk_id
) t where rn = 1


text:
Q: how to use CGAL library while programming in visual studio 10 in windows 7 I am new working with CGAL and need help how to use when I will start a project in Visual Studio 10 in windows 7. How can I use this CGAL libraries with my program in VS 10. Anyone's help will be really appreciable. Thanks

A: There is a complete tutorial here.


text:
Q: Exception thrown in jax-rs ResponseFilter doesn't cause rollback I'm stuggling with auto-rollback of a container managed transaction. I understand that when throwing an exception, this should happen automatically, but somehow, this isn't happening.
To be clear, I have a JAX-RS ContainerResponseFilter which throws some kind of RuntimeException (I can't throw a checked exception btw, as that would mean I need to specify "throws", which can't be done on an implementing method).
When I call sessionContext.setRollbackOnly() myself, the transaction is rolled back indeed, but I don't really want to handle it myself.
I tried marking the exception as @ApplicationException(rollback=true) but that doesn't make a difference.
Any ideas?
This is on JBOSS 7.2 with RestEasy.

A: I've been unable to confirm this is intended behaviour, but any manual rollback within the ContainerReponseFilter is just too late, as the transaction was committed already.
To resolve the problem, I've reworked my solution to throw the exception from within an Ìntegercepter with @AroundInvoke . This appears to be in time for the auto-rollback, and allows me to avoid throwing further exceptions in the ContainerResponseFilter


text:
Q: How do I "capture" the part of the path matched by ** I've got a @RequestMapping that looks like:
@RequestMapping("/foo/{bar}/blah/**")
public void handleRequest(@PathVariable String bar, @PathVariable String remainder) {

How do I configure things so that remainder gets whatever is matched by "**"?

A: While Spring does support Ant style path patterns, they have not provided a way to return what was captured.
Fear not though, as this is something you can calculate yourself.  You can define your controller method to take in the HttpServletRequest object.  From there, you are able to access the URI by calling getRequestURI() on the request object.
It will require some String processing, but that just sounds like more fun code to write.


text:
Q: Complex Permutations I am a middle school math teacher helping my niece with permutations. Her teacher gave her a problem and later gave her the solution to the problem. I do not agree with the way her teacher solved it and I would like guidance.
Here is the problem:
Twelve people try out for a basketball team. In how many ways could they select:
a. a center and a point guard?
b. a forward and another forward after the cent and the point guard have been selected?
c. a second guard and an alternative after the center, point guard, and two forwards have been selected?
Here's how her teacher solved it:
a. P(12,2)=132
b. [P(12,1)*P(12,1)]-P(12,2) --> 144-132=12
c. [P(12,1)*P(12,1)]-5 --> 144-5=139
Here's How I solved it:
a.P(12,2)=132
b.n-->12-2=10. P(10,2)=90
c.n-->12-4=8. P(8,2)=56
Can you tell me which is correct and why and what the error was with the incorrectly solved problem?

A: For a. You are going to label one a centre and another a point guard, there are $12 \cdot 11 = 132$ ways of doing this.
For b. you have $10$ remaining and you wish label two of the $10$ as forwards, there are $\binom{10}{2} = {10 \cdot 9 \over 1 \cdot 2} = 45$ ways of doing this. Note that there is no distinction between the two forwards, hence a combination, if I select Players $5,9$ that is the same as selecting Players $9,5$.
(Alternatively could view this as labeling two remaining players in which case there are $10 \cdot 9$ ways of doing this, and noticing that each couple will be double counted so I need to divide by $2$).
For c. you have $8$ remaining and you want to label one as a centre and one as an alternative, there are $8 \cdot 7 = 56$ ways of doing this.
I can't even guess what the teacher was trying to do with b & c.


text:
Q: How to override the opacity of document.body? I want to make the body of my website have a low opacity but keep a popup at the default opacity of 1 so that it stands out.
How can I do this? I've tried specifying that the popup has opacity: 1 !important; but it doesn't take effect.
Here is a jsfiddle with my attempt: https://jsfiddle.net/80351/0xo10tjc/
Please note that I know how to achieve this by setting the opacity of an outer div instead of body at 0.2 but I really want to know if this is possible to do when changing body.

A: You can set html and body to have 100% height and apply background-color to a div
html,
body {
   height: 100%;
}

body{
  margin: 0;
  padding: 0;
}

.overlay {
  background-color: yellow;
  opacity: 0.2;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/0xo10tjc/4/


text:
Q: Making a decimal a variable So I have a type of code that tells me the number of boxes and packages needed. So for an instances E = number of engines and B = boxes and P =packages. Lets say I need 67 engines, I have B = E(67)/24 which should give me 2.7 because 67/24. I have to have the computer say 2 boxes and 7 engines, but I dont know how to do that.
Thanks!
    // Include Section
     #include <iostream>
     #include <iomanip>
     #include <cstdlib>
     using namespace std;

     // Main Program
     int main( )
     {
        int E;     // number of engines needed
        double CB; // The cost of the boxes containing 24 engines
        double CP; // The cost of the packages containing 3 engines
        int B;     // The number of boxes needed to get the amount
        int P;     // The number of packages needed to get the amount of engines
        double C;  // The total cost of all the engines desired.

    // Output Identification
     system("CLS");
     cout << "Take Home #5 by Yousef Saqer - "
         << "Calculate Engine Purchase\n\n";

    cout << " Enter the number of engines needed: ";
    cin >> E;
    cout << " Enter the cost of a box of 24 engines: ";
    cin >> CB;
    cout << " Enter the cost of a package of 3 engines: ";
    cin  >> CP;

   if(E < 24)
   {
    B = E / 24;
    P = E / 3;
    C = CB * B + CP * P;

    if(E > 3)
    {
        P++;
        cout << " You will need to purchase " << P
        << " packages of engines at a total cost of $"<< C << endl;
    }

    else
    {
        cout << " You will need to purchase " << 1
        << " package of engines at a total cost of $"<< CP << endl;
    }

   }

   else
   {
    B = E / 24;
    P = E/24.0;
    C = CB * B + CP * P;

    if( B != 1)
    {
        cout << " You will need to purchase " << B << " boxes and "
         << P << " packages of engines at a total cost of $"<< C<< endl;
    }

    else
    {
        cout << " You will need to purchase " << B << " box and "
        << P << " packages of engines at a total of $" << C << endl;
    }

}
cout << "\n\nEnd Program.\n";

cin.get();
cin.get();

return 0;

}

A: int main (){
    double param, fractpart, intpart;

    param = 2.7;
    fractpart = modf (param , &intpart);

    return 0;
}

This way param=2 and intpart=0.7
Here is the whole code
http://www.cplusplus.com/reference/cmath/modf/


text:
Q: ListView from SQLite with EditText and CheckBox in each row I've an ListView with data from SQLite that works correctly. Now I want to add more things to this list. To each row I want to add EditText and CheckBox. Something like this:

item1   CheckBox
EditText

item2 CheckBox
EditText

This is my List Class:
public class SeleccionarRelacionPregResp extends Activity implements, OnItemClickListener {

private ListView listaTodo;

private ListAdapter uGraduateListAdapter;
private String bundledCodigoPuntoDeControl;

private ArrayList<UndergraduateDetailsPojo> pojoArrayList;
protected DokesimApplication app;
String codigocaja;
Button btnPruebasGuardar;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.seleccionartodo);

    listaTodo = (ListView) findViewById(R.id.ListaTodo);
    listaTodo.setOnItemClickListener(this);

    pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();

    uGraduateListAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, populateList());

    listaTodo.setAdapter(uGraduateListAdapter);

    PuntosDeControl pControlSeleccionado = new PuntosDeControl();
    app = (DokesimApplication) getApplicationContext();
    pControlSeleccionado = app.getpuntocontrol();

    codigocaja = pControlSeleccionado.codigocaja;

}

public List<String> populateList() {

    List<String> uGraduateNamesList = new ArrayList<String>();

    AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

    SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

    Cursor cursor = sqliteDatabase.query("RelacionPregResp", null,
            " relprcodigocaja = '" + codigocaja + "'",
            null, null, null, null);

    startManagingCursor(cursor);

    while (cursor.moveToNext()) {

        String numeropregunta = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.numeropregunta));
        String relprcodigocaja = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.relprcodigocaja));
        String codigopregunta = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.codigopregunta));
        String pregunta = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.pregunta));
        String codigorespuesta = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.codigorespuesta));
        String respuesta = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.respuesta));
        String valor = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.valor));
        String tipodeguia = cursor.getString(cursor
                .getColumnIndex(AndroidOpenDbHelper.tipodeguia));

        UndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();

        ugPojoClass.setNumeroPregunta(numeropregunta);
        ugPojoClass.setRelPrCodigoCaja(relprcodigocaja);
        ugPojoClass.setCodigoPregunta(codigopregunta);
        ugPojoClass.setPregunta(pregunta);
        ugPojoClass.setCodigoRespuesta(codigorespuesta);
        ugPojoClass.setRespuesta(respuesta);
        ugPojoClass.setValor(valor);
        ugPojoClass.setTipoDeGuia(tipodeguia);

        pojoArrayList.add(ugPojoClass);

        uGraduateNamesList.add(pregunta);

    }

    sqliteDatabase.close();

    return uGraduateNamesList;
}

@Override
protected void onResume() {
    super.onResume();
    uGraduateListAdapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, populateList());
    listaTodo.setAdapter(uGraduateListAdapter);
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

}
}

I need some suggestions or examples of how can I do it.
Thanks for any help.

A: What you basically need is Custom SimpleCursorAdapter.
I am pasting sample program which has Two TextViews in each list row.
You will have to modify it according to your requirement.
package org.sample;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyAdapter extends SimpleCursorAdapter
{
    private Context context;
    private Cursor cursor;
    private int layout;

    public MyAdapter(Context context, int layout, Cursor cursor, String[] from,
            int[] to, int flags)
    {
        super(context, layout, cursor, from, to, flags);
        this.context = context;
        this.cursor = cursor;
        this.layout = layout;
    }

    @Override
    public int getCount()
    {
        if (cursor != null)
            return cursor.getCount();
        else
            return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup)
    {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (view == null)
        {
            view = inflater.inflate(layout, null);
        }
        cursor.moveToPosition(position);
        String title = cursor.getString(cursor
                .getColumnIndex(DBHelper.BOOK_TITLE));
        String author = cursor.getString(cursor
                .getColumnIndex(DBHelper.BOOK_AUTHOR));

        TextView titleTxt = (TextView) view.findViewById(R.id.bTitle);
        TextView authorTxt = (TextView) view.findViewById(R.id.bAuthor);

        titleTxt.setText(title);
        authorTxt.setText(author);

        return view;
    }

}

Once you are ready with your cursor in MainActivity you can write following code.
myAdapter = new MyAdapter(context, R.layout.row, cursor, new String[]{ DBHelper.BOOK_TITLE, DBHelper.BOOK_AUTHOR }, new int[]{ R.id.bTitle, R.id.bAuthor }, 0);
listView.setAdapter(myAdapter);

A: You have to create your own class that extends from adapter what you need for example SimpleCursorAdapter, then specific with XML file, which elements will be included to your ListView and override getView() method to controling each item in ListView.
It's recommended to create and use design pattern Holder, which represents arbitrary object that holds child widgets of every row and then you will have full control over items.
So let basic example:
Declaration and init of ListView
this.contactList = new ListView(this);
this.contactList = (ListView) findViewById(R.id.contactList);
this.contactList.setAdapter(new ContactsAdapter());

This ContactsAdapter is your own created adapter.
public ContactsAdapter() {
            super(getApplicationContext(),
                    R.layout.listview, cursor, new String[] {"name", "email", "phone"}, new int[] {R.id.name, R.id.email});
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            rowsWrapper = null;
            LayoutInflater inflater = getLayoutInflater();
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.listview, null, false);
                rowsWrapper = new ListWidgetWrapper(convertView);
                convertView.setTag(rowsWrapper);
            }
            else {
                rowsWrapper = (ListWidgetWrapper) convertView.getTag();
            }
            Cursor tempC = cursor;
            tempC.moveToPosition(position);

            setActivitySettings();
            rowsWrapper.getNameColumn().setText(tempC.getString(1));
            rowsWrapper.getEmailColumn().setText(tempC.getString(2));

            tempC = null;

            return convertView;
        }
    }

rowsWrapper is mentioned design pattern Holder.
public class ListWidgetWrapper {

    private View inView;
    private TextView nameColumn = null, emailColumn = null, phoneColumn = null;

    public ListWidgetWrapper(View inView) {
        this.inView = inView;
    }

    public int getNameId() {
        return inView.findViewById(R.id.name).getId();
    }

    public int getEmailId() {
        return inView.findViewById(R.id.email).getId();
    }

    public TextView getNameColumn() {
        if (this.nameColumn == null) {
            this.nameColumn = (TextView) inView.findViewById(R.id.name);
        }
        return this.nameColumn;
    }

    public TextView getEmailColumn() {
        if (this.emailColumn == null) {
            this.emailColumn = (TextView) inView.findViewById(R.id.email);
        }
        return this.emailColumn;
    }
}

So i have here TextView elemets, you have here widgets which you want have in ListView.
This require to write much more implementation but it's more faster, less energy consume when you don't use for example design pattern Holder because without it, your rows in ListView would be creating repeatedly when won't be in View and later go back.
More about SimpleCursorAdapter


text:
Q: how can i edit and run the python nltk program how can i edit and run the python nltk program

A: nltk is not a program (in the sense of something that you are intended to execute) but a library.  You need to import the particular modules that you need and then call their functions, or construct their objects, or whatever you want to do.
This article has some examples.
Notice the first two lines of the first example:
>>> from nltk.tokenizer import *
>>> t = Token(TEXT='This is my first test sentence')

The first line indicates that he is importing all of the definitions in the module nltk.tokenizer - this includes the Token class.  In the next line, he is able to instantiate a Token object (something he would not be able to do without the import statement).
nltk is a very large library with many modules encompassing different types of natural language processing functionality.  The first thing to do would be to figure out which specific functionality you would like to take advantage up, and then look it up in the documentation.


text:
Q: Can someone explain and help me with this circuit? This is a board that controls a circular knitting machine, this machine has 108 MPF feeders, those feeders controls 108 yarn, when a yarn breaks the feeder lights its bulb the machine decelerates to stop, at this moment, the worker must fix the yarn and run the machine again, I want to take 2 wires from somewhere to activate a relay when the switch of one or more is closed I want to use this relay to operate a bulb I'll put it on the top of the machine so the worker can see it easily and come to fix the yarn again:
please see the pictures below:

This question contains a unique parts which differentiate it from my other question, I'am asking for the function of the components in this circuit and how can I benefit from them.

A: Here's the circuit diagram based on my interpretation of the photographs.

U 1520 is a 15A diode. When the switch is closed the optocoupler in TLP 504A would be turned on and would shut-down the machine through a relay.
The circuit diagram may be verified for its correctness.
A relay driver circuit is shown below.