text:
Q: Handle mouse and touch events only inside a div I am trying to follow the cube code from https://codepen.io/jordizle/pen/haIdo/
Eventually the cube works on a project that I am working on. But I have run into an issue. The cube responds to events outside the div container that it is in. For example, if I use the mouse to drag on a different div, the cube which is on a separate div responds to the event.
I am not sure as to how to fix this issue.
I have created a fiddle here: https://jsfiddle.net/sourabhtewari/75c6qcm5/2/
I am not much of a JavaScript/jQuery expert but this is the initializing method
var cube = new Cube({
    viewport: viewport,
    element: document.getElementsByClassName('cube')[0]
});

with viewport being initialized in
var viewport = new Viewport({
    element: document.getElementsByClassName('cube')[0],
    fps: 20,
    sensivity: 0.1,
    sensivityFade: 0.93,
    speed: 2,
    touchSensivity: 1.5
});

I see that the element where the events are being binded looks OK to me. Hence, I am in a fix as to why the cube reacts to events which are outside its parent div.
The Binding events look like these
 bindEvent(document, 'mousedown', function () {
        self.down = true;
    });

    bindEvent(document, 'mouseup', function () {
        self.down = false;
    });

    bindEvent(document, 'keyup', function () {
        self.down = false;
    });

    bindEvent(document, 'mousemove', function (e) {
        self.mouseX = e.pageX;
        self.mouseY = e.pageY;
    });

    bindEvent(document, 'touchstart', function (e) {

        self.down = true;
        e.touches ? e = e.touches[0] : null;
        self.mouseX = e.pageX / self.touchSensivity;
        self.mouseY = e.pageY / self.touchSensivity;
        self.lastX = self.mouseX;
        self.lastY = self.mouseY;
    });

    bindEvent(document, 'touchmove', function (e) {
        if (e.preventDefault) {
            e.preventDefault();
        }

        if (e.touches.length === 1) {

            e.touches ? e = e.touches[0] : null;

            self.mouseX = e.pageX / self.touchSensivity;
            self.mouseY = e.pageY / self.touchSensivity;

        }
    });

    bindEvent(document, 'touchend', function (e) {
        self.down = false;
    });

If someone could help me out here, I would be thankful!

A: That's because mouse event listeners are bound to the document (whole page).
This is the part where the mouse events are being captured. Note the document variable which essentially references the page's document.
bindEvent(document, 'mousedown', function() {
  self.down = true;
});

You can use a div in front of the cube to capture events instead:

*

*Add a

 in front of your cube. Make sure it covers the whole "area" of your cube in all orientations.

*Grab that overlay div and pass that in the bindEvent functions instead of the document.

Example:
var overlay = document.getElementById("cube-overlay");

bindEvent(overlay, 'mousedown', function() {
  self.down = true;
});

// Make sure you do this change on all the `bindEvent` functions that
// deal with mouse/touch events

Updated Fiddle:
Here's an updated JSFiddle. In this fiddle, I simply gave an id="viewport" on your already existing
 element and used that as the bindEvent argument.


text:
Q: Configure apache2 and host to pass traffic to a docker container with nginx I'm currently running a ubuntu webserver with apache2, hosting multiple sites and subdomains. I would like to host bitwarden on my own webserver, which is only shipped in a docker container with nginx.
I would like to use a subdomain e.g. bitwarden.domain.com to access bitwarden. But I have no idea how to configure apache2 / host to pass through traffic going to bitwarden.domain.com to the docker container running bitwarden (without affecting the other domains).
My question: How to configure apache2/docker to achieve this? Is there any documentation/tutorial for this?

A: After starting the docker container, grab the container ip, port:
local_docker_ip, local_docker_port
And you have a couple of options:
Use apache2 Virtual host with a redirect:
<VirtualHost *:80>
    ServerName  bitwarden.domain.com
    Redirect permanent / http://{local_docker_ip}:{local_docker_port}/
</VirtualHost>

Or use the apache2 proxy module. First, enable proxy modules by running the commands:
a2enmod proxy
a2enmod proxy_http

Then, add the following virtual host:
<VirtualHost *:80>
    ProxyPreserveHost On
    ProxyRequests Off
    ServerName bitwarden.domain.com
    ProxyPass / http://{local_docker_ip}:{local_docker_port}/
    ProxyPassReverse / http://{local_docker_ip}:{local_docker_port}/
</VirtualHost>

I hope it helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chef mysql version 5.7 cookbook can't login as root I'm using the chef cookbook for mysql found at
https://supermarket.chef.io/cookbooks/mysql
Under a vagrant running ubuntu-16.04
My recipe contains the block:
mysql_service 'foo' do
  port '3306'
  version '5.7'
  initial_root_password 'hello'
  action [:create, :start]
end

It installs just fine, but when I shell into my vagrant and try
mysql -uroot -h127.0.0.1 -phello

I get an access denied message.  Is anyone else experiencing this issue?  Is this a bug in the recipe, and is there a patch somewhere that fixes it?

A: There was a strange conflict when installing that Apache and OpenSSL cookbooks in addition to MySQL.  I have not determined the exact cause, but on rebuilding the cookbook bit by bit, starting with the database server, this appears to have been the case.


text:
Q: Variable in windows function in VBA I am writing some VBA codes for a daily report. In itself, the ActualDate is a variable dimmed as Date. It is changing according to the date of the report and I want to use the input file to implement a few columns. Once I try to activate it once again after changing the window, I am not able to.
My code:
Windows("Inputfile" & ActualDate).Activate

How should I change the code so command Windows will work with a variable in it? I just need to activate the Excel file called for example Inputfile201021.xlsx. A hint is that at the beginning of the macro, I am used to opening the latest input file. Can I set its name to some constant and use it further in the code?

A:
, I am used to opening the latest input file. Can I set its name to some constant and use it further in the code?

No need to activate the window. You can work with the workbook like this.
Option Explicit

Sub Sample()
    Dim wb As Workbook
    Dim flName As String
    Dim ActualDate As String

    ActualDate = "201021"

    flName = "Inputfile" & ActualDate

    '~~> Change path as applicable
    Set wb = Workbooks.Open("C:\" & flName & ".xlsx")

    With wb
        '
        '~~> No need to activate. directly work with it here
        '
    End With
End Sub


text:
Q: How can I integrate result of API into container CSS? CSS is a container, and I expect to integrate API field value result into container. Could you please indicate how to proceed please?
Have a good day.
head

body

METEO CHAVENAY

"temperature"
 c° (temperature)
"pressure" hpa (pression par rapport au niveau de la mer)
"visibility" km (visibilité horizontale)
"windspeed" km/h (vitesse du vent)
"winddire" ° (direction du vent)
"clouds" % (couverture nuageuse)
"sunrise" (Heure du lever du soleil)
"sunset" (Heure du coucher du soleil)
"timezone" H GMT Time zone

A: try to put the fields INSIDE the div block with that css class:

    METEO CHAVENAY

"temperature"
 c° (temperature)
    "pressure" hpa (pression par rapport au niveau de la mer)
    "visibility" km (visibilité horizontale)
    "windspeed" km/h (vitesse du vent)
    "winddire" ° (direction du vent)
    "clouds" % (couverture nuageuse)
    "sunrise" (Heure du lever du soleil)
    "sunset" (Heure du coucher du soleil)
    "timezone" H GMT Time zone

Then, why all those double quotes?
And, why not put everything BETWEEN the div or span blocks? Normally there is no need to put text outside those blocks. But that is not the CSS problem.
To get width working on the div, you might want to add in the css:
display: inline-block;

It looks like you need more experience. I would focus on the basics first, before using complicated CSS like box-shadow.


text:
Q: Moving an app from a django project to another I created a django project(prjct1) and has an app in it(app1)
I also created another django project(prjct2) which also has an app(app2)
How can I move app2 in prjct1

A: Step 1: copy the app2 from project2 and paste it into project1.
Step 2 :In the settings of project2 include the app2 inside the installed apps.
Step 3: Go to urls.py in the project1 and configure the URL for app2.
Step 4: Run migration commands in the terminal
python manage.py makemigrations
python manage.py migrate

miscellaneous: If it shows errors delete the migration file and do the migration again.

A: As long as that app doesn't reference any other app then you just need to copy it over, delete the migrations (just in case it references the other projects migrations) add the app to your INSTALLED_APPS, run migrations and you should be good to go.


text:
Q: PHP - how to auto increment value and name when dynamically adding a checkbox Good day! I would like to ask for help.
I'm currently making an Evaluation System for my school project. In my code, I can generate ALL the questions in my dbase together with 5 checkboxes.
e.g. If I add a new question to a particular criteria, it will be show to a table together with 5 auto-generated checkboxes.
how can I auto increment the name and value of my checkbox so if I save them to my dbase the value will be incremented every time there's a new question added?
I currently have 5 criterias, each have 5 questions and 5 sets of checkbox each. consisting of 25checkbox per criteria, but they have the same value and name when auto-generating.
<?php

        $sql = "SELECT * FROM question_pool_registrar WHERE criteria_id = 1";
        $result = $connect->query($sql);

        if($result->num_rows > 0){
            $nr = 0;
            while($row = $result->fetch_assoc()){
            $question = $row['question'];

                echo "

                $question
                <input type='checkbox' value=\"1c5".$nr."\" name=\"answer1".$nr."\" class='radio'>
                <input type='checkbox' value=\"1c4".$nr."\" name=\"answer1".$nr."\" class='radio'>
                <input type='checkbox' value=\"1c3".$nr."\" name=\"answer1".$nr."\" class='radio'>
                <input type='checkbox' value=\"1c2".$nr."\" name=\"answer1".$nr."\" class='radio'>
                <input type='checkbox' value=\"1c1".$nr."\" name=\"answer1".$nr."\" class='radio'>

";
                $nr++;
            }
        }

        ?>


text:
Q: ¿Cómo añadir y quitar varias clases en JavaScript en función de la altura de scroll? estoy intentanto que los elementos de una lista que estan en un nav cambien su color en función de la parte de scroll que estén, lo he conseguido con el primero, pero luego no soy capaz de remover la clase que le añado con JS, el problema esta en el condicional que hago, que no sé como decirle que si es menor de altura que el siguiente elemento que voy a usar remueva la clase.
El código hasta ahora:
  var studio = $('#studio').height();
  var portfolio = $('#portfolio').height();
  var contacto = $('#contacto').height();
  var equipo = $('#equipo').height();

  $(window).scroll( function () {
    if( $(document).scrollTop() > studio ){
    $('#bgTop1').addClass('colorcito');
    } else {
    $('#bgTop1').removeClass('colorcito');
    }
  });

  $(window).scroll( function () {
    if( $(document).scrollTop() > portfolio ){
    $('#bgTop2').addClass('colorcito');
    } else {
    $('#bgTop2').removeClass('colorcito');
    }
  });

Como es lógicos los elementos de el HTML están en orden y con su id y todos tienen su altura.

A: .height() te regresa el alto del contenido del elemento, en este caso no te sirve para saber en que posición se encuentra, para eso podemos utilizar .offset(), tampoco hay necesidad de declarar dos manejadores de scroll, puedes hacerlo todo dentro de uno, que según este post de John Resig (el creador de jQuery) tampoco es recomendable.
¿Entonces que podemos hacer?
Como dice en ese post podemos crear un timer que se ejecutará cada cierto tiempo y solo tomará acción si el usuario ha hecho scroll, y cuando la posición del div esté donde deseamos asignamos el color al item.
En este ejemplo aplico todo eso, el navbarHeight lo utilizo para que cambie de color justo cuando esté pasando por el borde de la barra de navegación.

var navbarHeight = 20;
var didScroll = false;

$(window).scroll(function() {
  didScroll = true;
});

setInterval(function() {
  if (didScroll) {
    didScroll = false;
    // Check your page position and then
    // Load in more results
    var top = $(window).scrollTop() + navbarHeight;
    if ($('.studio').offset().top < top) {
      $('li').removeClass('colorsito');
      $('#studio').addClass('colorsito');
    }
    if ($('.portfolio').offset().top < top) {
      $('li').removeClass('colorsito');
      $('#portfolio').addClass('colorsito');
    }
    if ($('.contacto').offset().top < top) {
      $('li').removeClass('colorsito');
      $('#contacto').addClass('colorsito');
    }
    if ($('.equipo').offset().top < top) {
      $('li').removeClass('colorsito');
      $('#equipo').addClass('colorsito');
    }
  }
}, 100);
body {
  margin: 0;
  padding: 0;
}

nav {
  position: fixed;
  width: 100%;
}

ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
  list-style: none;
}

li {
  width: 25%;
  text-align: center;
  padding: 10px 0;
  background-color: #FFF;
  transition: background-color 0.5s ease-out;
}

.hint {
  position: fixed;
  padding: 5px;
  color: #FFF;
  right: 15px;
  bottom: 15px;
  background-color: red;
}

.tall {
  height: 100vh;
}

.colorsito {
  background-color: #a357b3;
}

      Studio

      Portfolio

      Contacto

      Equipo

Haz scroll :)


text:
Q: Is it possible to override the form action with jquery on an external hosted page that contanis it? I'm trying to change the form's action of an externally hosted page that redirects to an URL so that it redirects to another one. I tried the following code:

$('.shopify-challenge__button').click(function(){
   $('form').get(0).setAttribute('action', 'https://url');
});

I think that there could be the following problems: Maybe I can't override the page from local, or I'm not identifying the form correctly (it has no id or class).
Thanks for your time!


text:
Q: iOS8 Device appears stuck in portrait, but rendering landscape This is a strange issue that may be related to all the orientation issues I'm seeing in iOS8.
I have a universal app. The iPad version supports only landscape and the iPhone version supports only portrait.
When a user opens the iPad version, it opens in landscape mode, which is expected. However, every control on the right side of the view is unresponsive to user touch events. The affected area is 256 wide, and the area on the left that 'works' is 768 wide (portrait width). Therefore, even though the app opens in landscape, the app thinks it's in portrait. Since the phone version only supports portrait, the issue doesn't reveal itself there, though I believe the issue is not device specific, however, the issue only affects devices running iOS8.
The app was originally developed for iOS4 and has gone through several iterations since. However, much of the original code and nibs are still in use. Other orientation issues have shown up with iOS8 and could be related, or not, who knows?
Since the app was originally designed for iOS4, storyboards were not used, and still aren't. I have checked some things: made sure all nibs have 'Auto resize subviews' checked, and made sure that only landscape orientations existed in the app plist (verified in XML). Here is a code snippet from AppDelegate didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    [self.window setFrame:[[UIScreen mainScreen] bounds]];

    self.viewController = [[AppMainViewController alloc] initWithNibName:nib bundle:nil];

    //...

    return YES;
}

In the image, I'm showing both portrait and landscape sizes. As I mentioned earlier, the view controller renders and looks as it should in landscape, but anything in the red area of the image is unresponsive to user taps.
Perhaps I've looked at this issue too long and hopefully somebody has some insight on why this is happening. Anyone? Thanks!


text:
Q: Need to determine some columns while creating an excel file via .bat So I want to make an excel file with inputting some info into batch file. It is ok until here. But my problem is I want to seperate those infos into some specified columns.
@echo off

set /p VarOne=Isim girin:
set /p VarTwo=Soyisim girin:
set /p VarThree=Mudurluk girin:
set /p VarFour=IP girin:

echo %VarOne%          %VarTwo%         %VarThree%          %VarFour% >> %C:\test%\test.csv

echo Dosya kaydedildi. %C:\test%
pause

As a basic example, I want to put "VarOne" into "A" column in excel file, "VarTwo" into "B" column etc.


text:
Q: WTFforms field values initialised when not desired I have a WTFforms "user add" form which takes common attributes for a user and commits them to a database. The values of these html form fields are being populated on page load when not desired.
I have not set any jinja code to set the fields and in the route for this page I have not passed a user to the render_template call.
The fields of the user form and the user class are very similar as you would expect
User Object
class User(UserMixin, db.Model):

id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(64), index=True, unique=False)
surname = db.Column(db.String(64), index=True, unique=False)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
num_records_added = db.Column(db.Integer, unique=False, default=0)
num_records_edited = db.Column(db.Integer, unique=False, default=0)
role = db.Column(db.String(20), index=False, unique=False, default='Editor')

User form
class AddUserForm(FlaskForm):

firstname = StringField('First name', validators=[DataRequired()])
surname = StringField('Surname', validators=[DataRequired()])
email = StringField('Email address', validators=[DataRequired(), Email()])
role = SelectField('Role', choices=[], validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
num_records_added = IntegerField('Number of Records Added')
submit = SubmitField('Submit')

My assumption is that there is interaction between the logged in user via flask_login and the form because they share similar atributes/fields.
To prove this I modified the form so that each field has a trailing "_" as part of it's name and updated the route/template to work with this new naming style and the problem goes away.
Can someone explain what is happening here and what is the correct approach to avoiding this problem?

A: I discovered the problem and it turns out to be the autofill behaviour of lastpass that was causing the issue.
It was filling in the fields with the information it had as id/labels of the form field match up with it's entry for the website.
I assume this could happen for other autofill behaviours of browsers.
In this case I have to accept that I need to use ids for the form fields which do not match these automatic fill fields use otherwise they will be populated.


text:
Q: Python / BeautifulSoup webscraper returning "None" trying to build a webscraper to return lists of freelance gig postings on different websites into one place. My code is below and it keeps returning "None". I'm a bit stuck at this point, if you can help identify why it keeps doing this that would be great.
import requests
from bs4 import BeautifulSoup
import pprint

res1 = requests.get('https://www.airtasker.com/tasks/?task_states=posted&lat=-33.7918&lon=151.0806&location_name=Eastwood%2C%20NSW&radius=20000000&carl_ids=&task_types=both&max_price=9999&min_price=5&search_term=python&badges=&sort_by=posted_desc')  # this is where we will scrape the info from
soup1 = BeautifulSoup(res1.text, 'html.parser')  # this tells BS to give us HTML code for the page
links1 = soup1.select('.new-task-list-item new-task-list-item--open')  # link of each gig
subtext1 = soup1.select('.new-task-list-item__date at-icon-calendar')  # date of each gig

res2 = requests.get('https://www.airtasker.com/tasks/?task_states=posted&lat=-33.7918&lon=151.0806&location_name=Eastwood%2C%20NSW&radius=20000000&carl_ids=&task_types=both&max_price=9999&min_price=5&search_term=web%20developer&badges=&sort_by=posted_desc')
soup2 = BeautifulSoup(res2.text, 'html.parser')
links2 = soup2.select('.new-task-list-item new-task-list-item--open')
subtext2 = soup2.select('.new-task-list-item__date at-icon-calendar')

res3 = requests.get('https://www.upwork.com/freelance-jobs/website/')
soup3 = BeautifulSoup(res3.text, 'html.parser')
links3 = soup3.select('.job-title')
subtext3 = soup3.select('.text-muted')

res4 = requests.get('https://www.upwork.com/freelance-jobs/data-science/')
soup4 = BeautifulSoup(res4.text, 'html.parser')
links4 = soup4.select('.job-title')
subtext4 = soup4.select('.text-muted')

res5 = requests.get('https://www.upwork.com/freelance-jobs/bot-development/')
soup5 = BeautifulSoup(res5.text, 'html.parser')
links5 = soup5.select('.job-title')
subtext5 = soup5.select('.text-muted')

res6 = requests.get('https://www.upwork.com/freelance-jobs/python-script/')
soup6 = BeautifulSoup(res6.text, 'html.parser')
links6 = soup6.select('.job-title')
subtext6 = soup6.select('.text-muted')

mega_links = links1 + links2 + links3 + links4 + links5 + links6
mega_subtext = subtext1 + subtext2 + subtext3 + subtext4 + subtext5 + subtext6

def extract(links, subtexts):
    joblist = []
    for indx, item in enumerate(links):
        title = item.getText()
        href = item.get('href')
        joblist.append({'title': title, 'link': href})
        return joblist

pprint.pprint(extract(mega_links , mega_subtext))

A: I have no idea what exactly you are trying to extract from the scraped web page requests. Here's what I tried from my end:
Your links variable are null or empty lists since there is no such querySelector present for the web page you're trying to scrape. For example, the console of the first web page that you are scraping (the element you're trying to scrape doesn't exist):

I would recommend you to confirm the element you're trying to scrape and confirm it's class.
Another Point of Consideration:
When you will print your soup variables you will notice that you get CloudFare as the output.


text:
Q: Embedding the $\ 2^n+1$-point metric 1-space A metric space $\ (S\ d)\ $ is said to be a 1-space $\ \Leftarrow:\Rightarrow\ \forall_{x\ y\in S}\ (x\ne y\ \Rightarrow\ d(x\ y)=1).$
Question:   Do there exist a non-negative integer $n,\ $ and an $n$-dimensional Banach space $\ X,\ $ and an isometric embedding of the
$\ (2^n+1)$-point metric 1-space $\ (S\ d)\ $ into $\ X$.

My obvious conjecture is NO.

Added AFTER @Fedor Perov's Answer:
The power of the surprisingly simple Fedor's solution is in involving the measure theory. It worked regardless of any choice of any Banach norm.
In fact, now Fedor may follow with writing down a solution of my old conjecture from 1972/3 which a priori was harder:
CONJECTURE:   Let Banach norm $\ ||.||\ $ in $\ \mathbb R^n\ $ be such that $\ B^n:=(\mathbb R^n\,\ ||.||)\ $ contains a $2^n$-point 1-space $\ S.\ $ Then $\ B^n\ $ is a metrically injective space, i.e. it admits affine coordinates such that the norm is given by $\ \max.\ $ Then--furthermore--under such coordinates, there exists $\ (a_1\ \ldots\ a_n)\in \mathbb R^n\ $ such that
$$ S\ =\ \prod_{k=1}^n\ \{a_k\,\ a_k\!+\!1\} $$
Indeed, Fedor's construction provides a decomposition of the convex hull $\ Cv(S)\ $ into $\ 2^n\ $ copies of the $\frac 12$-scaled of $\ Cv(S)\ $ where these copies have disjoint interiors.

A: Indeed no. If it exists, for each of our points $p_i$ consider the set $A_i$ homothetic to their convex hull with center $p_i$ and coefficient bit less than $1 /2$. By volume argument some two such sets $A_i, A_j$ must have a common point $q$,  but this contradicts to triangle inequality as $p_iq, p_jq$ are less than $1/2$.


text:
Q: Adding a reverse arrow on a chain For the MWE below:
\documentclass[a4paper,11pt,twoside]{report}
\usepackage[left=2.5cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage[T1]{fontenc}

\usepackage{pgfplots,tikz}

\usetikzlibrary{calc,trees,positioning,fit,arrows,chains,shapes.geometric,%
    decorations.pathreplacing,decorations.pathmorphing,shapes,%
    matrix,shapes.symbols,automata}

\tikzset{
>=stealth',
  punktchain/.style={
    rectangle,
    rounded corners,
    % fill=black!10,
    draw=black, very thick,
    text width=10em,
    minimum height=3em,
    text centered,
    on chain},
  line/.style={draw, thick, <-},
  element/.style={
    tape,
    top color=white,
    bottom color=blue!50!black!60!,
    minimum width=8em,
    draw=blue!40!black!90, very thick,
    text width=10em,
    minimum height=3.5em,
    text centered,
    on chain},
  every join/.style={->, thick,shorten >=1pt},
  tuborg/.style={decorate},
  tubnode/.style={midway, right=2pt},
  every rectangle node/.style={thick}
}

\begin{document}

\begin{center}
\begin{tikzpicture}
  [node distance=.5cm,
  start chain=going below,]
     \node[punktchain, join] (timing) {Timing Solver};
     \node[punktchain, join] (solver)      {Solver};
     \node[punktchain, join] (impl)      {SolverImpl};
     \node[punktchain, join] (stp) {STPSolver};
     \node[punktchain, join, ] (stpimpl) {STPSolverImpl};

    \draw[tuborg, decoration={brace}] let \p1=(solver.north), \p2=(impl.south) in
     ($(2.5, \y1)$) -- ($(2.5, \y2)$) node[tubnode] {*};

    %\draw[red,thick,dashed] ($(solver.north west)+(-0.2,0.2)$)  rectangle ($(impl.south east)+(0.2,-0.2)$);

    \draw[red,thick,dashed] ($(timing.north west)+(-1,0.3)$)  rectangle ($(stpimpl.south east)+(1,-0.2)$);
    \node[anchor=south] at (current bounding box.north) {The Solver Instance};

 \end{tikzpicture}
\end{center}

\end{document}

How can I add an arrow from STPSolverImpl to STPSolver ? I know it's a chain but is there any way to do it ? EDIT: I actually want two arrows. One up one down. So don't want to just replace that arrow

A: You can provide extra options to the join style. Changing the relevant line as
\node[punktchain, join= by {<-}, ] (stpimpl) {STPSolverImpl};

would reverse the arrow.


text:
Q: Nitro PDF Express removing already outputted files when I cancel it Im converting lots of .doc files into .pdf using Nitro PDF Express. The program isn't finish converting the 37 files yet maybe 10 are converted and are in the output directory already.
But when I cancelled it, even the converted one's are deleted. Can I still find it somewhere or are they gone for good.

A: Start the conversion again, and copy the files before stopping the program?

A: Use a recovery program like http://www.piriform.com/recuva


text:
Q: Storing a string as a binary string of 'unsigned char's to in matters of compression I need to store a string of 8 chars (they're all digits) in a compressed method,
As I understand it, each char uses 8 bits which are 1 byte and since I only use digits I can use 4 bits (2^4=16 combinations) so for each unsigned char I can store two digits instead of one. Thus I need 4 bytes to store 8 digits instead of 8 bytes.
Until here am I right or wrong?
Now how am I storing this data in a string of 4 unsigned chars? I'm not looking for an explicit answer just a kick start to understand the motivation.

A: There are three obvious ways to store eight decimal digits in four eight-bit values.
One is to reduce each decimal digit to four bits and to store two four-bit values in eight bits.
Another is to combine each pair of decimal digits to make a number from 0 to 99 and store that number in eight bits.
Another is to combine all eight decimal digits to make a number from 0 to 99999999 and store that in 32 bits, treating the four eight-bit values as one 32-bit integer.
To decide between these, consider what operations you need to perform to encode the value (what arithmetic or bit operations are needed to combine two digits to make the encoded value) and what operations you need to perform to decode the value (given eight bits, how do you get the digits out of them?).
To evaluate this problem, you should know about the basic arithmetic operations and the bit operations such as bit-wise AND and OR, shifting bits, using "masks" with AND operations, and so on. It may also help to know that division and remainder are usually more time-consuming operations than other arithmetic and bit operations on modern computers.

A: I prefer you use unsigned int as suggested by harold in comments. In unsigned char[4] you may require additional one char for terminating '\0' character.
Use shifting as you yourself suggested for proper conversion from uchar to uint.


text:
Q: scale object size viewport-> preview I toying with a project where I can position objects runtime on the screen. I also have an small "preview"-window, where I want to see the outline of the objects.
I have an object array who have size and location on the "scene". Now I want to loop through my scene-objects and create one picturebox in the preview-window for each object in the "scene".
So, I have the size of the "Scene" and an array of the objects that are visible on the scene. Every object have an size and location mapped to the scene.
I also have a preview window that have an dynamic size. How do I create a preview that scales down to the preview window? To make it easy, I loop through the scene objects in the scene and create a picturebox on the preview-form for each object, that uses the preview-forms size to do the scaling.
SceneSize=new size(800,600)
PreviewSize=new size(80,60)

For each obj as SceneObject in Scene
   dim p as new picturebox
    p.size=?? scaling here (we have obj.size and obj.location)
    p.location=?? scaling here (we have obj.size and obj.location)
    previewWindow.controls.add (p)

next

Any example in .Net would be nice.
Thanks.

A: Bob Powell's site on GDI+ might have some useful information on how to proceed. Check out his page on Matrix Transformations. This article might provide you with some good ideas on how to proceed
Bob Powell GDI+ Transformations

A: This did the trick, it wasn't harder than that.
Function GetPreviewRectangleForObject(ByVal ScreenSize As Size, ByVal PreviewSize As Size, ByVal OriginalRect As Rectangle) As Rectangle
    Dim xFactor As Integer = ScreenSize.Width / PreviewSize.Width
    Dim yFactor As Integer = ScreenSize.Height / PreviewSize.Height
    With OriginalRect
        Return New Rectangle(.X / xFactor, .Y / yFactor, .Width / xFactor, .Height / yFactor)
    End With
End Function


text:
Q: Python Tkinter treeview.heading command not working right in for loop I am trying to assign a different function to each of the headings on a tkinter treeview widget.
the following code has the inteded outcome, but is hardcoded:
from tkinter import *
from tkinter.ttk import *

root = Tk()

treeview = Treeview(root, columns=['c1', 'c2'])
treeview.pack()

treeview.heading('c1', text='c1', command=lambda:print('c1'))
treeview.heading('c2', text='c2', command=lambda:print('c2'))

root.mainloop()

but when I try to make the same exact code, but use a for loop to set the column names and commands, each column's command is set to the last command in the loop:
from tkinter import *
from tkinter.ttk import *

root = Tk()

treeview = Treeview(root, columns=['c1', 'c2'])
treeview.pack()

for c in ['c1', 'c2']:
    treeview.heading(c, text=c, command=lambda:print(c))

root.mainloop()

why is this happening? I know that a similar question has been answered in this post, but I would like to try to use the intended options if possible.

A: If I change
for c in ['c1', 'c2']:
    treeview.heading(c, text=c, command=lambda:print(c))

to
for c in ['c1', 'c2']:
    treeview.heading(c, text=c, command=lambda col=c:print(col))

It seems to solve the issue


text:
Q: AngularJS : Hide popup from child controller (popup content) I have a problem with my directives.
If I call the line $scope.popup.show = false from the popup controller, it works fine.
If I call $scope.hideModal() from the child contentDirective the code is called (checked in debug) but the $scope.popup.show value doesn't change (in debug the value is "false") and the popup does'nt hide :/.
Have you got any idea ? :)
index.html:
<popup title="sometitle">
  <contentDirective> </contentDirective>
</popup>

popup.html :

popup.js
.directive(....
    return {....
        scope: {}
    }
})
.controller(....
    $scope.hideModal = function()
    {
        $scope.popup.show = false;
    }
}]);

contentDirective.htlm (NOT isolated scope)

    <button onclick="changeSomethingAndHide()"/>

contentDirective.js
.controller(....
    $scope.changeSomethingAndHide = function()
    {
        //calls the parent function
        $scope.hideModal();
    }
}]);

Maybe I missed something..
Thank you !

A: When you're dealing with transcluded content, scope gets a little bit tricky.
Transcluded scope is not inherited by default (you can change this), it's a "sibling" scope to the enclosing directive, which is somewhat confusing but there are good reasons for this.
So, your contentDirective really can't see anything in your popup directive by default. When you set the $scope.popup.show = false in the hideModal() function, all it's doing is setting a new variable the contentDirective's scope as opposed to setting the one in the popup's scope.
Two options to address this:

*

*You can manually transclude contentDirective and have it use the same scope as your popup directive. See http://angular-tips.com/blog/2014/03/transclusion-and-scopes/ for more details.

*You can declare contentDirective with the require keyword indicating you want access to the popup directive's controller. This will be passed into your link function, which you can use to call methods on your popup directive's controller. See https://egghead.io/lessons/angularjs-directive-to-directive-communication for more details.


text:
Q: Rewriting data in logs with log4net This is my logger.config
 <?xml version="1.0"?>
    <logger>
      <path>C:\</path>
      <file>dd-MM-yyyy'.log'</file>
      <levels>
        <add>ERROR</add>
        <add>INFO</add>
      </levels>
      <pattern>{level}|{date}|{method_guid}|{method_name}|{description}|{status}|{msg}|{inout}|{param0}</pattern>
      <dateFormat>MM/dd/yy H:mm:ss.fff</dateFormat>
      <reloadEveryMinutes>1</reloadEveryMinutes>
      <appendToFile value="true" />
      <maxSize>1MB</maxSize>
    </logger>

Here I set add settings for logger.
     var hierarchy = (Hierarchy)LogManager.GetRepository();
            hierarchy.Configured = false;
        hierarchy.Root.RemoveAllAppenders();

        var patternLayout = new PatternLayout() { ConversionPattern = "%m%n" }; //%m - message, %n - new line
        patternLayout.ActivateOptions();

        var roller = new RollingFileAppender
        {
            AppendToFile = true,
            StaticLogFileName = false,
            File = config.Path,
            DatePattern = config.FileName,
            PreserveLogFileNameExtension = true,
            Layout = patternLayout,
            MaxSizeRollBackups = 10000,
            MaximumFileSize = "10000",
            RollingStyle = RollingFileAppender.RollingMode.Composite,
            CountDirection = 0

        };
        roller.ActivateOptions();
        hierarchy.Root.AddAppender(roller);

        hierarchy.Root.Level = Level.All;
        hierarchy.Configured = true;

And log4net generate files with such name 15-05-2017. When the size of file will more 1MB it creates new file 15-05-2017.1 and put old data to it and write new data to 15-05-2017.
What should I do that it writes new data in 15-05-2017.1 ?

A: I think you need to change CountDirection to -1 (this is default value) according to documentation,
 see CountDirection


text:
Q: best setting for exporting a map ( jpeg ) that will be used in an A4 report Often i find some of the maps i make will make there way into reports. This can be either taken up a whole page of A4. Or being 50 percent of the Page or sometimes. 25.
Do people have any page settings they would use

A: 300 DPI is a pretty standard resolution for printing. For a sheet of A4 paper (210 × 297 cm / 8.27 × 11.7 in) that would come to a resolution of 2481 x 3510. For 50% of an A4 page, which is A5 paper (148 × 210 cm /  5.83 × 8.27 in) that would come to a resolution of 1749 x 2481. For 25% of an A4 page, which is A6 paper (105 × 148 cm /    4.13 × 5.83 in) that would come to a resolution of 1239 x 1749. As far as what quality of compression to use for the JPEG, that greatly depends on the specific map, but personally I would not use a quality level below 80%, since fine features will be noticeably blurry. One thing to keep in mind too is if the report will be included in a presentation, in that case you will want to have even higher resolution to work well with a projector.

A: you may want to look at the Exporting a Map function on ArcGIS Help to start. I have found success in establishing the resolution DPI to be 300 as seen below
and in addition making sure to set the JPEG Quality to MAX.
You should also take a look at the StackExchange article Is there a way to improve the render quality of ESRI basemaps when exporting a map to PDF or JPG?
and finally, if need be take a look at the ExportToJPEG ArcPy functionality to establish how to increase the quality using the parameters outlined. (The info is from the French ESRI Site so you will need to convert to your language)


text:
Q: How to do HMAC-SHA512 signing in Python? I want to do a get request in the following format:
https://bittrex.com/api/v1.1/account/getbalance?apikey=API_KEY&currency=BTC

I do have the public and the secret key. However I found the following statement:

For this version, we use a standard HMAC-SHA512 signing. Append apikey and nonce to your request and calculate the HMAC hash and include it under an apisign header

I don't really know how to properly encrypt my key. Using the plain secret key obviously returns "NONCE_NOT_PROVIDED". Everything I got is this:
current_price = requests.get("https://bittrex.com/api/v1.1/account/getbalance?apikey=API_KEY&currency=BTC")

How to properly sign and encrypt the keys? Thank you.
Edit:
Current attempt looks like the following.
def getWalletSize():
    APIkey = b'29i52wp4'
    secret = b'10k84a9e'
    s = "https://bittrex.com/api/v1.1/account/getbalance?apikey=29i52wp4&currency=BTC"
    digest = hmac.new(secret, msg=s, digestmod=hashlib.sha512).digest()
    current_balance = requests.get(digest)
    return current_balance

However it raises the error Unicode-objects must be encoded before hashing

A: import hmac
import hashlib
import base64

API_KEY = 'public_key'
s = """GET https://bittrex.com/api/v1.1/account/getbalance?apikey=%s&currency=BTC""" % API_KEY

base64.b64encode(hmac.new("1234567890", msg=s, digestmod=hashlib.sha512).digest())

it signs the request
digest = hmac.new(secret_key, msg=thing_to_hash, digestmod=hashlib.sha512).digest()

and this encode it in base64
base64.b64encode(digest)


text:
Q: shopify remove collection banner text overlay I just want to ask if anyone encountered this on shopify where text is overlaying the collection banner and how you get this doneenter image description here. TIA!
i already tried searching for hours.


text:
Q: Cakephp Containable not attaching to Model I've used containable tons of times but I can not figure for the life of me why it is not working correctly now.
I have 3 models Project, User, and Country.
Project belongsTo User
User belongsTo Country
here is the models
<?php
class User extends AppModel {
    var $name = 'User';
    var $displayField = 'username';
    var $belongsTo = array(
        'AccountType' => array(
            'className' => 'AccountType',
            'foreignKey' => 'account_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'PaymentType' => array(
            'className' => 'PaymentType',
            'foreignKey' => 'payment_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Country' => array(
            'className' => 'Country',
            'foreignKey' => 'country_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'InstantMessenger' => array(
            'className' => 'InstantMessenger',
            'foreignKey' => 'instant_messenger_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'TimeZone' => array(
            'className' => 'TimeZone',
            'foreignKey' => 'time_zone_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Language' => array(
            'className' => 'Language',
            'foreignKey' => 'language_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
    );
}

<?php
class Project extends AppModel {
    var $name = 'Project';
    var $displayField = 'project_title';

    var $belongsTo = array(
            'User' => array(
                    'className' => 'User',
                    'conditions' => '',
                    'fields' => '',
                    'order' => ''
            ),
            'ProjectType' => array(
                    'className' => 'ProjectType',
                    'foreignKey' => 'project_type_id',
                    'conditions' => '',
                    'fields' => '',
                    'order' => ''
            ),
            'BiddingType' => array(
                    'className' => 'BiddingType',
                    'foreignKey' => 'bidding_type_id',
                    'conditions' => '',
                    'fields' => '',
                    'order' => ''
            ),
            'ProjectStatus' => array(
                    'className' => 'ProjectStatus',
                    'foreignKey' => 'project_status',
                    'conditions' => '',
                    'fields' => '',
                    'order' => ''
            ),
            'EmploymentType',
            'PaymentType',
    );
}

<?php
class Country extends AppModel {
    var $name = 'Country';
    var $displayField = 'name';
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $hasMany = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'country_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

}

Now here is my code to try to attach a containable to project and add User
function smartbid($projid = null)
{
    $this->loadModel('Content');
    $content = $this->Content->findById(53);
    $this->set('content',$content);
    $this->Project->Behaviors->attach('Containable');
    $options = array(
       array(
        'conditions'=>
           array(
                'Project.id'=>$projid
            ),
           'contain'=>array(
               'User'
           )
        )
     );
    $project = $this->Project->find('first',$options);

    $this->set(compact('project'));
}

Now cakephp completely ignores my attached containable and returns this
Array
(
    [Project] => Array
        (
            [id] => 1
            [user_id] => 19
            [status] => 1
            [approval_status] => 0
            [project_status] => 2
            [approval_date] => 2012-02-08
            [project_title] => Database Reporting
            [project_type_id] => 3
            [budget] => 100
            [bidding_type_id] => 1
            [employment_type_id] =>
            [esl] => 1
            [secrecy] => 0
            [secrecy_file] =>
            [description] => this is my first post
            [performance] => 0
            [cme] => 6
            [files_share] =>
            [project_deadline] => 1
            [delivery_deadline] => 2012-02-16
            [bidding_deadline] => 2012-02-27
            [legal] => 1)Employer requires complete and fully-functional working program(s) in executable form as well as complete source code of all work done.

2) Deliverables must be in ready-to-run condition as follows (depending on the nature of the project and deliverables):

2a) If there are any server-side deliverables (intended to only exist in one place in the Employer's environment) then they must be installed by the Consultant in ready-to-run condition (unless specified elsewhere by the Employer).

2b) All other software (including but not limited to any desktop software or software the Employer intends to distribute) must include a software installation package that will install the software in ready-to-run condition on the platform(s) specified in this project (unless specified elsewhere by the Employer).

3) All deliverables will be considered 'work made for hire' under U.S. Copyright law. Employer will receive exclusive and complete copyrights to all work purchased.

3b) No part of the deliverable may contain any copyright restricted 3rd party components (including GPL, GNU, Copyleft, etc.) unless all copyright ramifications are explained AND AGREED TO by the Employer on the site per the Consultant's Worker Legal Agreement.
            [close] => 0
            [agree] => 1
            [created] => 2012-02-06
            [top_employer] => 0
            [view_counter] => 41
            [pause_deadline] =>
            [payment_type_id] =>
            [status_date] => 2012-02-08
            [redeem_amount] =>
        )

    [User] => Array
        (
            [id] => 19
            [username] => EmployerWarrior
            [password] => 7c6a180b36896a0a8c02787eeafb0e4c
            [account_type_id] => 2
            [picture] =>
            [resume] =>
            [alert] => 0
            [first_name] => Yaser
            [last_name] => Ibrahim
            [company_name] => Software Momentum, Inc.
            [company_incorporated] => 1
            [email] => Yaser43082@hotmail.com
            [address] => 123 Somewhere
            [apartment_number] =>
            [city] => Some City
            [state] => Some State
            [country_id] => 1
            [phone_city] => 614
            [phone_country] => 1
            [phone_number] => 1234567
            [fax_city] =>
            [fax_country] =>
            [fax_number] =>
            [instant_messenger_id] => 1
            [im_username] =>
            [postal] => 43082
            [time_zone_id] => 58
            [language_id] => 23
            [esl] => 1
            [us_resident] => 1
            [ssnum] => 1234567
            [have_ssnum] => 1
            [work_permit_number] =>
            [alien_number] =>
            [work_permit] => 0
            [green_card] => 0
            [payment_type_id] => 4
            [ip] =>
            [created] => 2012-02-06 08:59:35
            [top_employer] => 0
            [top_consultant] => 0
            [rating] => 0
            [money_invested] => 0
            [money_earned] => 0
            [total_projects] => 0
            [last_project] => 0
            [active] => 0
            [last_login] =>
            [last_seen] => 2012-02-26 14:13:08
            [is_logged_in] => 0
            [time_format_id] => 1
            [paypal_id] =>
            [momentum_expiration] => 2014-02-12
        )

    [ProjectType] => Array
        (
            [id] => 3
            [name] => Small Business Project
            [min] => 100
            [max] => 499.99
            [order] => 4
        )

    [BiddingType] => Array
        (
            [id] => 1
            [type] => Public Bidding
            [percentage] => 15
        )

    [ProjectStatus] => Array
        (
            [id] => 2
            [status] => Open Bids
            [icon] => bid_open.png
            [order] => 3
            [default] => 1
        )

    [EmploymentType] => Array
        (
            [id] =>
            [name] =>
        )

    [PaymentType] => Array
        (
            [id] =>
            [type] =>
        )

    [BidWinner] => Array
        (
            [id] =>
            [comment_group_id] =>
            [bid_status_id] =>
            [project_id] =>
            [bid_amount] =>
            [performance_guaranteed] =>
            [isSmartBid] =>
            [user_id] =>
            [comment] =>
            [isWinner] =>
            [created] =>
        )

    [HRWWallet] => Array
        (
            [id] => 1
            [user_id] => 19
            [account_type_id] =>
            [entity_id] => 1
            [payment_type_id] => 1
            [entity_type_id] => 1
            [payment_to_id] =>
            [payment_status_id] => 2
            [payment_number] =>
            [service_id] => 4
            [created] => 2012-02-10 18:45:52
            [description] => Payment for project
            [credit] => 100
            [debit] => 0
            [billing_address] =>
            [billing_city] =>
            [billing_state] =>
            [billing_country_id] =>
            [billing_name] =>
            [exp_year] =>
            [exp_month] =>
            [security_code] =>
        )

    [EmployerRating] => Array
        (
            [id] =>
            [owner_id] =>
            [project_id] =>
            [rated_by_id] =>
            [account_type_id] =>
            [rating] =>
            [comment] =>
            [created] =>
        )

    [ConsultantRating] => Array
        (
            [id] =>
            [owner_id] =>
            [project_id] =>
            [rated_by_id] =>
            [account_type_id] =>
            [rating] =>
            [comment] =>
            [created] =>
        )

    [Arbitration] => Array
        (
            [id] => 5
            [project_id] => 1
            [defendent_id] => 20
            [plantiff_id] => 19
            [magistrate_id] => 17
            [arbitration_status_id] => 1
            [verdict] =>
            [created] => 2012-02-11 23:00:00
            [end] =>
        )

    [Bid] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [comment_group_id] => 1
                    [bid_status_id] => 1
                    [project_id] => 1
                    [bid_amount] => 75
                    [performance_guaranteed] => 10
                    [isSmartBid] => 0
                    [user_id] => 20
                    [comment] => Hi, I was writing about your project
                    [isWinner] =>
                    [created] => 2012-02-08 14:15:04
                )

            [1] => Array
                (
                    [id] => 2
                    [comment_group_id] => 2
                    [bid_status_id] => 1
                    [project_id] => 1
                    [bid_amount] => 100
                    [performance_guaranteed] => 25
                    [isSmartBid] => 0
                    [user_id] => 18
                    [comment] => I can do this work
                    [isWinner] =>
                    [created] => 2012-02-08 14:16:39
                )

            [2] => Array
                (
                    [id] => 5
                    [comment_group_id] => 2
                    [bid_status_id] => 1
                    [project_id] => 1
                    [bid_amount] => 45
                    [performance_guaranteed] => 10
                    [isSmartBid] => 1
                    [user_id] => 18
                    [comment] => This is a smart bid bid
                    [isWinner] => 0
                    [created] => 2012-02-25 15:40:54
                )

        )

    [PaymentTransaction] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [user_id] => 19
                    [account_type_id] =>
                    [entity_id] => 1
                    [payment_type_id] => 1
                    [entity_type_id] => 1
                    [payment_to_id] =>
                    [payment_status_id] => 2
                    [payment_number] =>
                    [service_id] => 4
                    [created] => 2012-02-10 18:45:52
                    [description] => Payment for project
                    [credit] => 100
                    [debit] => 0
                    [billing_address] =>
                    [billing_city] =>
                    [billing_state] =>
                    [billing_country_id] =>
                    [billing_name] =>
                    [exp_year] =>
                    [exp_month] =>
                    [security_code] =>
                )

        )

    [WorkAcceptanceLog] => Array
        (
        )

    [Comment] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [comment_group_id] => 1
                    [project_id] => 1
                    [to_id] => 19
                    [from_id] => 20
                    [cc_id] =>
                    [isArbitration] =>
                    [no_contest] =>
                    [subject] => Re:
                    [comment] => Hi, I was writing about your project
                    [created] => 2012-02-08 14:15:04
                    [file_name] =>
                    [parent_id] =>
                    [last_message] =>
                )

            [1] => Array
                (
                    [id] => 2
                    [comment_group_id] => 2
                    [project_id] => 1
                    [to_id] => 19
                    [from_id] => 18
                    [cc_id] =>
                    [isArbitration] =>
                    [no_contest] =>
                    [subject] => Re:
                    [comment] => I can do this work
                    [created] => 2012-02-08 14:16:39
                    [file_name] =>
                    [parent_id] =>
                    [last_message] =>
                )

            [2] => Array
                (
                    [id] => 3
                    [comment_group_id] => 2
                    [project_id] => 1
                    [to_id] => 18
                    [from_id] => 19
                    [cc_id] =>
                    [isArbitration] =>
                    [no_contest] =>
                    [subject] => Broadcasted Message
                    [comment] => This is a broadcast to all consultants in regards to the project.
                    [created] => 2012-02-08 14:18:52
                    [file_name] =>
                    [parent_id] =>
                    [last_message] => 2012-02-08 14:18:51
                )

            [3] => Array
                (
                    [id] => 4
                    [comment_group_id] => 1
                    [project_id] => 1
                    [to_id] => 20
                    [from_id] => 19
                    [cc_id] =>
                    [isArbitration] =>
                    [no_contest] =>
                    [subject] => Broadcasted Message
                    [comment] => This is a broadcast to all consultants in regards to the project.
                    [created] => 2012-02-08 14:18:52
                    [file_name] =>
                    [parent_id] =>
                    [last_message] => 2012-02-08 14:18:52
                )

            [4] => Array
                (
                    [id] => 7
                    [comment_group_id] => 0
                    [project_id] => 1
                    [to_id] => 19
                    [from_id] => 27
                    [cc_id] => 20
                    [isArbitration] => 1
                    [no_contest] =>
                    [subject] => Arbitration
                    [comment] => What seems to be the issue ?
                    [created] => 2012-02-12 18:28:11
                    [file_name] =>
                    [parent_id] =>
                    [last_message] =>
                )

            [5] => Array
                (
                    [id] => 8
                    [comment_group_id] => 5
                    [project_id] => 1
                    [to_id] => 17
                    [from_id] => 19
                    [cc_id] => 20
                    [isArbitration] => 1
                    [no_contest] =>
                    [subject] => Arbitration
                    [comment] => Well I would like to say I am not happy
                    [created] => 2012-02-12 19:35:51
                    [file_name] =>
                    [parent_id] =>
                    [last_message] =>
                )

            [6] => Array
                (
                    [id] => 9
                    [comment_group_id] => 6
                    [project_id] => 1
                    [to_id] => 17
                    [from_id] => 19
                    [cc_id] => 20
                    [isArbitration] => 1
                    [no_contest] =>
                    [subject] => Arbitration
                    [comment] => I would like to make a complaint
                    [created] => 2012-02-12 22:07:08
                    [file_name] =>
                    [parent_id] =>
                    [last_message] =>
                )

            [7] => Array
                (
                    [id] => 10
                    [comment_group_id] => 2
                    [project_id] => 1
                    [to_id] => 19
                    [from_id] => 18
                    [cc_id] =>
                    [isArbitration] =>
                    [no_contest] =>
                    [subject] => Re:Broadcasted Message
                    [comment] => This is a smart bid bid
                    [created] => 2012-02-25 15:40:54
                    [file_name] =>
                    [parent_id] =>
                    [last_message] =>
                )

        )

)
as you can see it ignores my attachment. what am i doing wrong.

A: This is a fairly old question, but for what its worth.
Here is the documentation for the Containable Behavior.
It states that, to load the behavior on the fly, you should use:
$this->Model->Behaviors->load('Containable');

I believe the difference is merely due to the fact that attach and detach have been deprecated.
Also, why not just set the $actAs property in your model, or even in AppModel?
class AppModel extends Model {
    public $actAs = array('Containable');
    // public $recursive = 0;
    //...
}

The relation with the User model defined in the Project model is missing the foreignKey field, which may cause trouble. I assume Cake defaults that to user_id which should of course be the name of the column in the projects table.
Other than that, your use of the contain options seems ok.

A: Try this:
$this->Project->Behaviors->attach('Containable');
$this->Project->contain(array(
            'conditions' => array('Project.id' => $projid),
            'User'));
$project = $this->Project->find('first');
$this->Project->Behaviors->detach('Containable');


text:
Q: How do you map subclass properties to columns in Table per Hierarchy? I have a TPH situation where I have an abstract base class and 8 derived classes from it by using a discriminator. Two of them share a list of sub classes.
 public abstract class StepBase : FullAuditedEntity<Guid>
    {
        public int Order { get; set; }
        public StepType StepType { get; set; }
    }

The thing is I have two types which shares a SubClass
 public class DestinationVesselStep : StepBase
    {
        public virtual List<DestinationVessel> VesselsDestination { get; set; }
    }

 public class LiquidNitrogenStep : StepBase
    {
        public virtual List<DestinationVessel> DestinationsBoxes { get; set; }
    }

    private static void ConfigureVesselsStep(ModelBuilder builder)
    {
        builder.Entity<DestinationVesselStep>(b =>
        {
            //Properties
            b.HasMany(p => p.VesselsDestination).WithOne().HasForeignKey(x => x.StepId);
        });
    }

    private static void ConfigureLiquidNitrogenStep(ModelBuilder builder)
    {
        builder.Entity<LiquidNitrogenStep>(b =>
        {
            //Properties
            b.HasMany(p => p.DestinationsBoxes).WithOne().HasForeignKey(x => x.StepId);
        });
    }

But when I request a LiquidNitrogenStep with two or more destinationBoxes I get the following error:
System.InvalidOperationException : Sequence contains more than one element.
it works fine if I only have one destinationBox
I am expecting to get a LiquidNitrogenStep with all its destination boxes, the error do not happnd with DestinationVesselStep

A: DestinationVessel.StepId can't refer to both a DestinationVesselStep and LiquidNitrogenStep.
So either add separate foreign keys to DestinationVessel, eg LiquidNitrogenStepId, and DestinationVesselStepId, or make the relationships many-to-many, which uses separate linking tables for each relationship, instead of putting foreign keys on the target Entity.
private static void ConfigureVesselsStep(ModelBuilder builder)
{
    builder.Entity<DestinationVesselStep>(b =>
    {
        //Properties
        b.HasMany(p => p.VesselsDestination).WithMany( d => d.DestinationSteps);
    });
}

private static void ConfigureLiquidNitrogenStep(ModelBuilder builder)
{
    builder.Entity<LiquidNitrogenStep>(b =>
    {
        //Properties
        b.HasMany(p => p.DestinationsBoxes).WithMany(d => d.LiquidNitrogenSteps);
    });
}


text:
Q: Post JSON to PHP Server I want to send some data to a PHP file and all I get as response is {"status":"error","code":-1,"original_request":null}
My Objective C code:
NSMutableDictionary *questionDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:questionTitleString, @"question_title", questionBodyString, @"question_body", nil];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myURL/post.php"]];
[request setHTTPMethod:@"POST"];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:questionDictionary options:kNilOptions error:nil];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setValue:@"json" forHTTPHeaderField:@"Data-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];

NSURLConnection *postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

And now my PHP code:
    $postdata = file_get_contents("php://input");
$obj = json_decode($postdata);

if (is_array($post_data))
    $response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
    $response = array("status" => "error", "code" => -1, "original_request" => $obj);

$processed = json_encode($response);
echo $processed;

The Problem is that the PHP receives a request from my app but does not receive the content I send to it.

A: Why are you using json_decode() on php://input directly, when there are multiple parameters?
Try this:
// See the underlying structure of your data; attempt to decode the JSON:
var_dump($_POST);

$data = json_decode($_POST['question_title'], true);
var_dump($data);

$data = json_decode($_POST['question_body'], true);
var_dump($data);

PHP gives us the $_POST superglobal for a good reason. Also, json_decode($string, true) will return an associative array.


text:
Q: How to use "for" with __VA_ARGS__ in macros? I've written a macro like this for my project:
#define CLICK_IF_VISIBLE(string,...) \
    for (auto iterator in __VA_ARGS__)\
    {\
        Handle(iterator); \
    }

I need to handle each individual string in the arg list instead of all the list (because the function Handle does take a list of strings as argument and I cannot do anything about it). But as you can guess, the compiler returns errors at the "for" function.
What did I do wrong? How can I use "for" and "in" to deal with "VA_ARGS" as a list of strings?
Thank you.

A: Don't use a macro for this. Write a function template.
template <typename... Strings>
void click_if_visible(Strings... strings)
{
    for (auto iterator : { strings... })
    {
         Handle(iterator);
    }
}


text:
Q: Memory allocation with std430 qualifier I'm using the compute shader bound with a SSAO. And I use the following structure in the compute shader:
struct Particle
{
    vec4 pAnds;
    vec3 velocity;
    float lifespan;
    float age;
};

layout (std430, binding = 0) buffer members_in
{
    Particle particle[];
} input_data;

yet it seems that the memory block allocated for each of these data structure is not equal to (4 + 3 + 1 + 1) * 4. And I also tried another one:
struct Particle
{
    vec4 pAnds;
    vec3 velocity;
    float lifespan;
};

This time it worked fine. I was wondering how the memory is allocated with std430 qualifier. How to make my first data structure work just as the second one?
updated:
I changed it to the following form:
struct Particle
{
    float px, py, pz, s;
    float vx, vy, vz;
    float lifespan;
    float age;
};

This time it worked fine, but I still have no idea why there's problem using vec4 / vec3.

A: From the std430 Layout Rules:

Structure alignment is the same as the alignment for the biggest structure member, where three-component vectors are not rounded up to the size of four-component vectors. Each structure will start on this alignment, and its size will be the space needed by its members, according to the previous rules, rounded up to a multiple of the structure alignment.

The alignments for vec4 is four times the size of float.
Source: OpenGL Programming Guide, 8th Edition

First example:
struct Particle {
    vec4 pAnds;      // 4 * 4 bytes
    vec3 velocity;   // 3 * 4 bytes
    float lifespan;  // 1 * 4 bytes
    float age;       // 1 * 4 bytes
};

The biggest member of the structure is vec4 pAnds and it has 16 byte alignment. Therefore the structure's alignment is also 16 bytes, meaning, that inside an array each structure has to start at a position multiple of 16. In order to satisfy that, a 12 byte padding will be appended to the end of each structure.

Second example:
struct Particle {
    vec4 pAnds;      // 4 * 4 bytes
    vec3 velocity;   // 3 * 4 bytes
    float lifespan;  // 1 * 4 bytes
};

The structure has an alignment of 16 bytes and the size of the structure nicely fits into 2 times the alignment of the structure.

Third example:
struct Particle {
    float px, py, pz, s;
    float vx, vy, vz;
    float lifespan;
    float age;
};

The structure doesn't have any elements bigger than one size of float, therefore the alignment of the structure is only 4 bytes.

The workaround could be inserting an array of floats as an explicit padding or trying to pack your data tightly into a size multiple of the structure's alignment.


text:
Q: How to make akka-http to forward a GET request to a POST request and change attributes? I am handing a get request using akka-http and I want to forward to the same host but changing the following parameters:

*

*convert the GET to a POST

*change the port from 8080 to 8081

*erase the parameters and send a JSON. I already created the JSON value to send.

I consulted this page and this answer. I am extracting the request using extract(_.request) { request => and then creating a redirect( with the StatusCodes.MovedPermanently.
val routes: Route = {
    get {
      (path(IntNumber) & parameterSeq) { (adId: Int, params: Seq[(String, String)]) =>
        // handling requests as: "http://localhost:8080/2?c=5&b=2", make sure to use the request between quotes
        println(s"The ad ID: $adId contains the parameters: ${params.map(paramString).mkString(", ")}")

        val bid = getBid(adId, params)
        println(s"bid request: ${bid.toJson.prettyPrint}")

        // HOW TO REDIRECT TO ANOTHER PORT, CHANGE THE METHOD FROM GET TO POST, AND SEND A JSON PAYLOAD?
        val newRequest = HttpRequest(
          HttpMethods.POST,
          uri = "/",
          entity = HttpEntity(ContentTypes.`application/json`, bid.toJson.toString)
        )

        redirect(
          newRequest
            .uri
            .withHost("localhost")
            .withPort(8082),
          StatusCodes.MovedPermanently
        )
        // complete(StatusCodes.OK)

      } ~ pathEndOrSingleSlash {
        complete(StatusCodes.BadRequest)
      } ~ {
        complete(StatusCodes.Forbidden)
      }
    }
  }

But when I send a get to the akka-http application $ http GET "localhost:8080/3?b=5&c=10&d=19&c=10" the server on the port 8082 does not answer.
$ http GET "localhost:8080/3?b=5&c=10&d=19&c=10"
HTTP/1.1 301 Moved Permanently
Content-Length: 92
Content-Type: text/html; charset=UTF-8
Date: Fri, 19 Feb 2021 15:49:21 GMT
Location: //localhost:8082/
Server: akka-http/10.2.2

This and all future requests should be directed to this URI.

To test if the server is working I can send POST requests and I receive the answer:
$ http POST localhost:8082 < src/main/resources/bidders-request-10.json
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Date: Fri, 19 Feb 2021 15:51:02 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked

{
    "bid": 0,
    "content": "b:$price$",
    "id": "10"
}

A: So, I solved by creating an actor that executes a Http().singleRequest(HttpRequest(uri = "https://akka.io")) like this example. the working solution that I have is:
import akka.actor.{Actor, ActorLogging, ActorSystem, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.util.ByteString
import spray.json._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport

object MyselfClient {
  def main(args: Array[String]): Unit = {
    val system = ActorSystem("AuctionClientSystem")
    val auctionClientActor = system.actorOf(Props[AuctionClientActor], "auctionClientActor")
    auctionClientActor ! BidRequest(1, Bid(2, List(("c", "5"), ("b", "2"))))
  }
}

case class BidRequest(requestId: Int, bid: Bid)

class AuctionClientActor extends Actor with ActorLogging
      with BidJsonProtocol with SprayJsonSupport {

  import akka.pattern.pipe
  import context.dispatcher

  implicit val system = context.system
  val http = Http(system)

  def receive = {
    case bidRequest@BidRequest(requestId, bid) =>
      println(s"received bid request: $bidRequest")
      val content = bidRequest.bid.toJson.toString
        .replace("[[", "{")
        .replace("]]", "}")
        .replace("\",\"", "\": \"")
        .replace("[", "")
        .replace("]", "")
      println(content)
      // create the request
      val httpRequest = HttpRequest(
        HttpMethods.POST,
        uri = Uri("http://localhost:8081"),
        entity = HttpEntity(
          ContentTypes.`application/json`,
          content
          // """{"id": 10, "attributes" : { "a": "1", "b": "0" }}""".stripMargin
        )
      )
      // send the request
      http.singleRequest(httpRequest).pipeTo(self)
    case HttpResponse(StatusCodes.OK, headers, entity, _) =>
      entity.dataBytes.runFold(ByteString(""))(_ ++ _).foreach { body =>
        println("Got response, body: " + body.utf8String)
      }
    case resp@HttpResponse(code, _, _, _) =>
      println("Request failed, response code: " + code)
      resp.discardEntityBytes()
  }
}

I just could not figure out how to make Spray JSON not use [ and ]. Then I am doing that nasty conversation using .replace("[[", "{"). However, the solution is already working. The Spray JSON I am looking for a better way to convert it. I guess there is another form to create the case class to not have [ and ].
import spray.json._

case class Bid(id: Int, attributes: List[(String, String)])

trait BidJsonProtocol extends DefaultJsonProtocol {
  implicit val bidFormat = jsonFormat2(Bid)
}


text:
Q: How to access this inside prototype function in js I am using nodejs and mysql client in nodejs
I am trying to use pool function od the mysql module.
"use strict";
var mysqlClient = require('mysql')
  , dbPool = mysqlClient.createPool(require('../config/database'));
function MyModel(params) {
  this.tbl = params.tbl;
  this.primary_key = params.primary_key;
  this.primary_name = params.primary_name;
  this.dbPool = dbPool;
}
module.exports = MyModel;
//primary key
MyModel.prototype.fromPK = function fromPK(pk, callback) {
  this.dbPool.getConnection(function (err, connection) {
  var query = "SELECT * FROM " + this.tbl + " WHERE " + this.primary_key + " = " + connection.escape(pk);
    connection.query(query, callback);
  });
};

I know I cannot access this inside getConnection and I could simply set var t = this outside it and access it with var t, but is there any other way to access this var in this condition. Should I define var t = this in each prototype function I write?
I have following detailed gist
https://gist.github.com/yalamber/6bd1df0cc27849eb09b3

A: You can determine what this is in a function using .bind().
The elaborate syntax is:
var newfunction = oldfunction.bind(THIS_OBJECT);

That would make THIS_OBJECT be the this object inside the oldfunction. As you can see, .bind() returns a new (bound) function.
You don't need that elaborate syntax though, it works on anonymous functions as well:
var newfunction = function() { ... }.bind(THIS_OBJECT);

In your case, you could use this:

this.dbPool.getConnection(function (err, connection) {
  var query = "SELECT * FROM " + this.tbl + " WHERE " + this.primary_name + " = " + connection.escape(pn);
  connection.query(query, callback);
}.bind(this));

This makes the this inside the callback function the same as the this on the outside.


text:
Q: SQL: INTO OUTFILE Error: File /data.csv already exists I am trying to export sql query result to a file so that I can provide user a download link to download. But I am getting some issues:
Issue 1: After execution I could not find data.csv in the root folder.
Issue 2: If I try again then it says that file already exists.
I am using following code:
 $query = <<<EOL
   SELECT * FROM data
   INTO OUTFILE '/data.csv'
   FIELDS TERMINATED BY ','
   ENCLOSED BY '"'
   LINES TERMINATED BY '\n'
EOL;

 $result = mysql_query($query);

Solutions I want:
1- I need to know from where I can locate file.
2- I need to be able this csv file through php after execution.
Details about the Environment I am using for this script:

*

*Local Host

*Xampp (Apache & MySQL)

*Operating System: Windows 10


text:
Q: SwiftUI: Cannot set 'zoomScale' of an PKCanvasView() I want to set the Zoom scale of my PKCanvasView()
I tried adding this function:
func setCanvasZoom() {
    canvasView.zoomScale = 2.0
    print("CanvasView: \(canvasView.zoomScale)")
}

But that function always throws 1.0 in the console...
I am calling the setCanvasView() function, after my ScrollView appeared:
ZStack {
    ScrollView {
        VStack {
            CanvasView(canvasView: $canvasView)
        }
    }.onAppear(perform: {
        setCanvasZoom()
    })
}

The canvasView variable is declared like that:
@State var canvasView = PKCanvasView()

Do you guys have any Idea why this happens?


text:
Q: Fragment: Programmatically create view for xml to fill Is there a way to create a new layout that you can then have your XML inflate?
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle){

            one_third = (RelativeLayout)getActivity().findViewById(R.id.list3);

            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            String width = "" + dm.widthPixels;

            int WIDTH;
            int SIZE;

            SIZE = Integer.parseInt(width.toString());

            WIDTH = (SIZE / 3);

            one_third.setMinimumWidth(WIDTH);

    View homeselect = inflater.inflate(R.layout.listelements, container, false);
    setListAdapter(new ArrayAdapter<String>(getActivity(),
                R.layout.start_row, R.id.label, views));
    return homeselect;

}

I'm trying to take this bit of code in the fragment and here is where I want to have the new layout be created. I want to give it the width of the value WIDHT and then have my xml fill that.

A: This question is not really about Fragment.  The API here is just providing the part of the view hierarchy that the Fragment manages.  All layout is based around the view hierarchy.  You do *not* do your layout here, because you don't even know the space in which to do the layout.
The correct answer then is the same any time you are using the view hierarchy: participate in the regular layout flow through onMeasure() and onLayout().  If the standard layout managers won't do what you want, you can implement your own special subclass of ViewGroup that does your desired layout based on the size it gets.


text:
Q: Is there a group with a proper subgroup such that the quotient is isomorphic to itself? While studying for my finals this question came across my mind. Is there a group $G$ and a proper subgroup $H$ such that $G/H\cong G$? I immediatly discarded a finite group or even the integers, as for a finite group the orders wouldn't match and for the integers, the proper subgroups are all of the form $n\mathbb{Z}$ with $n$ integer. Having in mind the first isomorphism theorem I'm looking for a surjective homomorphism with non-trivial kernel. That would give $G/\ker(f) \cong G$. Is there any example?

A: Take your favourite group $\tilde{G}$ and let $G = \prod_{n=1}^{\infty} \tilde{G}$. Let $f : G \to G$ be the shift $f(x_1, x_2, \ldots) = (x_2, x_3, \ldots)$. Then $f$ is a surjective group homomorphism with $\ker(f) \cong \tilde{G}$.


text:
Q: Iptables blocking remote MySQL remote I'm trying to set my server (CentOS 6.9) to accept remote MySQl connections and I'm stuck on the firewall config.
I have everything set right on the MySQL side; I can connect through telnet if I stop iptables, but not when it's active.
I've already tried:
-A INPUT -i lo -p tcp -m tcp --dport 3306 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 3306 -j ACCEPT

But still I get "connection refused" with iptables active. What am I doing wrong?
EDIT: output of iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:mysql
2    acctboth   all  --  anywhere             anywhere
3    tcpchk     tcp  --  anywhere             anywhere
4    udpchk     udp  --  anywhere             anywhere
5    icmpchk    icmp --  anywhere             anywhere
6    ipdrop_global  all  --  anywhere             anywhere
7    input_custom  all  --  anywhere             anywhere
8    ACCEPT     all  --  anywhere             anywhere
9    ssh        tcp  --  anywhere             anywhere            state NEW tcp dpt:22022
10   ACCEPT     icmp --  anywhere             anywhere            icmp echo-request limit: up to 2/sec burst 10 mode srcip
11   LOG        icmp --  anywhere             anywhere            icmp echo-request limit: avg 5/min burst 5 LOG level error prefix `ICMP_DROP '
12   DROP       icmp --  anywhere             anywhere            icmp echo-request
13   ACCEPT     icmp --  anywhere             anywhere            icmp echo-reply
14   ACCEPT     icmp --  anywhere             anywhere            icmp fragmentation-needed
15   ACCEPT     icmp --  anywhere             anywhere            icmp port-unreachable
16   ACCEPT     icmp --  anywhere             anywhere            icmp host-unreachable
17   ACCEPT     icmp --  anywhere             anywhere            icmp time-exceeded
18   ACCEPT     icmp --  anywhere             anywhere            icmp parameter-problem
19   ACCEPT     icmp --  anywhere             anywhere            icmp type 30
20   ACCEPT     icmp --  anywhere             anywhere            state ESTABLISHED
21   ACCEPT     tcp  --  103.21.244.0/22      anywhere            tcp dpt:http
22   ACCEPT     tcp  --  103.22.200.0/22      anywhere            tcp dpt:http
23   ACCEPT     tcp  --  103.31.4.0/22        anywhere            tcp dpt:http
24   ACCEPT     tcp  --  104.16.0.0/12        anywhere            tcp dpt:http
25   ACCEPT     tcp  --  108.162.192.0/18     anywhere            tcp dpt:http
26   ACCEPT     tcp  --  131.0.72.0/22        anywhere            tcp dpt:http
27   ACCEPT     tcp  --  141.101.64.0/18      anywhere            tcp dpt:http
28   ACCEPT     tcp  --  162.158.0.0/15       anywhere            tcp dpt:http
29   ACCEPT     tcp  --  172.64.0.0/13        anywhere            tcp dpt:http
30   ACCEPT     tcp  --  173.245.48.0/20      anywhere            tcp dpt:http
31   ACCEPT     tcp  --  188.114.96.0/20      anywhere            tcp dpt:http
32   ACCEPT     tcp  --  190.93.240.0/20      anywhere            tcp dpt:http
33   ACCEPT     tcp  --  197.234.240.0/22     anywhere            tcp dpt:http
34   ACCEPT     tcp  --  198.41.128.0/17      anywhere            tcp dpt:http
35   ACCEPT     tcp  --  vps.retireja.com.br  anywhere            tcp dpt:http
36   ACCEPT     tcp  --  server.thenarcissistswife.com  anywhere            multiport dports ssh,http
37   ACCEPT     icmp --  server.thenarcissistswife.com  anywhere            icmp echo-request
38   ACCEPT     tcp  --  54.e2.adb8.ip4.static.sl-reverse.com  anywhere            multiport dports ssh,http
39   ACCEPT     icmp --  54.e2.adb8.ip4.static.sl-reverse.com  anywhere            icmp echo-request
40   ACCEPT     tcp  --  32.e0.acb8.ip4.static.sl-reverse.com  anywhere            multiport dports ssh,http
41   ACCEPT     icmp --  32.e0.acb8.ip4.static.sl-reverse.com  anywhere            icmp echo-request
42   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:domain
43   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ftp
44   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
45   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:smtp
46   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:26
47   ACCEPT     udp  --  anywhere             anywhere            udp dpt:domain
48   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:http
49   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:pop3
50   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:imap
51   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:https
52   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:urd
53   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:submission
54   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:infowave
55   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:radsec
56   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:sunclustergeo
57   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:gnunet
58   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:eli
59   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:sep
60   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:EtherNet/IP-1
61   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:nbx-ser
62   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:nbx-dir
63   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:imaps
64   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:pop3s
65   ACCEPT     udp  --  google-public-dns-b.google.com  anywhere            udp spt:domain
66   ACCEPT     tcp  --  google-public-dns-b.google.com  anywhere            tcp spt:domain
67   ACCEPT     udp  --  google-public-dns-a.google.com  anywhere            udp spt:domain
68   ACCEPT     tcp  --  google-public-dns-a.google.com  anywhere            tcp spt:domain
69   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:22022
70   ACCEPT     udp  --  anywhere             anywhere            udp dpt:22022
71   ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
72   LOG        all  --  anywhere             anywhere            limit: avg 1/sec burst 5 LOG level warning prefix `LOG_INPUT: '
73   DROP       all  --  anywhere             anywhere
74   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:mysql
75   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:mysql
76   ACCEPT     tcp  --  vps.retireja.com.br  anywhere            tcp dpt:mysql
77   ACCEPT     tcp  --  vps.retireja.com.br  anywhere            tcp dpt:mysql

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination
1    tcpchk     tcp  --  anywhere             anywhere
2    udpchk     udp  --  anywhere             anywhere
3    icmpchk    icmp --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
1    cpanel-dovecot-solr  all  --  anywhere             anywhere
2    acctboth   all  --  anywhere             anywhere
3    tcpchk     tcp  --  anywhere             anywhere
4    udpchk     udp  --  anywhere             anywhere
5    icmpchk    icmp --  anywhere             anywhere
6    output_custom  all  --  anywhere             anywhere
7    ACCEPT     all  --  anywhere             anywhere
8    ACCEPT     icmp --  anywhere             anywhere            state NEW,ESTABLISHED
9    ACCEPT     icmp --  anywhere             server.thenarcissistswife.com icmp echo-reply
10   ACCEPT     icmp --  anywhere             54.e2.adb8.ip4.static.sl-reverse.com icmp echo-reply
11   ACCEPT     icmp --  anywhere             32.e0.acb8.ip4.static.sl-reverse.com icmp echo-reply
12   ACCEPT     udp  --  anywhere             anywhere            udp dpt:saphostctrls
13   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:saphostctrls
14   ACCEPT     udp  --  anywhere             anywhere            udp dpt:30000
15   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:30000
16   ACCEPT     udp  --  anywhere             anywhere            udp dpt:pop3
17   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:pop3
18   ACCEPT     udp  --  anywhere             anywhere            udp dpt:nicname
19   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:nicname
20   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:rsync
21   ACCEPT     udp  --  anywhere             anywhere            owner UID match root
22   ACCEPT     icmp --  anywhere             anywhere
23   ACCEPT     all  --  anywhere             anywhere
24   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ftp
25   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
26   ACCEPT     tcp  --  anywhere             gateway07.websitewelcome.com tcp dpt:smtp
27   ACCEPT     tcp  --  anywhere             gateway03.websitewelcome.com tcp dpt:smtp
28   ACCEPT     tcp  --  anywhere             gateway04.websitewelcome.com tcp dpt:smtp
29   ACCEPT     tcp  --  anywhere             gateway05.websitewelcome.com tcp dpt:smtp
30   ACCEPT     tcp  --  anywhere             gateway06.websitewelcome.com tcp dpt:smtp
31   ACCEPT     tcp  --  anywhere             gateway09.websitewelcome.com tcp dpt:smtp
32   ACCEPT     tcp  --  anywhere             gateway10.websitewelcome.com tcp dpt:smtp
33   ACCEPT     tcp  --  anywhere             gateway11.websitewelcome.com tcp dpt:smtp
34   ACCEPT     tcp  --  anywhere             gateway12.websitewelcome.com tcp dpt:smtp
35   ACCEPT     tcp  --  anywhere             gateway13.websitewelcome.com tcp dpt:smtp
36   ACCEPT     tcp  --  anywhere             gateway14.websitewelcome.com tcp dpt:smtp
37   ACCEPT     tcp  --  anywhere             gateway15.websitewelcome.com tcp dpt:smtp
38   ACCEPT     tcp  --  anywhere             gateway16.websitewelcome.com tcp dpt:smtp
39   ACCEPT     tcp  --  anywhere             gateway02.websitewelcome.com tcp dpt:smtp
40   ACCEPT     tcp  --  anywhere             gateway01.websitewelcome.com tcp dpt:smtp
41   ACCEPT     tcp  --  anywhere             gateway08.websitewelcome.com tcp dpt:smtp
42   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:smtp owner UID match mailnull
43   LOG        tcp  --  anywhere             anywhere            ! owner UID match root multiport dports smtp,urd,submission limit: avg 1/sec burst 5 LOG level notice prefix `OUTBOUND-SMTP : '
44   ACCEPT     udp  --  anywhere             anywhere            udp dpt:domain ! owner UID match nobody
45   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:domain ! owner UID match nobody
46   ACCEPT     udp  --  anywhere             google-public-dns-b.google.com udp dpt:domain
47   ACCEPT     tcp  --  anywhere             google-public-dns-b.google.com tcp dpt:domain
48   ACCEPT     udp  --  anywhere             google-public-dns-a.google.com udp dpt:domain
49   ACCEPT     tcp  --  anywhere             google-public-dns-a.google.com tcp dpt:domain
50   ACCEPT     udp  --  anywhere             anywhere            udp dpt:domain owner UID match nobody limit: avg 20/sec burst 5
51   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:domain owner UID match nobody limit: avg 20/sec burst 5
52   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:http
53   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:https
54   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:urd
55   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:submission
56   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:gnunet
57   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:eli
58   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:sep
59   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:mysql
60   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:time
61   ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:sms-chat
62   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:domain
63   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:ftp
64   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:ssh
65   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:22022
66   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:smtp
67   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:26
68   ACCEPT     udp  --  anywhere             anywhere            udp spt:domain
69   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:http
70   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:pop3
71   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:imap
72   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:https
73   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:urd
74   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:submission
75   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:infowave
76   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:radsec
77   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:sunclustergeo
78   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:gnunet
79   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:eli
80   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:sep
81   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:EtherNet/IP-1
82   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:nbx-ser
83   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:nbx-dir
84   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:imaps
85   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:pop3s
86   ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
87   LOG        all  --  anywhere             anywhere            limit: avg 1/sec burst 5 LOG level warning prefix `LOG_OUTPUT: '
88   DROP       all  --  anywhere             anywhere
89   ACCEPT     tcp  --  anywhere             anywhere            tcp spt:mysql

Chain acctboth (2 references)
num  target     prot opt source               destination

Chain cpanel-dovecot-solr (1 references)
num  target     prot opt source               destination
1    ACCEPT     tcp  --  anywhere             anywhere            multiport sports 8984,7984 owner UID match cpanelsolr
2    ACCEPT     tcp  --  anywhere             anywhere            multiport sports 8984,7984 owner UID match root
3    REJECT     tcp  --  anywhere             anywhere            multiport sports 8984,7984 reject-with icmp-port-unreachable

Chain icmpchk (3 references)
num  target     prot opt source               destination

Chain input_custom (1 references)
num  target     prot opt source               destination

Chain ipdrop_global (1 references)
num  target     prot opt source               destination
1    DROP       all  --  43.255.190.0/23      anywhere

Chain output_custom (1 references)
num  target     prot opt source               destination

Chain ssh (1 references)
num  target     prot opt source               destination
1    ACCEPT     all  --  supra.websitewelcome.com  anywhere
2    ACCEPT     all  --  wizard2.hostgator.com  anywhere
3    ACCEPT     all  --  wizard-backup.hostgator.com  anywhere
4    ACCEPT     all  --  216-106-185-169.ds1-static.mia1.net.ststelecom.com  anywhere
5    ACCEPT     all  --  12.96.160.0/24       anywhere
6    ACCEPT     all  --  216.19.0.0/24        anywhere
7               tcp  --  anywhere             anywhere            state NEW recent: SET name: DEFAULT side: source
8    LOG        tcp  --  anywhere             anywhere            state NEW recent: CHECK seconds: 60 hit_count: 10 name: DEFAULT side: source limit: avg 10/min burst 5 LOG level notice prefix `SSH-ATTACK : '
9    REJECT     tcp  --  anywhere             anywhere            state NEW recent: UPDATE seconds: 60 hit_count: 10 name: DEFAULT side: source reject-with tcp-reset
10   ACCEPT     tcp  --  anywhere             anywhere

Chain tcpchk (3 references)
num  target     prot opt source               destination

Chain udpchk (3 references)
num  target     prot opt source               destination

A: Remove this rule:

-A INPUT -p tcp -m tcp -j REJECT --reject-with tcp-reset

You can remove a rule by printing the line numbers this way:
iptables -L --line-numbers

and then deleting the line by it's line number.
For instance, if the offending line is number 7, then:
iptables -D INPUT 7