text:
Q: Angular Favourite Row with checkboxes in star form for adding projects to a different table I have an Angular4 project and a table with projects.
Projects will have different columns like ID, Name, Costs, ...
now I want to add a Row with checkboxes in Star Form for adding projects in a favourite List. How can I do it in Angular4 (not Angular Material or AngularJS) like this?
Both tables should be shown in the same component "projects"
The  [x] will be a star and its filled yellow if star-icon will be clicked.
Then the project will be putted in the favourite list.
Project Table:
|Favourite|ID|Name|Costs|...|
| [X]     |1 |A   |500  |...|
| [ ]     |2 |B   |600  |...|
| [X]     |3 |C   |750  |...|
| [ ]     |4 |D   |200  |...|

Favourite Table:
|ID|Name|Costs|...|
|1 |A   |500  |...|
|3 |C   |750  |...|

==UPDATE==

HTML-table row with checkboxes:

       <input type="checkbox" [value]="project" (click)="favourite($event)"/>

HTML-Favourite Table

                {{f.id}}

                {{f.title}}

TS:
...
    private projects: Project[] = [];
    private favouriteProjects: Project[] = [];
...
favourite(ev){
        this.favouriteProjects.push(ev.target.defaultValue);
    }

A: You need to make an API call, for each of the item that you are adding in the favorite array or once send the all array. I have create the code boilerplate, you can refer this and implement solution. Here is stackblitz link.
app.component.ts
import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  projects = [];
  favProjects = [];
  constructor(){
    // get this data from API
    // After getting the data from API make fav property false if it is not in the API response

    // Ideally if you are mainting it on backend level it should be the in the object.
    this.projects = [
      {name: 'Abhinav', age: 15, fav:false, id:1}, // id for unique identifier
      {name: 'Ravi', age: 23, fav:false, id:2},
      {name: 'Kalam', age: 35, fav:false, id:3},
      {name: 'Sunny', age: 25, fav:false, id:4},
    ];

    // check if from API is any favriout project is there add it to the favriout table
    this.initFavProject();
  }
  // load the fav project if user saved it earlier in the db
  initFavProject(){
    for(let i = 0 ; i < this.projects.length; i++){
      if(this.projects[i].fav){
        this.favProjects.push(Object.assign({},this.projects[i]));
      }
    }
  }

  addItemToFav(e){
    this.projects = this.projects.filter((item)=> item.id !== e.id);
    e.fav = true;
    // make an API all and send the upadte for row 'e', so next time user
    // reload the webpage, its fav property will be true and it will automatically go to the favriout table.

    // Either save each time one object or all the favProjects array at once based on the click
    this.favProjects.push(Object.assign({},e));
  }

  saveFavTODB(){
    // access the this.favProjects and send it to the database to save a new one or update the exhisting one.
  }
}

app.component.html

Project Table

<app-table [tableData]="projects" [allowFavrout]="true" (favEvent)="addItemToFav($event)"></app-table>

Favrout Project

<app-table [tableData]="favProjects"></app-table>

table.component.html

 0">

      Name
      Age
      Action

      {{item.name}}
      {{item.age}}
      <button (click)="addToFav(item)">Add To Favriout</button>

table.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  @Input() tableData : Array<any> = [];
  @Input() allowFavrout = false;
  @Output() favEvent: EventEmitter<any> = new EventEmitter(false);
  constructor() { }

  ngOnInit() {
  }
  addToFav(item){
    this.favEvent.emit(item)
  }
}


text:
Q: Friendlist Program Java I'm trying to create a friendlist program in Java.
However, I have to concurrently add a user (object) to two array list.
Is there any way to do so?
My current code is as such but it doesn't seem correct.
/* Add this particular person (person in the parameter list) to your friendList
     * Add yourself to this particular person's friendList as well
     *
     * If either you or person-to-be-added's friendList is full (already have 5 friends),
     *          - print "Friends limit reached."
     *          - Both parties will not add each other.
     * NOTE: Your total number of friends cannot exceed 5 (friendsLimit)
     */

public void befriend(Person p){
    //Implement your code here..

            for(Person i : friendList) {
                if(!i.equals(p) && friendList.size() < 5) {
                    friendList.add(p);
                }
                else
                   if(!i.equals(p) && friendList.size() >= 5) {
                       System.out.println("Friends limit reached.");
                   }
                   else {
                       System.out.println("Friend already exist in list");
                   }
            }

}

A: I'm just curious, is it intentional that you check if the person to add is already present in the friendlist, because it is not mentioned in the method's comment.
Under the assumption that you have access to the other person's friendlist in, in some way, and the befriend method is a method of a Person:

*

*You do not have to iterate over all Persons in your friendlist to assure that neither yours or the other person's friendlist is at full capacity. Just check the bounds and if there is not enough room print the message and call return; inside the if clause.

*If the method befriend() is of Person.befriend() then you just need to add friendList.add(p) and p.getFriendList().add(this)

*If you need do make sure you do not add someone twice, then you can check this in a for loop. But because your Person class have an equals() method, and maybe a hashCode(), you could use the Java Collection method friendList.contains(p)(in case friendList is of type ArrayList for example). The collection.contains() method "[...] returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).", see List.html#contains(java.lang.Object)
I hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring Data JDBC invert OneToMany navigation I have an existing data scheme I'm reluctant to change. There are two entities/tables: parent and child, with child having the foreign key column parent_id. It's a 1(parent)-to-n(children) relationship.
Is it possible within Spring Data JDBC to have Child class reference Parent and not Parent have a Set<Child> property? Maybe both? (I know it is possible with hibernate, but I'd like to stay with JDBC).
I.e. I want something like this:
@Data
public class Parent {
    @Id
    private Long id;
}

@Data
public class Child {
    @Id
    private Long id;

    private Parent parent;
}

Somewhat related question: Spring Data JDBC invert OneToOne navigation

A: Spring Data JDBC doesn't offer direct support for a reference from Child to Parent. If you are modelling Parent and Child as one aggregate, i.e. with a direct reference, Parent must be the aggregate root. So any child gets only accessed the via the Parent at all times. Therefore a back reference should be superfluous.
Actually, the desire to have a back reference might be an indication that the two don't really form a single aggregate but separate aggregates and should be modelled as such. See https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
But if you really want your back reference you can easily establish that in an AfterLoadCallback.
For this mark the back reference with the @Transient annotation so it doesn't get actually stored in the database.
Then in the AfterLoadCallback which will get triggered once for each Parent navigate from the Parent to each Child and set the back reference.


text:
Q: how to use a struct defined in a certain header file from another header in C? I have two headers files, stack.h
#ifndef __STACK_H__
#define __STACK_H__

typedef struct StackElement_
{
  int value;
  struct StackElement_ *next;
} StackElement, *Stack;

/*----------------------Prototypes----------------------*/

Stack new_stack();

void push_to_stack(Stack *, int);
int pop_stack(Stack *);
int peek_stack(Stack);

int stack_length(Stack);
void print_stack(Stack);
Bool is_empty_stack(Stack);

void clear_stack(Stack);

/*------------------------------------------------------*/

#endif

and utils.h
#ifndef __UTILS_H__
#define __UTILS_H__

#define INT_MIN -2147483648

/*------------------------Typedef-----------------------*/

typedef enum Boolean_ {
  FALSE,
  TRUE
} Bool;

/*------------------------------------------------------*/

#endif

In stack.h, I need to know Bool but when I include utils.h in stack.c, the structure is still not known in stack.h. How to do this without having to define it directly in stack.h?

A: You need to include utils.h in stack .h (not stack.c).  The #include statements are part of the C macro language, which is a simple pre-processor.  It literally takes the file given as the filename (#include filename) and inserts it into your program (during the pre-processor stage of the compile).

A: A source file or include file should include all files necessary.
So if stack.h is dependent on declarations in util.h, then you should #include "util.h" in stack.h.  That way, any module that includes stack.h doesn't need to worry about also including util.h and putting it in the right order.
If a module decides to include both that should be fine as well.  The include guards you've added should address that.
You didn't show the source of stack.c, but you most likely included stack.h before util.h.  That would explain your issue since the definitions needed by stack.h appear after them instead of before.


text:
Q: how to remove empty space in this nav bar at the start hi I was just wondering how to get rid of the space in my nav bar, help would be much appreciated.
here is the jsfiddle example: http://jsfiddle.net/Kmum7/
here is what I mean in an image: http://imgur.com/Gmrok9T
here is the code:

            .

    .

Home

hyperlink 2               .
▼

hyperlink 2.1

hyperlink 2.2

hyperlink 2.3

hyperlink 3

hyperlink 4                   .    ▼

hyperlink 4.1

hyperlink 4.2

hyperlink 4.3
▶

hyperlink 4.3.1

hyperlink 4.3.2

hyperlink 4.3.3

hyperlink 5

Thanks alot for the help!! :)

A: Change the css so that your navmanu li is display:block and float it left, whilst adding a new css class for navmenu li li which is inline-block...
Here is the code chaged:
 ul#navmenu li {
        width: 203px;
        text-align: center;
        position: relative;
        margin-right: -2px;
        display:block;
    float:left;
    }
ul#nav menu li li { display:inline-block;}

and updated fiddle: http://jsfiddle.net/Kmum7/2/

A: I'm a bit concerned with the previous answer simply because it uses a -Xpx margin and if the font changes, then this will not be enough. I would recommend setting the li's to float left and positioning their parent ul by using inline block with text-align, or simply making the ul block and positioning with margins. Chris Coyier gives a fairly extensive list of the ways you can fight this.
http://css-tricks.com/fighting-the-space-between-inline-block-elements/


text:
Q: How to reduce git repo size on Bitbucket? Summary of my problem: One of my private repositories on Bitbucket suddenly more than doubled in size after I pushed an addition of a few hundred bytes to two existing files. The repo is now over 2GB, which has caused Bitbucket to put it into read-only mode. Because it is in read-only mode, I cannot push changes that would reduce the repo size. (Catch 22.)
Details: My company recently began hosting git repositories on Bitbucket. One of the repositories I am in charge of had a size of about 973MB, which was uncomfortably close to the 1GB soft limit. To reduce the repo size, I followed the instructions in the Bitbucket documentation article Split a repository in two and moved about 450MB worth of documentation and online help files into their own private repo. I then followed the instructions in the Bitbucket documentation articles Reduce repository size and Maintaining a git repository, specifically:
git count-objects -vH showed me a size-pack of about 973MB.
I ran git filter-branch --index-filter 'git rm --cached --ignore-unmatch doc' HEAD to remove the doc directory (which is the content I'd moved to the new repo).
I ran the following commands to expire reference and prune:
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git reflog expire --expire=now --all
git gc --prune=now

git count-objects -vH then showed me a size-pack of 881.1 MiB and du -sh .git/objects returned 882M. I was disappointed that moving over 450MB reduce the repo size by less than 90MB, but pushed the changes to Bitbucket nevertheless:
git push --all --force
git push --tags --force

The settings page for the Bitbucket copy of the repo continued to show a size of 973MB. I logged out, refreshed the browser, logged back in, but that didn't help -- the repo size remained at 973MB.
This morning (three days after the changes described above) I made a couple of minor additions to two existing files which increased the files' sizes by a total of less than 1KB, added and commited them to my local repo, then pushed the change to Bitbucket. A few minutes later I took a look at the Bitbucket page for the repo and saw a red warning banner informing me "This repo is over the 2 GB limit and is in read-only mode." The settings page now says the repo has a size of 2.3 GB.
The push of a few hundred bytes added to two files was definitely the only activity to occur on the remote repo in the last three days, according to Bitbucket. That push may not have been the cause of the repo more than doubling in size, but the two events were closely correlated in time.
git reflog show returns nothing.
Cloning a new copy into an alternate directory, then running git count-objects give me a size-pack of 881.29 MiB.
The local repository is on a CentOS 6.5 system. git version is 1.8.5.3.
Questions

*

*Why did moving 450MB of files out of the repo only reduce the size of my local repo by 90MB?

*Why did even that modest reduction not get pushed to the remote repo on Bitbucket?

*How on Earth did the remote repo size jump from 973MB to 2.3GB?

*How do I fix it? I cannot push to the remote repo even with the --force flag. Any push gets me the error message "conq: repository is in read only mode (over 2 GB size limit).
fatal: Could not read from remote repository."

A: I've found that the easiest way to reduce the Bitbucket repo size if you are over the 2GB limit is to

*

*Create a branch on Bitbucket

*Delete that branch on Bitbucket

This should trigger Bitbucket to run git gc on the repo.

A: After conferring with Bitbucket technical support, I can now answer some of my own questions:

*

*Why did moving 450MB of files out of the repo only reduce the size
of my local repo by 90MB? Something in the history got missed. I
don't what exactly, but the filter-branch command missed something.
I was able to successfully reduce the repo size by 450MB by running
the utility BFG Repo-Cleaner.

*Why did even that modest reduction not get pushed to the remote repo
on Bitbucket? It did, but Bitbucket support must then run git gc on
their side. One can contact Bitbucket request and ask them to run
git gc on a repo.

*How on Earth did the remote repo size jump from 973MB to 2.3GB?
Unknown. Bitbucket technical support didn't have the answer to this
one either.

*How do I fix it? Contact Bitbucket support. They can put a
repository back into read-write mode so that you can push a smaller
repository and they can run git gc on their end.

A: How on Earth did the remote repo size jump from 973MB to 2.3GB?
This is a known bug on bitbucket cloud side, see BCLOUD-19794.

Garbage file is intermittently counted in the repository size.
When pushing to the remote repository a GC is triggered afterwards
  which generates a garbage file. This garbage file is cleared on the
  next subsequent GC. Between those two GC's the size of the repository
  is displayed incorrectly within Bitbucket UI as the garbage file size
  is intermittently counted towards the repository total size.

As noted in the workaround section, you need to contact bitbucket to manually run the GC.
Bitbucket might take action sooner rather than later if enough people go vote for it.

A: First of all check the repository size in your local using the following command :-
git count-objects -Hv

We can use following commands
git reflog expire --expire="1 hour" --all
git reflog expire --expire-unreachable="1 hour" --all
git prune --expire="1 hour" -v
git gc --aggressive --prune="1 hour"

Now , again use the command git count-objects -Hv to notice the change in the size and garbage of repository

A: As I am sure those familar with got already know, but git stores your version history for files, so making changes and pushing files will not reduce your repo size.
There are still several ways to reduce repo sizes on bitbucket, GitHub, gitlab, etc.  The best way is to delete branches, as that permanently deletes any files being recorded by that branch, as long as it is not being tracked by another.  But you may want the latest files in that branch, so do the following:

*

*On local machine, create a duplicate repo.  (Backup, so you don't lose info)

*Delete a branch that you want to move, or create a fresh version of.  You can use --cached to delete remote branch.

*If you want to refresh branch, you can copy files into new branch and push.

*If you want to create new remote repo, you can do that too.

Depending on host, you may have to run special commands, but this should work in most cases.


text:
Q: NewRelic not listing all processes on server monitoring I have set up a server monitoring on New Relic and on the processes list, only nrsysmond (the deamon reporting data to NewRelic) is listed and no other processes (like apache, postgresql, etc.). After many search, I only found a turnaround for Cloud Linux but I'm on a dedicated server, running Debian 7, so it does not work.
I tried to raise newrelic user privilege by assigning it to adm group (event root with some hope) but it does not change anything.
I also tried to add hidepid=0,gid=adm flags on the proc line on /etc/fstab but the result is also the same.
Do you have any idea on how to fix this ?

A: You can add newrelic user to "procread" group:
usermod -a -G procread newrelic

A: After posting on the New Relic forum, it appears that it was due to grsecurity.
Indeed, this security patch for Linux kernel was present on my server and one of its feature is hiding processes that do not belong to the user checking it. As the new relic daemon is monitoring processes as a UNIX user (newrelic in this situation), it is concerned by this restriction and so he can only see it own processes.
To check if grsecurity is applied to your kernel, type uname -a a have a look a the result. For me it contains 3.14.32-xxxx-grs-ipv6-64 (which is my Linux kernel), and grs in it stands for grsecurity.
I tried to find a way to edit its configuration to disable only this feature, but it seems that I should have to recompile my kernel (not really sure about this, feel free to leave a comment if you have more information !).
So I replaced my kernel with the same version, but without grsecurity patch applied to it, and now it works like a charm.


text:
Q: Convert unsigned char array of characters to int C++ How can I convert an unsigned char array that contains letters into an integer. I have tried this so for but it only converts up to four bytes. I also need a way to convert the integer back into the unsigned char array .
int buffToInteger(char * buffer)
{
    int a = static_cast<int>(static_cast<unsigned char>(buffer[0]) << 24 |
        static_cast<unsigned char>(buffer[1]) << 16 |
        static_cast<unsigned char>(buffer[2]) << 8 |
        static_cast<unsigned char>(buffer[3]));
    return a;
}

A: It looks like you're trying to use a for loop, i.e. repeating a task over and over again, for an in-determinant amount of steps.
unsigned int buffToInteger(char * buffer, unsigned int size)
{
    // assert(size <= sizeof(int));
    unsigned int ret = 0;
    int shift = 0;
    for( int i = size - 1; i >= 0, i-- ) {
        ret |= static_cast<unsigned int>(buffer[i]) << shift;
        shift += 8;
    }
    return ret;
}

A: What I think you are going for is called a hash -- converting an object to a unique integer.  The problem is a hash IS NOT REVERSIBLE.  This hash will produce different results for hash("WXYZABCD", 8) and hash("ABCD", 4).  The answer by @Nicholas Pipitone DOES NOT produce different outputs for these different inputs.
Once you compute this hash, there is no way to get the original string back.  If you want to keep knowledge of the original string, you MUST keep the original string as a variable.
int hash(char* buffer, size_t size) {
    int res = 0;
    for (size_t i = 0; i < size; ++i) {
        res += buffer[i];
        res *= 31;
    }
    return res;
}

A: Here's how to convert the first sizeof(int) bytes of the char array to an int:
int val = *(unsigned int *)buffer;

and to convert in back:
*(unsigned int *)buffer = val;

Note that your buffer must be at least the length of your int type size. You should check for this.


text:
Q: Iterate over different formControls of formGroup object in Angular I have an Angular (4) application that generates a formGroup object in my application component. I want to dynamically add all these components in my template, it expected the following to work.
<form [formGroup]="updateValuesForm">
    <ng-container *ngFor="let control of updateValuesForm.controls">
      <input formControlName='control.name' type="text"/>
    </ng-container>
</form>

But that generates the following error:

Cannot find a differ supporting object '[object Object]' of type
  'object'. NgFor only supports binding to Iterables such as Arrays.

Is it even possible to achieve this in Angular?


text:
Q: prevent iPAD scrolling while allowing list scrolling I need to disable the default iPAD scrolling (via capturing touchmove on the body) but still allow a list on my page to scroll.
I tried:
$('body').on('touchmove', function(e) { e.preventDefault(); });
$('itemList').on('touchmove', function(e) { alert('hi'); e.stopPropagation(); });

But it seems that itemList's touchmove is not being called at all. on the iPAD nothing gets scrolled.
see http://jsfiddle.net/e8dcJ
Any ideas how to solve this ?
Thanks!

A: maybe don't apply the event to the body, which covers everything.  Instead, apply the event to a the various elements you want to prevent scrolling.  Alternately, wrap everything in a DIV except the list and then set the position to fixed and add the event.


text:
Q: How to perform authorization to container engine REST API to get clusters data? I want access container engine REST API's given here -
http://kubernetes.io/third_party/swagger-ui/#/
To access above given API's, I did following-
1) I have created container cluster with project Id - virtual-cycling-11111 with zone- us-central1 and  API name - serverconfig
2) I created OAuth2.0 client Id and secret key.
I am using following method to generate access token:
curl -H "Content-Type: application/json" -d' {
    "client_id": "757054420263-09g36ip2jdt6kcl6cvlfl17faaaaaaa.apps.googleusercontent.com",
    "client_secret": "NyZ0YwvEQAMaeNTD4dfgtht",
    "refresh_token": "1/6BMfW9j53gdGIasdfUH5kU5RsR4zwI9lUVX-tqf8JXQ",
    "grant_type": "refresh_token"
} ' https://www.googleapis.com/oauth2/v4/token

How do generate access token and use it to access REST API?
Also can I use this in browser to get output?

A: Google has developer documentation for using OAuth 2.0 to Access Google  APIs (and the Google Container Engine is one such API). It explains the various authentication flows and how to get access tokens.


text:
Q: How to avoid double quoted string , site URL and email address from tokenization How we I stop word_tokenize from splittings strings like "pass_word", "https://www.gmail.com" and "tempemail@mail.com"? The quotes should prevent it, but they don't.
I have tried with different regex options.
from nltk import word_tokenize

s = 'open "https://www.gmail.com" url. Enter "tempemail@mail.com" in email. Enter "pass_word" in password.'
for phrase in re.findall('"([^"]*)"', s):
    s = s.replace('"{}"'.format(phrase), phrase.replace(' ', '*'))
tokens = word_tokenize(s)
print(tokens)

Actual response:
['open', 'https', ':', '//www.gmail.com', 'url', '.', 'Enter',
 'tempemail', '@', 'mail.com', 'in', 'email', '.', 'Enter',
 'pass_word', 'in', 'password', '.']

Expected response:
['open', 'https://www.gmail.com', 'url', '.', 'Enter',
 'tempemail@mail.com', 'in', 'email', '.', 'Enter',
 'pass_word', 'in', 'password', '.']

A: You can try this:
First, tokenize the text into sentences. If a sentence contains a special character, tokenize it with the str.split() function, otherwise use word_tokenize.
tokens=[]
for sent in sent_tokenize(s):
if re.match(r'^\w+$', s):
    for token in word_tokenize(sent):
        tokens.append(token)
else:
    for token in sent.split():
        tokens.append(token)
print(tokens)

Outputs:
['open', '"https://www.gmail.com"', 'url.', 'Enter', '"tempemail@mail.com"', 'in', 'email.', 'Enter', '"pass_word"', 'in', 'password.']

EDIT
You can tokenize periods by further splitting the string using period.


text:
Q: What is the difference between using LASTDATE and MAX to get the last date? What is the difference between using LASTDATE and MAX to get the last date value.
For example:
LASTDATE ( DateTable[Date]) )
vs
MAX ( DateTable[Date]) )

A: Type of the return value. LASTDATE returns a table with one row and one column.
Therefore, use cases are different. You use max if you want to display max date or use it as a comparison criterion, whereas lastdate can be used in filter part of CALCULATE, as you pointed out in the comment.


text:
Q: AWS: Using id token and access token generated by cognito in lambda functions I am looking for solution on how to make use of id token and access token generated by AWS Cognito after login. I followed the tutorial:link to implement amazon cognito with serverless. I am able to generate id_token & access_token. I am not sure how to make use of these tokens in lambda functions while executing. Should I add headers with certain details to make my lambda function work.
Everytime I get below error while executing API
{
    "message": "Unauthorized"
}

A: Please add Authorization id_token to header and perform API call. Make sure you have configured cognito authorizer at API gateway.
Please feel free to share your output then


text:
Q: reference error on javascript function using ajax i´m using ajax to use a keyword search on a mysql database, and when results are coming i want to show options as href with an onclick function, the search works fine, but when i click on any option i get a reference error on my firebug, this is the code:
index.php

        <form name="myForm">
            <input type="text" onkeyup="ajaxFunction(this.value);" name="username"
            />

        </form>

And this is the search.php
<?php
include ("dbinfo.php");
$in = $_GET['txt'];
$msg = "";
if (strlen($in) > 0 and strlen($in) < 20) {
    $t = mysql_query("select RubroId, RubroDisp from rubros where KeyWords like '$in%'");
    while ($nt = mysql_fetch_array($t)) {
        $valor = $nt[RubroDisp];
        $valorCodificado = str_replace(" ", "_", $valor);
        echo "$valor
";

                                        }
                                          }
?>

You can see the working page at this url
Can you please tell me how to solve it? or what i am doing wrong?
thanks

A: aca($valorCodificado); will generate JavaScript that calls a function with a variable (that probably doesn't exist) for the argument. It looks like you want a string there. Strings require quotes.


text:
Q: Combinaions from X,Y string in massive Firs of all excuse me for my bad english.
I'm trying to generate combinations of symbols taking them from str: TStringList (Xn, Yn) where X is the position of the char in the new word and Y is the variable for the position. For example lets say my StringList have
str[0]: '013456789'
str[1]: 'abcdef'
str[2]: '5421'

In this case I will expact 216 words (length(str[0]) * length(str[1]) * length(str[2])) The result will be like:
str[0][1]+ str[1][1]+ str[2][1] -> 0a5
str[0][1]+ str[1][1]+ str[2][2] -> 0a4
str[0][1]+ str[1][1]+ str[2][3] -> 0a2
str[0][1]+ str[1][1]+ str[2][4] -> 0a1

str[0][1]+ str[1][2]+ str[2][1] -> 0b5
str[0][1]+ str[1][2]+ str[2][2] -> 0b4
str[0][1]+ str[1][2]+ str[2][3] -> 0b2
str[0][1]+ str[1][2]+ str[2][4] -> 0b1

str[0][1]+ str[1][3]+ str[2][1] -> 0c5
str[0][1]+ str[1][3]+ str[2][2] -> 0c4
str[0][1]+ str[1][3]+ str[2][3] -> 0c2
str[0][1]+ str[1][3]+ str[2][4] -> 0c1

and so on untill
str[0][10]+ str[1][6]+ str[2][3] -> 9f2
str[0][10]+ str[1][6]+ str[2][4] -> 9f1

Now I'm comfused how to make the "FOR" loops to make cicles for every possible word.
Best regards Martin

A: This can be done with recursion.
procedure Recurse(startIx,stopIx: Integer; prefix: String; const aList: TStringList);
var
  ch : Char;
begin
  if (startIx > stopIx) then begin
    WriteLn(prefix);
  end
  else
  begin
    for ch in aList[startIx] do begin
      Recurse( startIx+1,stopIx,prefix + ch,aList);
    end;
  end;
end;

Recurse(0,str.Count-1,'',str);

Recursion may seem like magic at first, but is a very effective way to solve this kind of combinatorics.
The solution to this problem is a Cartesian product.
Should you have an older Delphi version, iterate the character like this:
procedure Recurse(startIx,stopIx: Integer; prefix: String; const aList: TStringList);
var
  i : Integer;
begin
  if (startIx > stopIx) then begin
    WriteLn(prefix);
  end
  else
  begin
    for i := 1 to Length(aList[startIx]) do begin
      Recurse( startIx+1,stopIx,prefix + aList[startIx][i],aList);
    end;
  end;
end;

A: You have to nest 3 for loops together. I assume that index of str array starts from zero but indices of second dimension start from 1:
var i,j,k:integer;

begin
    s = '';
    for i:=1 to length(str[0]) do
        for j:=1 to length(str[1]) do
            for k:=1 to length(str[2]) do
            begin
                combination := str[0][i]+str[1][j]+str[2][k];
                s := s + combination + chr(13) + chr(10);
            end;
    { you have all combinations in string s }
end;

If you need variable number of character length you could implement it like this:
procedure TForm1.FormCreate(Sender: TObject);
var str: array [0..10] of string;
    lengths : array [0..10] of integer;
    combination : string;
    index: array [0..10] of integer;
    n, i,j : integer;
    maxn : integer;
begin
    n := 3; { actual number of charaters in output word }
    str[0]:= '013456789';
    str[1]:= 'abcdef';
    str[2]:= '5421';

    { lengths will be used often later so they will be determined one time }
    for i:=0 to n-1 do lengths[i] := length(str[i]);
    maxn := 1; { maxn will be used to determine how meny iterations to make }
    for i:=0 to n-1 do maxn := maxn * lengths[i];
    { start at index 1 (first character) with each character position }
    for i:=0 to n-1 do index[i]:=1;

    memo1.Lines.Add(inttostr(maxn));

    { iterate all possibilities }
    for i:=1 to maxn do
    begin
      { start creating a combination }
      combination:='';
      for j:=0 to n-1 do
      begin
        combination := combination + str[j][index[j]];
      end;
      memo1.Lines.Add(combination);
      { increment indexes, from last to the first }
      for j:=n-1 downto 0 do
      begin
        index[j] := index[j]+1;
        { if index is in bounds of character posibilities stop incremented indexes,
          otherwise reset the index and increment next one }
        if index[j]<=lengths[j] then
        begin
            break; { stop incrementing indexes }
        end else begin
            index[j] := 1; { reset the index }
            { the loop will continue incrementing previous index }
        end;
      end;
    end;
end;

Instead of using fixed variables for character index like i,j,k you can store them in an array index. Incrementing of indexes works like when you hand add two numbers on a paper. Try to add
 999
+  1
----

to get the idea.


text:
Q: C++ CPU Graph inside window I'm starting a project in C++ and I want to create a graph of the CPU like found in the task manager.
Should I be looking for a graphing or display library?
Should I investigate using OpenGL to display a real time graph?
I'm looking for the most elegant solution to get a graph display inside a window.
I looked around and could not even find out what the task manager uses to display it's CPU and memory graphs, and I don't want to jump in and start using and learning the wrong tool for the job.

A: Something like Task Manager doesn't update the screen all that often (once a second or so). That means efficiency isn't really a huge problem for it. GDI is probably the easiest way to do the drawing, and will almost certainly still give perfectly adequate performance.
If you want to keep your life as easy as possible, you might consider a library that already implements what you want/need, such as one or another on CodeProject.


text:
Q: Python 3: Functions dependent on other functions, missing parameter? I have two functions, the latter of which is dependent on the results of the first.
They are both mathematical functions using floats.
The gist of the two functions are:
def function1(a,aa,b,bb):
    # get result z from a and b
    # get error in result, zz, from raw errors, aa and bb
    print (z,zz)

def function2(z,zz,c,cc):
    # get result x from z and c
    # get error in result, xx, from zz and cc
    print (x,xx)

With a, b, and c being measured variables defined outside of the functions
With aa, bb, and c being the errors in the measured variables, also defined outside of the functions.
After defining the functions, I write the following command:
function2(function1(a,aa,b,bb),c,cc)

I am hoping that function1 would produce two results (z, zz) and they would be accepted as the first two parameters of function2.
Instead, I get the error "TypeError: function2() missing 1 required positional argument: 'cc'
So I assume that function1 is only producing one result at the end. How do I fix this?
Full code here: http://tinyurl.com/sof-typeerror

A: If your function returns more than 1 argument, then these arguments are packed into a tuple. You should unzip the arguments returned with a * to pass them as parameters to the other function. But, as a convention, you can't unzip anything as a first argument, so, I would rather suggest the following.
function2( *(function1(a,aa,b,bb) + (c, cc)) ) # would work

function2(*function1(a,aa,b,bb),c,cc)          # won't work

If you are really interested as to why the latter won't work or why the convention, then visit - http://www.python.org/dev/peps/pep-3132/ or Unpacking arguments: only named arguments may follow *expression
Also, as suggested in the comments, you should return the parameters & not just print them. Like below.
def function1(a,aa,b,bb):
    get result z from a and b
    get error in result, zz, from raw errors, aa and bb
    print (z,zz)
    return z, zz

def function2(z,zz,c,cc):
    get result x from z and c
    get error in result, xx, from zz and cc
    print (x,xx)
    return x, xx


text:
Q: MVP, WinForms - how to avoid bloated view, presenter and presentation model When implementing MVP pattern in winforms I often find bloated view interfaces with too many properties, setters and getters. An easy example with be a view with 3 buttons and 7 textboxes, all having value, enabled and visible properties exposed from the view. Adding validation results for this, and you could easily end up with an interface with 40ish properties. Using the Presentation Model, there'll be a model with the same number of properties aswell.
How do you easily sync the view and the presentation model without having bloated presenter logic that pass all the values back and forth? (With that 80ish line presenter code, imagine with the presenter test that mocks the model and view will look like..160ish lines of code just to mock that transfer.) Is there any framework to handle this without resorting to winforms databinding? (you might want to use different views than a winforms view. According to some, this sync should be the presenters job..) Would you use AutoMapper?
Maybe im asking the wrong questions, but it seems to me MVP easily gets bloated without some good solution here..

A: This is just one idea, and I know where some people might not like it -- there are lots of different things you can do here.
If you find yourself using a lot of boilerplate code, encapsulate it.
public class UiField<ContentType>
{
    public bool IsEnabled { get; set; }
    public ContentType Value { get; set; }
    public bool IsVisible { get; set; }
}

In your view, then:
public interface ISampleView
{
    UiField<bool> IsStaffFullTime { get; set; }
    UiField<string> StaffName { get; set; }
    UiField<string> JobTitle { get; set; }
    UiField<int> StaffAge { get; set; }
    UiField<IList<string>> Certifications { get; set; }
}

Here you wrap up the various properties associated with each field.
Incidentally, I suggest that you not stub these interfaces by hand for testing -- use a mocking framework.

A: I started building on Jay's solution then realised that what I was building was implementation of the Adapter Design Pattern. Here is what I ended up with, its VB.Net rather than C#:
The adapter Interface which defines the properties you only want to set up once:
Public Interface IWinformsControlAdapter(Of T)

''' <summary>
''' Default value for the UI Control
''' </summary>
''' <returns></returns>
Property Value As T
Property IsEnabled As Boolean
Sub SetError(myValue As String)

''' <summary>
''' Select all the text in the UI Field if possible
''' </summary>
Sub [Select]()

''' <summary>
''' Gets a boolean value indicating whether all required inputs have been entered into the UI field
''' </summary>
''' <returns>true if all required input has been entered in the field</returns>
ReadOnly Property Completed As Boolean

Property DataSource As Object
Property DisplayMember As String
Property ValueMember As String
Property SelectedValue As Object
Property Checked As Boolean
End Interface

The Interface Implementation:
Public Class WinformsControlAdapter(Of T)
    Implements IWinformsControlAdapter(Of T)

    Private ReadOnly _control As Control 'The Adaptee
    Private ReadOnly _errorProvider As ErrorProvider
    Public Sub New(ByRef control As Control, ByRef errorProvider As ErrorProvider)
        _control = control
        _errorProvider = errorProvider
    End Sub

    Public Property Value As T Implements IWinformsControlAdapter(Of T).Value
        Get

            Select Case True
                Case TypeOf _control Is TextBoxBase
                    'Typically for Textbox T = String, but not always: _control could be adapting to Integer for inputting numbers or MaskedTextbox could be adapting to Date for inputting dates, etc
                    Return ConvertTo(Of T)(_control.Text)

                Case TypeOf _control Is RadioButton
                    Dim myRadioButton As RadioButton = _control
                    Return ConvertTo(Of T)(myRadioButton.Checked)

                Case Else
                    Throw New NotImplementedException("Some other control.property needs to be added for .Value Property Get")

            End Select

        End Get
        Set(myValue As T)

            Select Case True
                Case TypeOf _control Is TextBoxBase
                    _control.Text = ConvertTo(Of String)(myValue)

                Case TypeOf _control Is ListControl
                    'Its debatable should it be the list or the selected value
                    DataSource = myValue
                    'Dim myListControl As ListControl = _control
                    'myListControl.DataSource = ConvertTo(Of T)(myValue)

                Case TypeOf _control Is RadioButton
                    Dim myRadioButton As RadioButton = _control
                    myRadioButton.Checked = ConvertTo(Of Boolean)(myValue)

                Case Else
                    Throw New NotImplementedException("Some other control.property needs to be added for .Value Property Set")
            End Select

        End Set
    End Property

    Public Property Checked As Boolean Implements IWinformsControlAdapter(Of T).Checked
        Get
            If TypeOf _control IsNot RadioButton Then Throw New NotImplementedException()

            Dim myRadioButton As RadioButton = _control
            Return myRadioButton.Checked
        End Get
        Set(myValue As Boolean)
            If TypeOf _control IsNot RadioButton Then Throw New NotImplementedException()

            Dim myRadioButton As RadioButton = _control
            myRadioButton.Checked = myValue
        End Set
    End Property

    Public ReadOnly Property Completed As Boolean Implements IWinformsControlAdapter(Of T).Completed
        Get
            If TypeOf _control IsNot MaskedTextBox Then Throw New NotImplementedException()

            Dim myMaskedTextBox As MaskedTextBox = _control
            Return myMaskedTextBox.MaskCompleted
        End Get
    End Property

    Public Property DataSource As Object Implements IWinformsControlAdapter(Of T).DataSource
        Get
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            Return myListControl.DataSource
        End Get
        Set(myValue As Object)
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            myListControl.DataSource = myValue
        End Set
    End Property

    Public Property DisplayMember As String Implements IWinformsControlAdapter(Of T).DisplayMember
        Get
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

                Dim myListControl As ListControl = _control
                Return myListControl.DisplayMember
        End Get
        Set(myValue As String)
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            myListControl.DisplayMember = myValue
        End Set
    End Property
    Public Property ValueMember As String Implements IWinformsControlAdapter(Of T).ValueMember
        Get
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            Return myListControl.ValueMember
        End Get
        Set(myValue As String)
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            myListControl.ValueMember = myValue
        End Set
    End Property
    Public Property SelectedValue As Object Implements IWinformsControlAdapter(Of T).SelectedValue
        Get
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            Return myListControl.SelectedValue
        End Get
        Set(myValue As Object)
            If TypeOf _control IsNot ListControl Then Throw New NotImplementedException()

            Dim myListControl As ListControl = _control
            myListControl.SelectedValue = myValue
        End Set
    End Property
    Public Function ConvertTo(Of T)(myValue As Object) As T
        If (TypeOf myValue Is T) Then
            Dim variable As T = myValue
            Return variable
        End If

        Try
            'Handling Nullable types i.e, int?, double?, bool? .. etc
            If Nullable.GetUnderlyingType(GetType(T)) <> Nothing Then
                Return TypeDescriptor.GetConverter(GetType(T)).ConvertFrom(myValue)
            End If

            Return Convert.ChangeType(myValue, GetType(T))

        Catch ex As Exception
            Return CType(Nothing, T) 'Return the default value for the type - same as C#: return default(T)
        End Try
    End Function
    Public Property IsEnabled As Boolean Implements IWinformsControlAdapter(Of T).IsEnabled
        Get
            Return _control.Enabled
        End Get
        Set(myValue As Boolean)
            _control.Enabled = myValue
        End Set
    End Property

    ''' <summary>
    ''' Sets the error description string for the UI Field.
    ''' </summary>
    ''' <param name="myValue">The error message to assign to the control</param>
    Friend Sub SetError(myValue As String) Implements IWinformsControlAdapter(Of T).SetError
        _errorProvider.SetError(_control, myValue)
    End Sub

    Sub [Select]() Implements IWinformsControlAdapter(Of T).Select
        If TypeOf _control Is TextBoxBase Then
            Dim myTextBoxBase As TextBoxBase = _control
            myTextBoxBase.Select(0, _control.Text.Length)
        End If
    End Sub

End Class

In the WinForm/View, declare Properties that will expose view controls as simple data types using the Adapter:
Property YesNo1 As IWinformsControlAdapter(Of Boolean) Implements IMyView.YesNo1
Property YesNo2 As IWinformsControlAdapter(Of Boolean) Implements IMyView.YesNo2
Property StartDate As IWinformsControlAdapter(Of Date?) Implements IMyView.StartDate
Property EndDate As IWinformsControlAdapter(Of Date?) Implements IMyView.EndDate

In the WinForm/View constructor, wire up the properties to the Winforms UI controls (I am also using ErrorProvider):
Public Sub New()
MyBase.New()
Try
    InitializeComponent()

    Yes = New WinformsControlAdapter(Of Boolean)(rdoHNSYes, ErrorProvider1)
    No = New WinformsControlAdapter(Of Boolean)(rdoHNSNo, ErrorProvider1)
    StartDate = New WinformsControlAdapter(Of Date?)(mskStartDate, ErrorProvider1)
    EndDate = New WinformsControlAdapter(Of Date?)(mskEndDate, ErrorProvider1)

In the Presenter:
Private ReadOnly _view As IMyView
Public Sub New(view As IMyView)
    _view = view 'Inject dependency
End Sub

Now in your presenter code, you can use the adapter properties:
_view.YesNo1.Value = True
If _view.StartDate.Completed Then
etc
etc


text:
Q: rtorrent - How to keep information for reseeding later I have box with internet connection and limited space. I have also much more space offline.
I download fime files with rTorrent, share them for some time, then move them to offline space to be able download more files.
Sometimes later somebody asks me to share those files again, so I would like to put them back to sharing, but I do not know how.

Details

*

*I download magnet URL ( magnet:?xt=urn:btih:12345.... )

*cd ~/torrents

*echo "d10:magnet-uri${#1}:${1}e" > "meta-${BASH_REMATCH[1]}.torrent" # create meta-12345...torrent

*rtorrent downloads 12345...meta to ~/torrents/Downloads

*rtorrent downloads and share ~/torrents/Downloads/some_dir/some_files*

*I stop rTorrent, move all Downloads/some_dir to offline storage, free the space

*much later somebody asks to share some_dir again (as no seeded is active)

*I copy some_dir from offline to the box ~/torrents/Download/some_dir

*What now? How to say rtorrent, to share it again under the original magnet?

A: Not sure it will work, but try add the torrent again, exit rtorrent, move the completed file over the new created place holder which crated by the new torrent, and start rtorrent again, next forcing hash check (Ctrl-r) which will initiate a hash check of the torrent, and if you have the file in the same place, after the hash checking the file will marked as completed and will start seeding.

A: rtorrent has the posibility to "watch" directories for torrent-files. As soon as a new file arrives it loads them again (shares them again). I assume the torrent-file contain information for at least one tracker.
I did not test this by myself, but I think this page is a good starting point for solving your problem.
https://wiki.archlinux.org/index.php/RTorrent


text:
Q: How to remove user session attribute saved in namespace 'foo'? To remove a user session attribute foobar' saved in the default name space, simply do this:
$user->getAttributeHolder()->remove('foobar');

How do you remove attribute foobar if it was saved in namespace foobar like this:
$user->setAttribute('foobar', 123, 'foo');

A: I think you can specify the namespace like this :
$user->getAttributeHolder()->remove('foobar','','foo');


text:
Q: Does hard disks order matter when Windows boots? I had installed Windows on my hard disk 0 (and had another backup disk: 4TB DISK 1).
Several days ago, due to some reasons, I have changed cables of them, and now DISK 0 is my backup disk.

Does it matter for system speed? Because today I noticed Windows had 2-3 times increased boot time while I turned on my PC…   (My MotherBoard model)
Or is that of another problem probably?

A: Although this is dependent on your motherboard, say if SATA port 0 has a different operating mode than SATA port 1 (or whatever ports you have them connected to) there would be a difference, but most likely they are all the same type and speed and the actual location the drive is connected to on the motherboard will not affect performance.
However, in your case there is a significant difference, your motherboard, an MSI Z77MA-G45, does indeed have different speed ports, it has two SATA-III (6Gbps) and four SATA-II (3Gbps) ports. SATA1 and SATA2 are 6Gbps ports and SATA3-6 are are 3Gbps ports. On page 1-22 of your owners manual, it clearly shows the different ports and speeds.
It would usually be advisable to have your boot device on SATA1 (the first port) and then the drive you want the fastest access to besides the boot drive to be connected to SATA2 as those are SATA-III ports (assuming you have SATA-III drives), after that drives could be connected to any port. Optical drives do not need to be connected to SATA-III ports as most do only support SATA-II anyway.
The startup speed in this case could very well be related to which port the hard disk is connected to, but would require more information to diagnose (that wasn't really the point of your question).


text:
Q: FindBugs doesn't find a bug I would like to use FindBugs to create a report about an application.
I run it and it doesn't find a potential bug like this:
public List<String> getListTrace(A object) {

    String arg = object.getArg();
    ...
}

If object is null, my application will be down.
Why FindBugs doesn't raise an alert?

A: Findbugs doesn't know if object is allowed to be null or not.  You can tell it by using annotations:
import javax.annotation.Nullable;
...
public List<String> getListTrace(@Nullable A object) {

This tells Findbugs (and people reading the code) that it is okay to pass null as the argument to getListTrace.  So Findbugs will warn you if you dereference object without checking for null.

A: That code doesn't look like it has a bug.
If you changed the code to check if object was null, what would you do? The most reasonable action would probably to throw a NullPointerException, right?
That's exactly what your code snippet does; it just lets java do the test automatically when accessing a method.
That this function doesn't check for a null pointer is not a bug. The bug would be if someone passed a null pointer into your function and wasn't prepared for it raising a NullPointerException.

A: Findbug cannot detect potential null pointer accesses. But Eclipse can give you a warning for potential null pointer access, if you activate the corresponding compiler warning in the preferences.

A: Raising bug report in such case would result in really big noise. You would get thousands of irrelevant bug messages in the perfectly correct code. Actually FindBugs does smarter thing. If it discovers that the method dereferences the argument without a null-check, it marks internally this method argument as @Nonnull. If you have an explicit annotation (like in TimK answer) which contradicts with this, you will get a warning. Otherwise FindBugs assumes that nobody uses this method with possibly-null argument. And when somebody actually does this, you will get a corresponding warning on the call site. Here's an example:
import java.util.Collections;
import java.util.List;

public class FBNull {
    static class A {
        String getArg() {
            return "str";
        }
    }

    public static List<String> getListTrace(A object) {
        String arg = object.getArg();
        return Collections.singletonList(arg);
    }

    public void callSite(A a) {
        if (a == null) {
            System.out.println("a is null");
        }
        System.out.println(getListTrace(a)); // NP_NULL_PARAM_DEREF
    }
}

From the FindBugs poit of view getListTrace() method is ok. However the callSite method has a bug. It checks its argument for null explicitly, thus it can be null due to application logic. However, it's later passed to getListTrace() which immediately dereferences the argument. Thus you have a bug warning inside the getListTrace() method saying:

Bug: Null passed for non-null parameter of getListTrace(FBNull$A) in FBNull.callSite(FBNull$A)
This method call passes a null value for a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced.

So if you actually can pass nulls, it can be detected on the call sites.


text:
Q: inno setup create box to install additional programs I'm a newbie to inno setup and I'm trying to create my setup for the first time.
I need to add some components to my setup
my scenario:

*

*choose additional components with boxes

*copy necessary files to {pf}\myapp

*launch setup of additional components selected before
I don't find an easy solution for point 3.
any suggestions?
thanks to all

A: solved with TASKS .
[Files]

Source: "..\input\MRV\scripts\ConfigFile_FIRMA_STAMPA.ini"; DestDir: "{app}\Config\"; DestName: "ConfigFile.ini"; Flags: ignoreversion; Tasks: FCS
Source: "..\input\MRV\scripts\ConfigFile_FIRMA_NOSTAMPA.ini"; DestDir: "{app}\Config\"; DestName: "ConfigFile.ini"; Flags: ignoreversion; Tasks: FSS
Source: "..\input\MRV\scripts\ConfigFile_NOFIRMA_STAMPA.ini"; DestDir: "{app}\Config\"; DestName: "ConfigFile.ini"; Flags: ignoreversion; Tasks: NFCS
Source: "..\input\MRV\scripts\ConfigFile_NOFIRMA_NOSTAMPA.ini"; DestDir: "{app}\Config\"; DestName: "ConfigFile.ini"; Flags: ignoreversion; Tasks: NFSS
[Tasks]
Name: "FCS"; Description: "Description1"; GroupDescription: "Parametri Extra"; Flags: unchecked exclusive
Name: "FSS"; Description: "Description2"; GroupDescription: "Parametri Extra"; Flags: unchecked exclusive
Name: "NFCS"; Description: "Description3"; GroupDescription: "Parametri Extra"; Flags: unchecked exclusive
Name: "NFSS"; Description: "Description4"; GroupDescription: "Parametri Extra"; Flags: unchecked exclusive
thanks for help


text:
Q: Android Bluetooth data transmission using Handler As a beginner in Android I have stupid problem. I do application that can receive data from Bluetooth measurement system. Data transmission works cool because I can display it in console in Android Studio, but I need to display it in one of my Activities in loop.
Part of code of method run() in Bluetooth class (I know that input is String, I have converted it to int before sending)
while (true) {
        in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        input = in.readLine();
        if (input.contains("+++")) {
            handler.obtainMessage(input).sendToTarget();
        }
    }

Code of handler in Activity:
Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            textView.setText(message.what);
        }
};

After that application crashes with error:
FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x6

Anyone has an idea how to fix it?

A:
Resources$NotFoundException: String resource ID #0x6

Due to :
textView.setText(message.what);

line.
As see Message.what return int type of value but TextView.setText require CharSequence type value.
When we pass int value to TextView.setText method, system treat int value as resource id and trying to find it when no resource is available with given int then it will through NotFoundException: String resource ID
Show int value as in TextView:
textView.setText(String.valueOf(message.what));

A: you can also try
textView.setText(message.what+"");


text:
Q: Since which Android version is swipe-to-clear supported in notifications? My app has a preference item which regards what happens when the
user swipes away a notification.
However, I'd like to remove that item if the Android version being
used doesn't support swipe-to-clear notifications (as it makes no
sense to display a useless preference to the user). Thus, I need to
determine at run-time whether it's supported or not.
Since which API version is this feature included in stock android?

A:
I'd like to remove that item if the Android version being used doesn't
  support swipe-to-clear notifications (as it makes no sense to display
  a useless preference to the user).

In all previous version of android there is a option to clear All notification  ,
if your intention to clear  particular  notification then i am agree with you .
however android  introduce that feature from Ice Cream Sandwich version
refer this link for more information http://developer.android.com/about/versions/android-4.0-highlights.html

A: This feature was included in Android 4.0 ICS API 14.


text:
Q: SQL Server Force Results of Select Statement to Output Window Before End of Script Is there a way to force the results of a Select Statement to the Output window in SQL Server Management Studio before the end of the entire script is reached?
I have one select query that executes quickly, and one that takes a while to execute.  I would like to look at the results from the first query while the second is running.
My issue is that the same variables are used in both queries and if a "GO" statement is used, the variables will be lost.  Example below.
declare @MyVar int
set @MyVar = 1

-- Query with short execution time
select  *
from    MyTable t
where   t.Column = @MyVar

GO -- @MyVar is lost

-- Query with long execution time
select  *
from    MyOtherTable o
where   o.Column = @MyVar -- @MyVar no longer exists

A: You can use raiseerror , which will cause the buffer to flush :
RAISERROR( 'Just to print everything',0,1) WITH NOWAIT

you can put this between the queries.

A: As an alternative, you could store your variable in a temp table.
create table #MyTable (MyVar int)
insert into #MyTable (MyVar) values (1)

-- Query with short execution time
select  *
from    MyTable t
where   t.Column = (select MyVar from #MyTable)

GO -- #MyTable is preserved

-- Query with long execution time
select  *
from    MyOtherTable o
where   o.Column = (select MyVar from #MyTable)


text:
Q: Can't restore default text size I have never asked a question in an online forum before, but a few years of reading them have emboldened me, so here goes.
I'm running Ubuntu 14.04. While in the Unity "Keyboard" app, "Shortcuts" tab, "Universal Access" group, I changed "Increase text size" from "Disabled" to "Shift+Ctrl+>" and "Decrease text size" to "Shift+Ctrl+<". I tried the ">" shortcut and the text size did increase. However, I later decided to revert back to the smaller text, and could not. Neither shortcut worked anymore.
I searched online and found several possible solutions, neither of which has worked:

*

*As per one suggestion here, I tried ~$ rm -rf .gconf/ followed by a reboot. Alas, when it failed I noticed the negative score on the suggestion. Doh! Newbie error. Other than failing, no obvious ill effects. (A new .gconf directory has been created, and it no longer has a desktop subdirectory, which is where my changes to the default would have gone, I believe, so I think this is all as would be expected?)

*As per this post, I installed and ran ~$ unity-tweak-tool --reset-unity. This ran successfully (only when I switched to Python 3 BTW), but did not restore the text size.
I understand from elsewhere that there is a history to how configurations are handled in Unity, along the lines of gconf vs dconf etc. While my immediate concern is an answer to the above problem, I will appreciate any feedback, links etc. of a more general educational nature, on this or virtually any topic related to open sourcing.


text:
Q: Convert RJ11 to RJ45 I have random RJ11 wires in house which have been cut off as they were used for the master socket and the master socket was in an awkward place. And I was wondering if it was possible to convert both ends of that cable into a RJ45 cable to connect to my PS4 from the router saving time and money from having to buy and install a new cable.
Edit: I don't think it's a "cat" cable. It doesn't have any writings at all. It's the cable used in UK for the master socket (BT 5C) to connect it to the phone and router. Not sure if it's different in other countries. Just a thin white cable. Thinner than a standard RJ45 Cable. –
Is this possible?

A: The answer is possibly... but without knowing more about the cable and the layout it is difficult to tell.
In theory, telephony cable can be used to support 10/100 connections (not Gigabit) over short distances. If you can find a telephony cable that is not cut and is a "home run" between the two points you need to connect, and it contains at least 4 conductors, it may be possible.
For 10/100 Ethernet to work, you need to have a straight through connection of pins 1, 2, 3, and 6, and the other pins are not relevant/not used in this scenario.
For the purposes of this, we will say the cable has Red, Green, Yellow, and Black conductors. They may be different colored or contain more conductors, but this is all we are concerned with. If the cable is solid with a matching stripe (Blue with a white stripe and white with a blue stripe twisted together, even better).
Connect both ends of the cable the same to an RJ45 JACK (do not crimp ends on the cable), essentially we are going to substitute color pairs of the existing cable for "standard" color codes in EIA/TIA 568B color code.
In the 568B color code, we need W/O-O/W (Pins 1&2) and W/G-G/W pairs (Pins 3&6) Pins 4, 5, 7, and 8 can be ignored (they are for PoE and Gigabit applications, which we are not going attempt with this type of cable).
Now substitute... If you cable is Red/Green Yellow/Black, connect the green to Pin 1, the Red to pin 2, the black to pin 3 and the yellow to pin 6, do the same on both ends and connect with a standard patch cable to the router and computer. If the color are different, just substitute as necessary.

Now, the reality this might work perfectly at 100Mbps, or it may error out like crazy... it may function fine at 10Mbps or fail just as miserably... Or it may not link up at all. There is no way of knowing until you try it.

A: I would not recommend using an RJ11 / phone network cable for your PS4. I am assuming you use it for gaming and video streaming and  you would like to enjoy a delay free experience. To achieve a delay free use of your PS4, you will need a proper ethernet network cable installation(CAT5e, CAT6 or CAT6a). These network cables are designed to reach 1GB and 10GB speed. The biggest differences between these cables and telephone cables is the quantity of copper in the cable (the more the better) and the twists between the individual wires. The twists are important because they help cancel electrical noise that is inherent in electrical cables. Phone cables are designed to carry analog signals which is a low bandwidth requirement.


text:
Q: R boot::boot(): function which returns mean and the used samples I'm using the boot() function from the boot package to bootstrap means from a population. The used function is:
boot_mean <- function(data, i){

  ds_m <- data[i]
  return(mean(ds_m))

}

Works like charm but now I want to adapt the boot_mean function so that I can get the samples which lead to the mean too. I tried:
library('boot')

boot_mean <- function(data, i){

  ds_m <- data[i]
  ds_m_mean <- mean(ds_m)
  rlist <- list("means" = ds_m_mean, "data" = ds_m)
  return(rlist)

}

dummy_data <- rnorm(500)
dummy_boot <- boot(dummy_data, boot_mean, R = 1000)

Which results in an error:

Error in t.star[r, ] <- res[[r]] :    incorrect number of subscripts
on matrix

What's wrong here? How can I get the corresponding dataset to the bootstrapped mean?

A: From the documentation ?boot, describing the statistic argument.

A function which when applied to data returns a vector containing the statistic(s) of interest. ...

The boot() function only wants to deal with functions that output a single vector. Modifying your code to return a list of two elements means it won't work anymore. There's actually a little interesting oddity in R and the boot() function which means the code almost works if you set R=1 in the boot() call, but it's still wrong.
Fortunately for your purpose, the authors have already programmed the useful boot.array() function. It outputs a matrix with R rows and nrow(data) columns, indicating either how many times the jth individual was sampled for the ith bootstrap, or the indices of the sampled individuals. Getting the bootstrapped datasets can easily be found by selecting those individuals from the data. This can take a little while.
dats <- lapply(1:nrow(boot.array(dummy_boot)),
    FUN = function(x) dummy_data[boot.array(dummy_boot, indices = TRUE)[x, ]])

If you have multiple columns of data you should add , , drop = FALSE
dats <- lapply(1:nrow(boot.array(dummy_boot)),
    FUN = function(x) dummy_data[boot.array(dummy_boot, indices = TRUE)[x, ], , drop = FALSE])


text:
Q: Open Web Browser from XAML app I would like to open the external webbrowser from my XAML app, similar to this: want to open Link in external browser of WP7
I can't seem to find the WebBrowserTask object:
Dim wbt As New WebBrowserTask()
wbt.Uri = New Uri("http://xxx.xxx.com/xxx.aspx")
wbt.Show()

Is there another way for WindowsRT/XAML?
Thanx!

A: You should use Launcher class.
Dim uri As New Uri("http://www.bing.com")

Async Sub DefaultLaunch()

   ' Launch the URI
   Dim success = await Windows.System.Launcher.LaunchUriAsync(uri)

   If success Then
      ' URI launched
   Else
      ' URI launch failed
   End If

End Sub

A: await Launcher.LaunchUriAsync(new Uri(uri));


text:
Q: .Net Core 3.1 - Mutiple hosted services with independent configurations As far I know, it's possible to add multiple hosted services to run under the same 'host', like this example took from Microsoft page:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //Other DI registrations;

    // Register Hosted Services
    services.AddHostedService<GracePeriodManagerService>();
    services.AddHostedService<MyHostedServiceB>();
    services.AddHostedService<MyHostedServiceC>();
    //...
}

If instead of that I create three different projects, It would be possible to inject three different configurations for each one of them.
Is there any way to do that in same project? Maybe loading different configuration files(appsettings.json)?
Like:

*

*For hosted service GracePeriodManagerService appsettings.graceperiod.json

*For hosted service MyHostedServiceB appsettings.myHostedServiceB.json
Or separating it by folders:

*

*For hosted service GracePeriodManagerService GracePeriodManagerService\appsettings.json

*For hosted service MyHostedServiceB MyHostedServiceB\appsettings.json

A: You can do it in many ways.
The best way would be to use IOptions pattern:
In your appsettings file you can add:
"Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }

You should have a class matching the json object above:
public class PositionOptions

{
    public const string Position = "Position";

    public string Title { get; set; }
    public string Name { get; set; }
}

Finally you can inject it to the DI container by:
services.Configure<PositionOptions>(Configuration.GetSection(
                                        PositionOptions.Position));

If you still want to use multiple appsetings files you could do the following.
In the Startup.cs:
        private readonly IConfiguration _configurationName1;
        private readonly IConfiguration _configurationName2;
        public Startup(IConfiguration configuration)
        {
            _configurationName1 = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettingsWorker1.json")
            .Build();

            _configurationName2 = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettingsWorker2.json")
            .Build();
         }

Then you can use seperate configurations on demand.

A: When configuring your application, you can define where to get configuration from (see this blogpost for instance). Each file could have a section with the settings you want and the individual hosted services could get their relevant configuration by using configuration.GetSection().


text:
Q: How to split a text file into multiple text files I have a text file called entry.txt that contains the following:
[ entry1 ]
1239 1240 1242 1391 1392 1394 1486 1487 1489 1600
1601 1603 1657 1658 1660 2075 2076 2078 2322 2323
2325 2740 2741 2743 3082 3083 3085 3291 3292 3294
3481 3482 3484 3633 3634 3636 3690 3691 3693 3766
3767 3769 4526 4527 4529 4583 4584 4586 4773 4774
4776 5153 5154 5156 5628 5629 5631
[ entry2 ]
1239 1240 1242 1391 1392 1394 1486 1487 1489 1600
1601 1603 1657 1658 1660 2075 2076 2078 2322 2323
2325 2740 2741 2743 3082 3083 3085 3291 3292 3294
3481 3482 3484 3690 3691 3693 3766 3767 3769 4526
4527 4529 4583 4584 4586 4773 4774 4776 5153 5154
5156 5628 5629 5631
[ entry3 ]
1239 1240 1242 1391 1392 1394 1486 1487 1489 1600
1601 1603 1657 1658 1660 2075 2076 2078 2322 2323
2325 2740 2741 2743 3082 3083 3085 3291 3292 3294
3481 3482 3484 3690 3691 3693 3766 3767 3769 4241
4242 4244 4526 4527 4529 4583 4584 4586 4773 4774
4776 5153 5154 5156 5495 5496 5498 5628 5629 5631

I would like to split it into three text files: entry1.txt, entry2.txt, entry3.txt.  Their contents are as follows.
entry1.txt:
[ entry1 ]
1239 1240 1242 1391 1392 1394 1486 1487 1489 1600
1601 1603 1657 1658 1660 2075 2076 2078 2322 2323
2325 2740 2741 2743 3082 3083 3085 3291 3292 3294
3481 3482 3484 3633 3634 3636 3690 3691 3693 3766
3767 3769 4526 4527 4529 4583 4584 4586 4773 4774
4776 5153 5154 5156 5628 5629 5631

entry2.txt:
[ entry2 ]
1239 1240 1242 1391 1392 1394 1486 1487 1489 1600
1601 1603 1657 1658 1660 2075 2076 2078 2322 2323
2325 2740 2741 2743 3082 3083 3085 3291 3292 3294
3481 3482 3484 3690 3691 3693 3766 3767 3769 4526
4527 4529 4583 4584 4586 4773 4774 4776 5153 5154
5156 5628 5629 5631

entry3.txt:
[ entry3 ]
1239 1240 1242 1391 1392 1394 1486 1487 1489 1600
1601 1603 1657 1658 1660 2075 2076 2078 2322 2323
2325 2740 2741 2743 3082 3083 3085 3291 3292 3294
3481 3482 3484 3690 3691 3693 3766 3767 3769 4241
4242 4244 4526 4527 4529 4583 4584 4586 4773 4774
4776 5153 5154 5156 5495 5496 5498 5628 5629 5631

In other words, the [ character indicates a new file should begin.
Is there any way I can accomplish automatic text file splitting?  My eventual, actual input entry.txt actually contains 200,001 entries.
Doing the text split in either Windows or Linux would be great. I do not have access to a Mac machine. Thanks!

A: For a Windows solution, try this PowerShell script:
$Path = "D:\Scripts\PS\test"
$InputFile = (Join-Path $Path "log.txt")
$Reader = New-Object System.IO.StreamReader($InputFile)

While (($Line = $Reader.ReadLine()) -ne $null) {
    If ($Line -match "\[ (.+?) \]") {
        $OutputFile = $matches[1] + ".txt"
    }

    Add-Content (Join-Path $Path $OutputFile) $Line
}

Edit the $Path and $InputFile variables accordingly. With some minor modifications it could also accept that information as command-line parameters, or you could turn it into a function.

A: And here's a nice, simple gawk one-liner :
$ gawk '{if(match($0, /^\[ (.+?) \]/, k)){name=k[1]}} {print >name".txt" }' entry.txt

This will work for any file size, irrespective of the number of lines in each entry, as long as each entry header looks like [ blahblah blah blah ]. Notice the space just after the opening [ and just before the closing ].

EXPLANATION:
awk and gawk read an input file line by line. As each line is read, its contents are saved in the $0 variable. Here, we are telling awk to match anything within square brackets, and save its match into the array k.
So, every time that regular expression is matched, that is, for every header in your file, k[1] will have the matched region of the line. Namely, "entry1", "entry2" or "entry3" or "entryN". name=k[1] just saves the value of k[1] (the match) into a new variable name.
Finally, we print each line into a file called <whatever value k currently has>.txt, ie entry1.txt, entry2.txt ... entryN.txt.
This method will be much faster than perl for larger files.
I can't vouch for this as I have never used windows shell, but I am willing to bet it will be far faster than that also. Gawk/awk are FAST.

A: Yet another awk solution:
BEGIN {
  RS="\\[ entry[0-9]+ \\]\n"  # Record separator
  ORS=""                      # Reduce whitespace on output
}
NR == 1 { f=RT }              # Entries are of-by-one relative to matched RS
NR  > 1 {
  split(f, a, " ")            # Assuming entries do not have spaces
  print f  > a[2] ".txt"      # a[2] now holds the bare entry name
  print   >> a[2] ".txt"
  f = RT                      # Remember next entry name
}

A: The following perl script does the job:

#!/usr/bin/perl

while (<STDIN>) {
    if ($_ =~ m/^\[ (.+?) \]/) {
        $f = $1;
        close FH if tell(FH) != -1;
        open FH, ">", "$f.txt" or die "couldn't open file $f: $!\n";
    }
    print FH $_;
}
close FH;

Run the script like this:
script.pl < entry.txt

The script works no matter how many entry sections are included and how long the sections are as long as only the entry section headers are like [ some text ].

If you prefer unreadable code or just don't want to store a script somewhere, you can use this single command:

perl -e 'while(<STDIN>){if($_=~/^\[ (.+?) \]/){close FH if tell FH!=-1;open FH,">","$1.txt"or die"$1.txt: $!";}print FH $_;}close FH;' < entry.txt

A: Is it not simpler to use existing commands?  Not everything needs a new program.
csplit /\[/ file


text:
Q: Duda sobre TypeError: string indices must be integers Python InstaBot Hola comunidad de StackOverflow en español, estoy trabajando en este pequeño script de Python usando instabot y pandas para listar la cantidad de seguidores de determinada cuenta de IG y guardarlos en un dataframe, sin embargo se me está complicando un poco ya que me da un error de principantes
from instabot import Bot
import pandas as pd

total_seguidores = []
bot = Bot()
bot.login(username="usuario", password="contraseña")

followers = bot.get_user_followers("cuenta_ig")
for follower in followers:
    total_seguidores.append({
        "pk": follower["pk"],
        "username": follower["username"],
        "full_name": follower["full_name"],
        "is_private": follower["is_private"],
        "profile_pic_url": follower["profile_pic_url"],
        "profile_pic_id": follower["profile_pic_id"],
        "is_verified": follower["is_verified"],
        "follow_friction_type": follower["follow_friction_type"]

    })

df = pd.DataFrame(total_seguidores)
print(df)
df.to_csv("total_seguidores_ig.csv")

error
Traceback (most recent call last):
  File "C:\Users\Usuario\PycharmProjects\codeecuadorstats\ig selenium.py", line 13, in <module>
    "pk": follower["pk"],
  TypeError: string indices must be integers
 2021-07-02 15:21:42,516 - INFO - Total requests: 35

Muchas gracias de antemano


text:
Q: How do i get current processor id in macOS KEXT I found kern/processor.h files that include current_processor().
But I cannot use current_processor() even i include kern/processor.h file.
Is there any methods to get current processor id?
Add 030420 : I need any methods that get current processor id and methods should be possible to used in KEXT.  current_processor(), cpu_number() doesn't work on KEXT.

A: The following function is declared in <kern/cpu_number.h>:
extern int  cpu_number(void);

and returns the index of the CPU on which the code is currently executing.
Please note that this is in the unsupported KPI however, so you need to link against com.apple.kpi.unsupported.
Also note that the result will be meaningless unless preemption is disabled, which is of course normally not the case, only when a spinlock is held, or when running in a primary interrupt handler. Preemption being enabled means that the running thread can be rescheduled at any time, so by the time your code uses the CPU number it obtained by calling the above function, it may already have been rescheduled to run on a different CPU.


text:
Q: Javascript Snake Collision Understanding I need help with understanding this part of code with Snake collision in javascript, I marked parts that I do not fully understand how they work:
Full code at:
https://codeincomplete.com/posts/starting-snakes/
// do not understand this function
function occupies(a, b)   {
    return a && b && (a.x == b.x) && (a.y == b.y);
};

//do not understand this function
function snakeOccupies(pos, ignoreHead) {
    var segment = ignoreHead ? head.next : head;
    do {
        if (occupies(segment, pos))
            return true;
    } while (segment = segment.next);
    return false;
};

function unoccupied() {
    var pos = {};
    do {
        //understand this part but i do not understand what does while do
        pos.x = Math.round(random(0, nx-1));
        pos.y = Math.round(random(0, ny-1));
    } while (foodOccupies(pos) || snakeOccupies(pos));
    return pos;
};

A: In this code, a position on the game area is represented by an object with properties x and y.
occupies checks whether two such objects represent the same position. It's not sufficient to just return a == b; or return a === b;, because separate objects can be copies of each other and represent the same position. For example, the expression { x: 1, y: 1 } === { x: 1, y: 1 } will evaluate to false.
The a && b && part is to handle the case where one/both of the arguments a and b is undefined or null or something. If a is falsy, occupies will return a. If a is truthy but b is falsy, it will return b. (In javascript, the values false, undefined, null, 0, '' and NaN are falsy; all others are truthy.) Since the return value is only used inside an if(...), any falsy value is treated as false and any truthy value is treated as true.
The do-while loop in unoccupied runs the contents of the block, then evaluates foodOccupies(pos) || snakeOccupies(pos). If it evaluates to true (or otherwise truthy) it will run the block again; otherwise it will stop. It will keep running the loop until the condition is falsy. The only difference between this and a while loop without do is that this one will not check the condition before the first iteration of the loop (so it's guaranteed to run the block at least once).
The loop in snakeOccupies is slightly unusual: the condition (segment = segment.next) doesn't just return a value which is checked for truthiness, it also changes the value of a variable.
head is the position of the snake's head. It has properties x and y, just like the other positions, except that it also contains a property called next. The value of this property is another position, representing the next square after the snake's head, which has its own next property referencing the next position on the snake, and so on. This is what Bergi meant about a "linked list": It's a sequence of (x, y) pairs, and could have been implemented as an array, but instead it's implemented by links between the elements.
So the do-while loop iterates over the positions in the snake (possibly ignoring head). If it reaches one positioned at pos, snakeOccupies returns true. Otherwise, the loop will eventually reach the end of the snake, segment will be set to something falsy (probably undefined or null), the loop will be exited and snakeOccupies will return false.


text:
Q: NSTimer or Something Else for an Image Unlock? How can you have an image or a button unlock at a certain time or date?  Basically, I want an image to be 'locked' until a specific time.
When that time has passed I would like for the image to be unlocked.
Any help or guidance is very appreciated.
Thanks.


text:
Q: Force.com site Guest User unable to access events I am having hard trying to give access for the Force.com site Guest user to all contact events in the org.
When the contact is assigned to the Guest User, he does have access to his events.
But if the contact is assigned to a real user in the org, he doesn't.
Here how I tried to solve it but in vain:
I have given the Guest user read/write permissions on events through a permissions set.
I created two public groups, one containing real users and the other containing the guest user.
Then I created a sharing rule, to enable sharing of contacts assigned to users in the first public group with the second public group containing the guest user.
Am I missing anything?
I appreciate your help.


text:
Q: Empty and Zero Value I need to check if an age is empty so I do:
empty($age);

But when the age is 0, it still thinks it is empty.
How can I check if the age is empty but allow a 0 to validate as not empty?

A: You have to make a hack, for example:
if($age != "" && $age == false){
 // Age = 0
}

You can use is_null() too.

A: Why do not you define it all your own
function myempty($x)
{
  if(empty($x) || $x=0)
  retutn true;
  else
  return false;
}


text:
Q: Loading a UITableView From A Nib I keep getting a crash when loading a UITableView. I am trying to use a cell defined in a nib file.
I have an IBOutlet defined in the view controller header file:
UITableViewCell *jobCell;
@property (nonatomic, assign) IBOutlet UITableViewCell *jobCell;

This is synthesised in the implementation file.
I have a UITableViewCell created in IB and set it's identifier to JobCell.
Here is the cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *cellIdentifier = @"JobCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"JobsRootViewController" owner:self options:nil];
    cell = jobCell;
    self.jobCell = nil;
}

// Get this job
Job *job = [fetchedResultsController objectAtIndexPath:indexPath];

// Job title
UILabel *jobTitle;
jobTitle = (UILabel *)[cell viewWithTag:tagJobTitle];
jobTitle.text = job.title;

// Job due date
UILabel *dueDate;
dueDate = (UILabel *)[cell viewWithTag:tagJobDueDate];
dueDate.text = [self.dateFormatter stringFromDate:job.dueDate];

// Notes icon
UIImageView *notesImageView;
notesImageView = (UIImageView *)[cell viewWithTag:tagNotesImageView];
if ([job.notes length] > 0) {
    // This job has a note attached to it - show the notes icon
    notesImageView.hidden = NO;
}
else {
    // Hide the notes icon
    notesImageView.hidden = YES;
}

// Job completed button

// Return the cell
return cell;

}
When I run the app - I get a hard crash and the console reports the following:

objc[1291]: FREED(id): message style sent to freed object=0x4046400

I have hooked up all the outlets in IB correctly. What is the issue?
Thanks,

A: Your problem is in this block:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"JobsRootViewController" owner:self options:nil];
    cell = jobCell; <- THIS IS A SHALLOW COPY
    self.jobCell = nil; <- YOU JUST RELEASED IT
}

// Get this job
Job *job = [fetchedResultsController objectAtIndexPath:indexPath];

// Job title
UILabel *jobTitle;
jobTitle = (UILabel *)[cell viewWithTag:tagJobTitle]; <- CELL ISNT THERE ANYMORE

You're creating jobCell as an assigned property. The synthesized setter that you use when you say self.jobCell = nil releases the object that you just made cell reference. Make a deep copy instead, or don't set jobCell to nil.

A: The easiest way to do this is to break it up into two separate nib files and load the cell from the cell's own nib. Something to note is that you cannot set outlets like this, if you want to do that, you will need a custom UITableViewCell subclass. But if you are not wiring up anything in the cell, you can simply do this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    cell = [[[NSBundle mainBundle] loadNibNamed:@"JobsRootViewCell" owner:nil options:nil] objectAtIndex:0];
}

A: Swift 3

*

*Cell
You should register your xib file in order to use it in tableView:
override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerNib(UINib(nibName: "CellXibName", bundle: nil), forCellReuseIdentifier: "CellReuseIdentifier")
    }

UITebleViewDataSource method:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellReuseIdentifier", forIndexPath: indexPath) as! CellClass
    return cell
}

TableView
if let tableView: CustomTableView = nib?.first as? CustomTableView
{
   self.view.addSubview(tableView)
}


text:
Q: How to use IP_FILTER with python libtorrent The question I have is: How can I use ip_filter in libtorrent using the python language.
The goal I am trying to achieve is: Block all IP-addresses (in or out going traffic) using libtorrent ip-filter except for the one's I allow. Code snippet below is where I try to achieve my goal...
class Session:
   def __init__(self)
       self.session = libtorrent.session({'listen_interfaces': '0.0.0.0:6881'})
       self.ip_filter = None
   ….more….

   def set_access_rules(self):
       self.ip_filter = libtorrent.ip_filter()
       self.ip_filter.add_rule('0.0.0.0', '255.255.255.255', 1)  # I assume '1' means blocking
       self.ip_filter.add_rule('172.16.100.36', '172.16.100.36', 0)  # I assume '0' allow, prob. wrong...
       self.session.set_ip_filter(self.ip_filter)

The (c source) documentation said:
// Adds a rule to the filter. first and last defines a range of
// ip addresses that will be marked with the given flags. The flags
// can currently be 0, which means allowed, or ip_filter::blocked, which
// means disallowed.
ip_filter::blocked <- This is where I get stuck, how do I use/write that in python?
The thing is that if I call 'handle.get_peer_info()' I expect only to see 172.16.100.36 but I see all sorts of public addresses… Note: My torrent has no trackers and I configured no trackers elsewhere. Can you maybe give me an example in python how to achieve my goal?


text:
Q: Can't read my data while knitting to dashboard from Rmd I'm trying to knit my Rmd file to a Dashboard and this message pops up:

The weird thing is that if I run my code in the Rmd I get what I want and the object 'mapas_regiones' is found.
mapas_regiones %>%
  ggplot() +
  geom_sf(aes(geometry = geometry, fill = as.factor(treatment)))  +
  labs(title = "Regiones tratadas",
       caption = "Fuente: Elaboración propia en base de reportes de Carabineros y chilemapas") +
  coord_sf()   +
  theme_void() + geom_sf_label_repel(aes(label = nombre_region), force = 20, nudge_x = -20, seed = 100, size =2) +
  scale_fill_manual(values=c("skyblue2", "dodgerblue4")) +
  guides(fill=guide_legend(title="Treatment")) +
  theme(plot.title = element_text(hjust = 0.8), plot.caption = element_text(hjust = 0.5))

Running this code gives me my wanted output:

It might be relevant to say that the object 'mapas_regiones' is a dataset that uses geometry (not latitude or longitude) as the geographical reference that is used to plot the map.
I appreciate your time and help!


text:
Q: Button desativado quando não está em "resolução mobile" Bom dia, pessoal!
Sou iniciante no jQuery e no Bootstrap, e estou com algumas dificuldades ao utilizar os dois simultaneamente.
Eu estou querendo gerar um botão que, ao clicar, exiba um pequeno formulário para inserção de e-mail. Porém, só está funcionando quando a janela encontra-se em tamanho mobile (menor que 768px), em resoluções maiores, o botão fica desabilitado e o código não funciona.
Aqui está o meu código resumido:
[...]

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Nome da Página</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="css/bootstrap.min.css" />

[...]

    <button type="button" id="toggle-form-acesso">Cadastrar e-mail</button>
        <form id="form-acesso" action="" method="post">
            E-mail:
            <input class="field-text" type="text" name="email" id="email" placeholder="exemplo@dominio.com" required/>
            <input class="botao-login" type="submit" value="Solicitar acesso" />
        </form>
[...]

Fiz algo errado? Alguém sabe o que pode estar acontecendo?
Muito obrigado! :D

A: O que parece estar errado, é que vc n colocou uma classe de controle para forms do bootstrap, geralmente vc pode usar a classe .form-group para trabalhar com forms.
Aqui adicionei as classes, tente usa-las no seu codigo e veja se no seu contexto eles funcionarão.

    <button class="btn btn-primary" type="button" id="toggle-form-acesso">Cadastrar e-mail</button>
    <form class="form-group" id="form-acesso" action="#" method="post" >
        E-mail:
        <input class="field-text form-control" type="text" name="email" id="email" placeholder="exemplo@dominio.com" required/>
        <input class="botao-login btn btn-success form-control" type="submit" value="Solicitar acesso" />
    </form>

Separei o codigo que vc colocou no seu exemplo e ele n apresenta o disable em resoluções menores que vc mencionou, ficando normal.
Neste link o proprio bootstrap lhe avisa sobre o controle da classe com o titulo de inline form para trabalhar com campos um ao lado do outro e nele há um aviso sobre a resolução de 768px, de uma lida e veja se algum pedaço acima do seu codigo existe ou falta algo para que funcione corretamente.
http://getbootstrap.com/css/#forms


text:
Q: Docker pull is not giving real time downloaded-size/total-size when executed through Node.js child process sync When I run docker pull my-image from my terminal this is how my output looks like.
 59e69571f6c7: Pull complete
 43da27f69c98: Pull complete
 d22174e9eddd: Pull complete
 cc0ac48a6d21: Downloading 312.3 MB/2.888 GB
 b47aa969d5dc: Download complete

When I run a piece of Node.js code
const { exec } = require('child_process');
 exec('docker pull my-image', (error, stdout, stderr) => {
   if (error) {
     console.error('exec error: ${error}');
     return;
   }
   console.log('stdout: ${stdout}');
   console.log('stderr: ${stderr}');
 });

My output looks like this.
c49bda5ed612: Waiting
43da27f69c98: Verifying Checksum
43da27f69c98: Download complete
d22174e9eddd: Verifying Checksum
d22174e9eddd: Download complete
b47aa969d5dc: Verifying Checksum

I was expecting same output. Mainly the information regarding how much is downloaded and remaining. If I want to progress a progress bar based on the size of the image downloaded, there is no way to do with this output
Please let me know if there is a way to find real-time download size status.
FYI if you download any binary from curl, in Node.js exec command you get the real time bytes downloaded/total data.

A: The output that you are mentioning only happens if the docker CLI is running somewhere where there is a pseudo-tty allocated. You can force the output to not have a pseudo-tty on the command line by running the command this way:
docker pull my-image | cat

The pole will happen, and then you will get the same sort of output that you mentioned above.
It is likely that the way that you are calling the docker CLI is not allocating the pseudo-tty, causing it to not stream the progress information to standard out.
Try calling the executable with a pseudo-tty allocated to get the desired behavior.


text:
Q: Can't reload TableView I have 2 controllers: first is showing all records in db, second allows to add new record. Both of them connected with NavigationController. If I'll add new record and press "Back" button, first controller won't show new data (because of NavigationController, i guess).
So, I've tried to put tableView.reloadData() in viewDidAppear(). It won't help. Then I've tried to reload tableView with NSNotificationCenter (method from this thread), but it still doesn't show new data.
Here is my code:
func saveRecord() {
   //Creating cloud record
   let container = CKContainer.defaultContainer()
   let privateDatabase = container.privateCloudDatabase
   privateDatabase.saveRecord(cloudRecord, completionHandler: { (record, error) -> Void in
      if (error != nil) {
         print(error)
      }
      NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
         //creating core data record
         do {
            try managedContext.save()
         } catch let error as NSError {
            print("Could not save \(error), \(error.userInfo)")
         }
         NSNotificationCenter.defaultCenter().postNotificationName("reloadHistoryController", object: nil)
      })
   })
}

override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadHistoryController:", name:"reloadHistoryController", object: nil)
}

func reloadHistoryController(notification: NSNotification){
    self.tableView.reloadData()
}

Update
dispatch_async(dispatch_get_main_queue(),{
        self.tableView.reloadData()
})

Doesn't help me too.

A: Please check your no. of rows count is same both time i.e. when you load firstviewcontroller and after save new record and press back button. I think your array which hold your data not initialized with new data you added. Please try to initialize your array data in viewWillAppear() method and then reload your tableview.


text:
Q: Why should they be thankful that it's not red? In Action Fantasy movie, The Last Witch Hunter (2015), Dolan 37th says to Kalduer when he sees Kalduer's car:

Dolan 37TH: Uh...I guess we should be thankful it's not red.

A: I believe the point is that the fancy sports car (an Aston Martin Rapide) is fairly conspicuous, which is not what Dolan wants.  However, he admits the situation could be worse; it could have been bright red, not black.

A: It is obviously meant to be sarcasm or being flabbergasted that the immortal highly-experienced killer employed by the church would use a car that doesn't helps at all to maintain secrecy.


text:
Q: Does the term 'eccentric screw pump' have weird associations? A progressing cavity pump is sometimes referred to as an eccentric screw pump, because it features a screw that turns abound an axis other than its center. 'Eccentric screw pump' yields many Google hits, while professionals seem to use the term 'PC pump'.
The German term would be Exzenterschneckenpumpe, so to me and to other Germans it may come naturally to translate this verbatim and arrive at eccentric screw pump. But 'eccentric screw' might also sound like a sex act. Does the term 'eccentric screw pump' have sexual connotaions to a native English speaker?

A: I'd say "yes" to "weird association" and "no" to "sexual connotations".
I don't think sex is particularly weird, though certainly if the sex you were having was an eccentric screw, I suppose that would be weird by definition.
The sense of eccentric referring to people who act weirdly, (applied to anything from mildly unusual habits through to severe but physically non-threatening mental problems) might be one reason to avoid the term, and would also lead to screw being more likely to be misread as referring to weird behaviour (c.f. screw-ball, screwy) than in a sexual sense.
That may have led to people preferring other terms that don't use eccentric, though it's hard to judge how much that was an influence and how much other factors are; progressive cavity pump is a good description of how it works, after all.

A: It might. However, you should consider that this is fairly specific terminology and consider where the phrase is going to be used. People who know or should know what an eccentric screw pump is should not see the usage of the term as weird. On the other hand, people who have no idea what you are talking about and have no interest in such details should probably be spared said details.