text:
Q: Tracking multiple control forms for individual processing in Angular Reactive Forms (Clean Code) I'm using Angular 11.0.2. I have a form group with 20 fields that are displayed in two tables. Some of this formControls are shared between two forms.
~9 of those formControls are text input fields that I would like to observe. When a value changes, I would like to fire an event. However, the tricky part is that there are 3 fields I would like to process individually (each in a different way). Therefore subscribing to the whole form group doesn't cut it. For the remaining 6 fields, I also need to know their field name, to process it further.
My ideas are:

*

*Subscribe to each formControl individually and create an update method for each of them. However, this will result in an abundance of fields and methods. Example in my TS class:

ngOnInit(): void {
    this.direction$ = this.weatherForm.get('direction').valueChanges.subscribe(() => this.updateDirectionChange());
    this.speed$ = this.weatherForm.get('speed').valueChanges.subscribe(() => this.updateSpeedChange());
}

*Use (change) event on each form control input field, passing the field name, and dealing with it within the TS calls with control flow. This one seems to make the template unnecessarily complex with logic. Example in my template:

    Direction

      <input-field>
        <input input class='weather-input-field' formControlName='direction' (change)='handleFieldChange("direction")'/>
      </input-field>

    Speed

      <input input class='weather-input-field' formControlName='speed' (change)='handleFieldChange("speed")'/>

However, none of those ways seems to be efficient or be "clean code" from my perspective.
Are there any better ways to handle it? If not, what would be your preferred solution?
Thank you in advance.

A: I like use some like
 const inputs=["one","four"]
 const $obs=merge(...inputs.map((input:string)=>
     this.form.get(input).valueChanges.pipe(
       map((res:any)=>({id:input,value:res})
       ))
  ))

$obs return an object in the way,e.g. {id:"one":value:"what-ever"}
But I feel that there're a better approach that is use ngModel in your form to change the value of the two formControls. So you can
<input [ngModel]="form1.get('one').value">
       (ngModelChange)="form1.get('one').setValue($event);
                        form2.get('one').setValue($event);
       [ngModelOptions]="{standalone:true}"/>

See how the input get the value of the formControl "one" and, when change, change the value of the formControl "one" of the form1, and the formControl "one" of the form2


text:
Q: How do I construct this SQL query correctly I want to return the rows in my database that have the attribute in one of the fields equal to the parameter to the method. My code is:
    public Cursor fetchStatus(String status){
    Cursor mCursor =

            mDb.query(DATABASE_TABLE, new String[] {KEY_COMPANY, KEY_POSITION, KEY_NOTES, KEY_WAGE, KEY_STATUS},
                    KEY_STATUS+ "= "+status, null, null, null, null)
            ;
    if(mCursor!=null) mCursor.moveToFirst();
    return mCursor;
}

I want to return the KEY_COMPANY, KEY_POSITION, KEY_NOTES, KEY_WAGE and KEY_STATUS columns where the KEY_STATUS is equal to the parameter 'status'

A: Use PreparedStatement.
You can simply specify your query and set parameters in search query.

A: Perhaps you may try something like this:
public object GetValues (string status)
{
   string query = "SELECT KEY_COMPANY, KEY_POSITION, KEY_NOTES, KEY_WAGE,KEY_STATUS
   FROM DATABASE_TABLE
   WHERE KEY_STATUS = "'" +status+ "'" " ;

   dbcomands part...

   List<object> =  execute db comand....
}

The error you specified in your comment might be caused by the lack of ' ' in you query. Just a thought.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to code for iterating through multiple files in linux? I have code which I am trying to update from another example. The aim is to run plink using files of: each chromosome, snp ids, and a file containing only 1 ID which is an individual's ID. Running these files in plink ultimately makes a vcf file per individual for a given chromosome.
I have 22 chromosome files, 1 snp file (which is always the same), and 500 individual files. For each individual I am aiming to make a vcf for each chromosome, so I have 22*500 (11000) vcf files as output.
With doing this at the moment I have tried a bash script with this:
ID=$SGE_TASK_ID
indiv=$SGE_TASK_ID

plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual${indiv}.txt

This runs, however it only runs through 1 individual, giving me 22 chromosome vcf files for that one person, and stops there. How do I make this run for all 500 people, would it be with a for loop? Looking through other questions I haven't been able to find one that matches my question and is in linux, any help would appreciated.
${indiv} would just be a number, so the text file that runs looks like individual1.txt and increases through the 500 individuals (individual1.txt, individual2.txt, individual3.txt)

A: Assuming that ${indiv} contains no spaces,
for indiv in $(<individuals.data); do
    plink [...] individual${indiv}.txt
done

The file individuals.data would name the individuals, separated by spaces or newlines.
If unsure what the Bash shell's $(<...) operator does, try this:
for A in $(<individuals.data); do
    echo "[$A]"
done

Note that, as @Kaz has observed, if wish your script to work also in shells other than Bash, then you might write $(cat ...) rather than $(<...)


text:
Q: Calling one method into another Here's an assignment I have to do for school:

*

*Create a new project named AreaCircle

*Copy the distance method from section 5.2

*Copy the area method for circles from the exercise 4.2. Change it to return the area, rather
than printing it.

*Create another area method for circles that takes two points (four integer parameters: x1, x2, y1, y2) and returns a double. Be sure both methods have the same name. Since the
parameters will be different, the one that is executed will depend on the parameters
passed. In this new area method, call the distance method to obtain the radius of the circle.
Then call the OTHER (original) area method to obtain the area of the circle.

*You will need to make a couple of changes so that you don't get a loss of precison compiler error.

*In main, prompt the user for four integers that represent a point on the outside of the circle and the center point of the circle (these will be used to find the length of the radius). Call the appropriate area method. Display the result.

I'm not sure if my code is right but obviously there is something wrong because it isn't working...
public static void main(String[] args) {
    Scanner reader;
    reader = new Scanner (System.in);
    System.out.println("Please enter the coordinates of a circle:");
    newLine();
    System.out.println("Outside point:");
    newLine();
    System.out.println("x1:");
    int x1 = reader.nextInt();
    newLine();
    System.out.println("y1:");
    int y1 = reader.nextInt();
    newLine();
    System.out.println("Center Point:");
    newLine();
    System.out.println("x2:");
    int x2 = reader.nextInt();
    newLine();
    System.out.println("y2:");
    int y2 = reader.nextInt();
}

public static void area(double radius, int x1, int x2, int y1, int y2)
{
    double areaCircle = (Math.PI * area(x1, x2, y1, y2) * area(x1, x2, y1, y2));
}

public static double area(int x1, int x2, int y1, int y2) {
   double radius = distance (x1, y1, x2, y2);
   return radius;
}

public static double distance(int x1, int y1, int x2, int y2)
{
    double dx = x2 - x1;
    double dy = y2 - y1;
    double dsquared = dx*dx + dy*dy;
    double result = Math.sqrt (dsquared);
    return result;
}

//NewLine Method
public static void newLine () {
    System.out.println ("");
}

A: As previously mentioned, your code never calls any of the calculation methods, meaning that they're never run and area etc. is never calculated. There isn't any code for displaying the result either.
In addition, the area method doesn't even return anything, meaning that it calculates the value and then discards it.

A: Your main didn't call any of the other methods!. Complete the code first.


text:
Q: Ruby - Get Mouse Coordinates How do I get the position of the mouse pointer in ruby?
This should be the absolute (screen) position.
If this requires a system specific answer, I'm on Ubuntu.
Thanks

A: I assembled the following function. It does a dispatch on the operating system and follows a different strategy for each OS:
require 'rbconfig'

##
# Returns an array [x,y] containing the mouse coordinates
# Be aware that the coordinate system is OS dependent.
def getMouseLocation
  def windows
    require "Win32API"
    getCursorPos = Win32API.new("user32", "GetCursorPos", 'P', 'L')
    # point is a Long,Long-struct
    point = "\0" * 8
    if getCursorPos.Call(point)
      point.unpack('LL')
    else
      [nil,nil]
    end
  end

  def linux
    loc_string = `xdotool getmouselocation --shell`[/X=(\d+)\nY=(\d+)/]
    loc_string.lines.map {|s| s[/.=(\d+)/, 1].to_i}
  end

  def osx
    # if we are running in RubyCocoa, we can access objective-c libraries
    require "osx/cocoa"
    OSX::NSEvent.mouseLocation.to_a
  rescue LoadError
    # we are not running in ruby cocoa, but it should be preinstalled on every system
    coords = `/usr/bin/ruby -e 'require "osx/cocoa"; puts OSX::NSEvent.mouseLocation.to_a'`
    coords.lines.map {|s| s.to_f }
  end

  case RbConfig::CONFIG['host_os']
  when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
    windows
  when /darwin|mac os/
    osx
  when /linux|solaris|bsd/
    linux
  else
    raise Error, "unknown os: #{host_os.inspect}"
  end
rescue Exception => e
  [nil,nil]
end

Tested on Ubuntu 13.04 (gnome-shell), Windows 7 64bit, OS x 10.8.4 . I'd be glad, if someone could confirm that this works on other systems. A jruby solution is missing, too.


text:
Q: How to delete all old indices without elasticsearch-curator? I want to delete the old(let say last 10 days) indices from elasticsearch without using curator. Is there any other way to delete all old indices?. (Is there a way to delete indices using Node.js)
Note: I have googled about it but did not find any proper answers and also many are using curator.

A: Why not just use the delete index API directly? https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html
In order to find which index is the oldest, in case there is no naming convention around the indices names or rollover, you can just check what is the min & max timestamp in each index, and then decide based on that which indices to delete. a simple query to get these timestamp from an index can be found here: What's the fastest manner to retrieve min timestamp from Elasticsearch indices?


text:
Q: CodeIgniter Message: "Class not found" on live server After pushing our local CodeIgniter environment (Windows) to a test server (Linux) we've ran into the following Exception:
An uncaught Exception was encountered
 Type: Error
 Message: Class 'ManagementStatus' not found
 Filename: ../LO_MaintenanceItem.php
 Line Number: 300
 Backtrace:
 File: ../LO_MaintenanceItem.php
 Line: 34
. . .

In this case 'ManagementStatus' is a model that extends LODatamapper, as defined here:
class ManagementStatus extends LODataMapper
{
    . . . .
}

In turn, LODataMapper is a class that extends DataMapper, as defined here:
abstract class LODataMapper extends DataMapper
{    . . .

What we've tried

*

*Turning it off- and on-again

*Checked for existence of class file

*Check for capitalization of file names (as suggested here)

*Compared PHP versions of local / testing (as suggested here)
Any idea what else we might try / what might be going on?

A: Please check the capitalization on your models. This is most likely your issue.
Only the first letter in the filename can be a capital.


text:
Q: How can I design slant buttons on CSS? I want to achieve this design using HTML and CSS. I've been trying for hours, but I'm not very good at CSS:

I have tried this code here, but I want to copy the button exactly as the design above.

body {
  font-family: "Lato", sans-serif;
  font-weight: 300;
}

.button-default {
  color: white;
  background-color: teal;
  text-align: center;
  text-transform: uppercase;
  padding: 5px 10px;
  margin: 10px;
  display: inline-block;
}

.button-slanted {
  -ms-transform: skewX(-20deg);
  -webkit-transform: skewX(-20deg);
  transform: skewX(-20deg);
}

.button-slanted-content {
  -ms-transform: skewX(20deg);
  -webkit-transform: skewX(20deg);
  transform: skewX(20deg);
  display: inline-block;
}

.button-fixedwidth {
  width: 100px;
}

  Slanted Button

  Slanted Button with super long text

  Slanted Button fixed width

Also on https://codepen.io/imohkay/pen/FCdsb
Can someone help me on this?

A: You could obtain the same result using pseudo elements and hidden worflow, please find an example below

    .btn-container {
      overflow: hidden;
      border: 1px solid transparent;
      padding: 0;
      width:45px;
    }
    .my-div {
      width:25px;

      position: relative;
    }
    .btn {
      border: 1px solid #ccc;
      background-color: #fff;
      padding: 10px;
      outline: none;
    }
    .btn:hover {
      background-color: #eee;

    }
    .btn:before {
      position: absolute;
        content: '';
        top: -5px;
        left: -10px;
        transform: rotate(-45deg);
        background-color: #fff;
        border: 1px solid #ccc;
        height: 10px;
        width: 30px;
    }

        <button class="btn">test</button>

Quote from MDN

In CSS, ::before creates a pseudo-element that is the first child of
the selected element. It is often used to add cosmetic content to an
element with the content property. It is inline by default.

all the best

A: You can Achieve that by using clip-path property play with clip-path
The black button is relatively easy to achieve but for white button, you have to play with drop-shadow

.container{
  display: flex;
  flex-direction: column;
  gap: 3rem;
  align-items: center;
}

.btn-black{
  clip-path: polygon(25% 0%, 100% 0, 100% 50%, 75% 100%, 0 100%, 0% 50%);
  background: black;
  border: none;
  color: #fff;
  padding: 2rem 5rem;

}

.btn-white-wrapper{;
  display: inline-block;
    filter: drop-shadow(0px 2px 0px #111) drop-shadow(2px 0px 0px #111) drop-shadow(-2px 0px 0px #111) drop-shadow(0px -2px 0px #111);
}

.btn-white{
  display: inline-block;
  clip-path: polygon(25% 0%, 100% 0, 100% 50%, 75% 100%, 0 100%, 0% 50%);
  background: white;
border: 0;
  color: #111;
  padding: 2rem 5rem;

}

    <button class='btn-black'>
    CLICK ME
  </button>

  <button class="btn-white">
    CLICK ME
  </button>

A: The basic outline and infill of the shape can be achieved by using background images which are a combination of linear-gradients.
Using CSS variables each type of button can define the colors it wants.
The two little squares can be added with before and after pseudo elements.
Here's an (almost complete) snippet to get you going. Obviously you'll want to play around with angles and so on to get exactly what you want:

.button {
  position: relative;
  width: 30vmin;
  height: 10vmin;
  display: flex;
  justify-content: center;
  text-align: center;
  align-items: center;
  font-size: 3vmin;
  font-family: sans-serif;

  --linew: 0.3vmin; /* the height of the border line */
  background-image: linear-gradient(-30deg, white, white 18%, var(--linecol) calc(20% - var(--linew)), black 20%, var(--bgcol) 20%, var(--bgcol) 78%, var(--linecol) 78%, var(--linecol) 80%, white 80%, white), linear-gradient(to left, var(--linecol) 0%, var(--linecol) var(--linew), var(--bgcol) var(--linew), var(--bgcol) calc(100% - var(--linew)), var(--linecol) calc(100% - var(--linew)), var(--linecol) 100%), linear-gradient(var(--linecol) 0%, var(--linecol) var(--linew), var(--bgcol) var(--linew), var(--bgcol) calc(100% - var(--linew)), var(--linecol) calc(100% - var(--linew)), var(--linecol) 100%);
}

.button1 {
  --linew: 0.3vmin; /* the height of the border line */
  --linecol: black;
  --bgcol: transparent;
}

div.button1.notalt::before, div.button2.notalt::before, div.button1.notalt::after, div.button1.notalt::after{
  content: '';
  width: 3vmin;
  height: 3vmin;
  position: absolute;
  background-color: black;
  box-shadow: inset 0 0 0 5px black, inset 0 0 0 8px white;/*should make relative!*/
  z-index: 1;
  }
div.button1.notalt::before, div.button2.notalt::before {
  top: 0;
  right: 0;
}

div.button1.notalt::after, div.button2.notalt::after {
  bottom: 0;
  left: 0;
}

.button2  {
  --linecol: black;
  --bgcol: black;
  color: white;
}

.textlink {
  --linecol: gray;
  --bgcol: gray;
}

a .textlink {
  color: orange;
}

Button1

Alt.Button1

Button2

Alt.Button2

Text Link


text:
Q: Infinite descending set sequence In ZFC theory, the axiom of regularity guarantees there's no infinite descending sequence. But it seems I found one. Define $x_n=\{n, x_{n+1}\}$, then it is obvious that $x_0\ni x_1\ni x_2\ni\cdots$. And to see why's no contradiction with the axiom. Take any set $x_i$, there are only two elements $i$ and $x_{i+1}$. Neither of them intersects with $x_i$.
So what's wrong with this construction?

A: The Axiom of Regularity says that, for any nonempty set $y,$ there is an element $x\in y$ such that $x\cap y=\emptyset.$ This axiom, in the presence of the other axioms of Zermelo-Fraenkel set theory (particularly the Axiom Schema of Replacement), implies that there is no infinite descending
$\in$-sequence.
For suppose there were a sequence $\langle x_n:n\in\omega\rangle$ such that $x_{n+1}\in x_n$ for each $n.$ Then, by Replacement, the range of that sequence would exist, i.e., the set $y=\{x_n:n\in\omega\}.$ Thus $y$ is a nonempty set, and $y\cap x\ne\emptyset$ for each $x\in y,$ since $x_{n+1}\in y\cap x_n.$ But this contradicts the Axiom of Regularity.

A: In order to define $x_n$ you need to know what is $x_{n+1}$. So the only way your sequence makes sense is if there is an infinite decreasing sequence of natural numbers.
Or, let me simply ask you this, what is the first element of the sequence, exactly?


text:
Q: How to ftp a file over to a server from PhoneGap/webapp? Is it possible to connect to a server and FTP a file from within PhoneGap application? Basically I suppose - is there a way to open an FTP connection with Ajax/JQuery somehow?

A: I don't think you will be able to FTP a file from PhoneGap however they do provide an API for transferring a file to a server using HTTP multipart encoding:
http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html#FileTransfer
You would need a script on the server in your chosen technology to receive the file however you should then be able to do whatever you like with it, including move it to the directory you are trying to FTP to

A: Ftp program for phone gap is here please see this bellow link.
https://github.com/macdonst/FtpClient


text:
Q: How do I estimate enemy strength? I am playing Heroes of Might & Magic IV and I have the problem that sometimes I engage an enemy army and get whacked. How can I know ahead of time whether an army is too strong for me, or what casualties I might suffer?

A: There is no golden rule, as too many factors can affect battle result.
But I can give a few hints on how one can understand battle difficulty:

*

*You should know number of creatures you are going to face. Without scouting skill / mods you can see only estimate size, which translates as (source):

Few 1-4
  Several 5-9
  Band 10-19
  Dozens 20-49
  Scores 50-99
  Company 100-249
  Hundreds 250-500
  Host 500-999
  Legion 1000-2499
  Thousands 2500+

*All creatures have level - from 1 to 4. It's rough estimate of creature power, let's say that creature of level 2 will always beat any level 1 creature without hero's bonuses in 1 on 1 fight. You should learn creature levels or use some cheatsheets for it - for example, Nature Creatures. It's not a good idea to attack Dozens of 4 level creatures without at least Band of your own level 4s.

*Learn creatures special abilities. There are lots of them and they are hard to remember, but you can always check them during battle. For example, Efreet has Fire Shield, which reflects some % of melee damage back to attacker, it's better to shoot Efreets from distance!

*Difficulty affects enemy tactics. For example, on next-after-normal difficulty enemy creatures begin to wait instead of rushing onto your army. Also with higher difficulty neutral creature packs become stronger, and sometimes strong packs prevent AI players from expanding.

*Fights against armies with heroes are always more dangerous as heroes provide bonuses to creature stats. Heroes itself can cause a lot of problems with smart use of artifacts / spells / potions.

*Armies inside towns have advantage because of walls and towers. So plan your sieges carefully.


text:
Q: I am trying to use python 3 instead of python 2 Currently in my mac terminal when I type python --version it says I am using python 2.7.x. I would like to change so that I am using python 3.8.x. How can I update this in terminal? Also, if I would like to go back to using python 2.7, is there a way to revert it?
Thanks!

A: *

*If Python 3 is installed, you should be able to run python3. If not, install the current distribution from their website.

*Python 2.7.x is always available via the alias python2.

A: brew install python3

will install python 3 and you can use python3 command to run 3x version of python. If you want to use python 2x version you could either use virtualenv or you could just use python2 to run your program with python 2x version.
If you want to implicitly specify that inside a file you could use
#!/bin/env python2.7

on top of the script to run the program with python 2.7 version.
As you see, there are many options for the same.


text:
Q: Do I add MouseListeners to the Canvas or to JFrame I was trying to add a mouseListener and a mouseMotionListener to my game and noticed that I can add them to the Canvas or to the JFrame. Do I add it to both or one of them?

A: What I recommend is using the Canvas.  When you are using a listener of any kind, think of where the actions will occur.  Do all of your updates happen on the frame or on the canvas?  If it is the latter, use the canvas to handle all of your action listener objects.
Another way to think of it is that the JFrame is just a window holding the implementation of your game.  Your graphic updates, keyboard inputs, mouse inputs, and any other functionality is done through the canvas.
For example, compare the JFrame and canvas to this image of Skyrim.  The window on the outside (A JFrame Object) has a close/minimize feature and the window holds the game screen (A Canvas Object).

A: Attach it to the Canvas
You should add the mouse listener to the canvas, there is one reason for it:
Coordinates.
If you attach mouse listener to the frame the 0-point of coordinates will be on the left-up corner of JFrame border. It will be hard to calculate the coordinates relative to canvas.
Instead of you can attach mouse listener to Canvas. The coordinates will be better with this. But do not forget to gain focus on canvas after adding listener:
canvas.addMouseMotionListener(motionListener);
canvas.requestFocus();


text:
Q: Problems with WordPress Query. How To Re-order? Is there way that you can order your WordPress query in so post display by the id oder set in the query? I was not able to find any additional information on the WordPress codex page that will show me how this can be done even if you set orderby to ID. Ideas?
$gp_query_args = array(
                // 'post_type'             => 'event',
                // 'meta_key'              => 'gp_event_date',
                // 'meta_value'            => date('Y/m/d'),
                // 'meta_compare'          => '>=',
                // 'orderby'               => 'meta_value',
                // 'order'                 => 'ASC',
                // 'posts_per_page'        => 4
                'post_type' => 'page',
                'post__in' => array(172, 173, 174, 21826),
                'post__not_in' => array(181),
                'posts_per_page' => 4,
                'orderby' => 'menu_order'

            );

A: You should be able to use the 'post__in' parameter in your orderby like so:
$gp_query_args = array(
            // 'post_type'             => 'event',
            // 'meta_key'              => 'gp_event_date',
            // 'meta_value'            => date('Y/m/d'),
            // 'meta_compare'          => '>=',
            // 'orderby'               => 'meta_value',
            // 'order'                 => 'ASC',
            // 'posts_per_page'        => 4
            'post_type' => 'page',
            'post__in' => array(172, 173, 174, 21826),
            'post__not_in' => array(181),
            'posts_per_page' => 4,
            'orderby' => 'post__in'

        );

This will display them in the order you list them in your post__in parameter line of the query. Check the last parameter in this list: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters


text:
Q: Python backup android application problem with decoding I'm writing a python script to make a Backup from an Android Application with adb:
os.system("adb backup -apk -nosystem " + app_identifier)
Than I m trying to parse the .ab file with python into tar so I can open it:
os.system( "dd if=backup.ab bs=1 skip=24 | python -c \"import zlib,sys;sys.stdout.write(" + "zlib.decompress(sys.stdin.read()))\" > backup.tar" )
Sometimes this works and sometime I'm getting following error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.10/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xda in position 1: invalid continuation byte

Do you know why this error pops? As I said sometimes it works, sometime not.
Asked google, it shows me results for other context.
Reinstalled python, reconnected android phone, ran the command in console

A: Rather than using python to pipe a command into a new python interpreter, consider reading the file into a bytes object. You can do this using the open function (make sure to set mode="rb" to avoid decoding errors). The error you are hitting is because stdin is opened in text mode, which expects all input to be valid text, but you're reading in non-text (tarball) data.
For example:
with open("backup.ab", "rb") as input_file:
    input_data = input_file.read()
with open("backup.tar", "wb") as output_file:
    output_file.write(zlib.decompress(input_data))

You may find that your code is faster without using Python at all. For simple tasks like this, a simple shell script may be more suited (but less portable).


text:
Q: How to Empty the IMAP trash folder I have an iPhone 5s with iOS 8. There are about 80,000 emails in an IMAP trash folder. How do I get rid of these emails?
Perhaps my phone was set up incorrectly but I have no reason to want to keep these.

A: The setting that you are looking for is buried in advanced mail settings.
Open Settings > Mail, Contacts, Calenders > (Choose the IMAP account in question) > (choose it again) > Advanced
This screen will have a section titled "Deleted Messages", Set "Remove" to an option other than "never".
For what it's worth, it's the mail client, not the mail server, that is responsible for cleaning up the trash folder.  The client is the program or app that you use to read email, in this case your iPhone.  Many people have problems with this setting when using multiple clients, such as an iPhone, iPad, and Mac or PC at the same time.  In that case if the clients don't all have the same thing for this setting, whichever has the shortest time period is the device that will prevail.
Note: changing the setting should fix your issue, although it might not be an instant fix. I'm not positive how it will behave with 80,000 trash emails to cleanup.
Alternate: A more immediate method appears to be, open mail which will open your inbox, back up one screen by clicking whatever is the the top left (likely the account name, it will vary depending on how your phones is setup), then in the Accounts section choose your "Account" (not your Inbox for that account), from there select the trash folder, click "Edit" on the top right, and then "delete all" in the bottom right,  and "delete all" again to confirm.  Also be sure to adjust the advanced setting above so that in the future your trash folder will be maintained automatically for you.

A: *

*Open Inbox >> Edit >> Mark All >> Mark As Read

*Open Inbox >> Edit >> Check/select the top message; it will highlight the move button.

*Press and hold the move button and uncheck the message that you had checked earlier.

*Lift all your fingers off from the ipad screen and leave it alone. Wait until all your messages pile up on the right hand portion of the screen (in ipad); iphone will give you the actual number of emails it has selected for the action. Now they are just waiting for your command to be moved ALL at once.

*Choose trash to delete all of them or any other folder where u want to move them, like one piece. Remember this will replicate your action on the server so you will ACTUALLY move them or delete them on the server and not just the ipad.

Once you have moved all messages to the trash you can either leave them there for the scheduled cleaning or empty it right away by doing this: go to trash folder and touch Edit. The Delete All button shows up at the bottom of the screen. Hit it! You're done!
If you do not see the effects of your actions on the server make sure you have enabled your email accounts for such actions.


text:
Q: Adding mavenCentral() to build.gradle file I create my Android Project on Android Studio 3.0.1 , and Now I try to Open it in
Android Studio 3.5.3 to do that I Added this :
 mavenCentral()

 maven { url 'https://maven.google.com' }

to build.gradle file for Project in repositories two Parts (buildscript / repositories) and (allprojects/repositories) .
My Question is : Does the app need to test all its features again??

A: For manual update:
buildscript {
          ...
          dependencies {
            classpath 'com.android.tools.build:gradle:3.5.3'
          }
        }

No need to test anything because of gradle version change! But if downgrade the version then you might be change your some api,dependencies for lower gradle version.
Gradle:
Gradle is an advanced build toolkit for android that manages dependencies and allows you to define custom build logic. features are like. Customize, configure, and extend the build process. Create multiple APKs for your app with different features using the same project. Reuse code and resources.
And more about gradle: Link


text:
Q: SSD_MOBILENET V1 to TensorRT in Tensorflow 1.6 Folks,
I have a Jetson TX2 with tensorflow 1.6 and jetpack 3.2 (tensorrt 3.0) installed. I installed UFF as well.
How can I convert the ssd_mobilenet_v1 frozen graph from tensorflow into tensorRT equivalent?
Thanks,

A: Visit the github repo: https://github.com/NVIDIA-AI-IOT/tf_to_trt_image_classification
Follow the instructions, it should help you out.
You should convert the frozen graphs to a plan(TensorRT Engine equivalient) and then serialize it, while performing inference you deserialise the TensorRT engine and perform inference.


text:
Q: Comparison two files Can anyone create a shell script that would compare two files and return discrepancies from both the files.
One file is having five paragraphs and another file is having three paragraphs common from first file. But the comparison has to happen with appropriate paragraph.
I have tried with diff -y file1 file2 | grep "|" to identify discrepancies, but the result is inconsistent (line to line comparison but inconsistent comparison because of missing line in between).

A: diff -y file1 file2 | grep ' [|<>] '


text:
Q: Mutable with logic inside or immutable with logic outside? I know immutable objects are preferred to mutable objects for reasoning and maintenance. But in occasions making a class immutable have some costs, let me explain it with a simple example:
class Mutable
{
    private int i;
    public Mutable(int _i) { i = _i}
    public void Print() // impure function
    {
         print(i);
         i++;   // logic inside
    }
}

... caller

Immutable m = new Mutable(1);
while (true)
{
    m.Print();
}

I call it mutable because its internal state changes and Print varies on each call.
Versus.
class Immutable
{
    private int i;
    public Mutable(int _i) { i = _i}
    public int Print() // pure function
    {
         print(i);
         return i;  // returns its state
    }
}

... caller
int i =1;
while (true)
{
    Immutable im = new Immutable(i);
    i = im.Print(); // get the previous obeject's state
    i++; // logic outside
}

Preferring immutable solution make me to do a lot of work outside of an object which was supposed to encapsulate that logic.

My actual problem (you may skip the example below)
I have a class which draws a text in a box:
class TextDrawer
{
   private string text;
   private Rectangle box;
   public TextDrawer(_text, _box) {...}
   public void DrawTextInBox()
   {
   }
}

It is probable that the Text overflows from the box and part of it wasn't written. I should know the remaining unwritten part to draw it in a new box.(in fact I take an snapshot of the old box as a video frame and need to make a new frame for the remaining text to make a video of the text)
Now I have two options:
1- Make the TextDrawer mutable (its internal state is mutable) and DrawTextInBox a non-pure function and on each call it draws the remaining part of text in the box.
class TextDrawer
{

   private string text;
   private Rectangle box;
   private string remaining;

   public TextDrawer(_text, _box)
   {
      remaining = text = _text;
      box = _box;
   }
   public void DrawTextInBox()
   {
      draw as you can from remaining
      update remaining part;
   }
}

2- Keep the TextDrawer immutable and DrawTextInBox a pure function which returns the remaining part, then the caller should keep track of the remaining and pass it again to the TextDrawer or instantiate a new TextDrawer by the remaining text until there is nothing to write.
class TextDrawer
{
   private string text;
   private Rectangle box;
   public TextDrawer(_text, _box) { ... }
   public string DrawTextInBox()
   {
       draw as you can from text;
       return remaining part;
   }
}

The second approach is immutable but actually shifts the responsibility of tracking the remaining part outside of the class. The first approach is mutable, but it encapsulates the logic and just need a call to DrawTextInBox to draw the remaining part.

Question: The logic of the above examples was simple but this logic could be more complex, then I don't know whether to extract this logic from a class in order to make it immutable or let it be mutable and have the logic inside?

A: In your example:
int i =1;
while (true)
{
    Immutable im = new Immutable(i);
    i = im.Print(); // get the previous obeject's state
    i++; // logic outside
}

Immutable should return the new state that the mutable solution would've stored, i.e. i + 1. You already have the old state. Returning the old state and forcing the caller to update the state himself is pointless. You did this correctly in your real problem, where you return the remaining part of the string instead of the original string.
You should prefer an immutable solution unless you have good reasons otherwise. A good reason may be that the immutable solution is too slow, but first you have to clearly define what's "fast enough" and profile the application to show that the bottleneck is your immutable class and that the mutable alternative will solve the problem.


text:
Q: Value of this inside arrow function inside an Object I thought I understood the relationship between this and arrow functions but the following snippet is making me question my understanding.
let person = {
  name: 'Jim',
  sayName: () => {
    console.log(this.name);
  }
};

person.sayName();

I understand that arrow functions capture the this value of the enclosing context. I was expecting this would be the object but instead it is Window.
Can someone help me understand why this is the case?

A: TLDR;
Think of it this way, "if I used non arrow function, what would be this" From that you can then recall that this in an arrow function would be the more outer scope this compared to its counterpart.
Example

let arrow = {
  test: () => {
    console.log('arrow: this === window...', this === window);
  }
};

let nonarrow = {
  test: function() {
    console.log('non-arrow: this === window...', this === window);
  }
};

arrow.test()
nonarrow.test();

A: There is no binding of "this", so here is a working version of what you tried:
let person = {
  name: 'Jimmy the Greek',
  sayName: (obj) => {
    console.log(obj.name);
  }
};

person.sayName(person);

More to read on Mozilla DEV.

A: Your understanding of arrow functions is mostly correct: Arrow functions have a lexical this and its value within the arrow function is determined by the surrounding scope.
You probably assume that this gets a different value within the person object literal. This is not the case.
So let's see what this refers to in your (global) scope:

console.log(this === window); // true

let person = {
  name: 'Jim',
  test: console.log(this === window), // true
  sayName: () => {
    console.log(this === window); // true
  }
};

person.sayName();

As you can see, when the arrow function assigned to sayName is created, this refers to the window object.


text:
Q: Android ontouchlistener counter implementation I have set ontouch listener to implement a counter for my imagebutton. But I can only detect button being touched and release. I am not sure how to implement incrementing as long as the button is pressed and how to stop it after it is released. Following is the code I have:
up.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
       if (event.getAction()==MotionEvent.ACTION_DOWN) {
        pressdown();
    }
       else if (event.getAction()==MotionEvent.ACTION_UP) {
        pressrelease();
    }
       return true;
    }

A: Ok. Here's a solution to my own question. It might help someone else.
use a Handler object because you have to implement a separate thread for incrementing/decrementing
       public class MainActivity extends Activity{

       private boolean autoIncrement = false;
       private boolean autoDecrement = false;
       private final long REPEAT_DELAY = 50;
       private Handler repeatUpdateHandler = new Handler();

       @Override
        protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input);

        class RepetitiveUpdater implements Runnable{

         @Override
         public void run() {
         if (autoIncrement) {
         increment();
             repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
        }
         else if(autoDecrement){
         decrement();
             repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
        }
    }

     }
                up.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            increment();
         }
         });

                up.setOnLongClickListener(new OnLongClickListener() {

          @Override
          public boolean onLongClick(View v) {
          autoIncrement = true;
          repeatUpdateHandler.post(new RepetitiveUpdater());
          return false;
            }
            });

                up.setOnTouchListener(new OnTouchListener() {
                   @Override
           public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction()==MotionEvent.ACTION_UP && autoIncrement ){
                autoIncrement = false;
                     }
         return false;
          }
        });

               public void increment(){
       if (i<100) {
           i++;
           TextView no = (TextView)findViewById(R.id.no);
       no.setText(String.valueOf(i));
    }

}

    }

Do the same for decrement.
Courtesy: Github, author: Jeffrey F. Cole


text:
Q: Selenium Java - How to outsource @Config and call tests from an extern class? I'm sure, this question can be answered very quickly by a experienced Java-developer. But as I am not that familiar with Java I don't get how to source out the @Config part of Selenium in Java. It would be optimal, if I could have a config-file or -class where I can put the data (browser, website etc.) on the one hand and on the other hand the test-files.
Here is an example of a test file:
package com.example_test.selenium;

import io.ddavison.conductor.Browser;
import io.ddavison.conductor.Config;
import io.ddavison.conductor.Locomotive;
import org.junit.Test;

@Config(
        browser = Browser.CHROME,
        url     = "http://example.com"
)

public class test_a_Home extends Locomotive {
    @Test
    public void testifExists() {
        validatePresent(site_a_Home.EL_NEWCUSTOMERBANNER);
    }
}

Now I would like to have a seperate file called tests.java where I can call the "test_a_Home"-function. If I try it just with
package com.example_test.selenium;

public class tests {
    test_a_Home test = new test_a_Home();

    test.testifExists();

}

I am receiving the error, that "testifExists()" cannot be resolved.
I tried changing the public void testifExists() to public int testifExists() and tried to call it with int res = test.testifExists(); in the class tests but this does not work either, as I receive the error java.lang.Exception: Method testNewCustomersBannerExists() should be void.
I would be very happy, if anyone could help me. If you need more information please feel free to mention it. Thank you.

A: If you want your design to be like this, then you need to organize your tests as such:
public class BasePage {
    public Locomotive test;
    public BasePage(Locomotive baseTest) {
        test = baseTest;
    }
}

public class test_a_Home extends BasePage {
    public test_a_Home(Locomotive baseTest) {
        super(baseTest);
    }

    public void testifExists() {
        test.validatePresent(site_a_Home.EL_NEWCUSTOMERBANNER);
    }
}

Then your test class, i'd recommend creating a base class as well:
@Config(
    browser = Browser.CHROME,
    url     = "http://example.com"
)
public class BaseTest extends Locomotive {}

And then your test class:
public class tests extends BaseTest {
    test_a_Home test = new test_a_Home(this);

    @Test
    public void testHomePage() {
        test.testIfExists();
    }
}

Also you state state:

I don't get how to source out the @Config part of Selenium in Java.

Please make sure you know, that using Conductor abstracts you from the Selenium API.. It just wraps it.  @Config does not belong to Selenium, it belongs to Conductor.


text:
Q: Multiple TempData variables passed to same action I'm creating ASP.NET web application using MVC and Entity Framework. I have two different success messages I am passing to an index action for when a user clocks in or clocks out. The success message will print correctly when a user clocks in, but will not when a user clocks out for some reason.
The actions are very similar and I used all of the same conventions so I can't figure out why one would print and another would not. I've tried debugging and there are no red flags and everything updates in the database like it should. Is it not possible to pass multiple TempData variables to the same action?
Here is the relevant code:
Controller
        // GET: TimeClocks
    public ActionResult Index()
    {
        ViewBag.ClockInSuccess = TempData["ClockInSuccess"];
        ViewBag.ClockOutSuccess = TempData["ClockOutSuccess"];
        return View();
    }
    [HttpPost]
    public ActionResult ClockIn(TimeClock timeClock)
    {
        if(db.TimeClocks.ToList().Count == 1)
        {
            ModelState.AddModelError("ExistsError", "You already clocked in at" + timeClock.ClockIn);
        }
        string currentUserId = User.Identity.GetUserId();
        ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
        timeClock.ApplicationUser = currentUser;
        timeClock.ClockIn = DateTime.Now;

        if (ModelState.IsValid)
        {
            db.TimeClocks.RemoveRange(db.TimeClocks.ToList());
            db.TimeClocks.Add(timeClock);
            db.SaveChanges();
            TempData["ClockInSuccess"] = "You clocked in successfully at " + timeClock.ClockIn;
            return RedirectToAction("Index");
        }

        return RedirectToAction("Index", timeClock);
    }
    [HttpPost]
    public ActionResult ClockOut(TimeClock timeClock)
    {
        timeClock = db.TimeClocks.FirstOrDefault();
        if(timeClock.ClockIn == null)
        {
            ModelState.AddModelError("NullError", "You must clock in before you can clock out.");
            return RedirectToAction("Index");
        }
        timeClock.ClockOut = DateTime.Now;

        if (ModelState.IsValid)
        {
            db.Entry(timeClock).State = EntityState.Modified;
            db.SaveChanges();
            TempData["ClockOutSuccess"] = "You clocked out successfully at " + timeClock.ClockOut;
            return RedirectToAction("Index");
        }
        return RedirectToAction("Index", timeClock);
    }``

View
@model FinalProject.Models.TimeClock

@{
    ViewBag.Title = "Create";
}

Employee Time Clock

@using (Html.BeginForm("ClockIn", "TimeClocks"))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <input type="submit" value="Clock In" class="btn btn-lg" />

}
@using (Html.BeginForm("ClockOut", "TimeClocks"))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <input type="submit" value="Clock Out" class="btn btn-lg" />

}
@{
    if (@ViewBag.ClockInSuccess != "")
    {

@ViewBag.ClockInSuccess

    }
    else if (@ViewBag.ClockOutSuccess != "")
    {

@ViewBag.ClockOutSuccess

    }
}

    @Html.ActionLink("Back to List", "Index")

A: TempData is lost once you read it so you need to do a Peek or a Keep:
ViewBag.ClockInSuccess = TempData.Peek("ClockInSuccess");
ViewBag.ClockOutSuccess = TempData.Peek("ClockOutSuccess");

http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion


text:
Q: Check what tkinter OptionMenu item was selected How do you check if the user has selected "Other" from the hopOptions selection, and then enable otherEntry if they did? And then disable it again if they select one of the other options.
    class Interface():
        def __init__(self, window):
            frame = Frame(window)
            frame.pack()

            self.hopLabel = Label(frame, text="Hop:", anchor=E)
            self.hopLabel.grid(row=0, column=0, sticky=EW)

            hops = range(0,6)
            hops.append("Other")

            self.selectedHop = StringVar(frame)
            self.selectedHop.set(hops[0])
            self.hopOptions = OptionMenu(frame, self.selectedHop, *hops)
            self.hopOptions.grid(row=0, column=2, sticky=EW)

            self.otherEntry = Entry(frame, state=DISABLED)
            self.otherEntry.grid(row=0, column=1, sticky=EW)

    root = Tk()

    app = Interface(root)

    root.mainloop()

A: Bind the option menu to a command and add another method to your class. The command will run the class method with the value as an argument anytime an option is changed in the menu. There you can do validation to update the otherEntry widget. Also I would advise not doing from Tkinter import * as it appears that's what you've done. Generally importing an entire package could have conflicts with your namespace. This should suit your needs:
from Tkinter import *

class Interface():
        def __init__(self, window):
            frame = Frame(window)
            frame.pack()

            self.hopLabel = Label(frame, text="Hop:", anchor=E)
            self.hopLabel.grid(row=0, column=0, sticky=EW)

            hops = range(0,6)
            hops.append("Other")

            self.selectedHop = StringVar(frame)
            self.selectedHop.set(hops[0])
            self.hopOptions = OptionMenu(frame, self.selectedHop, *hops, command=self.optupdate)
            self.hopOptions.grid(row=0, column=2, sticky=EW)

            self.otherEntry = Entry(frame, state=DISABLED)
            self.otherEntry.grid(row=0, column=1, sticky=EW)

        def optupdate(self, value):
            if value == "Other":
                self.otherEntry.config(state=NORMAL)
            else:
                self.otherEntry.config(state=DISABLED)

if __name__ == "__main__":
    root = Tk()
    app = Interface(root)
    root.mainloop()

A: As an alternative to iChar's command approach, Use selectedHop.trace to register a function that will be called whenever the selected item changes.
from Tkinter import *

class Interface():
    def __init__(self, window):
        frame = Frame(window)
        frame.pack()

        self.hopLabel = Label(frame, text="Hop:", anchor=E)
        self.hopLabel.grid(row=0, column=0, sticky=EW)

        hops = range(0,6)
        hops.append("Other")

        self.selectedHop = StringVar(frame)
        self.selectedHop.set(hops[0])
        self.selectedHop.trace("w", self.selected_hop_changed)
        self.hopOptions = OptionMenu(frame, self.selectedHop, *hops)
        self.hopOptions.grid(row=0, column=2, sticky=EW)

        self.otherEntry = Entry(frame, state=DISABLED)
        self.otherEntry.grid(row=0, column=1, sticky=EW)

    def selected_hop_changed(self, *args):
        value = self.selectedHop.get()
        if value == "Other":
            self.otherEntry.config(state=NORMAL)
        else:
            self.otherEntry.config(state=DISABLED)

root = Tk()

app = Interface(root)

root.mainloop()


text:
Q: Does inserting an element in vector by re-sizing the vector every time takes more time? I got a decision making problem here. In my application, I need to merge two vectors. I can't use stl algorithms since data order is important (It should not be sorted.).

*

*Both the vectors contains the data which can be same sometimes or 75% different in the worst case.

*Currently I am confused b/w two approaches,
Approach 1:

   a. take an element in the smaller vector.
   b. compare it with the elements in bigger one.
   c. If element matches then skip it (I don't want duplicates).
   d. If element is not found in bigger one, calculate proper position to insert.
   e. re-size the bigger one to insert the element (multiple time re-size may happen).

 Approach 2:

   a. Iterate through vectors to find matched element positions.
   b. Resize the bigger one at a go by calculating total size required.
   c. Take smaller vector and go to elements which are not-matched.
   d. Insert the element in appropriate position.

Kindly help me to choose the proper one. And if there is any better approach or simpler techniques (like stl algorithms), or easier container than vector, please post here. Thank you.

A: You shouldn't be focusing on the resizes.  In approach 1, you should use use vector.insert() so you don't actually need to resize the vector yourself.  This may cause reallocations of the underlying buffer to happen automatically, but std::vector is carefully implemented so that the total cost of these operations will be small.
The real problem with your algorithm is the insert, and maybe the search (which you didn't detail).  When you into a vector anywhere except at the end, all the elements after the insertion point must be moved up in memory, and this can be quite expensive.
If you want this to be fast, you should build a new vector from your two input vectors, by appending one element at a time, with no inserting in the middle.

A: Doesn't look like you can do this in better time complexity than O(n.log(n)) because removing duplicates from a normal vector takes n.log(n) time. So using set to remove duplicates might be the best thing you can do.
n here is number of elements in both vectors.

A: Depending on your actual setup (like if you're adding object pointers to a vector instead of copying values into one), you might get significantly faster results using a std::list.  std::list allows for constant time insertion which is going to be a huge performance overhead.
Doing insertion might be a little awkward but is completely do-able by only changing a few pointers (inexpensive) vs insertion via a vector which moves every element out of the way to put the new one down.
If they need to end up as vectors, you can then convert the list to a vector with something like (untested)
std::list<thing> things;

//efficiently combine the vectors into a list
//since list is MUCH better for inserts
//but we still need it as a vector anyway

std::vector<thing> things_vec;
things_vec.reserve(things.size()); //allocate memory

//now move them into the vector
things_vec.insert(
    things_vec.begin(),
    std::make_move_iterator(things.begin()),
    std::make_move_iterator(things.end())
);

//things_vec now has the same content and order as the list with very little overhead


text:
Q: Generate $1$, ...,$ n$ as pairwise differences of a set of numbers Given $n \in \mathbb N$, I'm interested in sets $S \subset \mathbb Z$ such that the numbers $1$, $2$, ..., $n$ can be obtained as differences between pairs of elements in $S$.
I'd like to find the minimum size of $S$ given $n$. Call that $f(n)$. I'd also like to know if the sets $S$ can be restricted to be of the form $S \subset \{1,2,...n+1\}$ without loss of optimality (where "optimality" means smallest size).
For example, $f(6) = 4$ (found by exhaustive search). One optimal set for $n=6$ is $\{1,2,5,7\}$ (note that $2-1=1$, $7-5=2$, $5-2=3$, $5-1=4$, $7-2=5$ and $7-1=6$). This set is of the form $S \subset \{1,2,...n+1\}$.
So, my questions are:

*

*Is there some formula for $f(n)$, or an algorithm to construct an optimal $S$?

*Can a minimum-size set always be found that is a subset of $\{1,2,...,n+1\}$?

Even if the answers are not known, any pointer in these directions will be helpful.


text:
Q: How to index R matrix without it reverting to vector I declared a 1 by 6 matrix A by saying:
A <- matrix(1:6, nrow=1)

I then do dim(A) and as expected I get 1 by 6...but then I do A[,2:5] and I would expect that to be a matrix of dimension 1 by 4 with entries 2,3,4,5...but instead dim( A[,2:5] ) gives me NULL! it degraded into a vector or something. How can I avoid this?
I am ultimately trying to do something like:
A[,a:b] %*% X[a:b,a:b] %*% t(A[,a:b])

varying a and b so I can multiply only parts of the above matrices together..but this breaks when A decays into a vector...
Thanks

A: Use ,drop=FALSE as an additional (trailing) argument to involving ].
Example:
R> M <- matrix(1:4,2,2)
R> M[,2]                  ## looses matrix class
[1] 3 4
R> M[,2,drop=FALSE]       ## forced to a n x 1 matrix
     [,1]
[1,]    3
[2,]    4
R>

This may well be the main FAQ, but for compatibility reasons the behaviour is unlikely to change.


text:
Q: How can I convert str to bytes I have numbers of UTF-8 Bytes numbers
I want to convert these numbers to bytes to decode(utf-8)
uniA = 0xea
uniB = 0xb0
uniC = 0x80

ans = '\\x'+str("{0:x}".format(uniA))+'\\x'+str("{0:x}".format(uniB))+'\\x'+str("{0:x}".format(uniC))+''
print(ans)
>>> \xea\xb0\x80

I want to get ans.decode('utf-8)

A: You want to convert int objects to the corresponding bytes object, which is directly supported by bytes, by providing it an iterable of int objects, e.g. a list:
>>> uniA = 0xea
>>> uniB = 0xb0
>>> uniC = 0x80
>>> type(uniA)
<class 'int'>
>>> bytes([uniA, uniB, uniC]).decode('utf8')
'가'

A: The following will get a byte string that you can decode:
ans = bytes([uniA,uniB,uniC])
print(ans.decode('utf8'))


text:
Q: When calling a spring Non-Transactional method from a Transactional Method in another instance, does the transaction get propagated? Sorry if this has been discussed before, but I just could not find the answer in all the related discussions on @Transactional spring java annotation.
What happens if we call a method in another instance that does not have an @Transactional annotation from a method that has an @Transactional annotation? will the transaction from the @Transactaional annotated method be suspended? or would it be propagated?
I found a lot of discussions on if the call to the 2nd method is from the same instance, but not if the 2nd non-transactional method is in another instance. Thank you for your help!
Like in the example below, what would happen if methodb() in class B is called from methoda() in class A? Would the transaction from methoda be propagated or would methodb be non-transactional?
Example code below:
public class A
{

@Autowired
B b;

@Transactional
public void methoda(){

  b.methodb();

}

}

@Component
public class B
{
//this method is non transactional and is called from method A in class A
public void methodb()
{
  //do some db updates
}

}

A: If there are no @Transactional annotations in B to tell it otherwise, then the b method uses the transaction established in the call to A.methoda. This is normal for Spring, we have components marked transactional that call DAOs that participate in the current transaction without being marked transactional themselves.
If you really want to suspend the current transaction, you can add this annotation to the b method:
@Transactional(propagation = Propagation.NOT_SUPPORTED)

There is a caveat about suspending transactions in the Spring API doc:

NOTE: Actual transaction suspension will not work out-of-the-box on all transaction managers. This in particular applies to JtaTransactionManager, which requires the javax.transaction.TransactionManager to be made available to it (which is server-specific in standard Java EE).


text:
Q: Flash AS2.0 - Increase Label's Font Size I know this sounds like a really obvious question, but it's proving harder to figure out than I thought. I'm developing in Flash 8/ActionScript 2.0.
I have a label component, and I'm dynamically assigning it text from an xml document. For example:
label.text = "" + xml_node.firstChild + "";

This successfully changes the label's text to whatever is in that XML node, and since I enabled HTML, it makes it bold. However, I want to increase the size of the label's font, and using  tags won't work.
Am I missing something? How do I make the font larger? ActionScript is just so picky!

A: When you say "label component", do you mean a Flex 2 label, or a TextField?
In the latter case, the font tag should work just fine.  will set the font to 24px text for example. If it doesn't, you can use the stylesheet class to specify a font size and then assign it to the TextField.
In the case of of Flex 2 label, use label.setStyle("fontSize", 24) to set it to 24px text for example.

A: Thanks for everyone's input! After reading David Arno's post, I figured it out. Here's what I was doing.
label.text = "" + xml_node.firstChild + "";

Here's what works:
//note the 'single quotes' around the 24
label.text = "" + xml_node.firstChild + "";

I just tried different ways of typing 24 in there, and the single quotes worked. Also, don't forget to set HTML to true from the label's Parameters tab.

A: I can't say for sure but I think you probably need to set the fontSize style of the Label.

A: The font tag will really only work if you have a web ready font like Arial, Verdana, or Times New Roman and even then it's still kinda goofy. A lot of times AS will usually just ignore the font tag, at least that's what I've run into. If you want to format your text I'd use the TextFormat class to manipulate your text instead of trying to set it through HTML tags. Unless you're setting the HTML tags because it's really being formatted with CSS?
In that case I'd go through and make absolutely sure that your textfield is set up for HTML tags. Instead of using label.text I would try to use label.htmlText? It really could be any number of issues...


text:
Q: Regular Expression to replace " {" with "(newline){" in xcode I need to change my coding style of putting opening braces in same line to new line. I need to find and replace the (space){ with (newline){. I heard using regular expression find and replace, its pretty simple.
Could anyone help me on this?

A: You could try the following:

*

*In the Find box, type space \ { $

*In the Replace box, type control+q return {
control+q is needed to quote the return key. There's no visual feedback for typing control+q return, so the only visible character in the replace box is the opening curly brace:

Although this answers your question, there's (at least!) one problem: it won't indent the opening curly brace, so something like
- (void)method {
    for (obj in collection) {
        NSLog(@"%@", obj);
    }
}

is converted to
- (void)method
{
    for (obj in collection)
{
        NSLog(@"%@", obj);
    }
}

The menu item Edit > Format > Re-Indent will place the opening curly braces in the correct indentation tab but there might be non-desired side effects to your code style.

Edit: as commented in the other answer, you might want a regular expression that matches an arbitrary number of whitespaces surrounding the curly brace, e.g. \s*{\s*$

A: Just copy an example of needed replacement string (new line or else) from code to replacement box.

A: search for this \s\{ and replace with \n\{
Your editor needs to support regular expressions in both search and replace fields.  If you can't use the \n in the replace dialog because it takes the string literally, try a option-enter followed by {, that works in most editors I tried.

*

*the \s is a space character (if there
could be more spaces you can use \s+)

note it has to be \s+ instead of \s* as someone fixed because indeed \s* also matches in case there is no space.

*

*the \{ needs the backslash because {
needs to be escaped as it has another
meaning in a regex

*the \n is for a newline

The best way however would be to reformat your code where you choose to have your { on a new line.  Most editors allow you to set these options.
Another way is to use a code beautifier, you can google these online and some allow to change settings like that.

A: You can use [\n\r] to describe newline
It's a shame, I came across with that when I tap on magnifier icon next to search bar while finding something in a single file.
To see several other expressions:

*

*go to a file

*do cmd+f and open search

*tap on the magnifier icon at the left-hand side of search field at the top

*you can see other expressions in the dropdown menu

A: i searched a while to find out, that you have to enable the find options for regular expressions first on the small magnifier glass in the left side of the find-input field ;)


text:
Q: Accessing a member of struct in class, LinkedList Node So I am just starting out learning LinkedLists for C++. I know C+ has a library for them but I'm trying to focus on LinkedLists. An exercise I saw asks you to design a linked list class with 2 member functions and a default constructor: add, isMember, and the LinkedList() constructor. Add function adds a new node to the front of the list. isMember tests to see if the list contains a node with the value passed in to add.
My issue is, I am creating the ListNode *head in the struct, then I try to access it in the LinkedList constructor to set it to null, it is throwing me the error of "undeclared identifier". even if I set it to NULL in the struct it gives me the same error. The error goes away if I write "ListNode *head = NULL" in the constructor, but then my add method is still going crazy over the use of the "undeclared identifier" head.
Here's what I got so far:
LinkedList.h:
class LinkedList
{
protected:
    struct ListNode
    {
        double value;
        ListNode *next;
        ListNode(double value1, ListNode *next1 = NULL)
        {
            value = value1;
            next = next1;
        }
        ListNode *head;
    };
    // Public Interface
public:
    // Class Constructor(s)
    LinkedList();

    // Methods
    void add(double x);
    bool isMember(double x);

    // Private Class Members
private:
};

LinkedList.cpp:
#include "stdafx.h"
#include "LinkedList.h"  // Class Definition file

// Class Default Constructor
LinkedList::LinkedList()
{
    head = NULL;
}

// Class Destructor
LinkedList::~LinkedList(void)
{
    ListNode *nodePtr;
    while (nodePtr != NULL)
    {
        ListNode *garbage = nodePtr;
        nodePtr = nodePtr->next;
        delete garbage;
    }
}

void LinkedList::add(double x)
{
    ListNode *nodePtr, *prevNodePtr;
    if (head == NULL || head->value >= x)
    {
        head = new ListNode(x, head);
    }
    else
    {
        nodePtr = head->next;

        while (nodePtr != NULL && nodePtr->value < x)
        {
            prevNodePtr = nodePtr;
            nodePtr = nodePtr->next;
        }

        prevNodePtr->next = new ListNode(x, nodePtr);
    }
}
bool LinkedList::isMember(double x)
{
        //tbd
}

Any clues as to why this is would be a huge help. Thanks!

A: You declare ListNode structure, but you never declare anywhere any object which has ListNode type. So when you try to access head element from within your LinkedList method, it is indeed undeclared identifier, because LinkedList class doesn't have any element called head.
If you would have changed your LinkedList declaration like that:
class LinkedList
{
protected:
    struct ListNode
    {
        double value;
        ListNode *next;
        ListNode(double value1, ListNode *next1 = NULL)
        {
            value = value1;
            next = next1;
        }
        ListNode *head = NULL;
    } node; // actually instantiating ListNode element as part of LinkedList class
    // Public Interface
public:
    // Class Constructor(s)
    LinkedList();

    // Methods
    void add(double x);
    bool isMember(double x);

    // Private Class Members
private:
};

then you could have called the head element in this way:
LinkedList::LinkedList()
{
    node.head = NULL;
}

A: You probably want head to be a member of LinkedList, not ListNode.
class LinkedList {
    class ListNode {
        double value;
        ListNode *next;
    };
    ListNode *head;
};


text:
Q: jquery: Changing input label's color
<input type="radio" id="other" name="level_0" value="other" class="other">other

Say I have the above in an unordered list. On clicking the radio button, I want the label to be colored red.
I have tried the following:
$('input[type=radio]').click(function(){
if($(this).is(':checked')){
    $(this).prev().css("color","red");
}
});

Shouldn't this grab the previous element, 'label', and change its color to red?

A:

$('input[type=radio]').click(function() {
  if ($(this).is(':checked')) {
    $(this).closest('label').addClass("red");
  }
});
.red {
  color: red
}

  <input type="radio" id="other" name="level_0" value="other" class="other">other

*

*Use .closest()

*.prev() is used for siblings element.

*Can also use .parent()

*Suggestion use .addClass() instead of adding style directly

A: I'm assuming the prev() query searches too far back. When I changed it to parent() (which makes sense, because input is within label), it worked correctly. This is what happens when you don't study the fundamentals of what you're doing!

A: you can also use this
$('input[type=radio]').click(function(){
  if($(this).is(':checked')){
    $(this).closest('label').css({"color":"red"});
  }
});

change prev() in to closest() and bracket inside of parenthesis if you want to use css()
https://jsfiddle.net/darkrulerbreaker/neqrknkr/

A: You don't need to use jquery for this at all - have the CSS do it all. also - to be clear - are you after the label text - to be red (use color) or the label background to be red (use background). This will change the label color / background on the checked state of the input rather than the click event.
From the CSS tricks site (https://css-tricks.com/almanac/selectors/c/checked/) - "The :checked pseudo-class selector matches radio and checkbox input types when checked or toggled to an on state. If they are not selected or checked, there is no match.".
Note that this affects the label AFTER the input.

input[type=radio]:checked + label{
  color:red
}
<input type="radio" id="option1" name="level_0" value="1" class="other">
  option 1
<input type="radio" id="option2" name="level_0" value="2" class="other">
  option 2


text:
Q: Is there a way to curve Flatlist around the corners? i want to develop this view but i can't bend the flatlist and i also want to shadow the images other then the center one.i tried giving the border radius to the parent view and the flat list itself but it is not working for me
The required view
enter image description here
My View:enter image description here
here is my code:
...
`
import React from 'react';
import {Text, View, StyleSheet, FlatList} from 'react-native';

const List = () => {
  const image= <View style={{alignItems:'center',
  justifyContent:'center',
  width:100,
  height:100,
  backgroundColor:'red',
  borderRadius:50,}}/>
  const friends = [
    {name: image, Age: '20'},
    {name: image, Age: '45'},
    {name: image, Age: '30'},
    {name: image, Age: '37'},
    {name: image, Age: '90'},
    {name: image, Age: '200'},
  ];

  return (
    <View style={styles.containerStyle}>
      <FlatList
        style={styles.listStyle}
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        keyExtractor={friend => friend.Age}
        data={friends}
        renderItem={({item}) => {
          return (
            <Text style={styles.textpro}>
              {item.name}
            </Text>
          );
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
    containerStyle:{
        borderWidth:1,
        borderColor:'white',
        flex:1
        },
    listStyle:{
        borderWidth:1,
        borderColor:'red',
        borderRadius:100,
        flex:1,
    },
  op: {
    height: 10,
    width: 10,
    color: '#00ffff',
  },
});
export default List;
//App.js code
<View style={{backgroundColor:'rgb(50,117,220)',height:'30%',backgroundColor:'yellow'}}>
        <List />
</View>

`

A: someone asked me to try react native snap carousel and it worked like a charm idk why he deleted his comment.I feel blessed <3


text:
Q: what happens when mount a partition on / ? I have a partition /dev/sdb1 what happens after executing this command?
sudo mount /dev/sdb1 / -o rw
                     ^

I know that must change mountpoint "/" address as mentioned above. When I type this in my terminal. The command is executed but after some minutes my laptop will freeze. i want to know what happens?

A: I would have hoped for an error message but since it freezes, it apparently mounts it as requested, making the whole system lose reference to its resource mounts (/proc and /sys), its library references, any other mounts, and possibly other stuff.
Let this be a lesson as one of many things that you should never run.  At least it gets solved by a reboot.


text:
Q: Spherical Harmonic Plotting I have tried to plot on the surface of a sphere the spherical harmonic functions by closely following this demonstration
http://demonstrations.wolfram.com/NodalDomainsOfSphericalHarmonics/
I've copied the script from the picture available from the site as closely as I could, but when I run it the image doesn't change when I change the Manipulate settings.
    Manipulate[If[Abs[m] > l, m = Sign[m] l];
 coloredSphere[l, m, reim, ControlActive[30, pp]],
 {{reim, Re, "view"}, {Re -> "real", Im -> "imaginary"}},
 {{l, 6, "l"}, 0, 12, 1},
 {{m, 3, "m"}, -l, l, 1},
 {{pp, 40, "points"}, 3, 50, 1},
 Initialization :>
  {makeColoredSphereGraphicsComplex[points_, normals_, colors_] :=
    Module[{lOuter = Length[points], lInner = Length[points[[1]]]},
     GraphicsComplex[Flatten[N[points], 1], {EdgeForm[],
       GraphicsGroup[{Polygon[Flatten[#, 1] &@

           Table[{i lInner + j,
             i lInner + j + 1, (i + 1) lInner + j +
              1, (i + 1) lInner + j}, {i, 0, lOuter - 2}, {j,
             lInner - 1}]]}]},
      VertexNormals -> Flatten[N[normals], 1],
      VertexColors -> Flatten[N[normals], 1]]
     ];
   spherePoints[n_] := spherePoints[n] =
     Module[{\[Psi]s = 2. Pi (Range[0, 2 n]/(2 n)), \[Phi]s =
        1. Pi (Range[0, n]/n)},
      c\[Psi]s = Cos[\[Psi]s]; s\[Psi]s = Sin[\[Psi]s];
      c\[Phi]s = Cos[\[Phi]s]; s\[Phi]s = Sin[\[Phi]s];
      \[Psi]ones = Table[1., {k, 0, 2 n}];
      xs = Outer[Times, c\[Psi]s, s\[Phi]s];
      ys = Outer[Times, s\[Psi]s, s\[Phi]s];
      zs = Outer[Times, \[Psi]ones, c\[Phi]s];
      Transpose[{xs, ys, zs}, {3, 1, 2}]
      ];
   colors[n_, {l_, m_}, reim_] := colors[n, {l, m}, reim] =
     Module[{\[Psi]s = 2. Pi Range[0, 2 n]/(2 n), \[Phi]s =
        1. Pi Range[0, n]/n, \[Psi]L, \[Phi]L,
       hueData, \[CapitalDelta]h},
      \[Psi]L = reim[Exp[I m \[Psi]s]];
      \[Phi]L = LegendreP[l, m, Cos[\[Phi]s]];
      hueData = Outer[Times, \[Psi]L, \[Phi]L];
      \[CapitalDelta]h =
       If[Max[hueData] == Min[hueData], 1,
        Max[hueData] - Min[hueData]];
      Map[Hue, 0.8 (hueData - Min[hueData])/\[CapitalDelta]h, {2}]
      ];
   coloredSphere[l_, m_, reim_, pp_] :=
    Graphics3D[
     makeColoredSphereGraphicsComplex[spherePoints[pp],
      spherePoints[pp], colors[pp, {l, m}, reim]], Boxed -> False,
     ImageSize -> {400, 350}, SphericalRegion -> True,
     ViewAngle -> \[Pi]/10];}]

I went through the script thinking something was wrong but I simply cannot understand what's going on with the GraphicsComplex function.

A: Just replace VertexNormals -> Flatten[N[normals], 1] by VertexColors -> Flatten[colors, 1] in makeColoredSphereGraphicsComplex.


text:
Q: Removing dot (thousands separator) in a numeric apex:inputField I have one field "MyYear__c" on my custmon object. This field has following details:
Data Type: Number
Length: 4
Decimal Places: 0
At the visualforce page it looks like this:
<apex:inputField value="{!obj.MyYear_c}" required="true"/>

The user must fill this field out and then the outputPanel is re-rendered. After that there is a dot in this field:

Is there a way to remove the dot? I don't want to use any "not clear" solutions like Javascript. I want to know is there a "native" visualforce or apex solution for that. I know there are some workrounds, but only for the outputText, not for inputField.
Thank you.

Here my code:
Page:
<apex:pageBlock id="mainBlock">
    <apex:pageBlockSection columns="2">
        <apex:inputField value="{!obj.MyNumber__c}" required="true"/>
        <apex:commandButton value="Validate" action="{!doValidation}" reRender="mainBlock"/>
    </apex:pageBlockSection>
</apex:pageBlock>

Controller:
public MyObject__c obj { get; set; }

public MyClass(){
    obj = new MyObject__c();
}

public PageReference doValidation(){
    // Validation stuff here
    return null;
}

A: Have you tried using inputText in your Visualforce?:
<apex:inputText value="{!obj.MyNumber__c}" required="true"/>

You will need to validate that the text is a number in your controller.
You will also need to make use of a formula field for standard UIs.


text:
Q: How to have a custom display in ListBox with DataTemplate? I need to display cards in a ListBox in a specific layout:
https://imgur.com/a/0U8eqTc
I've tried to find a way to use 2 types of DataTemplate but I have no idea how to do it. I decided to make a template which contains 6 card Template (like this):
https://imgur.com/VrOlYcR
Here's what my current Template looks like:
<ControlTemplate x:Key = "CardTemplate" TargetType = "Button">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="4*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Image Grid.Row="0" Source="{Binding Path=Image}"/>
        <TextBlock Grid.Row="1" Text="{Binding Path=Titre}"/>
    </Grid>
</ControlTemplate>

<DataTemplate x:Key="DataTemplate">
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>

        <Button Grid.Column="0" Grid.Row="0" Template="{StaticResource CardTemplate}"/>

        <Grid Grid.Column="1" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Button Grid.Row="0" Template="{StaticResource CardTemplate}"/>
            <Button Grid.Row="1" Template="{StaticResource CardTemplate}"/>
        </Grid>

        <Grid Grid.Column="0" Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Button Grid.Row="0" Template="{StaticResource CardTemplate}"/>
            <Button Grid.Row="1" Template="{StaticResource CardTemplate}"/>
        </Grid>

        <Button Grid.Column="1" Grid.Row="1" Template="{StaticResource CardTemplate}"/>

    </Grid>
</DataTemplate>

Which I intend to display in a ListBox:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         Name="ListBox" ItemTemplate="{DynamicResource DataTemplate}"
         ScrollBar.Scroll="ScrollOnBottom">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

Here's how my cod behind basically works:
class Cards
{
    public List<Card> cards; // list of 6 Card objects
}

class Card
{
    string title;
    BitmapImage image;

    public string Title { get => title; set => title = value; }
    public BitmapImage Image { get => image; set => image = value; }
}

ObservableCollection<Cards> cc = new ObservableCollection<Cards>();
/*

Cards are already filled with 6 Card
cc filled with Cards

*/
formationListBox.ItemsSource = cc;

Here's the problem, it displays the right amount of Cards but the buttons are empty. I don't know how to bind a specific object to each button.

A: To Give an example of what Sinatr commented. You should approach this from an Mvvm perspective. first you should add a View Model for the View that this Window is in. This will contain a list of objects that are DisplayCards each object will store the string and image.
public class DisplayCard : INotifyPropertyChanged
{
    private string _title;
    public string Title
    {
        get { return _title; }
        set
        {
            if (value != _title) { _title = value; RaisePropertyChanged(); }
        }
    }
    private string _cardImage;
    public string CardImage
    {
        get { return _cardImage; }
        set
        {
            if (value != _cardImage) { _cardImage = value; RaisePropertyChanged(); }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
public class YourViewVM : INotifyPropertyChanged
{
    private ObservableCollection<DisplayCard> _cardCollection;
    public ObservableCollection<DisplayCard> CardCollection
    {
        get { return _cardCollection; }
        set
        {
            if (value != _cardCollection) { _cardCollection = value; RaisePropertyChanged(); }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Then you need to make the list CardCollection set to the ListBox's ItemSource. Then use a datatemplate to bind the DisplayCards properties to the containing object.
<ListBox Name="lbTodoList" HorizontalContentAlignment="Stretch" ItemSource="{Binding CardCollection}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <Grid.RowDefinitions>
          <RowDefinition Height="4*"/>
          <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Image Grid.Row="0" Source="{Binding Image}"/>
        <TextBlock Grid.Row="1" Text="{Binding Title}"/>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

You need to make sure you set the YourViewVM As the DataContext of the View. A simple search should solve how to do that.
The above should be enough to allow you to refactor your code such that it works.


text:
Q: MQTT Listener on ActiveMQ Artemis - how to ensure all messages (not just latest) are consumed by subscriber I would like to use use ActiveMQ Artemis as an MQTT broker to ensure that all subscribers to a MQTT topic will receive the MQTT messages, not just the latest one.
For example, an MQTT subscriber crashes and is unable to receive messages for a while. When the subscriber comes back online, it should receive all the messages that had been published to a topic.
From this post, which give the following graphic:

it appears that by setting the QOS to 1 and the retain to true, all messages to a topic will be saved until they are consumed by the subscribers. Is this the case?
If necessary, I could add a UUID to the topic. For example, publish to topic mytopic/13234141431432 and subscribe to mytopic/#.  However, the first option is preferable just for simplicity sake.

A: Retained is different to QOS delivery requirements.
Setting the retained flag will just tell the broker to hold on to the last message on a given topic with the retained flag set and always deliver that message to any new subscribers (including returning clients that have been offline). Retained is how to ensure a client always gets the current state/last state of a topic, not any of the preceding messages. (Also the retained message may be delivered before any queued messages)
If you want to ensure that all missed messages are delivered to a client that has been offline you must publish and subscribe at QOS 1 or 2 and ensure that the Clean Session flag is false when reconnecting.


text:
Q: How to display featured content first and then the rest in a scope? I have an app with a lot of content. Right now I have a boolean called featured. When feature is marked, I'd like this content to display at the top of the page. Right now, I have a scope order on the content, but I'm not sure how to display the featured items first. Any thoughts?  Below are the small scopes I have for content:
  scope :published, where(:published => true )
  scope :unpublished, where(:published => false )
  scope :ordering, order("published_date desc")
  scope :feature, where(feature: true )

Here is what my home controller looks like that displays the content:
  def index
    @contents = Content.includes(:author).published.ordering
    @collections = @user.try(:collections)
    @categories = Category.includes(:subcategories).all
  end

It seems like there's a better way to do this than an if else statement. Suggestions? I've been looking at the order documentation and not finding anything specific for this case.
Using:
Rails 3.2.14
Ruby 1.9.3

A: You can use a SQL CASE WHEN clause in the order to define a specific behavior on a specific attribute's value:
scope :ordered_by_featured_then_published, order("CASE contents.featured = 't' THEN 'a' ELSE 'b' END ASC, contents.published_date DESC")
# for readability, content of the order method:
# "CASE contents.featured = 't' THEN 'a' ELSE 'b' END ASC, contents.published_date DESC"

This SQL CASE WHEN works for me with PostGreSQL. You might have to make some syntax changes here, but you got the concept.
And use it that way:
@contents = Content.includes(:author).published.ordered_by_featured_then_published

Some explanations:

*

*"content.featured = 't'" => This will test if the value of content.featured = TRUE (in PostGreSQL, TRUEs are saved as 't', FALSEs as 'f')

*"CASE contents.featured = 't' THEN 'a' ELSE 'b' END" => if featured is TRUE, returns the letter 'a', if not, return 'b'

*"ORDER BY CASE contents.featured = 't' THEN 'a' ELSE 'b' END ASC": with the statement above, we order (ascendant) on a list of "a" and "b" => if featured is TRUE, returns "a" else returns "b", then order on the returned list of letters

Hope this helps!

A: scope :order_by_feature_then_published, order("contents.feature DESC").order("published_date DESC")

  def index
    @contents = Content.includes(:author).published.order_by_feature_then_published
    @collections = @user.try(:collections)
    @categories = Category.includes(:subcategories).all
  end

This works.


text:
Q: Why ZendFramework $this->getFrontController()->getBaseUrl() is returning empty string inside a controller? I'm using ZendFramework 1.11.11 for my application and I need know the URL (more specifically the path) that fire up my controller inside my controller.
When I try
$this->getFrontController()->getBaseUrl();

an empty string is returned. I test that code with the default application created by ZendStudio and accessing it typing http://test.com/default/index/index and nothing.
Any idea how get the URL that fireup a controller inside the controller?

A: The base url is the offset from the original slash that you've set up in your configuration. You do not have a base url, as default is the name of the module, index is the controller, and index is the action.
For firing up another controller, check out this link http://framework.zend.com/manual/en/zend.controller.action.html#zend.controller.action.utilmethods
To get the current path in a Zend fashion from a controller, do the following.
$this->getRequest()->getPathInfo();


text:
Q: Java:Yahoo contacts API is there any library or at least some documentation or example on how to import Yahoo! contacts using java and OAuth ?
in my website i need to display/get the yahoo contacts (with oauth)
is there any example.

A: There is no client library.
You can retrieve contacts in two steps:
Step 1:
Getting 'TOKEN' and 'TOKEN SECRET' of user , using OAuth1. Some libraries are scribe and signpost .
Step 2:
After retrieving these tokens you have to get the yahoo id of the user.
Example: (I am using signpost for this)
    OAuthConsumer consumer = new DefaultOAuthConsumer('YOUR CLIENT ID', 'YOUR CLIENT SECRET');
    URL url = new URL("http://social.yahooapis.com/v1/me/guid?format=json");
    HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
    consumer.setTokenWithSecret('TOKEN', 'TOKEN SECRET');
    consumer.sign(request1);
    request1.connect();
    String responseBody = convertStreamToString(request1.getInputStream());

After this, you have to use the yahoo id of the user retrieved from the user, to get user contacts.
Example:
    OAuthConsumer consumer = new DefaultOAuthConsumer('YOUR CLIENT ID', 'YOUR CLIENT SECRET');
    URL url = new URL("http://social.yahooapis.com/v1/user/YAHOO_USER_ID/contacts?format=json");
    HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
    consumer.setTokenWithSecret('TOKEN', 'TOKEN SECRET');
    consumer.sign(request1);
    request1.connect();
    String responseBody = convertStreamToString(request1.getInputStream());

Method for stream Conversion used above is:
    public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    } catch (IOException e) {
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
    return sb.toString();
}


text:
Q: mysql adjusting datetime values in the dbase, not in search returns This must be a ridiculously stupid question, because after numerous searches of the StackOverflow question archives (and elsewhere) I can't find an answer.
I recently posted a question about managing date & time data here:
mysql date storage & query performance with php
Following Mike B's advice I appended two zero's onto the end of my YYMMDDHHMM strings to make them DATETIME format compliant as YYMMDDHHMMSS and then copied them to a new column with DATETIME formatting. To my surprise (although perhaps predictably), when the script finished I now had a DATETIME column where every year was of the 20XX variety, rather than 19XX!
Oops.
Since then I've been trying to figure out how to change it via acting directly on the DATETIME column rather than trashing the new column and reusing the original integers (I want to do it the "right" way) and am guessing I'm supposed to use DATE_SUB and INTERVAL 100 YEAR but am stumped as to the actual construction of the code either directly in MySQL or via PHP.
Again, I apologize, this must be really freaking obvious.
Thank you,

*

*A

A: update my_table
   set my_date_column = date_sub(my_date_column, interval year 100);


text:
Q: How to get path to current exe file on Linux? The code below gives current path to exe file on Linux:
#include <iostream>
std::string getExePath()
{
  char result[ PATH_MAX ];
  ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
  return std::string( result, (count > 0) ? count : 0 );
}
int main()
{
  std::cout << getExePath() << std::endl;
  return 0;
}

The problem is that when I run it gives me current path to exe and name of the exe, e.g.:
/home/.../Test/main.exe

I would like to get only
/home/.../Test/

I know that I can parse it, but is there any nicer way to do that?

A: dirname is the function you're looking for.
#include <libgen.h>         // dirname
#include <unistd.h>         // readlink
#include <linux/limits.h>   // PATH_MAX

char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
const char *path;
if (count != -1) {
    path = dirname(result);
}


text:
Q: How to intentionally cause a compile-time error on template instantiation Sometimes when coding with C++ templates, you want to prevent users from instantiating a specific specialization or set of specializations, because the result would be nonsensical.  So you can define a (specific or partial) specialization whose definition, if instantiated, would cause a compiler error.  The goal would be, if a user "misuses" the template, to cause a compiler error right next to a comment in your header file explaining what not to do, rather than leaving the compiler to come up with some confusing error message by its own devices, or maybe allowing the questionable code to compile.
Example:
template <typename T> struct MyClassTemplate {
  // ...
};

template <typename T> struct MyClassTemplate<T*> {
  // Do not use MyClassTemplate with a pointer type!
  typedef typename T::intentional_error err;
};

There are a number of ways to do this (depending on whether your specialization is a complete or partial specialization of a class or function).  But the syntax used must (?) depend on a template parameter, or else the compiler will complain when it first parses the intentional-error definition.  The example above has a hole in that somebody could stubbornly define an intentional_error nested type or member typedef (though I'd say they would then deserve whatever problems come up as a result).  But if you use a trick too fancy, you're likely to get an indecipherable and/or misleading compiler error message, which mostly defeats the purpose.
Are there better straightforward ways to disallow template instantiations?
I'm aware that in C++0x, template Concepts and deleted function declarations will provide much better control over this sort of thing, but I'm looking for answers that are valid C++03.

A: You could just omit defining it.
template <typename T> struct MyClassTemplate<T*>;

You could also derive from a non-defined specialization
template <typename T> struct invalid;
template <typename T> struct MyClassTemplate<T*> : invalid<T> { };

Note that explicit specializations that declare classes or functions will never depend on template parameters. So, stuff like this that depend on template parameters can't work anyway. In that case, declaring a non-defined explicit specialization should be sufficient
template<> struct MyClassTemplate<int*>;

A: For me this sounds like a typical case for static_assert from C++0x or BOOST_STATIC_ASSERT. The static_assert functionality has the advantage that you can pass a custom error message so that the reason for the error is more clear.
Both ways are giving you the opportunity to prematurely end the compilation process under some custom defined compile time condition.
with static_assert:
template <typename T> struct MyClassTemplate<T*> {
    static_assert(always_false<T>::value, "Do not use MyClassTemplate with a pointer type!");
};

with BOOST_STATIC_ASSERT
template <typename T> struct MyClassTemplate<T*> {
    // Do not use MyClassTemplate with a pointer type!
    BOOST_STATIC_ASSERT(always_false<T>::value);
};

Always false would look something like this:
template< typename T >
struct always_false {
    enum { value = false };
};

HTH
Edit: Fixed the examples to make them actually work ;-) Thanks to GMan!

A: If you don't want to use a library, this construct is pretty reliable (it's roughly what Boost does internally):
template <typename T>
void must_be_specialized(T const&)
{
   enum dummy { d = (sizeof(struct must_be_specialized_for_this_type)
                     == sizeof(T)) };
}

You can put something analogous in a specialization to disallow instantiation of the template with that type.  I wouldn't, personally, worry about must_be_specialized_for_this_type gaining a definition from somewhere, but you could use a forward declaration to squirrel it away in a private namespace if you really wanted.

A: Concepts were removed from '0x. You can use a library, like Boost Concept Check.

A: "Are there better straightforward ways to disallow template instantiations?" Nothing significantly better than what you have already identified. I am pretty sure C++ protection mechanisms are there to protect you from accident not from malice. And someone defining a specialisation or a class to break your intended use I would consider malicious. Perhaps you could hit the person in the back of the head each time they do it.
I personally prefer to put the checks into templates that exist only to describe the checks. That allows interesting combinations of inheritance and templates.
template <class T>
class not_with_pointer_t { };

template <class T>
class not_with_pointer_t<T*>;

template <class T>
class some_class_t : public not_with_pointer_t<T> { };

template <class T, template <class U> class base_t>
class another_class_t : public base_t<T> { };

typedef some_class_t<int> a_t; // ok
typedef some_class_t<void*> b_t; // error if instantiated
typedef another_class_t<void*, not_with_pointer_t> c_t; // error if instantiated

template <class T> class unrestricted_t { };
typedef another_class_t<void*, unrestricted_t> d_t; // ok

A: boost::enable_if


text:
Q: Can't install additional printer 32-bit drivers on Windows 7 64-bit I get the error "Selected printer driver not found", what should I do?
Possible Duplicate:
When installing additional printer 32-bit drivers fails on Windows 7 64-bit I get the error "Selected printer driver not found", what should I do?

I've successfully installed Windows 7 (x64) and drivers for my HP Color LaserJet 2600n, and have no problem printing with this setup.
There is another PC in the network running XP SP3, and I want to share the printer so that users of that PC can also print.
On W7 I have the option of installing additional printer drivers for other system architectures (Itanium and x86). I've downloaded the most current 32-bit drivers for the printer, but every time I direct the install dialog to the folder containing the drivers, I get the following error message:
Selected printer driver not found

The specified location does not contain the driver for the requested processor architecture.

Retry Cancel

I'm stumped. I'm absolutely certain that the specified location actually does contain the correct drivers; I've even installed them on the XP system.
I've tried everything I can think of. What am I overlooking?

A: Windows needs a inf file to read to install the drivers.
Often I just keep clicking through the directories til I find it.  If that isn't possible and the printer requires a proprietary installer, there is an alternative.
http://technet.microsoft.com/en-us/library/cc732946.aspx
This specific articles involves installing the drivers on an x86 OS, like on XP mode and then using Print Management to upload them onto the print server, which would be your WIn7 machine.


text:
Q: I'm getting errors in GIMP, so what's a good batch photo processing program that can replicate GIMP's auto white balance? I'm running Ubuntu 14.04 and I'm having trouble batch processing images in GIMP because I'm getting the following error:
While parsing XMP metadata:
Error: No XMP packet found

I've researched the problem on the web and it appears like it's a problem with the EXIF metadata. I'm using a Sony camera (the A6000), and it apparently does not save the images with this "XMP packet" that GIMP is looking for.
So considering this, can anyone suggest a photo program/utility that can (1) process images in batches; and (2), replicate what GIMP's "auto white balance" does, because that tool really makes the image "pop out" and improve more often than not.
EDIT: I've tried ImageMagick and the tools it has does not produce the same effect.

A: I get this error when batch processing images straight out of my Nikon DSLR.
I believe that images straight out of a camera will not have any XMP data, and getting this error message is the correct behavior.
You can check if there is xmp data with exiftool:
"exiftool -xmp -a [filename]"
It seems to be actually a harmless warning message, and not an actual error that stops the batch processing. The task I have coded for (desaturating the image) still completes. Is this error actually preventing your script from doing the task(s) at hand?
If so, you can try adding in XMP data with the exiftool. I have not done this.