text:
Q: Reading data form a .txt file and adding it to my Database I've been working on a school assignment for a while and I have noticed I need a little help finishing it up. Specifically, I need help converting/importing a FlatFile.txt into my normalized DataBase in .
My flatfile has many rows, and in each row there are many attributes separated by a ' | '.
How can I add each line and take every element in the line to its unique corresponding attributes in my DataBase (assuming I already have my connection with my Database established)?
I know I might need to use something like:
hint*: comm.Parameters.AddWithValue("@FirstName", firstname);
How can make the first element of .txt file equal to firstname?
I hope this made sense.
Here is what I have so far:
string [] lines = File.ReadAllLines(pathString);

string[][] myRecords = new string[lines.Count() + 1][];
int k = 1;

foreach (var line in lines)
{
    var values = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
    for (int i = 1; i < values.Length; i++)
    {
        if (myRecords[k] == null)
        {
            myRecords[k] = new string[values.Length + 1];
        }

        myRecords[k][i] = values[i];
        Console.WriteLine(myRecords[k][i]);
    }
    k++;

A: You should be able to add each item from a line to a corresponding name in the database, by using it's position in the line; something like:
comm.Parameters.AddWithValue("@FirstName", values[i]);

(Note: The exact syntax needed here will depend on what you use for this, but I'm assuming you'll be able to figure that part out).
...However, for something like that to work, you'll want to change the code parsing the line and remove StringSplitOptions.RemoveEmptyEntrie, since that will affect the resulting number of data-parts from each line.
An example:
var line  = "one|two|||five|six";

// Will produce: {one, two, five, six}
var nonEmptyValues = line.Split(new char[] { '|' },
                                StringSplitOptions.RemoveEmptyEntries);

// Will produce {one, two, null, null, five, six}
var allValues = line.Split(new char[] { '|' });

The latter will allow your resulting array (values in your code) to always contain the correct number of "columns", which should make mapping from positions to DB column names easier.


text:
Q: Tesseract on iOS - bad results After spending over 10 hours to compile tesseract using libc++ so it works with OpenCV, I've got issue getting any meaningful results. I'm trying to use it for digit recognition, the image data I'm passing is a small square (50x50) image with either one or no digits in it.
I've tried using both eng and equ tessdata (from google code), the results are different but both get guess 0 digits. Using eng data I get '4\n\n' or '\n\n' as a result most of the time (even when there's no digit in the image), with confidence anywhere from 1 to 99.
Using equ data I get '\n\n' with confidence 0-4.
I also tried binarizing the image and the results are more or less the same, I don't think there's a need for it though since images are filtered pretty good.
I'm assuming that there's something wrong since the images are pretty easy to recognize compared to even simplest of the example images.
Here's the code:
Initialization:
    _tess = new TessBaseAPI();
    _tess->Init([dataPath cStringUsingEncoding:NSUTF8StringEncoding], "eng");
    _tess->SetVariable("tessedit_char_whitelist", "0123456789");
    _tess->SetVariable("classify_bln_numeric_mode", "1");

Recognition:
char *text = _tess->TesseractRect(imageData, (int)bytes_per_pixel, (int)bytes_per_line, 0, 0, (int)imageSize.width, (int)imageSize.height);

I'm getting no errors. TESSDATA_PREFIX is set properly and I've tried different methods for recognition. imageData looks ok when inspected.
Here are some sample images:
http://imgur.com/a/Kg8ar
Should this work with the regular training data?
Any help is appreciated, my first time trying tessarect out and I could have missed something.
EDIT:
I've found this:
    _tess->SetPageSegMode(PSM_SINGLE_CHAR);

I'm assuming it must be used in this situation, tried it but got the same results.

A: I think Tesseract is a bit overkill for this stuff. You would be better off with a simple neural network, trained explicitly for your images. At my company, recently we were trying to use Tesseract on iOS for an OCR task (scanning utility bills with the camera), but it was too slow and inaccurate for our purposes (scanning took more than 30 seconds on an iPhone 4 at a tremendously low FPS). At the end, I trained a neural-network specifically for our target font, and this solution not only beat Tesseract (it could scan stuff flawlessly even on an iPhone 3Gs), but also a commercial ABBYY OCR engine, which we were given a sample from the company.
This course's material would be a good start in machine learning.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex for name in Ruby I know this question has been asked a lot but I need a RegEx for a name validator.
The only requirements are letters are okay, No numbers, and no special characters other than 2 and the spaces cannot be at the beginning or end, the "-" and "`" are allowed also. Everything else would be invalid.
All the other answers seem to ask for a lot more and seem to get too complicated.
Currently I am using
/^([^\d\W]|[-])*$/

But this fails with the space
Sample data:
Pass:
Susan Johnson,
Stephanie Le'Sean,
John Pierre'-Frank

Fail:
Ricky2Good,
Jean,stewie,
Mike@dude,
Jim.  McNeil

A: I've assumed that for a string to be valid, it may contain only uppercase and lowercase letters, apostrophes, dashes and at most two spaces, provided the spaces are not at the beginning or end of the string.
STR= "-a-z'"

r = /
    \A           # match beginning of string
    (?:          # begin non-capture group
      [#{STR}]+  # match 1+ letters, "-" or "'"
      |          # or
      [#{STR}]+\s[#{STR}]*\s?[#{STR}]+
                 # match 1+ letters, "-" or "'", space, 0+ letters, "-" or "'",
                 # optional space, 1+ letters, "-" or "'"
    )            # end non-capture group
    \z           # match end of string
    /ix          # case-indifferent and free-spacing regex definition modes
      #=> /
          \A           # match beginning of string
          (?:          # begin non-capture group
            [-a-z']+   # match 1+ letters, "-" or "'"
            |          # or
            [-a-z']+\s[-a-z']*\s?[-a-z']+
                       # match 1+ letters, "-" or "'", space, 0+ letters, "-" or "'",
                       # optional space, 1+ letters, "-" or "'"
          )            # end non-capture group
          \z           # match end of string
          /ix

If I did not use free-spacing mode to define the regex it would look like this:
r = /\A(?:[-a-z']+|[-a-z']+\s[-a-z']*\s?[-a-z']+)\z/i

"a B-' v"    =~ r #=> 0
"aB-'v"      =~ r #=> 0
"aB-'1v"     =~ r #=> nil
"a B-'1  v"  =~ r #=> nil
" a B-1v"    =~ r #=> nil

If you wish to return true or false, rather than a truthy value 0 or a falsy value nil,  you could write, for example:
("a B-' v" =~ r) ? true : false #=> true

or (the "trick")
!!("a B-' v" =~ r) #=> true

The latter works because it is the same as:
!(!("a B-' v" =~ r))
  #=> !(!(0)) => !(false) => true

The question asks for a regex to validate names. Using a regex may be the best, but it's not the only way. If the question is really how to validate names--using a regex or otherwise--it should be stated in a way that doesn't stipulate a particular approach. Here's one way to validate without using a regex.
GOOD_CHARS = ('a'..'z').to_a.join << "'-"
  #=> "abcdefghijklmnopqrstuvwxyz'-"

def validate(str)
  return false if str.empty? || (str[0]==' ' || str[-1]==' ')
  nbr_spaces = str.count(' ')
  return false if nbr_spaces > 2
  str.downcase.count(GOOD_CHARS) + nbr_spaces == str.size
end

validate "a B-' v"   #=> true
validate "aB-'v"     #=> true
validate "aB-`1v"    #=> false
validate "a B-'1  v" #=> false
validate " a B-'1v"  #=> false

A: The following regex should filter for letters, no special characters (other than one space, dashes, and backticks), and no numbers:
/^[a-zA-Z\-\`]++(?: [a-zA-Z\-\`]++)?$/

Hope it helps!


text:
Q: Representing an AST in C with different structs for types of nodes I have many structs which look something like:
typedef struct ast_function_node
{
    int node_type;
    ast_node* arguments;
    symbol* sym;
} ast_function_node;

typedef struct ast_while_node
{
    int node_type;
    ast_node* condition;
    ast_node* while_branch;
} ast_while_node;

typedef struct ast_assignment_node
{
    int node_type;
    symbol* sym;
    ast_node* value;
} ast_assignment_node;

typedef struct ast_number_node
{
    int node_type;
    double value;
} ast_number_node;

typedef struct ast_string_node
{
    int node_type;
    char* value;
} ast_string_node;

etc...

And a base struct:
typedef struct // Basic AST node
{
  int node_type;
  struct ast_node* left;
  struct ast_node* right;
} ast_node;

I can populate this AST pretty easily, but when it comes to traversing it I get stuck in a hell of typecasting. If I wanted to visit each node, look at its type and then do something accordingly, what is the best way of doing this? Just casting it to the base node of ast_node won't do it of course.

A: The way I'd do this in C is to use a struct with a union member:
typedef struct ast_function
{
    ast_node* arguments;
    symbol* sym;
} ast_function;

typedef struct ast_while
{
    ast_node* condition;
    ast_node* while_branch;
} ast_while;

typedef struct ast_assignment
{
    symbol* sym;
    ast_node* value;
} ast_assignment;

/* Etc. */

typedef struct ast_node {
  int node_type;
  /* See anonymous unions in any C reference */
  union {
    ast_function   function_data;
    ast_while      while_data;
    ast_assignment assignment_data;
    /* Etc. */
  };
}

Then you don't need casts at all:
switch (node->node_type) {
  case AST_FUNCTION:
    handle_function(&node->function_data);
    break;
  /* Etc. */
}

If you make node_type an enum instead of an int, the compiler will be able to warn you if you miss a possibility in your switch statement.


text:
Q: __FUNCTION__ and friends act weird in Xcode This works
printf("%s body\n",__PRETTY_FUNCTION__);

But this does not (Error Expected ')'):
printf(__PRETTY_FUNCTION__" body\n");

I can't get the IDE to show me what __PRETTY_FUNCTION__ evaluates to to determine why it does not work.

A: __PRETTY_FUNCTION__ is not a macro. It behaves like a static variable created on the fly scoped in that function.
The last paragraph in the link above reads:

These identifiers are not preprocessor macros. In GCC 3.3 and earlier, in C only, __FUNCTION__ and __PRETTY_FUNCTION__ were treated as string literals; they could be used to initialize char arrays, and they could be concatenated with other string literals. GCC 3.4 and later treat them as variables, like __func__. In C++, __FUNCTION__ and __PRETTY_FUNCTION__ have always been variables.


text:
Q: mosaic dataset and overview failed in arcgis I m working with arcgis 10.
i m trying to optimize the storage and the visualization of heavy raster.
After importing raster in file geodatabase i put them in a mosaic dataset and i generate overview but:

*

*Some raster are missing, and some are cut.

*Overview are shifted

However i m sure that my input raster are in good projection, with stastistics calculated and pyramids.
Any help?


text:
Q: how to reload language files in "production" How to reload language files in Production?
I18n.backend.reload!

This method doesn't work.
(trying to reload via url, attached to this action)

A: You can reload language files without reloading application server using:
I18n.backend.load_translations


text:
Q: How to select only some fields from entity with ManyToMany related table I have two entities: BlogPost and Category. BlogPost entity has ManyToMany unidirectional relation with entity Category. I wrote a function in BlogPost repository to get only some fields of BlogPost entity and all fields of Category entity. This is it:
private function getLitePosts(){
    $q = $this->_em->createQuery(
        'select p.id as pid, p.updateDate, p.postTitle, c from ESGISGabonPostBundle:CorporatePost p left join p.categories c'
    );
    return $q->getResult();
}

When it runs I got error:
"message": "[Semantical Error] line 0, col -1 near 'select p.id,': Error: Cannot select entity through identification variables without choosing at least one root entity alias."

I don't know how to deal with it. I excepted to get something like this (represented in json):
[
    {
        "pid": 1,
        "updateDate": 2015-09-26T00:00:00+0100,
        "postTitle": "This is a test",
        "categories": [
            {
                "id": 1,
                "title": "Uncathegorized"
            }
        ]
    },
    {
        "pid": 1,
        "updateDate": 2015-09-26T00:00:00+0100,
        "postTitle": "This is a test 2",
        "categories": [
            {
                "id": 1,
                "title": "Uncathegorized"
            }
        ]
    }
]

May somebody help me ?

A: I'd recommend using query builder for this simple operation.
$query = $this->createQueryBuilder('p')
    ->select('p.id as pid, p.updateDate, p.postTitle, c')
    ->leftJoin('p.categories', 'c')
    ->getQuery();

return $query->getResult();

More inspiration can be found in this answer

A: I finally found a solution:
$query = $this->createQueryBuilder('p')
        ->select('partial p.{id, updateDate, postTitle}')
        ->leftJoin('p.categories', 'c')
        ->addSelect('partial c.{id}')
        ->getQuery();

return $query->getArrayResult();

It works like I want. Thank you Tomáš Votruba for your answer.


text:
Q: XDocument parse method encoding values I have below code snippet to read file containing xml string and convert it to the XDocument.
public static XDocument ReadXmlContent(string xmlFilePath)
        {
            if (!string.IsNullOrEmpty(xmlFilePath))
            {
                string content = File.ReadAllText(xmlFilePath);
                XDocument xDoc = XDocument.Parse(content);
                return xDoc;
            }
            return null;
        }

This is doing my job well but with one issue.
One of the node in xml string object is
<billDescriptionValue>This is the charge in advance for your %quantity% Line isolating unit No. 1A at £%quantity rate% per unit per month</billDescriptionValue>

now, when i parse this using XDocument.Parse, the above content becomes
<billDescriptionValue>This is the charge in advance for your %quantity% Line isolating unit No. 1A at £%quantity rate% per unit per month</billDescriptionValue>
so why '& #xA3;' is changed to '£' ?? how can i stop this?
Thanks a lot in advance.


text:
Q: Type hints of function with object child arguments does not accept child classes I'm trying to implement a type-hinted event subscription mechanism.
The listener subscribes by passing a handler function.
The subscribe function accepts any method that can handle BaseEvents.
However, when I narrow down the childclass, I get a type warning.
from typing import Callable

class BaseEvent:
  pass

class ChildEvent(BaseEvent):
  pass

class Listener:
  def __init__(self):
    # Expected type '(BaseEvent) -> None', got '(event: ChildEvent) -> None' instead
    self.subscribe(handler=self.handler)

    pass

  def subscribe(self, handler: Callable[[BaseEvent], None]):
    pass

  def handler(self, event: ChildEvent):
    pass

I understand that the 'contract' requires the handler to accept any BaseEvent, and that this approach does not satisfy Liskov substitution, but since Python has no interfaces, how can I "enforce" that the handler is going to at least handle some classes extending BaseEvent, and not strings for example?


text:
Q: Ace editor + Angular 2 => protractor cannot synchronize I'm developing an app using Angular 2 (2.0.0 release), angular-cli (1.0.0-beta.14).
I've integrated Ace editor using an Angular 2 directive, following https://github.com/fxmontigny/ng2-ace-editor
As soon as the Ace editor is instantiated, protractor cannot synchronize anymore:
✗ should display app name
  - Failed: Timed out waiting for Protractor to synchronize with the page after 11 seconds. Please see https://github.com/angular/protractor/blob/master/docs/faq.md
While waiting for element with locator - Locator: By(css selector, app-root .navbar a.active)

The Ace editor is instantiated using:
import { EventEmitter, Output, ElementRef, Input, Directive } from '@angular/core';
import 'brace';
import 'brace/theme/chrome';
import 'brace/mode/html';

declare var ace: any;

@Directive({
   selector: '[aceEditor]'
})
export class AceEditorDirective {
  editor: any;

  constructor(elementRef: ElementRef) {
    let el = elementRef.nativeElement;
    this.editor = ace['edit'](el); // Comment this line and Protractor works again
  }
}

Any hint what's the issue ?

A: Ok, finally found the issue.
It looks like Angular is lost tracking changes in the Ace Editor, hence thinks there are always ongoing changes. So
window.getAngularTestability($('app-root'))
    .whenStable(function(){
        console.log('stable')
    })

Does not return anymore when Ace Editor is instantiated.
Easy solution: instantiate the Ace Editor out of the zone:
constructor(elementRef: ElementRef, zone: NgZone) {
  let el = elementRef.nativeElement;
  zone.runOutsideAngular(() => {
    this.editor = ace['edit'](el);
  });
}

A: I was facing the same issue as above and instead of running the ace editor outside of Angular, I rather made multiple tests in protractor which would continue from where the previous test left off. Ace Editor would cause the browser not to finish synchronizing and hence my protractor test would time out.
You could have the tests as follows:
it('Runs Tests for components with ace edit')
  browser.ignoreSynchronization = true;
  testAngularElements();

it('Runs the rest of the test in which the ace edit is not present')
  browser.ignoreSynchronization = false;
  remainingTests();

Unfortunately I could not find an alternative approach yet.


text:
Q: Finding all Sub ranges for a list of ranges (one or more) I have some files which are written between Start Time and End Time as follows;
[0 , 1] , [1,2] , [2 , 3] , [3, 4] , [4, 7] , [7, 8]

I want to find all the sub ranges for the time between 2 and 5 with O(N);
For above example:
[1,2] , [2 , 3] , [3, 4] , [4, 7]

This works if I write condition like below
if (StartTime >= 2 and StartTime <= 5) or (EndTime >=2 and EndTime <= 5)
    add this to your list of sub ranges

But this fails if I have a single range:
[0,8]

and I am searching for file between 2 and 5
Can anyone suggest how to do this?

A: Note that intervals A and B overlap if
 (A.Start <= B.End) and (B.Start <= A.End)

Example:
 A = [2,5]
 B = [0,8]
 (A.Start <= B.End) and (B.Start <= A.End)
  (2<=8) and (0<=5)  is True, so they overlap

P.S. In general case it's worth to use dedicated data structures like interval tree to achieve better asymptotic time.

A: Here:
if(startTime<=5 && endTime>=2);

OR
if(max(startTime,2)<=min(endTime,5));

This will work in all conditions.


text:
Q: Detecting Ordinal plurals How can I detect ordinal plurals in DialogFlow?
I know there is the sys.ordinal entity. But that will only detect.
Third Fourth
But I want to detect
Thirds Fourths

A: Enter (be sure to actually press enter) your training phrase with an ordinal plural, for example, "I would like to cut the pie in fourths." Then highlight the word fourths and a dialogue box should pop up. Find @sys.ordinal:ordinal and click it. Do that with a couple of other plural ordinals for good measure and then it will recognize them all.
Note that sometimes the dialogue box fails to pop up when you highlight a word. If this happens just try highlighting it a couple more times. Usually it will work eventually.


text:
Q: Why one needs to create a new objects on each iteration of a loop when populating a List? I am working list of objects. My code looks something like this
public class emp
{
   public string emp_name{get;set;}
   public int emp_id{get;set;}
}

List<emp> emplist = new List<emp>;
emp empobj = new emp();
// fetching data from data table
foreach (DataRow row in ds.Tables[0].Rows)
{
    // initialize emp object
    empobj.emp_name = row["emp_name"].ToString();
    empobj.emp_id = (int)row["emp_id"];

    // add empobject to emp list
    emplist.add(empobj);
}

If 2 records are fetched from table then my list shows last record details in each list object.
what i found was if i dont create new emp object every time and add to list it overrides the previous value in list also.
solution for this is
// fetching data from data table
foreach (DataRow row in ds.Tables[0].Rows)
{
     // create new object every time
     emp empobj = new emp();

    // initialize emp object
    empobj.emp_name = row["emp_name"].ToString();
    empobj.emp_id = (int)row["emp_id"];

    // add empobject to emp list
    emplist.add(empobj);
}

Can any one please tell me why is it so?

A: If you don't create a new Emp object every time, you overwrite and insert the same object every time.
Imagine a piece of paper. You write on it, you put it into a book. Writing on the same piece of paper and putting in into the book multiple times will just not work. It will be a mess of writing on a single page. For every page you need a new piece of paper.

A: When you add to the emplist, you are adding 'empobj', which is a reference to a emp object.
Unless you create a new emp object each time, and assign that new entry to the empobj reference, you are just adding the same reference again and again.
Therefore, when you change the contents of that one reference, you change all the entries in the list.

A: In your code you are creating a single instance of the emp class, overwriting the elements in it for each row, and saving multiple references to the same object into the list.
You need to change the code to:
List<emp> emplist = new List<emp>;
// fetching data from data table
foreach (DataRow row in ds.Tables[0].Rows)
{
    // initialize emp object
    emp empobj = new emp();
    empobj.emp_name = row["emp_name"].ToString();
    empobj.emp_id = (int)row["emp_id"];

    // add empobject to emp list
    emplist.add(empobj);
}

A: In basic terms, your first piece of code effectively does this:
emp empobj = new emp();
empobj = new emp();
empobj = new emp(); // "final" version of the object

emplist.Add(empobj); // Same (final) added each time.
emplist.Add(empobj);
emplist.Add(empobj);
...

Your last piece of code effectively does
emplist.Add(new emp()); // New object each time.
emplist.Add(new emp());
emplist.Add(new emp());
...

2 Sidenotes:
You might want to simplify your code like this:
foreach (DataRow row in ds.Tables[0].Rows)
{
    emplist.add(new empobj{
                            emp_name = row["emp_name"].ToString(),
                            empobj.emp_id = (int)row["emp_id"]
                           });
}

..and you might want to stick to naming conventions to make your code easier to read and understand; that is, use Emp for class name (capitalized). The same goes for properties, but there, avoid the underscores (this is to separate them from fields and other variables):
public string EmpName{ get; set; } and public int EmpId{ get; set; }.

A: When you do emp empobj = new emp();, you create a new instance of emp.
This line of code tells the memory allocator to assign memory to the new instance of emp object.
In your first example, you only had one instance, and you were over-writing the properties value in the foreach loop.
In the second example though, you were creating a new instance of emp object within the loop.

A: We could say that List stores references to objects, that's why in first case we add same reference, but in second case we add references to different objects, because empobj in each cycle is a new object.


text:
Q: Tengo problema para subir una imagen, y no se que podrá ser Estoy usando angularjs y laravel... y asi esta mi formulario para subir un logo:
Logo:
<input type="file" name="logo" file-model="identidad.logo" ng-model="identidad.logo" id="logo" required>

y en el controlador laravel:
public function store(Request $request)
{
    $i = new Identidad();
    $i->direccion = $request->direccion;
    $i->club_id = auth()->user()->club->id;
    if (Input::hasFile('logo')){
        $file=Input::file('logo');
        $file->move(public_path().'/img/logos/', $file->getClientOriginalName());
        $i->logo=$file->getClientOriginalName();
    }
    $i->save();
    return $i;
}

La verdad no se cual pueda ser el problema.. porque uso ese mismo codigo en otro formulario para subir imagenes y los sube perfectamente!! en este formulario donde tengo el problema sube las otras cosas menos el logo, miren en la base de datos:

por favor ayudaa!!

A: Parece que estas usando una directiva file-model, por lo que se me ocurre que el problema es que ng-model apunta a la misma variable, por lo que seguramente la propiedad logo llega null al controlador.
Prueba de la siguiente manera:
Logo:
<input type="file" name="logo" file-model="identidad.logo" id="logo" required />


text:
Q: Jquery: pushing a fixed positioned div down with expanding Div? I'm using jquery to expand a hidden div on click in my page.
I have another div which is a fixed position div which is the header in my page.
what i am trying to do is to expand the div and then push the header div and everything else in my page down as this expandable div expands.
I have tried the relative position for the fixed div but i need this div to be present on the screen at all times which is why i've given it a fixed position!
Here is a Jsfiddle to see what I mean.
The html structure is like this:

Welcome

Click Here

could someone please advise on how to achieve this?
any help would be appreciated.

A: Closest I can can get.
As I mentioned, the fixed div is fixed so it's not going anywhere unless you tell it to. You could animate the top position and margins and so forth but I think I just prefer toggling the position property from fixed to relative.

$('#a-sidebar').click(function() {
  $('#bubs').toggleClass('down');
  $('.boxs').slideUp('slow', function() {
    // Animation complete.

  });
});

$('#reveal').click(function() {
  $('#bubs').toggleClass('down');
  $('.boxs').slideToggle('slow', function() {
    // Animation complete.

  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.boxs {
  height: 300px;
  background-color: #333;
  padding: 10px;
  display: none;
}
#welcome {
  color: #F8F8F8;
  font-size: 24px;
}
#bubs.down {
  position: relative;
}
main {
  height: 250px;
  background: #f00;
}

Welcome

Click Here


text:
Q: Shop by department in magento As shown in picture I want to show only Category in homepage instead of product.
For ex. I have 10 Categories & each category has 100 products!
So in homepage I am showing 5 products of each category.
I want to show only category name along with category picture. On clicking the picture it will take to Category Page where all products will be there.
How to do this?

A: I think you can use CMS page for this. Create a CMS page from the backend, there you can insert image and also create a widget to create the link to the category.
There is a button Insert Widget.There you can select the widget type as catalog category links and then selects the category.
Hope this will help.


text:
Q: Ruby on Rails - Bullet/N+1 On Rails 4. I recently installed the bullet gem for my development environment to clear up my app's N+1 queries. Relevant models:
Submissions: Belongs to Categories and Users. Has many SubmissionDetails.
Users: Has many Submissions
Categories: Has many Submissions. Belongs to Awards.
Awards: Has many Categories (and Submissions through Categories)
SubmissionDetails: Belongs to Submissions
In my submission's index page, I have an each do statement to display each submission made by the current user.
<% current_user.submissions.order('created_at DESC').in_groups_of(3, false) do |group| %>

    <% group.each do |submission| %>

After that, I list information about the submission, including its associated category, award, and submission details information. Bullet is saying I'm having N+1 issues with this statement:
N+1 Query detected Submission => [:category] Add to your finder: :include => [:category]
N+1 Query detected Submission => [:user] Add to your finder: :include => [:user]
N+1 Query detected Submission => [:submission_details] Add to your finder: :include => [:submission_details]

Every time I try to add .includes with all three of those models, it only picks the first one I list (this is not surprising). I figure I need to go a different route when multiple models are involved--perhaps a join statement?
(When I make :category the first item, it adds this notice):
N+1 Query detected Category => [:award] Add to your finder: :include => [:award]

(So I also need to include as part of the statement a way to make Award fit in there as well, which, again, has many Submissions through Categories).
So assuming I can't do one .includes for three different models, is there another way to go about this? Thanks.

A: Just to be more clear, let me make the details more visible:
class User < ActiveRecord::Base
  has_many :submissions
end

class Submission < ActiveRecord::Base
  belongs_to :category
  belongs_to :user
  has_many   :submission_details
end

class SubmissionDetail < ActiveRecord::Base
  belongs_to :submission
end

class Category < ActiveRecord::Base
  belongs_to :award
  has_many   :submissions
end

class Award < ActiveRecord::Base
  has_many :categories
  has_many :submissions, through: :categories
end

If I understand correctly, for your current_user, you are listing his submissions.
For each submission you want to list submission_details and the category it belongs.
For every category you list the award too.
<% current_user.submissions.order('created_at DESC').in_groups_of(3, false) do |group| %>

    <% group.each do |submission| %>
      ...

<%= submission.category %>

<%= submission.category.award %>

      <%= submission.submissions_details.each do |submission_detail| %>
        ...
      <% end %>
    <% end %>

<% end %>

You can remove N+1 problem by using includes in the following manner:
current_user.submissions.includes(:submission_details, :category => :award)

For more details about includes please refer to:

*

*Rails guides eager-loading-associations

*Rails guides eager-loading-multiple-associations

*Rails api - includes
associations

A: To include those associations, I would create a scope for submissions. While you're at it, add a latest scope.
class Submission
  scope :eager,  -> { includes(:submission_details, :category => [:award]) }
  scope :latest, -> { order("created_at DESC") }
end

Then simply
current_user.submissions.latest.eager [...]
You shouldn't have to include :user, but I've noticed Rails isn't too clever about such references.


text:
Q: Data not inside HTML table, Laravel PHP I just started using Laravel and wanted some data from my database to be in a html table, but not the php loads outside the table.
This is my code, This is done in Laravel.

                                    id
                                    merk
                                    type
                                    color
                                    price

                                <?php
                                use App\Models\Shoe;
                                foreach (Shoe::all() as $shoe) { ?>

                                        <tb> <?php echo $shoe->id ?> </tb>
                                        <tb> <?php echo $shoe->merk ?> </tb>
                                        <tb> <?php echo $shoe->type ?> </tb>
                                        <tb> <?php echo $shoe->color ?> </tb>
                                        <tb> <?php echo $shoe->price ?> </tb>

                                <?php } ?>

This is the result I get:

So all the php stuff loads and then comes the , idk how to make it that the database information actually shows inside the table
I'm probably just really dumb here but I've tried multible ways but I always keep getting this result. Anyone who can help? Thanks in advance.


text:
Q: Filtering data by time only in datetime column for sql Working with sqlite in Python.
I have data timestamped
2022-05-22 00:57:28
2022-05-22 14:40:18
2022-05-22 02:58:32
2022-05-22 03:59:30
2022-05-22 15:07:17

I would like to get all rows that fall in between a TIME range.
This produces no results
SELECT *
FROM speedtests
WHERE date_run BETWEEN time("00:00:00") AND time("06:00:00")

I tried the solution from a similar question, however it returns every single result in the database.
select * from table
where cast(date_run as time) >= '00:00:00'
   OR cast(date_run as time) <= '06:00:00'

I have also tried GROUP BY statements but could not get it to work.
If getting individual rows is not possible, the max, min, avg, count values are enough for the filtered dataset - aggregate statement which I also tried with no luck.

A: SELECT *
FROM Table_Name
WHERE time(Column_Name) BETWEEN ('14:30:00') AND ('14:55:00')
Above Query is to filter the data based on time, Replace Table_Name with your table name and Column_Name with your column name for what you want to filter the data.


text:
Q: Write an algo to write "thisisasentence" to "this is a sentence " using dictionary in java I have been trying to build the algorithm but I'm unable to find the solution. My sentence doesn't have any delimiters to split given sentence into multiple strings.

A: import java.util.TreeSet;

public class YourHomework {

    // Dictionary
    private static final TreeSet<String> dic = new TreeSet<String>() {
        {
            add("this");
            add("is");
            add("a");
            add("sentence");
        }
    };

    private static String convert(String input) {
        StringBuilder output = new StringBuilder();
        StringBuilder word = new StringBuilder();

        for (char c : input.toCharArray()) {
            // Each new char is added to the current word
            word.append(c);

            // If we have a match with the current word
            if (dic.contains(word.toString())) { // We will append it to our output
                if (output.length() > 0) { // But first we add a space if it's not the first word
                    output.append(' ');
                }

                // We add the word to the output sentence
                output.append(word);
                word.setLength(0);
            }
        }

        return output.toString();
    }

    public static void main(String[] args) {
        System.out.println(convert("thisisasentence"));
    }

}

A: I'm guessing this is Computer Science homework (and not specifically natural language processing).  I'll share an approach rather than provide a solution:

*

*Start with your input sentence

*In a loop, take N characters from the start of your sentence (start with 1, then 2, etc...)

*Check the N characters you just took off the start of your sentence against your dictionary of valid words.

*If you find a match, output that word and remove N characters from the input sentence.  Resume at step 2, unless you have reached the end of the sentence (in which case you are done).

*If you do not find a match, you are done.  The next word did not match anything in your dictionary.

Note that casing is important with a dictionary.  If everything is lower case you're fine, but if ThisisJohn is valid input, you need to give some thought to how to handle casing.
If you are attempting general case natural language processing, the solution is significantly more complex.

A: Here's the solution I improvised in Python:
dictionary = set([
    'this',
    'is',
    'a',
    'i',
    'sentence',
])
match_bkt = []
# ip_str = 'sentence'
# ip_str = 'thisisnotasentence'
ip_str = 'thisisasentence'
# ip_str = 'isa'

def sentence_chk(ip_list):
    for i in xrange(1, len(ip_list) + 1):
        sub_str = ''.join(ip_list[:i])
        if sub_str in dictionary:
            # push to match_bkt
            match_bkt.append(sub_str)
            if len(ip_list[i:]) > 0:
                if sentence_chk(ip_list[i:]) is not True:
                    # pop match_bkt & backtrack
                    match_bkt.pop()
                    continue
                else:
                    sentence_chk(ip_list[i:])
        if len(''.join(match_bkt)) == len([o for o in ip_str]):
            print ip_str, '-- is a sentence'
            exit()

ip_list = [i for i in ip_str]
if sentence_chk(ip_list) is None:
    print ip_str, '-- is not a sentence'

#I'm sure this can be further optimized

Gist Link: https://gist.github.com/svalleru/bbaae89dbee974b2ba6b

A: In brief, to split a string, try getting first part from input using different length, and if it is a valid word in dictionary, split the remaining part and construct the result strings accordingly.
Simple recursive thought (psuedo code):
List<String> split(String sentence) {
    result = new List<String>();
    if (sentence is empty) {
        return result;
    }
    for (i = 1; i < sentence.length; i++) {
        firstPart = sentence.substring(i)
        if ( s is in dictionary) {
            remaining = split(sentence.substring(i+1 .. end))
            foreach s in remaining {
                result.add(firstPart  + " " + s)
            }
        }
    }
    return result;
}


text:
Q: Consolidating Contacts from Multiple Services I'm looking for a good way to consolidate my many email/messenger contacts through my different accounts and services.  I'd like to have all my contacts in one place, or have them sync between all my different services so they are the same everywhere.  If possible, it should support Live Mail/Messenger, Google Contacts, and mobile syncing.
Windows Live Mail is great for accessing all your mail accounts, but the contacts viewer only works for contacts affiliated with that Live account.  I could go for the contacts folder built into Vista and above, but Live messenger doesn't access that so I would have a separate set of contacts for my IM account.
Is there software, or an online service, that can do this?
If this is asking to much, is there a proper solution to Live/Google Contacts bidirectional sync?

A: I'm looking for something similar. I haven't gotten anything that exactly suits my needs yet, but you might wanna check out the following sites. None of them are easy to use as you have to run them on your own webserver.

*

*http://knowee.net/

*http://noserub.com/

*http://diso-project.org/

A: You can export vcf (contact card) file from most of these services, then import it on your other account. Google also offers Outlook specific file (which is also compatible with Live). What you should do is decide on a primary service (live/gmail etc) to always update your contacts. Then once a month/week do the export->import the contact file (vcf, csv etc).


text:
Q: Save print settings from windows print settings dialog I call printer settings dialog via windows API
 private void OpenPrinterPropertiesDialog(PrinterSettings printerSettings)
        {
            IntPtr hDevMode = printerSettings.GetHdevmode(printerSettings.DefaultPageSettings);
            IntPtr pDevMode = GlobalLock(hDevMode);
            //int sizeNeeded = DocumentProperties(new WindowInteropHelper(this).Handle, IntPtr.Zero, printerSettings.PrinterName, pDevMode, ref pDevMode, 0);
            int sizeNeeded = DocumentProperties(new WindowInteropHelper(this).Handle, IntPtr.Zero, printerSettings.PrinterName, IntPtr.Zero, pDevMode, 0);
            IntPtr devModeData = Marshal.AllocHGlobal(sizeNeeded);
            DocumentProperties(new WindowInteropHelper(this).Handle, IntPtr.Zero, printerSettings.PrinterName, devModeData, pDevMode, 14);
            GlobalUnlock(hDevMode);
            printerSettings.SetHdevmode(devModeData);
            printerSettings.DefaultPageSettings.SetHdevmode(devModeData);
            GlobalFree(hDevMode);
            Marshal.FreeHGlobal(devModeData);
        }

My problem is that the settings are not saved. The settings should be saved on operating system level so that these settings stay for every application.

A: Have you read this post on msdn?
It seems that you should be calling
IntPtr hDevMode = printerSettings.GetHdevmode();

instead of
IntPtr hDevMode = printerSettings.GetHdevmode(printerSettings.DefaultPageSettings);

And I'd also be interested where the argument 14 in DocumentProperties comes from. Shouldn't that be DM_OUT_BUFFER?


text:
Q: Angularjs checkbox like gmail Im newbie in angularjs.
Now im having issues with a checkbox.
First: my web are paging , sorting and change page size by call api to get data from server in factory:
this.getData = function(page , sortColumm, sortType , pageSize, searchText){
$http({
        method = get;
        url = "api/data?page="+page +"&sortColumm=" +sortColumm +"&sortType="+sortType +"&pagesize="+pageSize+"&search="+searchText;
    }).success(function (data) {
    }).error(function (error) {
    });
}

now i have a page using angularjs to bind data using funciton getData.
html:

        <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()">
        Administrator Name
        Administrator Type
        Roles

        <input type="checkbox" ng-model="gladmin.Selected" value="{{gladmin.id}}" ng-click="selectionAdmin(gladmin.id)">
        {{gladmin.name}}
        {{gladmin.type}}

controller
app.controller('adminPage',function(){
   // call getData
   $scope.checkAll=function(){
       // what should i write here?
       // i want check all is for current page, next page checkall = fall,
       // same GMAIL
   }
   $scope.selectionAdmin = function(id){
       // what should i do here
   }
})

All i want is the checkall same the checkall in gmail ? anyone help me ? please, i am new bie in this!
i find some link here : http://plnkr.co/edit/N98IKTcHoZMCs18FjSRF?p=preview
http://vitalets.github.io/checklist-model/
but it work not same i want !

A: It is hard for me to understand the question but I think you just want a property of ng-checked="isAllChecked" in your ng-repeat for the inputs.  When that value is set to true all of them should check.


text:
Q: Gstreamer: how to ouput mp4 video into /dev/video0? I found that for .avi files

gst-launch-1.0 -v filesrc location=test.avi ! avidemux ! decodebin !
  videoconvert ! "video/x-raw,format=YUY2" ! v4l2sink device=/dev/video0

and this one ouptput screen into /dev/video0 :

gst-launch-1.0 -v ximagesrc startx=1 starty=1 endx=320 endy=240 !
  videoconvert ! "video/x-raw,format=YUY2" ! v4l2sink device=/dev/video0

Any idea on how to use Gstreamer to input a .mp4 file instead of .avi file ?

A:
gst-launch-1.0 -v filesrc location=test.mp4 ! qtdemux ! decodebin ! videoconvert ! "video/x-raw,format=YUY2" ! v4l2sink device=/dev/video0

Since MP4 files do not have a concept of a fixed frame rate you have to add a video rate element and set a desired frame rate (may depend on the output device).

gst-launch-1.0 -v filesrc location=test.mp4 ! qtdemux ! decodebin ! videorate ! videoconvert ! "video/x-raw,format=YUY2,framerate=30/1" ! v4l2sink device=/dev/video0


text:
Q: exe stringtable in C#? How do i read/set the exe's string table in C#? I don't mean resource file. I mean take any exe, open it in visual studios, right click and select "Add Resource" then select string table which is a uint16 key and string value.
How do i access that in C#?

A: Well... This is easy to answer... Harder to implement though.
What you need to do is:

*

*Create a Visual Studio Extension.

*Familiarize yourself with the file format, Portable Executable.

*Learn how to inject data into said Portable Executable.

*Write code to implement the above.

On the other hand, which type of executable are we talking about?
There a many different kinds and if you mean ANY kind then you're going to have fun for a long, long time.


text:
Q: CentOS DHCP server failover won't give out leases I have followed this tutorial: http://www.madboa.com/geek/dhcp-failover/
However, I can not seem to get a lease at my windows client.
I have set both servers (CentOS 6.2) in virtual machines, connected by the same LAN segment. (with VMWare Workstation).
My Windows client is also a virtual machine in the same network segment.
If I, as in the tutorial, made a single DHCP server, I was able to get a lease. But now that I have two DHCP servers, connected with the failover protocol, I can't seem to get the lease.
I have no idea where the problem could be. I have already synced both servers with the ntpdate command, giving them the same time and date (so there is no time difference).
The log from the secondary server gives me peer holds all free leases and the log from the master gives me not responding (recovering).
I can ping from master to slave and slave to master, but I can not ping from the Windows client to either the master or the slave. If I do so, I get this:

PING: transmit failed, error 1231.
PING: transmit failed, error 1231.

Please tell me whatever other relevant info I should give.

A: The error message peer holds all free leases can also mean that the request has been received on the wrong network interface, e.g. if a computer is only configured to get an IP on eth0, but the DHCP request is received on eth1. In my case one interface was for the workstation network and the other one for printers only and someone plugged a workstation into the printer network.
See my blog posting about when I ran into that error message and found no obvious reason, too. (Ran into it on Debian, but that shouldn't make a difference.)
The again, I can't remember having seen the message not responding (recovering) anywhere, but instead I had peer holds all free leases on both DHCP servers.
I though can imagine that in this case maybe one of the two machines may have two interfaces mixed up with regards to the network they're connected to.


text:
Q: how to get from jid & to jid using smack and java? By using below code I can only get  from userId but n't to userId.
public void processMessage(Chat chat, Message message) {

         if ((message != null) && (message.getBody() != null)) {

            System.out.println(chat.getParticipant());

          }
    }

A: I have created One Custom Message Listener which is intialized at a time when you have successfully connect to the Server as: messageListener = new MyMessageListener(); and the Custom MessageListener contains the code as :
class MyMessageListener implements MessageListener {
    @Override
    public void processMessage(Chat chat, Message message) {
        String from = message.getFrom();
        String body = message.getBody();
        System.out.println(String.format(
                "Received message '%1$s' from %2$s", body, from));
    }

}

May be it's help you.


text:
Q: Solr: At what index size should I start considering splitting up the indexes with sharding I've got 120GB of input data indexed currently (not storing data, just doc IDs & the indexes), it takes somewhere on the order of 12+ hrs to index the full data set.
We haven't yet moved that into production, what I want to know is what point will I need to start considering sharding, separating the index onto multiple servers?
Is sharding your index a question of index size, or is it only a question of indexing time/disk space/user load?
Will I run into memory limitations as my index grows to say 200GB, 300GB of input data, etc?


text:
Q: Difference between test suite, test case and test category What is the difference between test suite, test case and test category.
I found a partial answer here
But what about categories?

A: Test case is a set of test inputs, execution conditions, and expected results developed to test a particular execution path. Usually, the case is a single method.
Test suite is a list of related test cases. Suite may contain common initialization and cleanup routines specific to the cases included.
Test category/group is a way to tag individual test cases and assign them to categories. With categories, you don't need to maintain a list of test cases.
Testing framework usually provides a way to specify which categories to include or exclude from a given test run. This allows you to mark related test cases across different test suites. This is useful when you need to disable/enable cases that have common dependencies (API, library, system, etc.) or attributes (slow, fast cases).
As far as I can understand, test group and test category are different names for the same concept used in different frameworks:

*

*@Category in JUnit

*@group annotation in PHPUnit

*TestCategory in MSTest

A: Test Categories is like a sub Test Suite. Take this documentation by example. One a class file, you will have multiple test cases. A Test Suite is a grouping of Test classes that you want to run. A Test Category is a sub grouping of Test Cases. You could put a annotation at some test cases in your class file, and create to test suite pointing to the same test class, but filtering one of the suites to test only some categories. Example from documentation:
public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

public class A {
  @Test
  public void a() {
    fail();
  }

  @Category(SlowTests.class)
  @Test
  public void b() {
  }
}

@Category({SlowTests.class, FastTests.class})
public class B {
  @Test
  public void c() {

  }
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b and B.c, but not A.a
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b, but not A.a or B.c
}

Notice that both Test Suite points to the same test classes, but they will run different test cases.


text:
Q: history.push doesn't show the destination path This seems like a simple task, but can't seem to get it to work. I'm building a React SPA running Material UI and Typescript. Due to errors, when I'm using Material UI Tables, and I have a Cell that's a link, then I have to use
onClick={() => this.props.history.push('/link')}
This creates a problem that the destination path is not being displayed in the bottom left corner (Chrome, also can't remember what this is called, but hope that someone understands what I'm referring to).
I've done a few searches, but can't seem to find anything relating to this.

A: Why don't you use Link from react-router-dom directly?
For instance:
<Link to="/link">Some Page</Link>


text:
Q: Ideas on making a video file play only within my app on iPad The video files I have are 500mg-1gb.  I have tried AES encryption and it takes too long to decrypt and play.  I was hoping to modify the mp4 files within my app in someway when i store them that if someone does copy them off of the iPad they will appear "broken" and unplayable.
Can I accomplish this with moving some bits around in the file and then putting them back before I play it?  Is there a fast encryption the iPad supports?
I am not very familiar with encryption and how to do this.  Please someone point me in the right direction.  Any ideas would be appreciated.

A: Try XOR encoding. It should be much faster to decrypt but don't expect no ultra-speed if you are trying to decrypt the whole file at once. My guess would be to encode those video files in chunks of some size, each encrypted with a XOR which uses some pre-shared key(already existing on the iPod) to decrypt video data on the go.
After all - you are trying to achieve something that all major record and producing companies have been trying to accomplish for years. So good luck, you will need it.

A: Perhaps you will want to look at DRM support on the iPad? Similarly to what Artis has discussed, record  companies have been trying to do this for a long time and I believe DRM is their best choice so far.

A: Here is what I came up with for anyone who wants something that might not be full proof, but wants to make it hard for anyone to take video or anything from your iPad app...
This method requires no encryption and no files in memory so it works just as fast no matter the size of the file...
Using a file handle I read the first so many bytes from the media file and stored them in another file.  I then replaced those bytes with garbage data...this breaks the mp4 file for any media player.  In the app when someone requests that file I check to see if there is the corresponding file with the bytes in it and then I just replace the garbage with the actual bytes and play the file.
I copied the files off of the iPad to test and they will not play in any player I have tried.
Like I said it's not full proof and if someone wanted to they can put those files together, but they would need some knowledge of how many bytes I replaced and where in the file I got them from.  For me this worked great.
Thanks for the replies and if anyone has other suggestions post them.


text:
Q: Constant Dns.java line 5 errors on crashlytics I have implemented my okhttp client as follows in my app:
fun getOkhttpClient(): OkHttpClient {
val chuckerCollector = ChuckerCollector(
    context = MyApplication.appInstance!!,
    // Toggles visibility of the push notification
    showNotification = BuildConfig.DEBUG,
    // Allows to customize the retention period of collected data
    retentionPeriod = RetentionManager.Period.ONE_WEEK
)

// Create the Interceptor
val chuckerInterceptor = ChuckerInterceptor.Builder(MyApplication.appInstance!!)
    // The previously created Collector
    .collector(chuckerCollector)
    // The max body content length in bytes, after this responses will be truncated.
    .maxContentLength(250_000L)
    .alwaysReadResponseBody(BuildConfig.DEBUG)
    .build()

val executorService: ExecutorService =
    ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, LinkedBlockingQueue())
val myDispatcher = Dispatcher(executorService)

return OkHttpClient.Builder()
    .connectTimeout(15000, TimeUnit.MILLISECONDS)
    .retryOnConnectionFailure(true)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .protocols(listOf(Protocol.HTTP_1_1))
    .addInterceptor(HeaderInterceptor())
    .addInterceptor(chuckerInterceptor)
    .dispatcher(myDispatcher)
    .apply {
        if (BuildConfig.DEBUG) {
            val logging = HttpLoggingInterceptor()
            logging.setLevel(HttpLoggingInterceptor.Level.BODY)
            addInterceptor(logging)
        }
    }
    .build()
}

Open the app for the first time everything works fine.
Put the app in background for about 30 to 40 mins and come back to the app.
Call any api and it will give -
Non-fatal Exception: java.net.UnknownHostException Unable to resolve host "host_url":        No address associated with hostname java.net.Inet6AddressImpl.lookupHostByName (Inet6AddressImpl.java:157) java.net.Inet6AddressImpl.lookupAllHostAddr (Inet6AddressImpl.java:105) java.net.InetAddress.getAllByName (InetAddress.java:1154) okhttp3.Dns$Companion$DnsSystem.lookup (Dns.java:5) okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress (RouteSelector.java:133) okhttp3.internal.connection.RouteSelector.nextProxy (RouteSelector.java:20) okhttp3.internal.connection.RouteSelector.next (RouteSelector.java:17) okhttp3.internal.connection.ExchangeFinder.findConnection (ExchangeFinder.java:196) okhttp3.internal.connection.ExchangeFinder.findHealthyConnection (ExchangeFinder.java) okhttp3.internal.connection.ExchangeFinder.find (ExchangeFinder.java:47) okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.java:31) okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.java:11) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:191) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:167) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:34) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.chuckerteam.chucker.api.ChuckerInterceptor.intercept (ChuckerInterceptor.java:9) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.pharmasentinel.medsii.retrofit.HeaderInterceptor.intercept (HeaderInterceptor.java:37) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.java:113) okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.java:51) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:764)
Caused by android.system.GaiException android_getaddrinfo failed: EAI_NODATA (No address associated with hostname) libcore.io.Linux.android_getaddrinfo (Linux.java) libcore.io.BlockGuardOs.android_getaddrinfo (BlockGuardOs.java:172) java.net.Inet6AddressImpl.lookupHostByName (Inet6AddressImpl.java:137) java.net.Inet6AddressImpl.lookupAllHostAddr (Inet6AddressImpl.java:105) java.net.InetAddress.getAllByName (InetAddress.java:1154) okhttp3.Dns$Companion$DnsSystem.lookup (Dns.java:5) okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress (RouteSelector.java:133) okhttp3.internal.connection.RouteSelector.nextProxy (RouteSelector.java:20) okhttp3.internal.connection.RouteSelector.next (RouteSelector.java:17) okhttp3.internal.connection.ExchangeFinder.findConnection (ExchangeFinder.java:196) okhttp3.internal.connection.ExchangeFinder.findHealthyConnection (ExchangeFinder.java) okhttp3.internal.connection.ExchangeFinder.find (ExchangeFinder.java:47) okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.java:31) okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.java:11) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:191) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:167) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:34) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.chuckerteam.chucker.api.ChuckerInterceptor.intercept (ChuckerInterceptor.java:9) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.pharmasentinel.medsii.retrofit.HeaderInterceptor.intercept (HeaderInterceptor.java:37) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.java:113) okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.java:51) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:764)
Which i am logging from my interceptor using try catch.
Open any other app and they work fine.
Kill the app and restart resolves the problem, and sometimes switching between wifi and cellular also solves it.


text:
Q: WP scrolling issue with listbox and scrollviewer Hi I am trying to get my UI have scrolling in partial page having a list. Here's my code -
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="10,0,14,10">
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBox x:Name="searchTerm" Text="potato" Width="379"   />
                    <Button x:Name="btnSearch" Content="Go" Click="btnSearch_Click"  />
                </StackPanel>
                <TextBlock x:Name="noResultsTxt" Visibility="Collapsed" Margin="10, 30, 0, 0" Text="No results found! try different search term" Style="{StaticResource PhoneTextNormalStyle}" />
                <ScrollViewer Height="520" Width="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
                    <StackPanel>
                        <ListBox x:Name="itemlist"  SelectionChanged="itemlist_SelectionChanged" Margin="0,10,0,0" >
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Margin="10" >
                                        <TextBlock Text="{Binding Title}" FontSize="35" FontWeight="Normal"/>
                                        <TextBlock Text="{Binding CommaCategories}" FontSize="20" FontWeight="Light" FontStyle="Italic"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </StackPanel>
                </ScrollViewer>
            </StackPanel>
        </Grid>

Doesnt seem to be scrolling at the List area. i seem to have figured out that the issue is with Scrollviewer not able to interact where ListBox exists. I verified that the scrolling is happening perfectly fine by setting IsHitTestVisible property of ListBox to be false.
Can someone help me out!

A: Answering my own question! Just as AMR commented it, I figured out that I don't need the scroll viewer, I just set the height of ListBox and scrolling worked fine! :)
On why external scrollviewer wont work with Listbox - https://stackoverflow.com/a/1294786/729032


text:
Q: Zermelo-Fraenkel Set Theory Question regarding Ordered Pairs Problem:
Show that $\{x,\{y\}\}$ is not suitable as a definition of the ordered pair $(x,y)$, because it does not have the ordered pair property: For any sets $x,y,u,v$ if $( x,y ) = ( u,v )$, then $x=u$ and $y=v$.
To do this problem, do I have to find two pairs of sets, say $(x,y)$ and $(z,w)$, such that ordered pair $(x,y)$ = ordered pair $(z,w)$ but $(x,y)\neq(z,w)$?
I appreciate any support that can be given to me. Thank you.

A: Let's say that $(x,y)=(z,w)$. This means that $\{x,\{y\}\}=\{z,\{w\}\}$. We have that $z=x$ or $z=\{y\}$ and that $\{w\}=x$ or $\{w\}=\{y\}$ (which implies $w=y$). We want $x\neq z$ or $y\neq w$. Let's choose $x=\{\varnothing\}$, $z=\{\{\varnothing\}\}$, $y=\{\varnothing\}$, and $w=\varnothing$.
That works even more than we needed.


text:
Q: Will GetHashCode method return different result for an object between different AppDomain? According to this Eric blog,
Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains.
Suppose you have a Customer object that has a bunch of fields like Name, Address, and so on. If you make two such objects with exactly the same data in two different processes, they do not have to return the same hash code. If you make such an object on Tuesday in one process, shut it down, and run the program again on Wednesday, the hash codes can be different.
This has bitten people in the past. The documentation for System.String.GetHashCode notes specifically that two identical strings can have different hash codes in different versions of the CLR, and in fact they do. Don't store string hashes in databases and expect them tbe the same forever, because they won't be.
I am using this class,
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ModelNumber { get; set; }
    public string Sku { get; set; }
    public string Description { get; set; }
    public double Price { get; set; }
    public double NewPrice { get; set; }

    public override int GetHashCode()
    {
        return Id ^ (Name ?? "").GetHashCode() ^ (ModelNumber ?? "").GetHashCode() ^ (Sku ?? "").GetHashCode()^ (Description ?? "").GetHashCode() ^ Price.GetHashCode() ^ NewPrice.GetHashCode();
    }
}

I am saving the hash of the product properties object in database for change tracking. Means the hash code will tell me whether the object changed or not. If a hash can be changed between app-domain then what is the other way?

A:
I am saving the hash of the product properties object in database for change tracking.

Don't do that. That's pretty much the definition of requiring the hash code to be stable over time. AppDomains are pretty irrelevant to this, to be honest.
If you need some sort of hash which is stable, you might want to convert your object to a stable binary representation (e.g. using BinaryWriter) and then take a SHA-256 hash of that - because SHA-256 (and similar cryptographic hashes) are designed to be stable.

A:
I am saving the hash of the product properties object in database for change tracking.

GetHashCode() is not suitable for that. It is not guaranteed - and actually the algorithm (and thus result) for strings has now changed twice, IIRC - and can now give different results per app-domain, as suggested.
But more: it doesn't tell you about all changes. A hash code difference tells you about non-equality, but getting the same hash-code not tell you about equality. It is not required to.
You would need to use a reliable known repeatable hashing algorithm for this; perhaps the SHA1 hash of some serialized form, where the serialization result it itself guaranteed to be reliable. Note: this still wouldn't be guaranteed to spot all changes, but it would be much much less likely to get collisions.


text:
Q: SQLite3 storing String which contains only numbers I have to run a very simple query like this in SQLite3.
INSERT OR REPLACE INTO tblPhoneList(Phone, PeopleId, StorageType) VALUES('+91912345789', '1','1');

But whatever I do, the number is stored as 91912345789. The + prefix is ignored.
The field Phone is a String. Why does it ignore the + prefix?
Is there anyway to avoid this?
P.S. This code is run inside Android
EDIT:
This is the schema of the table
CREATE TABLE tblPhoneList(Phone STRING PRIMARY KEY ON CONFLICT REPLACE, StorageT
ype INTEGER, PeopleId INTEGER, FOREIGN KEY(PeopleId) references tblPeople(id));

A: <UPDATE> from the manual:

the declared type of "STRING" has an affinity of NUMERIC, not TEXT

so please change the type of this column to TEXT, and you should be done.  </UPDATE END>
what is the type of your Phone column (try PRAGMA table_info (tblPhoneList))?. if it is TEXT (or BLOB), you shouldn't have any problems - just tried this here. if it is INTEGER or REAL, you should convert it to TEXT - you cannot expect an INTEGER or REAL column to store the + string.
for all the details, see Datatypes In SQLite Version 3.

A: It's text! SQLite only supports Integer, Text, Real and BLOB.

A: the field Phone in your DB cannot be a String, you'd better check it, TEXT or VARCHAR may work. Good Luck!

A: try this:
INSERT OR REPLACE INTO tblPhoneList(Phone, PeopleId, StorageType) VALUES('\+91912345789', '1','1');

A: Thanks for all the replies.
I changed the type String (yes, String type IS supported) to Varchar(32) and this error magically goes off. Looks like String type is poorly supported in here.


text:
Q: How can I debug OutOfMemoryException without stacktrace? When I run my .NET Core application on linux server I get OutOfMemoryException. I totally don't have any idea how can I debug that because stack trace is not provided. The only output is: "Unhandled Exception: OutOfMemoryException."
At the moment this exception is thrown there is enough space left. 200 GB of RAM is used and 300GB is free so I don't think there should be any problem with memory.
The moment when it happens is that I try to serialize an object into protobuf. The final file should be about 1GB. I have never had this issue before and models serialized pretty well.
I would be very thankful for any insight. I really need to make it work :( I already tried calling this right before serializing because I thought the problem was with fragmentation. After 10 hours of computation I realized it's not the case.
_logger.LogDebug("LOH compaction start");
GCSettings.LargeObjectHeapCompactionMode =
GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
_logger.LogDebug("LOH compaction end");

The code I am executing when the exception is thrown is this:
        public static void Serialize<T>(this ProtobufSerializer protobufSerializer, string filePath, T serializationObject)
        {
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                protobufSerializer.Serialize(fileStream, serializationObject);
            }
        }

A: You need a very systematic approach to identify and resolve OOMs.

*

*Do not assume that if you have lot of RAM free it is all for your application.

*OOMs are very notorious to disguise themselves, you might see the Stack Trace pointing somewhere else and the problem actually would be elsewhere, in the sense, some other code is leaking/consuming large memory and has put the memory usage on the verge and a legit code somewhere else trying to secure some limited memory would push it to OOM.

*Use some profiler and identify the area where the memory is increasing/leaking. (Looks like you have identified this as the code to serialize your large data.)

*Then work on those areas and try to minimize the memory usage.

A: OutOfMemory exception will be thrown only if you system bit size is not upto the level of size of object you use.
An OutOfMemoryException exception has two major causes:-
1.You are attempting to expand a StringBuilder object beyond the length defined by its StringBuilder.MaxCapacity property.
2.The common language runtime cannot allocate enough contiguous memory to successfully perform an operation


text:
Q: CREATE TABLE where multiple columns are inserted with same value Lets say I have a CREATE TABLE code like this:
CREATE TABLE Test (
  ID int NOT NULL IDENTITY(1,1),
  SortIndex int,
  Name nvarchar(50) NOT NULL
);

I was wondering if it's possible to make a table in MSSQL which had the ability to insert the ID's value into the SortIndex column when I run an INSERT.
So I would run this INSERT:
INSERT INTO Test (Name) VALUES ('Awesome Dude');

Which would normally yield the row:
ID,SortIndex,Name
1,NULL,"Awesome Dude"

But I'd like it to automatically be:
ID,SortIndex,Name
1,1,"Awesome Dude"

Is this even possible by altering the CREATE TABLE script, or do I have to use a TRIGGER?

A: I would be inclided to take a slightly different approach to this. If you want your SortIndex to default to the ID, but be overridable, I would use a nullable column, and a computed column:
CREATE TABLE Test (
  ID int NOT NULL IDENTITY(1,1),
  OverrideSortIndex int,
  Name nvarchar(50) NOT NULL,
  SortIndex AS ISNULL(OverrideSortIndex, ID)
);

If you need to change the sort index for any reason, update the column OverrideSortIndex and this takes precedence.


text:
Q: Unable to install pentaho kettle on mac I need to install just about any version that will work for some simple ETL jobs. I'm quite new to the mac world as I got one from my employer. I got pentaho 7.1 or 8.1 "installed" by unzipping the file to Applications and this seems to work at the first glimpse, but there are several follow up issues like crashing the whole application on right click in the sidebar.
I guess I need a clean installation/troubleshoot documentation for mac. I'm running the latest version of Java available for Mac which is 10.0.2 which might be the problem...
Is there any way I can test another Java Version without removing that one? I would be grateful for any documentation or help page that points me in the right direction.

A: Pentaho 7.1 and 8.1 run using Java 8, so the crashes are most definitely caused by version 10 of Java!
In regards to using another version, you can use a program called Jenv to switch between Java versions on your mac.
First install homebrew (a package manager) using the command
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then run the command
brew install jenv

Next you need to install Java 8 JDK (Oracle website)
Once installed, add it to jenv using the command
jenv add /System/Library/Java/JavaVirtualMachines/{YOUR_JAVA_VERSION}

Obviously replace {YOUR_JAVA_VERSION} with the actual directory of Java 8
Repeat for your Java 10 directory as well.
Run below command to view your added Java versions
jenv versions

You can change Java versions by running the following
jenv global oracle64-1.8.0.60

Replace oracle64-1.8.0.60 with whatever Java you want (The output of the jenv versions command)
Hope that helps!
Homebrew for Mac
Jenv

A: This question may be the same as this one. My answer (which was was not accepted as an answer, so I cannot flag your question as duplicate) was that the spoon.sh contains the following lines
echo "I'm sorry, this Mac platform [$ARCH] is not yet supported!"
echo "Please try starting using 'Data Integration 32-bit'
or" echo "'Data Integration 64-bit' as appropriate."
exit;

So my recommendation was to either follow Pentaho's recommendation to switch to java 32  bits (you can do this for DPI only), either to use Pentaho 7.1.
To switch to Java 32-bit, get the java software as in this question and copy it in a directory nearby your PDI (I am using ../myPDI/Java). Then edit the set-pentaho-env.sh so that the _PENTAHO_JAVA_HOME points to that ../myPDI/Java and and _JAVA_HOME point to ~../MyPDI/Java/bin/java.exe`.
You will need a few (not many) trials before to get it. To ease your debug, you may adding the following lines at the end of the set-pentaho-env.sh, may be of a great help:
echo "DEBUG: _PENTAHO_JAVA_HOME=$_PENTAHO_JAVA_HOME"
echo "DEBUG: _PENTAHO_JAVA=$_PENTAHO_JAVA"
$_PENTAHO_JAVA -version

as well as replacing temporarily the line "$_PENTAHO_JAVA" $OPT -jar "$STARTUP" -lib $LIBPATH "${1+$@}"with "$_PENTAHO_JAVA" -version.


text:
Q: Utilizador adicionar data para List MVC 4 Sou novo em ASP.NET MVC 4 e C# e preciso de ajuda. Criei uma classe Enrollment (disciplina)
public class Enrollment
{
    public virtual int EnrollmentId { get; set; }
    public virtual string Name { get; set; }

    public virtual ICollection<Component> Components { get; set; }
}

Como podem ver tem uma lista de componentes
public class Component
{
    public virtual int ComponentId { get; set; }
    public virtual int EnrollmentId { get; set; }

    public virtual string Name { get; set; }

    public virtual Enrollment Enrollment { get; set; }
}

Criei controllers e views usando EF. Gostaria de saber como posso fazer com que um utilizador possa seleccionar uma disciplina que já exista e adicione componentes a ela. Basicamente o que está feito é que um utilizador vai ao index das disciplinas e vê todas as disciplinas, essas disciplinas teem um link que vai para a pagina de details onde aparece os componentes, e queria que ai fosse possivel criar apenas os componentes para essa disciplina. Se souberem outra maneira de fazer também serve. Obrigado desde já.
View Index dos enrollments (disciplinas):

            @Html.DisplayNameFor(model => model.Name)

  @foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Name)

            @Html.ActionLink("Edit", "Edit", new { id=item.EnrollmentId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.EnrollmentId })

}

View Details dos Componentes:
<fieldset>

            Name

        @foreach (var item in Model.Components)
        {

                    @Html.DisplayFor(modelItem => item.Name)

        }

A: Tem algumas formas de fazer. A mais didática seria criar uma Action em ComponentsController para criar um componente da disciplina usando o Id da Disciplina. Por exemplo:
public ActionResult CreateByEnrollmentId(int id)
{
    var enrollment = context.Enrollments.FirstOrDefault(e => e.EnrollmentId == id);
    if (enrollment == null)
        return HttpNotFound();

    // Aqui sabemos que a disciplina já existe, então posso montar um
    // objeto com EnrollmentId já definido.

    var component = new Component
    {
        EnrollmentId = enrollment.EnrollmentId
    }

    return View("Create", component);
}

Com isso, a tela de Create já vem com EnrollmentId preenchido e você pode transformar a dropdown de disciplinas em um @Html.HiddenFor(model => model.EnrollmentId).
Outra forma é usando o componente BeginCollectionItem nas telas de criação e edição das disciplinas. Já há muitas respostas sobre isso aqui, então peço para que veja as respostas para ver se é isso mesmo que procura.


text:
Q: Nativescript fallback exception when referencing external dependencies Summary
Include details about your goal:
I am attempting to include external libraries in a nativescript (vue) app; specifically openpgp
Describe expected and actual results:
Initially, I expected to be able to add the external library to package.json and proceed. Upon further reading I realize there are some dependancies which are not available (fs, path, crypto, etc.). Investigating this issue, I found nodeify however, this did not resolve my issue. I've also tried node-polyfill without success.
Include any error messages:
When not using nodeify/node-polyfill, I get 4 errors similar to this:
Module not found: Error: Can't resolve 'os' in 'PATH'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
        - install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "os": false }

The four libraries referenced in the exceptions are: 'os-browserify', 'browserify-zlib', 'crypto-browserify', 'stream-browserify'
When using node-polyfill my issue remains but the errors are semi-masked and look as follows:
ERROR in Cannot read property 'fallback' of undefined
ERROR in Cannot read property 'fallback' of undefined
ERROR in Cannot read property 'fallback' of undefined
ERROR in Cannot read property 'fallback' of undefined
ERROR in Cannot read property 'fallback' of undefined

What I've tried
As mentioned, I've tried with and without nodeify and node-polyfill. When not using node-polyfill I have attempted to set fallback however I am unsure of the syntax
EDIT: proper syntax for setting fallback
const webpack = require("@nativescript/webpack");

module.exports = (env) => {
    webpack.init(env);

    // Learn how to customize:
    // https://docs.nativescript.org/webpack

    webpack.chainWebpack(config => {
        config.resolve.set('fallback', {
            "os": require.resolve("os-browserify/browser"),
            "zlib": require.resolve("browserify-zlib"),
            "crypto": require.resolve("crypto-browserify"),
            "stream": require.resolve("stream-browserify"),
            "util": require.resolve("util/"),
            "buffer": require.resolve("buffer/")
        });
    });

    return webpack.resolveConfig();
};

The above code block resolves the build errors, however the following runtime errors occur
System.err: TypeError: util.inherits is not a function
.....

webpack.config.js (with node-polyfill):
const webpack = require("@nativescript/webpack");
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = (env) => {
    webpack.init(env);

    // Learn how to customize:
    // https://docs.nativescript.org/webpack

    webpack.chainWebpack(config => {
        config.resolve.plugin('polyfills').use(NodePolyfillPlugin);
    });

    return webpack.resolveConfig();
};

Reproduce issue
ns create <project-name> --vue //effects --ts as well

npm install openpgp

Include require/import in script section
import * as openpgp from 'openpgp';

Related articles
https://stackoverflow.com/a/55478500
https://stackoverflow.com/a/71567424
https://stackoverflow.com/a/64580815
Other considerations:
I've read downgrading to webpack 4 (4.1.0) may resolve this; in updating package.json I updated the webpack.conig.js:
./node_modules/.bin/update-ns-webpack --configs

When doing so I get the following:
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/[user]/projects/android/[project]/webpack.config.js',
    '/home/[user]/projects/android/[project]/node_modules/webpack-cli/bin/utils/convert-argv.js',
    '/home/[user]/projects/android/[project]/node_modules/webpack-cli/bin/cli.js',
    '/home/[user]/projects/android/[project]/node_modules/webpack/bin/webpack.js'
  ]


text:
Q: Limit checkbox based on condition Hi need help from expert as I'm totally newcomers.
I'm trying to limit checkbox based on condition.
As for example, if bank code from user selection is MBS they able to select only 3 checkbox, while if bank code is MBV they able to select only five.
Below are the codes that i'm trying to work with.

    <form id = "status"
          name = "status" >
        <input type = "checkbox"
               name = "check" /> london

        <input type = "checkbox"
               name = "check"/> japan

        <input type = "checkbox"
               name = "check"/> usa

        <input type = "checkbox"
               name = "check"/> korea

        <input type = "checkbox"
               name = "check"/> egypt

    </form>

A: This is how I'd go about it using jQuery assuming there are only two types of bankcodes (MBV and MBS)

<form id="status" name="status">
    <input type="checkbox" name="check"/>london

    <input type="checkbox" name="check"/>japan

    <input type="checkbox" name="check"/>usa

    <input type="checkbox" name="check"/>korea

    <input type="checkbox" name="check"/>egypt

</form>

PS : I have no idea what this (document.frmSearch) does as the code snippet is unclear regarding its function, but I choose to keep it since you provided it in the original code.

A: You can use a variable to keep track of how many elements are checked. This variable can be updated using the onchangeevent on the checkbox.
Here a JSFiddle with a complete working example.
Bonus
You can disable the unchecked boxes when the limit is reached, so that the user cannot check more boxes than allowed.
See this JSFiddle example.


text:
Q: Assign date/time from JSON in Angular I noticed, when receive data from my Server/API (in this case asp.net core 3.1) Angular assigns a string to the date target field instead of actually "converting" it into a Date.
As far as I can tell for now, it's not a problem with asp.net core or the "server side".
I did the following Test and either I understand something completly wrong here or the JSON parser is broken...(i hope not)?
//The target interface for testing
export interface DateTesting
{
  aText: string;
  aDate: Date;
}

//For testing
let input: DateTesting = { aText: "Hello World!", aDate: new Date() };
console.log(JSON.stringify(input));   //-> outputs the "input" object as JSON

let json = JSON.stringify(input);     //-> {"aText":"Hello World!","aDate":"2022-07-12T12:01:46.498Z"}
let output: DateTesting = JSON.parse(json);

console.log(output);                  //-> outputs the object "output"
console.log(typeof output.aDate);     //-> is a string! Looks like the parser is broken??
console.log(output.aDate.getDay());   //-> Results in an Error: "Uncaught (in promise): Invalid time"

So, what am I missing here? Can i tell the parser anyhow to assign a date and not a string when the target type is a Date?
I also don't think that the correct solution is to do "Date.parse(whatsoever)" for each date field, also because I want to keep the whole thing as "generic" as possible.
I'm using Angular 12.1.2

A:
Can i tell the json parser anyhow to assign a date and not a string when
the target type is a Date?

Yes, you can if you use the JSON.parse method with the optional reviver argument. From the documentation if a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. So in your specific case you can specify your aDate property and return your date string as a new Date object instead of a string like below:
let output: DateTesting = JSON.parse(json, (key, value) => {
    //instead of a string it returns a Date object
    if (key === 'aDate') return new Date(value);
    return value;     // return the unchanged property value for other keys.
});
console.log(typeof output.aDate);     //-> is a Date object
console.log(output.aDate.getDay()); //ok it works and returns a number

A: For a generic approach that covers any Date property in your interfaces you can use this Decorator
    import {map} from "rxjs/operators";

    let dateRegex = new RegExp(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/); // yyyy-MM-ddTHH:mm:ss

    /**
     * Automatically transforms all dates in json in defined regex format to Date entity
     */
    export function TransformDate(target, key: string, descriptor: any) {
      const originalMethod = descriptor.value;
      descriptor.value = function (...args: any[]) {
        return originalMethod.apply(this, args).pipe(
          map((obj) => convertDatesInObject(obj))
        );
      }
      return descriptor;
    }

    const isDate = (s) => dateRegex.test(s);

    function convertDatesInObject(obj): any {
      if (obj === null || obj === undefined) {
        return obj;
      }
      if (isDate(obj)) {
        return new Date(obj) as any;
      }
      if (obj instanceof Array) {
        return obj.map((n: any) => convertDatesInObject(n)) as any;
      }
      if (typeof obj === 'object' && obj !== {}) {
        Object.keys(obj).forEach(k => {
          obj[k] = convertDatesInObject(obj[k]);
        });
        return obj;
      }
      return obj;
    }

And then you can just put this decorator to any function calling your API and all string that match the defined regexp will be then parsed to Date object automatically.
@TransformDate
getData$(): Observable<Data[]> {
    return this.httpService.getRequest<Data[]>('yourURL');
}

A: Another solution would be to write an interceptor, which will automatically convert all date strings into Date objects.
@Injectable({
    providedIn: 'root'
})
export class DateInterceptor implements HttpInterceptor {
    public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    this.postProcessDates(event.body);
                    return event;
                }
            })
        );
    }

    /**
     * PostProcessing Dates
     * Converting UTC to Local Date
     * Date must be in ISO 8601 format
     */
    private postProcessDates(obj: any): any {
        if (obj === null || obj === undefined) {
            return obj;
        }

        if (typeof obj !== 'object') {
            return obj;
        }

        for (const key of Object.keys(obj)) {
            const value = obj[key];
            const iso8601 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/;

            if (iso8601.test(value) === true) {
                obj[key] = new Date(value);
            } else if (typeof value === 'object') {
                this.postProcessDates(value);
            }
        }
    }
}


text:
Q: CSV file cannot be accessed via BufferedReader in Android I am trying to read a CSV file using BufferedReader in android. My program works perfectly fine in Java but when I try read those data from Android following error I get.
01-31 17:09:58.466: W/System.err(15912): java.io.FileNotFoundException:
/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv: open failed: ENOENT (No
such file or directory)

Following code I am using here.
public double getLongitudes() {
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ";";
    String[] nextLine;
    double longitudes = 0;

    try {

        br = new BufferedReader(
                new FileReader(

"/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv"));
        while ((line = br.readLine()) != null) {
            // use comma as separator

            String[] country = line.split(cvsSplitBy);
            longitudes = Double.parseDouble(country[5]);
            Log.d("worked", "worked");

            // System.out.println("Latitude " + longitudes);

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Done");

    return (longitudes);
}}

Any idea why its happening ??

A: The path /Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv is invalid. This looks like the path to a file on your computer rather than your Android device.  You need to push the file to your device or your emulated device and access it from there.  Even the Android emulator will not read files directly from your computer's filesystem.

A: The .csv file needs to be in your project resources. You can copy the file into assets folder and read it this way
AssetInputStream asset_stream = (AssetInputStream)getAssets().open("input.csv");
InputStreamReader reader = new InputStreamReader(asset_stream);
BufferedReader br = new BufferedReader(reader);

This is one method that has worked for me before.
Another method would be to put the file into res/raw folder and access it
InputStream file = getResources().openRawResource(R.raw.inputfile);

You can also refer to https://stackoverflow.com/a/3851429/3092829
Hope this helps!

A: Proper way to store your CSV in Android is:
("/sdcard/Android/data/filename.csv");

A: So i have solved my problem.
public class ReadCSV {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
String[] country;

AssetInputStream asset_stream = null;

public String[] getLatitude() {

    try {
        asset_stream = (AssetInputStream) MainActivity.getContext()
                .getAssets().open("Input.csv");
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStreamReader reader = new InputStreamReader(asset_stream);

    Log.d("logg", "log" + reader);
    br = new BufferedReader(reader);
    Log.d("logg", "log" + br);

    try {
        while ((line = br.readLine()) != null) {
            country = line.split(cvsSplitBy);

        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return country;

}

As you can see I am trying to get my latitude by returning it through country. But when I trying get it from another fragment class through this,
String[] lat;
lat = csv.getLatitude();
Log.d("", "" + lat);

Why I don't get latitude  back ?


text:
Q: Assembly Language Bomb Lab I have tried looking for similar bombs with similar assembly and I cant seem to find one. I am having trouble with this phase specifically what is going on at line <70>. Here is my assembly and below are my findings:
   0x00000000004011f1 <+0>: sub    $0x18,%rsp
   0x00000000004011f5 <+4>: lea    0xc(%rsp),%rcx
   0x00000000004011fa <+9>: lea    0x8(%rsp),%rdx
   0x00000000004011ff <+14>:    mov    $0x402af1,%esi
   0x0000000000401204 <+19>:    mov    $0x0,%eax
   0x0000000000401209 <+24>:    callq  0x400cb0 <__isoc99_sscanf@plt>
   0x000000000040120e <+29>:    cmp    $0x1,%eax
   0x0000000000401211 <+32>:    jg     0x401218 <phase_5+39>
   0x0000000000401213 <+34>:    callq  0x401785 <explode_bomb>
   0x0000000000401218 <+39>:    mov    0x8(%rsp),%eax
   0x000000000040121c <+43>:    and    $0xf,%eax
   0x000000000040121f <+46>:    mov    %eax,0x8(%rsp)
   0x0000000000401223 <+50>:    cmp    $0xf,%eax
   0x0000000000401226 <+53>:    je     0x401254 <phase_5+99>
   0x0000000000401228 <+55>:    mov    $0x0,%ecx
   0x000000000040122d <+60>:    mov    $0x0,%edx
   0x0000000000401232 <+65>:    add    $0x1,%edx
   0x0000000000401235 <+68>:    cltq
   0x0000000000401237 <+70>:    mov    0x402820(,%rax,4),%eax
   0x000000000040123e <+77>:    add    %eax,%ecx
   0x0000000000401240 <+79>:    cmp    $0xf,%eax
   0x0000000000401243 <+82>:    jne    0x401232 <phase_5+65>
   0x0000000000401245 <+84>:    mov    %eax,0x8(%rsp)
   0x0000000000401249 <+88>:    cmp    $0xf,%edx
   0x000000000040124c <+91>:    jne    0x401254 <phase_5+99>
   0x000000000040124e <+93>:    cmp    0xc(%rsp),%ecx
   0x0000000000401252 <+97>:    je     0x401259 <phase_5+104>
   0x0000000000401254 <+99>:    callq  0x401785 <explode_bomb>
   0x0000000000401259 <+104>:   add    $0x18,%rsp
   0x000000000040125d <+108>:   retq enter code here

I know that the function taking two integers. The first one entered is at rdx and the second one is at rcx. It then puts the first integer into eax <39> after it makes sure two numbers were inputted.
<43> It then takes the least significant bit of eax with a bitwise and and stores it in eax
<46> the new value of eax is then stored in the original location of the first integer.
<50> eax is compared with 15 and if its less than 15 the program continue
<55,60> ecx and edx are now 0
<65> we start a loop edx is the index and 1 is added to it before starting the loop.
<70> I am not sure what exactly is happening here mov    0x402820(,%rax,4),%eax but i know that it is changing the value of eax
<77> adds the summ of eax and ecx (im not sure how ecx ever gets a value as it was already set at 0 <55> and there is no change up until this instruction
<79>checks if eax = 15 if it doesnt the loop reruns
<88>when eax is 15 it then checks if the loop counter edx has been run 15 times
<93> compares the second int entered to ecx which i beleive eax would equal to eax from line <77>
any help or guidance is greatly appreciated.


text:
Q: how to move element in dom and on screen with javascript or jquery Lets say I have a "p" tag like this:

This is a text example.

If I later insert other elements into that div is it possible to move the paragraph tag somewhere else in the dom, and it be visible to the user where I want it. So the result should be like this:

Another block of text.

This is a text example.

Yet another block of text.

So not only do I want to move it around...perhaps even into another div or different area of the page, but I also would like the ability to make sure that the user sees the text exactly as I want them too...maybe moved to the bottom or something.

A: You can't exactly "move" elements in jQuery (as far as I know), per se, but you can remove them and insert them somewhere else.
$("#eg").remove().insertAfter("#eg1");

EDIT: This is not true. You can move DOM elements wherever you like.

A: If you wish to move an element from one position to another you can simply do the following:
$("#eg1").after($("#eg"));

Example on jsfiddle.

A: Any change you make to the DOM will be reflected on the screen. You don't have to handle that separately.


text:
Q: Laptop not charging while plugged Hi on my Asus laptop F751L and Windows 10 home edition. I have problem having charger plugged in and still it is disscharging. After battery run out I can try to plug out and plug in charger again and I am able to turn on laptop after a while.

A: No that is very unlikely, personally I'd say it's the charger, but if you have warranty just claim your warranty
@DavidPostill What is the reason to delete a comment that actually tries to narrow down the problem and help people? Do we really need a +50 rep to be able to provide the obvious and useless comments?
Using the warranty is something I assume OP could've come up with him- or herself


text:
Q: SQL Query-calculating last week data for an ordinary calendar year I have to retrieve the last week data from a table.
i am using the following condition.
@prmCurrent_Year=Datepart(year,getdate())

 last_week=case when Datepart(week,col_name)=1
                then 52
                else Datepart(week,col_name)-1 and
                     year_num=case
                              when Datepart(week,col_name)=1
                              then @prmCurrent_Year-1
                              else @prmCurrent_ Year

will this work properly or is there any other better query for this???

A: Something like this might suffice:
SELECT *
FROM Table
WHERE MyDate BETWEEN DATEADD(wk, -1, GetDate()) AND GetDate()

DateAdd reference on MSDN: http://msdn.microsoft.com/en-us/library/ms186819.aspx