text:
Q: Postfix External SMTP Authentication - Wrong login user? I am trying leverage Postfix as an SMTP relayer on a Raspberry Pi to allow other systems on my network to email outbound system messages. It appears there are two problems, (1) it's not authenticating as the specified user and (2) it appears to be trying deliver the email message to a localmail box on the remote server as depicted here:

550-Verification failed for  550-The mail server could
  not deliver mail to root@unifipi

mail.log
Jan 10 21:43:47 UniFiPi postfix/master[28775]: reload -- version 2.11.3, configuration /etc/postfix
Jan 10 21:43:50 UniFiPi postfix/pickup[786]: 31D8C3F9F5: uid=0 from=<root@UniFiPi>
Jan 10 21:43:50 UniFiPi postfix/cleanup[793]: 31D8C3F9F5: message-id=<20170111024350.31D8C3F9F5@unifipi.home.lan>
Jan 10 21:43:50 UniFiPi postfix/qmgr[785]: 31D8C3F9F5: from=<root@UniFiPi>, size=383, nrcpt=1 (queue active)
Jan 10 21:43:51 UniFiPi postfix/smtp[795]: 31D8C3F9F5: to=<johndoe@outlook.com>, relay=mail.mydomain.com[170.75.252.58]:587, delay=1, delays=0.08/0.08/0.67/0.22, dsn=5.0.0, status=bounced (host mail.mydomain.com[170.75.252.58] said: 550-Verification failed for <root@UniFiPi> 550-The mail server could not deliver mail to root@unifipi.  The account or domain may not exist, they may be blacklisted, or missing the proper dns entries. 550 Sender verify failed (in reply to RCPT TO command))
Jan 10 21:43:51 UniFiPi postfix/cleanup[793]: 412C53F9F6: message-id=<20170111024351.412C53F9F6@unifipi.home.lan>
Jan 10 21:43:51 UniFiPi postfix/bounce[797]: 31D8C3F9F5: sender non-delivery notification: 412C53F9F6
Jan 10 21:43:51 UniFiPi postfix/qmgr[785]: 412C53F9F6: from=<>, size=2640, nrcpt=1 (queue active)
Jan 10 21:43:51 UniFiPi postfix/qmgr[785]: 31D8C3F9F5: removed
Jan 10 21:43:52 UniFiPi postfix/smtp[795]: 412C53F9F6: to=<root@UniFiPi>, relay=mail.mydomain.com[170.75.252.58]:587, delay=0.75, delays=0.02/0/0.51/0.22, dsn=2.0.0, status=sent (250 OK id=1cR8tC-003Asy-Tc)
Jan 10 21:43:52 UniFiPi postfix/qmgr[785]: 412C53F9F6: removed

main.cf
smtpd_banner = $myhostname ESMTP $mail_name (Raspbian)
biff = no
append_dot_mydomain = no
readme_directory = no
myhostname = unifipi.home.lan
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:user@mydomain.com:password
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_use_tls = yes
header_size_limit = 4096000
relayhost = [mail.mydomain.com]:587
inet_interfaces = all
inet_protocols = all

Any help would be most appreciated! Thanks!

A: You must rewrite your source to be the same as your sasl auth user.
From name can be whatever, if this isn't what you want or you are allowed to impersonate with that account then use a valid from address
See https://serverfault.com/a/674984/200560


text:
Q: What are all the members created by compiler for a class? I'm asking the exact same question as this one, but for Java.
What are all the special methods, fields, etc. that are created by the compiler and are therefore not in the Javadoc? Examples of this are default constructors and the values and valueOf methods added to enums.

A: In addition to what you mentioned:

*

*this$0 for the outer object reference of inner classes

*access$NNN() methods for inner classes

*bridge methods for overridden methods with generic parameters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make this program to accept n number of test cases? I have been practising dynamic coding, So here I want to accept n number of test cases, but when I enter more than one number of testcases it only accepts only one test case . Lets say I enter the number of test cases as 2 and the number of player and villains as 3 and entered their energies but it only runs for one iteration and the program ends on the next iteration. How to make it to accept many test cases?
/* Read input from STDIN. Print your output to STDOUT*/

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
class Testcase // Name should be in PASCAL
{
    int N;
    int [] play;
    int [] villain;
    String status;

    public Testcase (int n) { // Constructor
        this.N=n;
        play = new int [N];
        villain=new int [N];
    }

}
public class Main {
    static List<Testcase> caseno=new ArrayList<Testcase>();
    public static void main(String args[] ) throws Exception {
        List<Testcase> caseno=new ArrayList<Testcase>();
        Scanner sc=new Scanner(System.in);
        //int n1=10;
        System.out.println("Enter the number of Test Cases:");
        int n1=sc.nextInt();
        int i,j;
        Testcase t;
        for(i=0;i<n1;i++)
        {
            //int n=6;
            System.out.println("Enter the number of players and villains:");
            int n=sc.nextInt();
            t=new Testcase(n);

            System.out.println(t.N+" "+t.play.length);
            System.out.println("Enter the Player Energies");
            for(i=0;i<n;i++)
            {
                t.play[i]=sc.nextInt();
            }
            System.out.println("Enter the Villain Energies");
            for(i=0;i<n;i++)
            {
                t.villain[i]=sc.nextInt();
            }
            Arrays.sort(t.play);
            Arrays.sort(t.villain);
        }
        for(Testcase t1:caseno)
        {
            for(i=0;i<t1.N;i++)
            {
                System.out.println(t1.villain[i]+" "+t1.play[i]);
            }
            int flag=0;
            for(i=0;i<t1.N;i++)
            {
                if(t1.play[i]<t1.villain[i])
                {
                    flag=0;
                }
                else
                {
                    flag=1;
                    t1.status="LOSS";
                    break;
                }
            }
            if(flag==0)
            {
                t1.status="WON";
            }
            System.out.println(t1.status);

        }

        for (Testcase j1:caseno)
        {
            System.out.println(j1.status);

        }

        //Write code here

    }
}

A: The problem in your case is the visibility of variables.
I will show you the problem in a short way:
int i;
for (i=0; i<2; i++) {        // loop 1
   for (i=0; i<3; i++) {     // loop 2
       // do something
   }
}

In loop2 the variable i will run from 0 to 2. After the exit of the 2nd loop the variable "i" holds the number 3 (that's why it exited). So loop 1 will exit as well because the end-condition has been reached (i<2). But that is not what you want.
It's better to surpass the problem like that:
for (int i1=0; i1<2; i1++) {     // loop 1
   for (int i2=0; i2<3; i3++) {  // loop 2
      // do something
   }
}

This way every variable holds its own scope and will not interfere with other variables who have the same name. It will run through loop2 ("i2" ==0, ==1 and ==2) now two times (one for "i1"==0 and one for "i1"==1).
And that is the basic problem in your example.
You can find more informations here:

*

*https://www.java-made-easy.com/variable-scope.html

*http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm


text:
Q: How to use a private image from AWS ECR with Airflow's DockerOperator? I created a custom package with a CLI (built with Click). This package can do two things: run preprocessing and run the machine learning model.
I created a Docker image of this customer package and pushed it to a private registry on AWS (ECR).
Now I want to run this container with Airflow, which I want to run on an EC2 instance. I am running it with docker-compose.
For this example I will only focus on one task: run the container for the preprocessing.
However, now I get 'upstream failed' for t2.
from datetime import timedelta
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.docker_operator import DockerOperator

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(1),
    'email': ['airflow@example.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

dag = DAG(
    'example_pipeline',
    default_args=default_args,
    description='example data pipeline.',
    schedule_interval=timedelta(minutes=3)
)

t1 = BashOperator(
    task_id='starting_airflow',
    bash_command='echo "Starting Airflow DAG..."',
    dag=dag,
)

t2 = DockerOperator(
    task_id='data_pipeline',
    image='XXXXXXXX.dkr.ecr.eu-central-1.amazonaws.com/rwg:latest',
    container_name='task__export_data',
    command="run-preprocessing",
    network_mode="bridge",
    api_version="auto",
    docker_url="unix://var/run/docker.sock",
    docker_conn_id='aws_con',
    dag=dag
)

t1 >> t2

I created via the UI the 'aws_con'. But it does not seem to work.
Furthermore, this is my docker-compose.yml file.
version: '3'
services:
  postgres:
    image: postgres:9.6
    environment:
      - POSTGRES_USER=airflow
      - POSTGRES_PASSWORD=airflow
      - POSTGRES_DB=airflow
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data

  webserver:
    build: .
    restart: always
    depends_on:
      - postgres
    environment:
      - LOAD_EX=n
      - EXECUTOR=Local
      - FERNET_KEY=jsDPRErfv8Z_eVTnGfF8ywd19j4pyqE3NpdUBA_oRTo=
    volumes:
      - ./dags:/usr/local/airflow/dags
    ports:
      - "8080:8080"
    command: webserver
    healthcheck:
      test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
      interval: 30s
      timeout: 30s
      retries: 3

What am I doing wrong regarding the Docker Operator?
And second question: how can I create this "aws_con" via code or the cli?

A: You should specify docker connection.
This is the standard way of passing credentials in Airflow and Docker has a dedicated Docker connection for that which you can define in Airlfow DB or Secrets and pass the id of the connection to DockerOperator as docker_conn_id - parameter (you can also specify the url there so you should not need to pass docker_url in your operator).
See Python API here:
https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/_api/airflow/providers/docker/operators/docker/index.html
And the separate page about the Docker connection here (the docker_conn_id description links to this page):
https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/connections/docker.html#howto-connection-docker


text:
Q: Action behind self created button won't work. I've got a simple problem but I don't know why it doesn't work.
I created a button programatically and I'd like to add the method "backLogin" to the action.
Strange enough, I don't get any errors, but the button just won't respond in any way. Anywhere I look on the internet, this code should definitely work.
Any ideas what I'm doing wrong?
-(void) loginAppear{

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(20, 20, 75, 37); // position in the parent view and set the size of the button
[myButton setTitle:@"Back" forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
// add to a view
[myButton setAlpha:1];
[loginImage addSubview:myButton];
}

The code behind "backLogin" has already worked in other circumstances:
-(void) backLogin{

CALayer *layer = loginImage.layer;

//spin frame
CABasicAnimation *anim1 =
[CABasicAnimation animationWithKeyPath: @"transform" ];
anim1.toValue = [ NSValue valueWithCATransform3D:
                 CATransform3DMakeRotation(180 * M_PI, 0.0, 1.0, 0) ];
anim1.duration = .2;
anim1.cumulative = YES;
anim1.repeatCount = 1;
[layer addAnimation: anim1 forKey: @"transformAnimation" ];

}

A: Instead of adding myButton to loginImage, try adding it to the main view (e.g. [self.view addSubview:myButton]). You may need to change the frame coordinates to position the button properly.


text:
Q: Displaying whole table with optionally empty fields Here is how the database looks like

So I would like to display it like
Champion name
name of the column e.g. Q name of the spell - Surging Tides
the rest of spells for that champion
Next Champion etc.,

This is the way I display Champion names right now
$champions = $conn->prepare("SELECT *
                             FROM champions
                             Where Patch_No = ?");
$champions->bind_param('s', $Patch_No);
$champions->execute();
$champions_result = $champions->get_result();

while($row = $champions_result->fetch_assoc()){
    echo $row['Champion'].' '.$row['NumNotNull'].'
';
}

I can't really think of an easy way to do this with the least amount of queries possible.
Here is another example how it should look like

A: $row is an associative array, so you can loop through it with foreach and test whether the column is empty.
while($row = $champions_result->fetch_assoc()){
    echo $row['Champion'].' '.$row['NumNotNull'].'
';
    foreach ($row as $column_name => $column) {
        if ($column_name == 'Champion' || $column_name == 'NumNotNull') {
            continue; // These fields were already displayed above
        }
        if (!empty($column)) {
            echo "$column_name $column
";
        }
    }
}


text:
Q: Determining if Graphs are Isomorphic. Is it true that two graphs must be Isomorphic if:

*

*They have 8 vertices, each with a degree of 3?

*They are both connected, without cycles, and have 6 edges?

So I know that to be Isomorphic, each graph must have the same number of vertices connected in the same way. So for for the first question, I would have to show that a vertex might have a degree of 3 on one graph but not connect to the same three vertices as another, or that it must... I am confused on how to show this.
And my understanding for the second question, is that two connected graphs without cycles are pretty much a tree (?). I am confused on how to show these are/aren't isomorphic as well.
Any help/hints are appreciated.

A: The answer is no to both of them.
For $1$, consider $G$ to be two disjoint $K_{4}$'s. Then $G$ has $8$ vertices and all vertices have degree $3$. Let $H$ be $4$ copies of $K_{2}$ with  multi-edges on each $K_{2}$ to satisfy the degree condition. These graphs aren't isomorphic.
You can also take an $8$-cycle and add chords in between the vertices to get another graph which you can use as a counterexample (if you like connected graphs).
for $2$, the question is asking if there are two different trees with $6$ edges.
Take $P_{7}$ and any other tree which isn't a path and you have a counterexample.

A: Just give examples of non-isomorphic graphs satisfying the conditions. For #1, you could have on one hand a bipartite graph with 4 vertices in each part, and three edges at each vertex. On the other hand, you can have two copies of $K_4$.
For #2, just give two different trees with 6 edges! For instance, a path and a star.


text:
Q: SQL Server: capture table updates only Question
Is there any generic (reusable between multiple tables) and easy to implement/understand way to capture only updates at SQL Server table?
Objective
I have SQL Server 2012 SP4 transactional replica. I'm reading (loading) multiple 10GB+ tables on daily basis from SQL Server to my cloud storage.
It appears those 10GB+ tables aren't 100% immutable: 98-99% of operations are inserts, BUT 1-2% - updates.
Mitigations

*

*Full table load
It requires more resources at Nifi side, but the implementation is very
simple and straighforward

*Incremental load by ID column plus capture last day updates with triggers
Performance-wise but it is more complex: it requires configuring triggers on SQL  Server side plus reducing multiple versions of row (updates) on ETL layer.

*Generate MODIFIEDAT column during replication for all tables
It would be greate, but I think very hard to impossible: we don't have right to modify master database.

CDC looks like not an option because 98-99% of operations are inserts, means CDC will duplicate tables/database volume almost twice. AFAIK, from SQL Server CDC doc and this post it looks like SQL Server CDC can't be configured to capture updates only.


text:
Q: How to change the font of polari IRC chat client? Is it possible to change the default font of the polari IRC chat client? I would like to change it to DejaVu Sans Mono.

A: It turns out to be using the  GTK's fonts. You can't customize it in Polari. My GTK Theme was causing the "issue".


text:
Q: Resize div with drag handle when rotated I could find similar questions involving jQuery UI lib, or only css with no handle to drag, but nothing with pure maths.
What I try to perform is to have a resizable and rotatable div. So far so easy and I could do it.
But it gets more complicate when rotated, the resize handle does calculation in opposite way: it decreases the size instead of increasing when dragging away from shape.
Apart from the calculation, I would like to be able to change the cursor of the resize handle according to the rotation to always make sense.
For that I was thinking to detect which quadrant is the resize handle in and apply a class to change cursor via css.

*

*I don't want to reinvent the wheel, but I want to have a lightweight code and simple UI. So my requirement is jQuery but nothing else. no jQuery UI.

*I could develop until achieving this but it's getting too mathematical for me now.. I am quite stuck that's why I need your help to detect when the rotation is enough to have the calculation reversed.

Eventually I am looking for UX improvement if anyone has an idea or better examples to show me!
Here is my code and a Codepen to try: http://codepen.io/anon/pen/rrAWJA

Thanks for the help!

A: Here is a modification of your code that achieves what you want:
$(document).ready(function() {
  new resizeRotate('#square');
});

var resizeRotate = function(targetElement) {
  var self = this;
  self.target = $(targetElement);
  self.handles = $('

');
  self.currentRotation = 0;
  self.w = parseInt(self.target.width());
  self.h = parseInt(self.target.height());
  self.positions = ['bottom-right', 'bottom-left', 'top-left', 'top-right'];

  self.bindEvents = function() {
    self.handles
      //=============================== Resize ==============================//
      .on('mousedown', '.resize', function(e) {
        // Attach mouse move event only when first clicked.
        $(document).on('mousemove', function(e) {
            var topLeft = self.target.offset();

            var centerX = topLeft.left + self.target.width() / 2;
            var centerY = topLeft.top + self.target.height() / 2;

            var mouseRelativeX = e.pageX - centerX;
            var mouseRelativeY = e.pageY - centerY;

            //reverse rotation
            var rad = self.currentRotation * Math.PI / 180;
            var s = Math.sin(rad);
            var c = Math.cos(rad);
            var mouseLocalX = c * mouseRelativeX + s * mouseRelativeY;
            var mouseLocalY = -s * mouseRelativeX + c * mouseRelativeY;

            self.w = 2 * mouseLocalX;
            self.h = 2 * mouseLocalY;
            self.target.css({
              width: self.w,
              height: self.h
            });
          })
          .one('mouseup', function(e) {
                $(document).off('mousemove');
          });
      })
      //============================== Rotate ===============================//
      .on('mousedown', '.rotate', function(e) {
        // Attach mouse move event only when first clicked.
        $(document).on('mousemove', function(e) {
            var topLeft = self.target.offset(),
              center = {
                x: topLeft.left + self.target.width() / 2,
                y: topLeft.top + self.target.height() / 2
              },
              rad = Math.atan2(e.pageX - center.x, center.y - e.pageY) - Math.atan(self.w / self.h),
              deg = rad * 180 / Math.PI;

            self.currentRotation = deg;
            self.target.css({
              transform: 'rotate(' + (deg) + 'deg)'
            });
          })
          .one('mouseup', function(e) {
            $(document).off('mousemove');
            $('.handle.resize').attr('data-position', self.positions[parseInt(self.currentRotation / 90 - 45)]);
          });
      });
  };
  self.init = function() {
    self.bindEvents();
    self.target.append(self.handles.clone(true));
  }();
}

The major changes are the following:
In the resize event, the mouse position is transformed to the local coordinate system based on the current rotation. The size is then determined by the position of the mouse in the local system.
The rotate event accounts for the aspect ratio of the box (the - Math.atan(self.w / self.h) part).
If you want to change the cursor based on the current rotation, check the angle of the handle (i.e. self.currentRotation + Math.atan(self.w / self.h) * 180 / Math.PI). E.g. if you have a cursor per quadrant, just check if this value is between 0..90, 90..180 and so on. You may want to check the documentation if and when negative numbers are returned by atan2.
Note: the occasional flickering is caused by the box not being vertically centered.

A: Nico's answer is mostly correct, but the final result calculation is incorrect -> which is causing the flickering BTW.  What is happening is the increase or decrease in size is being doubled by the 2x multiplication.  The original half-width should be added to the new half-width to calculate the correct new width and height.
Instead of this:
self.w = 2 * mouseLocalX;
self.h = 2 * mouseLocalY;

It should be this:
self.w = (self.target.width() / 2) + mouseLocalX;
self.h = (self.target.height() / 2) + mouseLocalY;


text:
Q: Ubuntu 20.04 freezes for no apparent reason, media continues to play, mouse moves but click doesn't work tired of running out of resources, two months ago I moved Ubuntu (new install) 20.04 to a HP ZBook 15 G6, Intel Quad-core CPU, with 48GB RAM, thinking it will never run out of RAM or CPU usage.
But already twice, the system seems to freeze for no apparent reason, the media (my Udemy course) continue to play. The mouse moves, but not reacting to clicking. Even my Virtualbox lab processes seem to be running, except I can't access them.
I have to press the power button to do a cold start. Below is the output from lspci. Does any of them raise an alarm?
@heynnema
ls -al /var/crash
total 8
drwxrwsrwt  2 root whoopsie 4096 Mar  3 10:47 .
drwxr-xr-x 14 root root     4096 Feb  3 21:40 ..

free -h
              total        used        free      shared  buff/cache   available
Mem:           46Gi       4.4Gi        39Gi       518Mi       2.6Gi        41Gi
Swap:         2.0Gi          0B       2.0Gi

sudo lshw -C memory
  *-firmware
       description: BIOS
       vendor: HP
       physical id: 0
       version: R92 Ver. 01.07.01
       date: 10/19/2020
       size: 64KiB
       capacity: 32MiB
       capabilities: pci pcmcia upgrade shadowing cdboot bootselect edd int5printscreen int9keyboard int14serial int17printer acpi usb smartbattery biosbootspecification netboot uefi
  *-memory
       description: System Memory
       physical id: 6
       slot: System board or motherboard
       size: 48GiB
     *-bank:0
          description: SODIMM DDR4 Synchronous 2667 MHz (0.4 ns)
          product: M471A2K43CB1-CTD
          vendor: Samsung
          physical id: 0
          serial: 13F78110
          slot: Top-Slot 1(left)
          size: 16GiB
          width: 64 bits
          clock: 2667MHz (0.4ns)
     *-bank:1
          description: [empty]
          physical id: 1
          slot: Top-Slot 2(right)
     *-bank:2
          description: SODIMM DDR4 Synchronous 2667 MHz (0.4 ns)
          product: 16ATF4G64HZ-2G6B2
          vendor: Micron
          physical id: 2
          serial: 2612692F
          slot: Bottom-Slot 1(left)
          size: 32GiB
          width: 64 bits
          clock: 2667MHz (0.4ns)
     *-bank:3
          description: [empty]
          physical id: 3
          slot: Bottom-Slot 2(right)
  *-cache:0
       description: L1 cache
       physical id: 11
       slot: L1 Cache
       size: 384KiB
       capacity: 384KiB
       capabilities: synchronous internal write-back unified
       configuration: level=1
  *-cache:1
       description: L2 cache
       physical id: 12
       slot: L2 Cache
       size: 1536KiB
       capacity: 1536KiB
       capabilities: synchronous internal write-back unified
       configuration: level=2
  *-cache:2
       description: L3 cache
       physical id: 13
       slot: L3 Cache
       size: 12MiB
       capacity: 12MiB
       capabilities: synchronous internal write-back unified
       configuration: level=3
  *-memory UNCLAIMED
       description: RAM memory
       product: Cannon Lake PCH Shared SRAM
       vendor: Intel Corporation
       physical id: 14.2
       bus info: pci@0000:00:14.2
       version: 10
       width: 64 bits
       clock: 33MHz (30.3ns)
       capabilities: pm cap_list
       configuration: latency=0
       resources: iomemory:400-3ff memory:ed332000-ed333fff memory:404a112000-404a112fff

sysctl vm.swappiness
vm.swappiness = 60

grep -i swap /etc/fstab
/swapfile                                 none            swap    sw              0       0

sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile                               file        2097148 0   -2

A: BIOS
You have BIOS R92 Ver. 01.07.01 dated 10/19/2020. There' a newer BIOS available, version 01.08.02 Rev.A, dated Jan 29, 2021, and can be downloaded here.
Note: Confirm that I have the correct web page for your model #.
Note: Have good backups before updating the BIOS.
vm.swappiness
With 48G RAM, we can tweak vm.swappiness to reduce swapping. Edit /etc/sysctl.conf and add vm.swappiness=10, then do sudo sysctl -p or reboot.
memory
With 48G RAM, you have an odd size amount of RAM, and because you have dis-similar SODIMMs, you don't get the speed advantage of memory interleaving. Assuming that you only have two SODIMM slots, recommend replacing one/both current SODIMMs with similar size/spec SODIMMs... ie: two 16G, or two 32G (check the maximum memory capacity specs for your model #).
swap
After setting vm.swappiness, we really shouldn't see too much swap activity, however 2G /swapfile is really too small. We'll change it to 4G...
Note: Incorrect use of the rm and dd commands can cause data loss. Suggest copy/paste.
In the terminal...
sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 48G RAM and 4G swap

Edit /etc/fstab, using sudo -H gedit /etc/fstab or sudo pico /etc/fstab.
Confirm this /swapfile line in /etc/fstab... and confirm no other "swap" lines... use SPACES in this line... confirm NO TABS...
/swapfile  none  swap  sw  0  0

reboot                    # reboot and verify operation


text:
Q: What to do if a RESTful api is only partly successful In our design we have something of a paradox. We have a database of projects. Each project has a status. We have a REST api to change a project from "Ready" status to "Cleanup" status. Two things must happen.

*

*update the status in the database

*send out an email to the approvers

Currently RESTful api does 1, and if that is successful, do 2.
But sometimes the email fails to send.  But since (1) is already committed, it is not possible to rollback.
I don't want to send the email prior to commit, because I want to make sure the commit is successful before sending the email.
I thought about undoing step 1, but that is very hard.  The status change involves adding new records to the history table, so I need to delete them.  And if another person make other changes concurrently, the undo might get messed up.
So what can I do?  If (2) fails, should I return "200 OK" to the client?
Seems like the best option is to return "500 Server Error" with error message that says "The project status was changed. However, sending the email to the approvers failed. Please take appropriate action."
Perhaps I should not try to do 1 + 2 in a single operation?  But that just puts the burden on the client, which is worse!

A: Just some random thoughts:
You can have a notification sent status flag along with a datetime of submission. When an email is successful then it flips, if not then it stays. When changes are submitted then your code iterates through ALL unsent notifications and tries to send. No idea what backend db you are suing but I believe many have the functionality to send emails as well. You could have a scheduled Job (SQL Server Agent for MSSQL) that runs hourly and tries to send if the datetime of the submission is lapsed a certain amount or starts setting off alarms if it fails as well.
If ti is that insanely important then maybe you could integrate a third party service such as sendgrid to run as a backup sending mech. That of course would be more $$ though...
Traditionally I've always separated functions like this into a backend worker process that handles this kind of administrative tasking stuff across many different applications. Some notifications get sent out every morning. Some get sent out every 15 minutes. Some are weekly summaries. If I run into a crash and burn then I light up the event log and we are (lucky/unlucky) enough to have server monitoring tools that alert us on specified application events.


text:
Q: navigation based on percentages I have a simple layout but it needs to be altered to work so it takes on a liquid layout capability.
Example:

There is a left and right arrow. This is only for placement for now. In the center I have time slots. Here is my html markup.

Previous

7:00pm

7:30pm

8:00pm

8:30pm

Next

What I need to do is have my time slots be spaced out evenly based on a percentage.
My overall width of the design is 1010px.
I have my prev button set to float left and my next button floating right. Then for my slots div I have it set to a fixed left margin of 159px from the left floating previous button. the starting position of slots is represented by a white dotted line before the 7:00pm text. Then all my li elements are floated left inside the slots div. These need to expand according to percentages. I wanted to set a specific width which was say 80 px which is represented by the blue in the example. Then the yellow represents the margins left and right to allow for the spacing. This is where I'm lost how to work out the percentage of spacing needed between the li elements so it spaces out correctly when you scale your browser.
I was taking the value between the 2 dotted white lines as my overall width of the slots. 657px so do I try and work out my margin percent based on that value or the total value of the design which is 1010px. Then do I divide it by the number of li elements inside the slots div.
I haven't really dealt with percentage based layout before so any help would be great.
For now this is just placement so I don't want to use JS for placement.

A: http://jsfiddle.net/pDPFW/ should get you started.
Please note that if you want to add px/em based css, like for margin, border, padding you should nest a div in the % based element and define the px/em based property there. this is basically the whole trick for fluid layouts. Always make sure the % based element has NO px based properties at all.
For example you should not have a list item with width: 16% and margin: 10px instead you nest a element inside the list and give it 10px margin


text:
Q: Varias imagenes en HTML Hola soy nuevo en esto y queria saber si alguien me puede orientar un poco. El tema es el siguiente... Estoy haciendo un catalogo web en el cual debo mostrar verias imagenes en un mismo HTML pero el codigo es muy largo ya que serian mas o menos unos 50 productos y solo he conseguido hacerlo de la siguiente manera.

    <?php
    $sql="SELECT * FROM products where codigo_producto=001";
    $res=mysqli_query($con,$sql);

    while($mostrar=mysqli_fetch_array($res)){
        ?>
   <?php echo $mostrar['codigo_producto']?>
   <?php echo $mostrar['precio_producto']?>
<?php
}
?>

        Codigo
        Precio

    <?php
    $sql="SELECT * FROM products where codigo_producto=002";
    $res=mysqli_query($con,$sql);

    while($mostrar=mysqli_fetch_array($res)){
        ?>

        <?php echo $mostrar['codigo_producto']?>
        <?php echo $mostrar['precio_producto']?>

<?php
}
?>

Y ese codigo lo tengo que repetir por cada producto (no se como hacerlo de otra manera). Hay alguna manera de mostrar las 50 imagenes y no repitir el mismo codigo por aca una y asi no quede tan largo?
Quisiera que se viera asi. Pero sin tener que colocar 50 veces el codigo con el div fondo1,fondo2,3... etc.

Codigo Css.
body {}
#fondo1{background-image: url("/Catalogo-simple/img/1.png");
height: 210mm;
width: 297mm;
display: block;
margin: auto;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#fondo2{
background-image: url(/Catalogo-simple/img/2.png);
height: 210mm;
width: 297mm;
display: block;
margin: auto;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

A: Edito la respuesta para mostrar así la imagen, lo primero que se me ocurre rápido es que en tu base de datos agregues un campo nuevo que tenga el nombre de la imagen y su extencion y la imagen se la pongas en el HTML en lugar del CSS :
<?php
    $sql="SELECT * from products order by codigo_producto";
    $result=mysqli_query($con,$sql);
    while($mostrar=mysqli_fetch_array($result)){
 ?>
   <div style="background-image: url(/Catalogo-simple/img/<?php echo $mostrar['imagen'] ?>);">

                Codigo
                Precio

                <?php echo $mostrar['codigo_producto'] ?>
                <?php echo $mostrar['precio_producto'] ?>

<?php
}
 ?>


text:
Q: rvest table scraping including links I would like to scrape some table data from Wikipedia. Some of the table columns include links to other articles I'd like to preserve. I've tried this approach, which didn't preserve the URLs. Looking at the html_table() function description, I didn't find any options of including those. Is there another package or way to do this?
library("rvest")

url <- "http://en.wikipedia.org/wiki/List_of_The_Simpsons_episodes"

simp <- url %>%
        html() %>%
        html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
        html_table()

simp <- simp[[1]]

A: Try this
library(XML)
library(httr)
url <- "http://en.wikipedia.org/wiki/List_of_The_Simpsons_episodes"
doc <- content(GET(url))
getHrefs <- function(node, encoding) {
  x <- xmlChildren(node)$a
  if (!is.null(x)) paste0("http://", parseURI(url)$server, xmlGetAttr(x, "href"), " | ", xmlValue(x) ) else xmlValue(xmlChildren(node)$text)
}
tab <- readHTMLTable(doc, which = 3, elFun = getHrefs)
head(tab[, 1:4])
# No. in\nseries No. in\nseason                                                                                Title                                                               Directed by
# 1              1              1 http://en.wikipedia.org/wiki/Simpsons_Roasting_on_an_Open_Fire | Simpsons Roasting on an Open Fire http://en.wikipedia.org/wiki/David_Silverman_(animator) | David Silverman
# 2              2              2                                     http://en.wikipedia.org/wiki/Bart_the_Genius | Bart the Genius                                                           David Silverman
# 3              3              3                    http://en.wikipedia.org/wiki/Homer%27s_Odyssey_(The_Simpsons) | Homer's Odyssey                      http://en.wikipedia.org/wiki/Wes_Archer | Wes Archer
# 4              4              4       http://en.wikipedia.org/wiki/There%27s_No_Disgrace_Like_Home | There's No Disgrace Like Home                    http://en.wikipedia.org/wiki/Gregg_Vanzo | Gregg Vanzo
# 5              5              5                                   http://en.wikipedia.org/wiki/Bart_the_General | Bart the General                                                           David Silverman
# 6              6              6                                           http://en.wikipedia.org/wiki/Moaning_Lisa | Moaning Lisa                                                                Wes Archer

The URLs are preserved and separated by a pipe (|) from the text. So you could split it up for example by using strsplit(as.character(tab[, 3]), split = " | ", fixed = TRUE).


text:
Q: Google Vision API authentication on heroku What is a best, simple way to authenticate Vision API on heroku?
In development I just use:
@vision = Google::Cloud::Vision.new( project:  "instacult",
                                     keyfile:  "path/to/keyfile.json" )

Where keyfile is a json produced by google after creating service account (https://cloud.google.com/vision/docs/common/auth).
But obviously I can't just upload the keyfile to github.
I tried saving whole json to Heroku's config vars and running:
Rails.env.production? ? ENV["GOOGLE_CREDENTIALS"] : path

But I got "is not a valid file" in heroku's logs. Seems logical since I'm not passing a file but an object. But how to get over it?
Cheers,
Kai

A: SOLVED:
Turns out you can provide a json object in environment variable, but there is a naming convention.

Here are the environment variables (in the order they are checked) for
  credentials:

*

*VISION_KEYFILE - Path to JSON file

*GOOGLE_CLOUD_KEYFILE - Path to JSON file

*VISION_KEYFILE_JSON - JSON contents

*GOOGLE_CLOUD_KEYFILE_JSON - JSON contents

source: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-vision/v0.23.0/guides/authentication
So I ended up with calling:
@vision = Google::Cloud::Vision.new( project:  "instacult")

Having set VISION_KEYFILE_JSON in my ~/.bashrc:
export VISION_KEYFILE_JSON='the_json_content'

and on heroku (https://devcenter.heroku.com/articles/config-vars#limits).


text:
Q: Why get params are crashing my redirects in my authorize helper? I'm using a helper to authorize the access to admin pages.
The problem is when try access paths with 2 or more params.
Exemples:
- when I try to access /admin it redirects to /admin/login (OK)
- when I try to access /admin/ it redirects to /admin/admin/login (BAD)
- when I try to access /admin/users it redirects to /admin/admin/login (BAD)
- when I try to access /admin/users/add it redirects to /admin/users/admin/login (VERY BAD)
    module.exports = {
        authorizeAll: function(req,res,next){
            /*
                nivel
                if (req.isAuthenticated() && req.user.nivel >= 1){
            */
            if (req.isAuthenticated()){
                return next()
            }
            req.flash("error_msg", "Você precisa estar logado para ter acesso!");
            res.redirect('admin/login');
        }

}

what can i do to use a "base" url to redirect?
Thank you!!!

A: try adding / in front of admin/login. Express routing is looking relative to the route that you are hitting when it is set up with admin/login. Adding / should make it look from the root.
 module.exports = {
    authorizeAll: function(req,res,next){
        /*
            nivel
            if (req.isAuthenticated() && req.user.nivel >= 1){
        */
        if (req.isAuthenticated()){
            return next()
        }
        req.flash("error_msg", "Você precisa estar logado para ter acesso!");
        res.redirect('/admin/login'); // Only this line should change
    }
}


text:
Q: Internal Server Error while doing an insertion in Codeigniter I am working on a simple CRUD application using Codeigniter, and this section of code was working perfectly well until I added more functions.
Here is the problem:
I was adding 3 items to the database from user inputs, and it had no error. But when I added more input fields to get more inputs from the user, I ended up getting an Internal Server Error when I click on the "Add Item" button.
Below is the View Code:
<?php
    if ($_SESSION[AppStrings::$NOMENCLATURE] != AppStrings::$SERVICE) {
    if ($_SESSION[AppStrings::$SIZE] != AppStrings::$MICRO) {
?>
        <form data-toggle="validator" class="form-horizontal form-material" method="post" action="#" onsubmit="addProduct(); return false;">

                            <input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Code" id="product_code" required/>

                        <input class="form-control" type="text" required="" placeholder="<?= $nomenclature ?> Name" id="product_name" required/>

                            <input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Cost Price" name="product_cp" id="product_cp" required/>

                            <input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Selling Price" name="product_sp" id="product_sp" required/>

                        <textarea class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Description" id="product_des" required/></textarea>

                        <input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Expiry Date" id="product_exp" onfocus="(this.type = 'date')" onblur="if (this.value == '') {
                            this.type = 'text'
                        }" required/>

                            <select name="supplier" class="form-control form-control-line" type="text" id="supplier" placeholder="<?= $nomenclature ?> Supplier">
                                <option value="">Supplier</option>
                                <?php
                                    foreach ($suppliers as $supplier) {
                                ?>
                                        <option value='<?= $supplier[DbStrings::$SUPPLIER_NAME] ?>'><?= $supplier[DbStrings::$SUPPLIER_NAME] ?></option>
                                <?php
                                    }
                                ?>
                            </select>

                                <select name="department" class="form-control form-control-line" type="text" id="department" placeholder="<?= $nomenclature ?> Department">
                                    <option value="">Department</option>
                                    <?php
                                        foreach ($departments as $department) {
                                    ?>
                                            <option value='<?= $department[DbStrings::$DEPARTMENT_NAME] ?>'><?= $department[DbStrings::$DEPARTMENT_NAME] ?></option>
                                    <?php
                                        }
                                    ?>
                                </select>

                                <select name="sub_departments" class="form-control form-control-line" type="text" id="sub_department" placeholder="<?= $nomenclature ?> Department">
                                    <option value="">Sub-Department</option>
                                    <?php
                                        foreach ($sub_departments as $sub_department) {
                                    ?>
                                            <option value='<?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?>'><?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?></option>
                                    <?php
                                        }
                                    ?>
                                </select>

                                    <input class="form-control" type="number" placeholder=" <?= $nomenclature ?> Vat" id="vat"/>

                            <button class="btn btn-primary btn-login btn-lg btn-block text-uppercase waves-effect waves-light" type="submit" name="product-btn">Add <?= $nomenclature ?></button>

        </form>
<?php
    }
}
?>

Here is the AJAX code:
function addProduct() {
    var product_code = $("#product_code").val();
    var product_name = $("#product_name").val();
    var product_cp = $("#product_cp").val();
    var product_sp = $("#product_sp").val();
    var product_des = $("#product_des").val();
    var product_exp = $("#product_exp").val();
    var supplier = $("#supplier").val();
    var department = $("#department").val();
    var sub_department = $("#sub_department").val();
    var vat = $("#vat").val();

    var addUrl = "home/addproduct";
    addUrl += "/" + product_code;
    addUrl += "/" + product_name;
    addUrl += "/" + product_cp;
    addUrl += "/" + product_sp;
    addUrl += "/" + product_des;
    addUrl += "/" + product_exp;
    addUrl += "/" + supplier;
    addUrl += "/" + department;
    addUrl += "/" + sub_department;
    addUrl += "/" + vat;

    $.ajax({type: 'GET', url: addUrl, data: {},
        success: function (result) {
            $.alert({
                content: result
            });
            $("#product_code").val("");
            $("#product_name").val("");
            $("#product_cp").val("");
            $("#product_sp").val("");
            $("#product_des").val("");
            $("#product_exp").val("");
            $("#supplier").val("");
            $("#department").val("");
            $("#sub_department").val("");
            $("#vat").val("");
            location.reload();
        },
        error: function (xhr, status, error) {
            $.alert({
                content: 'Could not complete the process. ' + error
            });
        }
    });
}

Here is the Controller Function:
private function addproduct($product_code = null, $product_name = null, $product_cp = null, $product_sp = null, $product_des = null, $product_exp = null, $supplier = null, $department = null, $sub_department = null, $vat = null) {
    if (isset($product_code, $product_name, $product_cp, $product_sp, $product_des, $product_exp, $supplier, $department, $sub_department, $vat)) {
        $email = $_SESSION[DbStrings::$EMAIL];
        $product_code = $this->test_input($product_code);
        $product_name = $this->test_input($product_name);
        $product_cp = $this->test_input($product_cp);
        $product_sp = $this->test_input($product_sp);
        $product_des = $this->test_input($product_des);
        $supplier = $this->test_input($supplier);
        $department = $this->test_input($department);
        $sub_department = $this->test_input($sub_department);
        $vat = $this->test_input($vat);
        $product_exp = strtotime($product_exp);

        $insertedProduct = $this->member->insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp);

        if ($insertedProduct) {
            echo "Your " . $_SESSION[AppStrings::$NOMENCLATURE] . " has been added succesfully";
        } else {
            echo "There was a problem inserting your " . $_SESSION[AppStrings::$NOMENCLATURE] . ". Please try again.";
        }
    } else {
        echo 'Please fill all fields';
    }
}

And this is the Model that does the insertion before sending back a result:
public function insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp) {
    $data = array(
        DbStrings::$PRODUCTID => "",
        DbStrings::$EMAIL => $email,
        DbStrings::$PRODUCT_CODE => $product_code,
        DbStrings::$PRODUCT_NAME => $product_name,
        DbStrings::$PRODUCT_COST => $product_cp,
        DbStrings::$PRODUCT_SELLING => $product_sp,
        DbStrings::$PRODUCT_MARKUP => 9,
        DbStrings::$PRODUCT_DESCRIPTION => $product_des,
        DbStrings::$SUPPLIER => $supplier,
        DbStrings::$DEPARTMENT => $department,
        DbStrings::$SUB_DEPARTMENT => $sub_department,
        DbStrings::$VAT => $vat,
        DbStrings::$STOCK_BALANCE => 1,
        DbStrings::$MIN_LEVEL => 1,
        DbStrings::$MAX_QUANTITY => 1,
        DbStrings::$QUANTITY_SOLD => 1,
        DbStrings::$EXPIRY_DATE => $product_exp,
        DbStrings::$DATE_CREATED => time(),
        DbStrings::$DATE_STOCKED => time()
    );

    return $this->db->insert(DbStrings::$PRODUCTS_TABLE_NAME, $data);
}

I still get an error from the server, and don't know what else to do.
Correcting the above issue, the code works fine. I used: $this->output->enable_profiler(TRUE); and  i was able to see the MySQL query sent by the model to the server, and when i copied the query and pasted it in my localhost:phpmyadmin, i got flagged for errors and there seem to be no syntax error.
Now this is creeping me out, as i can't fix it.


text:
Q: Set a certain tab as active on load with custom jquery tabs I'm using http://jqueryfordesigners.com/jquery-tabs/ for a project, the tabbing javascript code looks like this:

and the tabs html looks like this :

First

Second

Third

First

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Second

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Third

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The question is : How do I set a second tab to be selected and shown by default when page loads? I've tried to replace all instances of "first" with "second" in javascript code but it wouldnt work...
Here is a demo page completed with css for you to toy around http://jqueryfordesigners.com/demo/tabs.html :)
Please help!

A: There are two parts that are selecting the first tab and thus need to change:
tabContainers.hide().filter(':first').show();

and
.filter(':first').click();

The filters are using :first, a selector that selects the first matching element. :second is not a valid selector. To select the second tab instead, try this:
var tabContainers = $('div.tabs > div');
tabContainers.hide(); // don't need to show a tab here; it'll be shown below

$('div.tabs ul.tabNavigation a').click(function () {
    tabContainers.hide();
    tabContainers.filter(this.hash).show();
    $('div.tabs ul.tabNavigation a').removeClass('selected');
    $(this).addClass('selected');
    return false;
}).filter('[href="#second"]').click(); // click second link, based on href attr

This could be cleaned up further, but hopefully it gets you started. You can read up on the jQuery filter() method at http://api.jquery.com/filter/ and the jQuery click() method at http://api.jquery.com/click/.


text:
Q: Getting statusCode of 400 from GET I am trying to do a get from the API, but it returns a 400, I have tried putting my local IP and putting 10.0.2.2, but he has continued to do the same, in the Event Log shows me this too: Emulator: CANNOT TRANSLATE guest DNS ip.From the PostMan I get the JSON back correctly so I do not think the problem is in the API
This is where I do everything
    public void PendingTrajects(){

     AsyncHttpClient client = new AsyncHttpClient();
       String URL = "http://ip:port/api/trajectes";
       client.get(this, URL, new AsyncHttpResponseHandler() {

       @Override
       public void onStart() {
           Toast.makeText(PendingTrajectRecyclerView.this, "Carregant...", Toast.LENGTH_SHORT).show();
       }

       @Override
       public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
           JSONArray Usuaris = new JSONArray();
           JSONArray trajectes = new JSONArray();

           String Nom = null;

           String strResponseBody = new String(responseBody);

           try {
               //Usuari = new JSONArray(strResponseBody);
               trajectes = new JSONArray(strResponseBody);
           }catch (JSONException e){
               Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
           }

           try {
               for(int i = 0; i < trajectes.length(); i++){
                   JSONObject trajecte = trajectes.getJSONObject(i);
                   JSONArray realitzas = trajecte.getJSONArray("realitzas");
                   for(int j = 0; j < realitzas.length(); j++){
                       JSONObject realitza = realitzas.getJSONObject(j);
                       JSONObject usuari = realitza.getJSONObject("usuari");
                       Log.d("xd", ""+usuari.getString("name"));
                   }
               }
           }catch (JSONException e){
               Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
           }
       }

       @Override
       public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
           Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió ONFailure", Toast.LENGTH_SHORT).show();
           Log.d("Error",""+statusCode);
       }

   });

A: 400 BAD REQUEST

The server cannot or will not process the request due to something
  that is perceived to be a client error (e.g., malformed request
  syntax, invalid request message framing, or deceptive request
  routing).

You should DEBUG your Application. Check your parameters.
Add a Break-point here
 String URL = "http://ip:port/api/trajectes";

Actually server could not understand the request due to invalid syntax.


text:
Q: Learner Question: A way to conditionally style a set of fields based on state I have a set of fields using MS Fabric UI which I would like to blur if a radioButton is either selected or not.
The fields are all within the one component.
Here's the code:

       Job Code and Position Details

 ETC..

I have this function which is triggered when the radio button is selected and changed:
private _evalTypeChange = (ev: React.FormEvent<HTMLInputElement>, option: any) => {
    this.setState({
      EvalType: option.text
    });
    if(option.text === 'New'){
      this.setState({IsEvalTypeDisabled: false});
    } else if(option.text === 'Re-evaluation') {
      this.setState({IsEvalTypeDisabled: true});
    } else if(option.text === 'Appeal') {
      this.setState({IsEvalTypeDisabled: true});
    }

      if(this.state.EvalType === null) {
       this.setState({
        BlurOrNot: true
       }, () => {console.log(this.state.BlurOrNot+'BlurOrNot if null');});
       return
;
      } else if (this.state.EvalType === 'New') {
        this.setState({
        BlurOrNot: false
        },() => {console.log(this.state.BlurOrNot+'BlurOrNot if New'+this.state.EvalType+'evaltype');});
      } else if (this.state.EvalType === 'Re-evaluation') {
        this.setState({
        BlurOrNot: false
        }, () => {console.log(this.state.BlurOrNot+'BlurOrNot if Re-evaluation'+this.state.EvalType+'evaltype');});
      } else if (this.state.EvalType === 'Appeal') {
        this.setState({
        BlurOrNot: false
        }, () => {console.log(this.state.BlurOrNot+'BlurOrNot if Appeal'+this.state.EvalType+'evaltype');});
    }
  }

But it's not working because the blurred fields are showing correctly when the radio button is blank but when the New radio button is selected the fields disappear completely. I believe it might be the setState using the previous selected?
Can someone show me where I am going wrong?
EDIT AFTER SOLVED: The BlurOrNot is a Boolean set to null. This is IMPORTANT! :) and also Saqib's answer below.

A: Just an example if the BlurOrnot is true a class that will be applied is stylesEvalReq.blurText otherwise stylesEvalReq.NotblurText class will be applied.
This ternary operator is the way to make conditional styles.
className={this.state.BlurOrNot?stylesEvalReq.blurText:stylesEvalReq.NotblurText}


text:
Q: How to implement a script folder to a Wordpress website? I have bought a script with a boostrap base. The folder has this structure:
csgoboost
├── css/
├── fonts/
├── img/
├── js/
└── index.php

Should I just put it in the Public_HTML folder and declare it on a webpage? I want to run it on one specific webpage, it is basically a form where you can select different options. Thank you very much!

A: You can register and enqueue the script so WordPress knows what it's called and where to find it like so:
 wp_enqueue_script( 'script-name', get_home_path() . '/js/example.js', array(), '1.0.0', true );

This would work if the js folder is in the root directory where you installed WordPress. You can put it in functions.php.

A: You can put either in a root or in a theme folder.
If you put it into root and want to include any files then use base_url() and if you have put script folder into theme then use get_template_directory_uri() function to retrieve files.

A: hi you can use css by <link rel="stylesheet" type="text/css" href="<?php echo get_template_directory_uri ();?>/css/bootstrap.min.css">
 and  script by
<script src="<?php echo get_template_directory_uri ();?>/js/bootstrap.min.js" ></script>

Same for images you just need to match path after <?php echo get_template_directory_uri ();?>


text:
Q: How to generates curves from fabric pattern uploaded My main aim is to generate a such curves that it should get fit full sleeves of shirt as shown in image.
I tried but still lines are not coming properly as expected
help me for this.
test fabric pattern is vertical fabrics of below shown image.
 what I got out out from scripted function is

I want more accurate to fit in sleeves shape
I have worked on following script.

function curve2(event)
{

   var ctx = c.getContext("2d");

    var getImagePath =  URL.createObjectURL(event.target.files[0]);

     // just some inits for demo
    var img = new Image;
    img.onload = slice;
    img.src = getImagePath;

    function slice() {
      c.width = img.height;
   c.height = img.width;

     // var step = Math.PI / h; // full circle / width of canvas
     // var scale = 75; // max displacement on y
  var w = c.width = this.height;
      var h = c.height = this.width+10;
    //var h = c.height = this.width+10;    //2
   //var h = c.height = this.width-40;

   //396

       var step = Math.PI / 500; // full circle / width of canvas
   // var step = Math.PI / 500; // 2
      var scale = 240; // max displacement on y
 //  var scale = 230; // 2
   // var scale = 200; // max displacement on y

      for (var y = 0; y < h; y++) {
        ctx.drawImage(this,
          -1, y, w, 1, // source line from image
          Math.cos(step * y) * scale, y,w, 1); // displaced line
      }
    }

}

<canvas id="c"></canvas>
<div id="ror">
<input type='file' id='getval' name="background-image" onchange="curve2(event)"  />

A: I'll leave the maths to someone more qualified but I think the problem stems from the fact that you are offsetting each line in order to form a curve. I think you should rotate around the centre of curvature.
A rough illustration of what I mean:


text:
Q: Three-tier architecture in Ruby and Ruby on Rails I'm an ASP.NET MVC developer who decided to learn Ruby and Ruby on Rails. I already know something and created a web site on RoR. Developing on ASP.NET MVC, I have always used a three-tier architecture: data layer, business layer and UI (or presentation) layer.
Trying to use this approach in a Ruby on Rails application, I found that there was no information about it (or maybe I just couldn't find it?).
Perhaps someone can suggest me how to create or use three-tier architecture on Ruby on Rails?
P.S. I use ruby 1.9.3 and Ruby on Rails 3.2.3.

A: I would suggest following Ruby on Rails (RoR) style while making RoR applications. Rails way of seeing MVC architecture does not quite fit into Asp.net 3 Tier architecture.
UI (Presentation Layer | View)
These two follow the same logic. No major differences.
Controller (Business Layer | Controller)
Both Business Layer and Controller receive requests from UI and they send back responses. In Asp.net Business Layer takes care of validation and business logic. But in Rails, validations and business logic belong to Model.
Model (Data Layer | Model)
Rails' Model does more than Asp.net's Data Layer. Model deals with business logic and validations. Data Layer and Model take care of data transfer to storage.
When moving from Asp.net to RoR, try to keep your controllers thin. RoR sets serious constraints on how you structure your web application. And once you'll stick with those, you'll make more professional RoR apps.

A: Ruby on Rails is a three tier (MVC) architecure. In rails the data layer is the called the Model, the buisness layer is called the Controller, and the user interface layer is called Views.
Here are a couple good places to start:
rails guides,
rails tutorial for rails 3.2

A: After 4+ years, this is still a relevant question. It appears there's a confusion around what people mean by application tiers.
Previous answers are of course correct when you think of MVC tiers, and when you define an application as being 3-tier if it has proper models, views and controllers. Of course Rails is by default 3-tier in this sense, with notable differences to ASP.NET MVC as pointed out by others.
However, I have a feeling that the original question referred to how things are deployed (I may of course be wrong, but people looking at this question may still be looking for this). Enterprise applications often have the requirement to be three tier in a sense that a web application (presentation) can only talk to services (business logic), which can only talk to a database due to network level restrictions, and for security reasons.
In this model, the front-end web application performs security functions (protection against several types of attacks like CSRF or Clickjacking, maybe session management, etc.), and presents any data read from services on application servers. These application servers are not directly accessible by endusers, often trust web servers (or not, depending on the security model), and persist their data in databases, which cannot be accessed directly by web servers. In a Windows environment, web, app and database servers are typically in different domains.
Rails, as described in pretty much all tutorials, is a web and app server at the same time, which does not fit the latter model, and there really are not much resources available on how to do this properly. However, especially with Rails 5, it is very easy to turn Rails into a proper service to be used as an application server with an API (see the API-only Applications Guide), and it is also possible to create another Rails application for the web (presentation) tier. You will have to solve quite a lot of things for yourself though, from authentication between web and app to making service queries from web to app, especially now that ActiveResource is kind of retired.


text:
Q: When second domain controller is down, clients lose authentication Our domain controller is on Windows Server 2008 R2.
I recently set up another server to be our second domain controller.
Whenever I take this second DC down, many of our client computers, some Win 7 some Win 10, lose their authentication.  Drives mapped to server share names become inaccessible.  Server shares can be accessed by IP only.  Users get prompted to enter their network authentication, with a message that "the system cannot contact a domain controller".  All clients are set to DHCP, all have their DNS and DHCP correctly pointed to the main DC.
When I both DCs are running, and I run nltest /dsgetdc:mydomain on one of the problematic clients, it returns with the secondary DC, not the main one.
On one of these clients, I did an IPCONFIG /release and /flushdns, rebooted, and it was fine.  Others weren't.
When I run NTDSUTIL, and connect it to our main DC, it "knows about 5 roles" - all of the following roles are assigned to itself:
Schema
Naming Master
PDC
RID
Infrastructure
When I run NTDSULTIL and connect it to the secondary DC, it provides the exact same information - it "knows about 5 roles", each one points to the main DC.
Why are clients getting disconnect / de-authenticated when the second DC goes down?
Many thanks!!
Matthew


text:
Q: Try to make a IF on a page but it dont work I have a small problem with Laravel:
This is my web.php
Route::get('contakt/{code?}', function ($code = "null") {
    return view('contakt',compact('code'));
})->name("contakt");

And this is my Page:
@if (strcmp($code,"success"))

        Success!

@endif

When i var_dump out on the contact page the content of $code this is the result:
.../storage/framework/views/8ebd5bc41eecbc72e9a5480450fe96d3ba115d33.php:81:string 'success' (length=7)

so why do it not work? The Content of strcmp($code,"success") is 0. I tried everything but without any success (I tried also @if ($code == "success")) :(


text:
Q: How to automatically run python script, when file is added to folder? How can I automatically run a python script, whenever a Word-File is added to a specific folder? This python script would need to work with the Word-File afterwards. My operating system is Windows.
Thanks for your help in advance.

A: There are several ways to do this and also a special Python package for this
Watchdog Python script for Windows file system
https://pypi.python.org/pypi/watchdog
https://blog.philippklaus.de/2011/08/use-the-python-module-watchdog-to-monitor-directories-for-changes

A: I have tried all these solutions, but it didnt worked well for me
But!
I have got the solution,
Heres the code:
path_to_watch = "your/path"
print('Your folder path is"',path,'"')
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
        after = dict ([(f, None) for f in os.listdir (path_to_watch)])
        added = [f for f in after if not f in before]
        if added:
                print("Added: ", ", ".join (added))
                break
        else:
             before = after

I have edited the code, the orginal code is available at http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
The original code was made in python 2x so you need to convert it in python 3.
Note:
Whenever you add any file in path, it prints the text and breaks, and if no files are added then it would continue to run.

A:
How can I automatically run a python script, whenever a Word-File is added to a specific folder?

A solution for this can be found in the following code:
import os

# define path for file
word_file = "path/to/file"

while True:

    if os.path.exists(word_file):
        # your code here

This code uses the os module to interact with the PC's file system, and starts a while loop that always runs. The conditional statement's condition is the existence of the word_file in the specified location, and you can execute your desired code within the if statement.
I hope this is helpful - let me know if you have any questions!

A: You may want to look into creating a python service.
How do you run a Python script as a service in Windows?
Like the other answer here, you will create an enduring loop to periodically check the filesystem for your file and then do something if/when it finds it.

A: you can use watchdog, and create your own eventHandler, like, overwriting original functions inside filesystemeventhandler, by creating a class using filesystemeventhandler(class MyHandler(fileSystemEventHandler):), you can change on_any_event or on_created_ or on_modified.

A: If you want to run this script infinite you can use this one:
import os

path_to_watch = "C:/Users/someone/"
print('Your folder path is"',path_to_watch,'"')

old = os.listdir(path_to_watch)
print(old)

while True:
    new = os.listdir(path_to_watch)
    if len(new) > len(old):
        newfile = list(set(new) - set(old))
        print(newfile[0])
        old = new
        extension = os.path.splitext(path_to_watch + "/" + newfile[0])[1]
        if extension == ".zip":
            print("hello")
        else:
            continue
    else:
        continue

In this case, I was monitoring for a new .zip file. But when you change it into your wanted extension, it will run something when there's a new word document. When you put the script you want to run when there is a new word document under the "if extension..." it should work.
Code is based on the script from @Faraaz Kurawle.


text:
Q: Change Table Structure in SQl Server 2008 I am trying to change a design of a table in SQL Server 2008, but I am getting an error stating that I need to drop and recreate the table.How Can I Solve This Problem.

Saving Changes is Not Permitted.The
  Changes you Have Made require the
  following tables to be dropped and
  re-created.you have either made
  changes to a table that can't be
  re-created or enabled the option
  prevent saving changes that require
  the table to be re-created.

A: Go to: Tools - Options - Designers - Table and Database Designers and de-select "Prevent saving changes that requiere table re-creation"

A: You can do most things with ALTER TABLE. Changing a datatype, nullability, adding/removing most constraints, adding/removing columns (ignoring order) should not require a table rebuild.
The GUI designer will ask for a table rebuild if you reorder columns, or add IDENTITY.

A: As  Pcofre has said the answer is:
click Tools ---> Options ----> Designer ---->
on the right pane find the option meaning prevent the tables from being recreated
then Remove its tick


text:
Q: SQL to standardize PostalCode data I have a SQL Server table with one column that stores Canadian Postal Codes.  Sometimes they're in the proper format H0H 0H0, and othertimes they're written like H0H0H0 or H0H-0H0.  I'm looking to be able to update all records to standardize the format as H0H 0H0 but I cannot figure out the SQL.  Any help would be appreciated.

A: UPDATE PostalCodes SET PostalCode = LEFT(PostalCode, 3) + ' ' + RIGHT(PostalCode, 3 )

This assumes that the postal code field has already been trimmed on both the left and right sides.  It literally grabs the left 3 digits, places a space and then the right 3 digits.

A: Assuming that the following constraints hold:

*

*the field in question is always at least 6 characters in length.

*the first segment of the postal code is in columns 1-3 of the field

*the last segment is in the rightmost 3 columns of the field.

*There are zero or more extraneous characters located at column 4.

This should do the trick, for any number of characters in the field.:
update PostalCodes
set PostalCode = stuff( PostalCode , 4 , len(PostalCode) - 6 , ' ' )

Alternatively, you could do something like this — a case statement to look for all the different ways people have found to create junk postal codes and treat each according to its needs:
update PostalCodes
set PostalCode = case
                 when PostalCode like '[A-Z][0-9][A-Z][ -][0-9][A-Z][0-9]' then ...
                 when PostalCode like '![A-Z][0-9][A-Z][0-9][A-Z][0-9]'    then ...
                 ...
                 else PostalCode
                 end

A select statement like
select PostalCode,count(*)
   from  PostalCodes
   where PostalCode not like '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]'
   group by PostalCode
   order by 2 desc
should show you the junk data.


text:
Q: Conversion Integer to Roman Numeral i want to convert integer to roman numeral.
As we know, format for roman numeral is like this:

*

*1 = I

*5 = V

*10 = X

*50 = L

*100 = C

*500 = D

*1000 = M

For example, if we have number 497, it will be CDXCVII.
In Java, i know we can use Switch Case for the condition.
Is there any idea to implement this in apex?

A: Represent the number with just I, and then we replace the characters in ascending value of the roman characters.
String intToRoam(integer Num){
  return  'I'.repeat(Num)
            .replace('IIIII', 'V')
            .replace('IIII', 'IV')
            .replace('VV', 'X')
            .replace('VIV', 'IX')
            .replace('XXXXX', 'L')
            .replace('XXXX', 'XL')
            .replace('LL', 'C')
            .replace('LXL', 'XC')
            .replace('CCCCC', 'D')
            .replace('CCCC', 'CD')
            .replace('DD', 'M')
            .replace('DCD', 'CM');
}

system.debug('Romanstr ' + intToRoam(497));

A: I don't think there is any native functionality to implement this. So you need to write custom logic to implement this. As Java and Apex share similar code concept so you can take help from there
public static String IntegerToRomanNumeral(int input) {
    if (input < 1 || input > 3999)
        return "Invalid Roman Number Value";
    String s = "";
    while (input >= 1000) {
        s += "M";
        input -= 1000;        }
    while (input >= 900) {
        s += "CM";
        input -= 900;
    }
    while (input >= 500) {
        s += "D";
        input -= 500;
    }
    while (input >= 400) {
        s += "CD";
        input -= 400;
    }
    while (input >= 100) {
        s += "C";
        input -= 100;
    }
    while (input >= 90) {
        s += "XC";
        input -= 90;
    }
    while (input >= 50) {
        s += "L";
        input -= 50;
    }
    while (input >= 40) {
        s += "XL";
        input -= 40;
    }
    while (input >= 10) {
        s += "X";
        input -= 10;
    }
    while (input >= 9) {
        s += "IX";
        input -= 9;
    }
    while (input >= 5) {
        s += "V";
        input -= 5;
    }
    while (input >= 4) {
        s += "IV";
        input -= 4;
    }
    while (input >= 1) {
        s += "I";
        input -= 1;
    }
    return s;
}

Converting Integers to Roman Numerals - Java


text:
Q: A Multi-Index Construction for Intraday TimeSeries (10 min price data) I have a file with intraday prices every ten minutes. [0:41] times in a day. Each date is repeated 42 times. The multi-index below should "collapse" the repeated dates into one for all times.

*

*There are 62,035 rows x 3 columns: [date, time, price].

*I would like write a function to get the difference of the ten minute prices, restricting differences to each unique date.
In other words,  09:30 is the first time of each day and 16:20 is the last: I cannot overlap differences between days of price from 16:20 - 09:30. The differences should start as 09:40 - 09:30 and end as 16:20 - 16:10 for each unique date in the dataframe.
Here is my attempt. Any suggestions would be greatly appreciated.
def diffSeries(rounded,data):

'''This function accepts a column called rounded from 'data'
 The 2nd input 'data' is a dataframe
'''

df=rounded.shift(1)
idf=data.set_index(['date', 'time'])
data['diff']=['000']

  for i in range(0,length(rounded)):

    for day in idf.index.levels[0]:

      for time in idf.index.levels[1]:

        if idf.index.levels[1]!=1620:

          data['diff']=rounded[i]-df[i]

        else:
          day+=1
          time+=2

data[['date','time','price','II','diff']].to_csv('final.csv')

return data['diff']

Then I call:
data=read_csv('file.csv')

rounded=roundSeries(data['price'],5)

diffSeries(rounded,data)

On the traceback - I get an Assertion Error.

A: You can use groupby and then apply to achieve what you want:
diffs = data.groupby(lambda idx: idx[0]).apply(lambda row: row - row.shift(1))

For a full example, suppose you create a test data set for 14 Nov to 16 Nov:
import pandas as pd
from numpy.random import randn
from datetime import time

# Create date range with 10 minute intervals, and filter out irrelevant times
times = pd.bdate_range(start=pd.datetime(2012,11,14,0,0,0),end=pd.datetime(2012,11,17,0,0,0), freq='10T')
filtered_times = [x for x in times if x.time() >= time(9,30) and x.time() <= time(16,20)]
prices = randn(len(filtered_times))

# Create MultiIndex and data frame matching the format of your CSV
arrays = [[x.date() for x in filtered_times]
         ,[x.time() for x in filtered_times]]
tuples = zip(*arrays)

m_index = pd.MultiIndex.from_tuples(tuples, names=['date', 'time'])
data = pd.DataFrame({'prices': prices}, index=m_index)

You should get a DataFrame a bit like this:
                       prices
date       time
2012-11-14 09:30:00  0.696054
           09:40:00 -1.263852
           09:50:00  0.196662
           10:00:00 -0.942375
           10:10:00  1.915207

As mentioned above, you can then get the differences by grouping by the first index and then subtracting the previous row for each row:
diffs = data.groupby(lambda idx: idx[0]).apply(lambda row: row - row.shift(1))

Which gives you something like:
                       prices
date       time
2012-11-14 09:30:00       NaN
           09:40:00 -1.959906
           09:50:00  1.460514
           10:00:00 -1.139036
           10:10:00  2.857582

Since you are grouping by the date, the function is not applied for 16:20 - 09:30.
You might want to consider using a TimeSeries instead of a DataFrame, because it will give you far greater flexibility with this kind of data. Supposing you have already loaded your DataFrame from the CSV file, you can easily convert it into a TimeSeries and perform a similar function to get the differences:
dt_index = pd.DatetimeIndex([datetime.combine(i[0],i[1]) for i in data.index])
# or dt_index = pd.DatetimeIndex([datetime.combine(i.date,i.time) for i in data.index])
# if you don't have an multi-level index on data yet
ts = pd.Series(data.prices.values, dt_index)
diffs = ts.groupby(lambda idx: idx.date()).apply(lambda row: row - row.shift(1))

However, you would now have access to the built-in time series functions such as resampling. See here for more about time series in pandas.

A: @MattiJohn's construction gives a filtered list of length 86,772--when run over 1/3/2007-8/30/2012 for 42 times (10 minute intervals). Observe the data cleaning issues.
Here the data of prices coming from the csv is length: 62,034.
Hence, simply importing from the .csv, as follows, is problematic:
filtered_times = [x for x in times if x.time() >= time(9,30) and x.time() <= time(16,20)]
DF=pd.read_csv('MR10min.csv')
prices = DF.price
 # I.E. rather than the generic: prices = randn(len(filtered_times))  above.

The fact that the real data falls short of the length it "should be" means there are data cleaning issues. Often we do not have the full times as bdate_time will generate (half days in the market, etc, holidays).
Your solution is elegant. But I am not sure how to overcome the mismatch between the actual data and the a priori, prescribed dataframe.
Your second TimesSeries suggestion seems to still require construction of a datetime index similar to the first one. For example, if I were use the following two lines to get the actual data of interest:
DF=pd.read_csv('MR10min.csv')
data=pd.DF.set_index(['date','time'])

dt_index = pd.DatetimeIndex([datetime.combine(i[0],i[1]) for i in data.index])

It will generate a:
TypeError: combine() argument 1 must be datetime.date, not str

How does one make a bdate_time array completely informed by the actual data available?
Thank you to (@MattiJohn) and to anyone with interest in continuing this discussion.


text:
Q: Writing promises without opening then calls In an effort to stop writing a lot of duplicate code I'm trying to not open then calls. I'd preferably only like to pass functions around from a top level. Like this.
function ensureLink(srcPath, dstPath){
  dstPath = fsRedux.predictDir(srcPath, dstPath)
  var dstDir = path.dirname(dstPath)
  return fsRedux.exists(dstPath)
    .then(_.partialRight(fsRedux.ifFalseThrow, false, new Error(dstPath+" exists cannot ensure link")))
    .then(_.bind(fsExtra.mkdirsAsync, fsExtra, dstDir))
    .then(_.bind(_.bind(fsExtra.linkAsync, fsExtra, srcPath, dstPath)))
}

However the above code doesn't work. The test below shows that you cant pass a bound promisifyAll async function. The reason is that the then value is passed into these promises which causes them to act as the next argument in the call, for these functions that means they fire as a callback, which is why the first test error's out with Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test. in mocha.
var chai = require("chai")
var chaiAsPromised = require("chai-as-promised")
chai.use(chaiAsPromised)
chai.should()

var path = require("path")
var _ = require("lodash")
var mock = require("mock-fs")

var Promise = require("bluebird")
var fsRedux = require("./fs-redux")
var fsExtra = Promise.promisifyAll(require("fs-extra"))
var fs = Promise.promisifyAll(require("fs"))

mock({
  'path/hello-alpha.txt': 'file content here',
  'path/hello-beta.txt': 'file content here'
})

var dstPath = "path/to/fake/dir/"

function closedThen(srcPath, dstPath){
  dstPath = fsRedux.predictDir(srcPath, dstPath)
  var dstDir = path.dirname(dstPath)
  return fsRedux.exists(dstPath)
    .then(_.partialRight(fsRedux.ifFalseThrow, false, new Error(dstPath+" exists cannot ensure link")))
    .then(_.bind(fsExtra.mkdirsAsync, fsExtra, dstDir))
    .then(_.bind(_.bind(fsExtra.linkAsync, fsExtra, srcPath, dstPath)))
}

function openThen(srcPath, dstPath){
  dstPath = fsRedux.predictDir(srcPath, dstPath)
  var dstDir = path.dirname(dstPath)
  return fsRedux.exists(dstPath)
    .then(_.partialRight(fsRedux.ifFalseThrow, false, new Error(dstPath+" exists cannot ensure link")))
    .then(function(){
      return _.bind(fsExtra.mkdirsAsync, fsExtra, dstDir)()
    })
    .then(function(){
      return _.bind(fsExtra.linkAsync, fsExtra, srcPath, dstPath)()
    })
}

describe("issue", function(){
  describe("closedThen()", function(){
    it("should return then and run promise", function(){
      return closedThen("path/hello-alpha.txt", dstPath).then(function(){
        return fsExtra.readFileAsync("path/to/fake/dir/hello-alpha.txt", "utf8").should.eventually.equal("file content here")
      })
    })
  })
  describe("openThen()", function(){
    it("should return then and run promise", function(){
      return openThen("path/hello-beta.txt", dstPath).then(function(){
        return fsExtra.readFileAsync("path/to/fake/dir/hello-beta.txt", "utf8").should.eventually.equal("file content here")
      })
    })
  })
})

What functions exist, or way of wrapping the bound function would allow for working with promises this way?
Update:
I'm looking for a library of suite of function wrappers (lodash has a bunch of them) that allow for an easy interface of partialing or binding from my question earlier or wrapping functions to pass to a then or run within a Promise.reduce. That way chaining promises are really easy.
Ideally I just want to know how to get the line working, a way of wrapping it so that when it's passed a result from the then it ignores it. Or a recommended alternative.
.then(_.bind(fsExtra.mkdirsAsync, fsExtra, dstDir))

A: Here are three functions that allow you to only have to ever write one-method deep promises. They use the module dotty to edit an object set to a global scope outside the promise chain.
With wrap you can ignore the current then value in the chain.
function wrap(fn){
  return function(){
    return fn()
  }
}

With exportResult you can store the value for later use.
function exportResult(obj, property){
  return function(value){
    dotty.put(obj, property, value)
    return value
  }
}

With provideResult you can return a previous result value to return to the next then call.
function provideResult(obj, property){
  return function(){
    return dotty.get(obj, property)
  }
}

Resulting in something like this.
function ensureLink(srcPath, dstPath){
  dstPath = fsRedux.predictDir(srcPath, dstPath)
  var dstDir = path.dirname(dstPath)
  var values = {}
  return fsRedux.exists(dstPath)
    .then(exportResult(values, "exists"))
    .then(_.partialRight(fsRedux.ifFalseThrow, false, new Error(dstPath+" exists cannot ensure link")))
    .then(wrap(_.bind(fsExtra.mkdirsAsync, fsExtra, dstDir)))
    .then(wrap(_.bind(fsExtra.linkAsync, fsExtra, srcPath, dstPath)))
    .then(provideResult(values, "exists"))
    // continue the chain provide result from exists...
}

I originally was looking for a more elegant solution to this. Or recommendations on a current standard that does this.

A: Here's an example using Ramda.
var Promise = require("bluebird")
var R = require("ramda")
var path = require("path")
var fs = Promise.promisifyAll(require("fs"))
var fse = Promise.promisifyAll(require("fs-extra"))

function ifThrow(value, desiredValue, error){
  if(value == desiredValue) throw error
  return value
}

var fsEnsureLink = function(srcpath, dstpath){
  return R.pipeP.apply(null, [
    R.always(fs.lstatAsync(srcpath).then(R.T, R.F)),
    R.partialRight(ifThrow, false, new Error("source path does not exist")),
    R.always(fs.lstatAsync(dstpath).then(R.T, R.F)),
    R.partialRight(ifThrow, true, new Error("destination path exists")),
    R.always(fse.mkdirsAsync(path.dirname(dstpath))),
    R.always(fs.linkAsync(srcpath, dstpath)),
    R.T,
  ])()
}

fsEnsureLink("./package.json", "./test/package.json")
// promise -> true || Error thrown


text:
Q: What linux is easy to attach to a windows domain for a development test bed I need to attach ANY linux machiene to a test AD Domain and do single sign on through it. Is there a Linux Distro that is easy to connect to AD?

A: perhaps it was a silly question, this was stupid simple.
Ubuntu-10.04:
sudo apt-get install likewise-open
sudo domainjoin-cli join example.com Administrator

then ssh 'DOMAIN\username'@hostname and poof single sign on magic!
EDIT: today (June 2010) the likewise-open package is missing a dependency on psmisc so you have to run this first:
sudo apt-get install psmisc

if you already installed likewise-open then:
sudo apt-get purge likewise-open
sudo apt-get install likewise-open

EDIT1:
   need to add the AD DNS server as the hosts dns server first, and set the hostname.
EDIT2:
   need to make sure the reverse dns is correct.

A: CentOS, just open a terminal and type "setup" - then follow the instructions

A: On RHEL or CentOS 4 or newer the following command will reconfigure the auth system and join AD.  You can remove the flag for PAM /etc/security/access.conf if you don't want to configure it but I find that not everyone with a valid AD account should be allowed onto every host, only members of certain AD groups.  I believe there is also a flag to configure winbind to allow disconnected authentication, for laptops and such which need to log in when not on the network.
sudo /usr/sbin/authconfig-tui \
 --enablewinbind \
 --enablewinbindauth \
 --enablemkhomedir \
 --enablepamaccess \
 --enablelocauthorize \
 --smbsecurity=ads \
 --smbrealm=DOMAIN.COM \
 --smbworkgroup=DOMAIN \
 --smbservers=dc.domain.com \
 --winbindtemplatehomedir="/home/%U" \
 --winbindtemplateshell="/bin/bash" \
 --enablewinbindusedefaultdomain \
 --kickstart \
 --winbindjoin=DomainAdminAcct

A: Actually any Linux distro with a current Samba install should be able to be joined to a Windows domain. As mentioned Likewise on Ubuntu makes it extremely easy to get it up and working but I found that it worked best if I didn't have Likewise AND Samba installed otherwise they tried to fight one another.
Samba would be a more involved installation process as Likewise appears to be solely a NSS plugin of sorts while Samba adds the whole kitchen sink along with it allowing file and printer sharing to be made available.


text:
Q: What is this early LCD/PDP interface? This is the pinout for the internal screen connector of a 1986 Toshiba T3100SX 'laptop'. The screen itself is a orange neon gas plasma display (although they also made some with an LCD).

Does anyone know what the protocol is?
This pinout comes from the maintenance manual, which is very patchy regarding technical information --- so the above is all I've got. I know that DSPV is probably +12V. PDP and COLOR will be used to tell the video hardware whether the laptop has the gas plasma or LCD screen plugged in, and I bet that BRCNTM is something to do with brightness. The numbers after the pins are significant, but I don't know what they mean yet.
The screen will display VGA with 16-colour greyscale, so it's probably really simply clocking the pixels in at the right rate. The four-bit wide buses corroborate that. I'm not sure why there are two, though; left and right? Also I'd expect to see lines for horizontal and vertical sync, so unless these are what LP and FP are, then I'm wrong.
The motherboard itself seems to use a bunch of custom ASICs to generate the signal, so there's no help there.
I'm sure someone should be able to tell at a glance what this is. Any ideas?


text:
Q: Possible to set HtmlDataTable column width in backingbean As the title suggests, I'm looking for a way to set a column's width in my backing bean. There's a panel on the jsp that is common to several screens; its content is loaded depending on which screen the user is currently viewing. For this particular screen, I'm creating an HtmlDataTable in the backing bean, which is then added to the panel.
I need to change its width for a specific column. I can access the column as a UIColumn, but UIColumn does not have a width attribute. Perhaps something using ColumnClasses, but searching Google turned up no leads.
Any ideas?

A: Since you have mentioned about column classes I post this. I don't know exactly whether this solves your problem. If not please clarify little bit.
1.You should have style classes like this.

<style>
  .first{
         background-color:green;
          width:100px;
    }
  .second{
          background-color:yellow;
          width:200px;
   }
</style>

Your table will be as below

<h:dataTable value="" binding="#{myBean.table}">
        <rich:column>First Column</rich:column>
        <rich:column>Second Column</rich:column>
</h:dataTable>

Your bean contains some what like this.

HtmlDataTable table = new HtmlDataTable();
      public HtmlDataTable getTable() {
        table.setStyle("border:solid");
        table.setColumnClasses("first, second");
        return table;
      }
  public void setTable(HtmlDataTable table) {
        this.table = table;
      }


text:
Q: UIImagePickerController Issue in iPhone? Hey I'm new to iPhone and I have been trying to make an gallery kind of app using ARC. where i am capturing image from camera using UIImagePickerController. Sometimes when i am clicking on camera button..then it is working fine but sometimes it is displaying the preview screen like below screenshot, then user have to tap on UIImagePicker preview cancel button and again click on camera button for capturing image successfully..Can anyone tell me the reason why i am getting this problem?

here is my code :
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.allowsEditing = YES;
imagePickerController.sourceType = sourceType;
[self presentViewController:imagePickerController animated:YES completion:nil];

Thank you for your help.

A: Your code looks fine, but I know that the UIImagePicker is resource consuming.
I think it is more optimized to do the instantiation only once. Put this in your viewWillAppear method:
self.imagePickerController = [[UIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
self.imagePickerController.allowsEditing = YES;
self.imagePickerController.sourceType = sourceType;

Then when you want to present it use:
[self presentViewController:self.imagePickerController animated:YES completion:nil];

I noticed that it is way faster to present it this way. Let me know if it solved your issue.

A: For Camera user these
 _imgPickerController = [[UIImagePickerController alloc]init];
[_imgPickerController setDelegate:self];
[_imgPickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
 _imgPickerController.showsCameraControls = YES;
[self presentViewController:_imgPickerController animated:NO completion:Nil];

Don't forget to import these two Delegates
UIImagePickerControllerDelegate and UINavigationControllerDelegate


text:
Q: The test still read from the real SharedPreferences I have made a simple instrumented test to verify that if the data read from the SharedPreferences is displayed properly on the UI.Both data-retrieving and displaying actions are performed in Activity's onResume()method.
But the problem is,even if I've mocked the preference object and defined the fake return value,the activity still read data from the real preference,ignoring when(...).thenReturn(...)statement.Does anyone have any idea?
@RunWith(AndroidJUnit4.class)
public class EditProfileActivityTest {

    @Mock
    private UserPreference userPreference;
    private String FAKE_NAME = "Test";

    @Rule
    public ActivityTestRule<EditProfileActivity> activityTestRule = new ActivityTestRule(EditProfileActivity.class,true,false);

    @Before
    public void setUp(){

        //Set fake SharedPreferences
        MockitoAnnotations.initMocks(this);
        when(userPreference.getName()).thenReturn(FAKE_NAME);

        //Start Activity
        Intent intent = new Intent();
        activityTestRule.launchActivity(intent);
    }

    @Test
    public void showUserData() throws Exception{
        onView(withId(R.id.name_tv)).check(matches(withText(FAKE_NAME)));
    }
}

where UserPreference is a custom class which simply wraps SharedPreference class and contains lots of getters and setters.This is its constructor
public UserPreference(Context context) {
    this.context = context;
    sharedPreferences = this.context.getSharedPreferences("Pref", Context.MODE_PRIVATE);
    prefEditor = sharedPreferences.edit();
}

and one of its getter and setter:
public String getName() {
    return sharedPreferences.getString(context.getString(R.string.pref_name), "Guest");
}
public void saveName(String name){
    prefEditor.putString(context.getString(R.string.pref_name), name);
    prefEditor.apply();
}

[EDIT]
Simplified version of my original Activity:
public class EditProfileActivity extends AppCompatActivity{
    //...
    private UserPreference userPreference;
    //...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userPreference = new UserPreference(this);
        setContentView(R.layout.activity_edit_profile);
        //...
    }
    @Override
    protected void onResume() {
        super.onResume();
        //...
        String name = userPreference.getName();
        nameEdt.setText(name);  //Display the name on an EditText
        //...
    }
}

A: The UserPreference mock is created, but the activity still uses the one created in its onCreate method. You need to set that activity's userPreference field to your mock.
There are a few ways to do that:

*

*Add a setter method for the userPreference field and call it in your @Before method:
@Before
public void setUp(){
    ...
    EditProfileActivity activity = activityTestRule.launchActivity(intent);
    activity.setUserPreference(mockedUserPreference);
}

This is simple but ugly: you alter the activity solely to accomodate the test.

*Set the userPreference field via reflection:
@Before
public void setUp(){
    ...
    EditProfileActivity activity = activityTestRule.launchActivity(intent);
    Field userPreferenceField = activity.getClass().getDeclaredField("userPreference");
    field.setAccessible(true);
    userPreferenceField.set(activity, mockedUserPreference);
}

This is a brittle test: changing the field name breaks it without compile error. The activity doesnt have to be altered, though, so it is useful when you cant change it.

*Don't instantiate the UserPreference in the onCreate method. In plain Java i'd add it as a constructor argument, but i don't know if that works as easily with Android. Maybe use a dependency injection framework, they're perfect to use with mocking: Android and Dependency Injection


text:
Q: Razor MVC 3 Ajax returns 404 I'm trying to do a basic autocomplete via jquery AJAX, using Razor MVC 3 and Visual Studio 2012 (all of which I had never used before) My code is as follows
JS:
$(document).ready(function () {
    $("#city").keyup(function () {
        var input = $(this).val();
        getCities(input);
    });
});

function getCities(input) {
    var serviceURL = $("#autocompleteURL").val();
    var url =
        $.ajax({
            type: "POST",
            url: serviceURL,
            data: {
                'guess': input
            },
            success: function (data) {
                alert('OK!!');
            },
        });
}

Since i learned that it's not possible to use Razor syntax in a JS file, I'm getting the value from the view via a hidden input, like:
<input type="hidden" id="autocompleteURL" value="@Url.Action("AutoCompleteCity", "Controllers/SearchController")" />

Controller:
 public class SearchController: Controller
   {
       public ActionResult AutoCompleteCity(string guess)
        {
            //database stuff here
        }
   }

I don't know if I'm missing something else. Any help will be greatly appreciated. Thanks!

A: The convention for the controller name is just the semantic name of the controller, not the file path.  Instead of this:
Url.Action("AutoCompleteCity", "Controllers/SearchController")

Try this:
Url.Action("AutoCompleteCity", "Search")

(Note also that you can use the debugging tools in your browser to examine the URL being used in the AJAX call.)


text:
Q: Is it possible to use Mvc3 razor scripts aspx page view? Is it possible to use Mvc3 razor scripts inside mvc 2 aspx page view and mvc 2 ascx control view?

A: I'm not sure what you are asking. What do you mean by "razor scripts"? Do you mean a razor partial? In that case, then yes. An aspx view can call a razor partial just fine (and vice versa).
If you mean embed a chunk of razor inside of an aspx/ascx, then no.
Razor is intended for MVC 3, but people have successfully gotten it working in MVC 2. Such as this question: How to Download Razor View Engine

A: In short No. You can use Razor and the WebForms view engines alongside each other, but you cannot mix them in the same view.
Besides, as far as I know, you can't use Razor with ASP.NET MVC 2 either although I'm not 100% sure on that last one.