text:
Q: Как расположить элементы grid по линии. Подробнее на скриншотах Первый скрин как это выглядит у меня:

Второй как это должно выглядеть на самом деле:

Проблема в том, что контент разный и поэтому всё идет неправильно(не по линии)

.services{

    &__content{
        text-align: center;

        &-title{
            color: $black;
            font-weight: 700;
            font-size: 36px;
            line-height: 56px;
            margin-bottom: 26px;
        }
        &-line{
            max-width: 56px;
            height: 2px;
            background: $black;
            border-radius: 5px;
            margin: 0 auto;
            margin-bottom: 33px;
        }
        &-text{
            color: $lightGray;
            font-weight: 300;
            font-size: 18px;
            line-height: 30px;
            max-width: 952px;
            margin: 0 auto;
            margin-bottom: 80px;
        }
        &-cards{
            display: grid;
            justify-content: center;
            grid-template-columns: auto auto auto;
            grid-column-gap: 35px;
            grid-row-gap: 37px;

            &-card{
                box-shadow: 10px 40px 50px rgba(229, 233, 246, 0.4);
                border-radius: 20px;
                text-align: left;
                max-width: 350px;
                padding: 47px 39px;
                img{
                    margin-bottom: 22px;
                }
                h3{
                    color: $black;
                    font-weight: 700;
                    font-size: 24px;
                    line-height: 56px;
                }
                p{
                    color: $lightGray;
                    font-weight: 300;
                    font-size: 16px;
                    line-height: 28px;
                }
            }
        }
    }
}

Our services

We provide to you the best choiches for you. Adjust it to your health needs and make sure your undergo treatment with our highly qualified doctors you can consult with us which type of service is suitable for your health

Search doctor

Choose your doctor from thousands of specialist, general, and trusted hospitals

Online pharmacy

Buy  your medicines with our mobile application with a simple delivery system

Consultation

Free consultation with our trusted doctors and get the best recomendations

Details info

Free consultation with our trusted doctors and get the best recomendations

Emergency care

You can get 24/7 urgent care for yourself or your children and your
                        lovely family

Tracking

Track and save your medical history and health data

A: Оберните картинки в блок с классом, например card-image-box и в стилях установите ему фиксированную высоту

  <div class="card-image-box"

Consultation

Free consultation with our trusted doctors and get the best
 recomendations

css
.card-image-box {
  height: 200px
}


text:
Q: SGE array job for Python taking input from a loop I'm trying to submit array job of a Python script that should get different inputs. For now I just submit every job separately like this:
#!/bin/bash

P_vec=($(seq 0.92 0.01 1.15))
length_P=${#P_vec[@]}

for (( i=0; i<${length_P}; i++ ));
do
    qsub -cwd python saver.py -s ${P_vec[i]}
done

However, I would like to submit it as array job as I've found in this tutorial, where the basic example is this:
#!/bin/sh
# Tell the SGE that this is an array job, with "tasks" to be numbered 1 to 10000
#$ -t 1-10000
# When a single command in the array job is sent to a compute node,
# its task number is stored in the variable SGE_TASK_ID,
# so we can use the value of that variable to get the results we want:
~/programs/program -i ~/data/input.$SGE_TASK_ID -o ~/results/output.$SGE_TASK_ID

How can I combine the -t flag inside of the loop at the previous script?
Trying the following approach:
#!/bin/bash

P_vec=($(seq 0.92 0.01 1.15))
length_P=${#P_vec[@]}
#$ -t 1-$length_P

python saver.py -s ${P_vec[$SGE_TASK_ID]}

Gave the error message:
Unable to read script file because of error: Numerical value invalid!
The initial portion of string "$length_P" contains no decimal number

While this gave no error messages, but not the required output:
#!/bin/bash
#$ -t 1-3

python saver.py -s $SGE_TASK_ID

A: Cannot test it, but my common sense says:
#!/bin/bash
# Tell the SGE that this is an array job, with "tasks" to be numbered 0 to length_P-1
#$ -t 0-???????

P_vec=($(seq 0.92 0.01 1.15))

python saver.py -s ${P_vec[$SGE_TASK_ID]}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Only Showing 1 Row So Im trying to Import data from my phpmyadmin server and trying to display different users and data. I have got this working but it would only show the 1st result and nothing else. I have taken a screenshot and will insert my code below.
Thanks,
cNTr1nity
Image (Website) - https://gyazo.com/c7ee16469f88406e6bd8c97532ff44aa?token=04f129fc8bd3d38adcb30e0fd261b618
Code -  https://pastebin.com/9P7VGBr5
My Code is stuffing up. Please find pastebin link

P.S DBConnect is just connecting the php file to the database.
P.P.S I am updating all my stuff to mysqli because of sql injection.

A: 1st : mysql_* api is deprecated try to use mysqli_*  or PDO
2nd :  Run the mysql_fetch_array() in while loop like below
            while($userInfo=mysql_fetch_array($sql)){
            echo "
";
            echo "".$userInfo['userId']."	";
            echo "".$userInfo['userName']."	";
            echo "".$userInfo['userEmail']."	";
            echo "".$userInfo['Dev']."	";
            echo "".$userInfo['Admin']."	";
            echo "".$userInfo['Mod']."	";
            echo "".$userInfo['Helper']."	";
            echo "
";
            }

Note : Don't forgot to move your code to mysqli_* or PDO

A: the first thing use pdo method msql is deprecated , second you not define
$_SESSION['user'] you most give a value to this $_SESSION['user']
something like
$_SESSION['user'] = email_user_after_login
and in your query you change "where id = " to "where email = "
bad staff ! isset this means wherever you send in $_SESSION['user'] make you staff work
if( !isset($_SESSION['user']) ) {
        header("Location: index.php");
        exit;
    }
// you most compare this $_SESSION['user'] with something if you don't someone can start you session with a injection


text:
Q: Cannot connect to jetty 9 Why can I not successfully connect to jetty?
I have the latest version of jetty 9.x running.  I have the jetty_base folder setup and when I drop war files into the folder I see them get expanded into the /tmp folder.
lsof -i :8080
java    26488 jetty   85u  IPv6 400595      0t0  TCPlocalhost.localdomain:webcache (LISTEN)

curl 'http://localhost:8080' curl: (7) Failed connect to
  localhost:8080; Connection refused
curl http://127.0.0.1:8080 curl: (7) Failed connect to 127.0.0.1:8080;
  Connection refused

A: From the below output of lsof -i:8080

java    26488 jetty   85u  IPv6 400595      0t0
  TCPlocalhost.localdomain:webcache (LISTEN)

It seems jetty is using ipv6 rather ipv4.
For ipv6, use ::1 as your loopback address. For ipv4, it is 127.0.0.1.
Changes you can make for localhost to work :
If you wish to set localhost to work for both ipv6 and ipv4 you can make below changes to /etc/hosts file.
127.0.0.1       localhost
# ... and below
::1             localhost ipv6-localhost ipv6-loopback

As always, you can test the connectivity using ping6 ::1 for an ipv6 ip and ping 127.0.0.1 for ipv4.
Give a try!


text:
Q: Do the conditions on the following real sequence guarantee it is dense in $\ [0,1]\ ?$ I should probably not be asking any more questions because it's too late, but this one fascinated me.

If $\ (a_n)_{n\in\mathbb{N}}$ is a strictly increasing sequence of
positive real numbers such that
$$\displaystyle\lim_{n\to\infty} a_n = \infty\quad \text{and}\quad
 \displaystyle\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=1,$$
then is the set:
$$ X = \left\{ \frac{a_i}{a_j}: i,j\in\mathbb{N} \right\} $$
dense in $\ [0,1]\ $ (and therefore also dense in $\ \mathbb{R}^+\ ) ?$

$$$$
Without the requirement $\displaystyle\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=1,\ $ the answer would be "no". For example, consider the sequence $\ a_n=2^n.$
So it is this requirement that makes this question interesting.

A: The answer is yes. Here is a sketch:
Let $0< a <b < 1 $ be arbitrary.
Since $\displaystyle\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=1$ there exists some $N$ such that
for all $n>N$ we have
$$
\frac{a_{n+1}}{a_n} < \frac{b}{a} \,.
$$
Since $a_n$ is increasing we have
$$
\frac{a}{b}< \frac{a_{n}}{a_{n+1}} < 1 \forall n >N  \qquad (*)
$$
Next, using again $\displaystyle\lim_{n\to\infty}\frac{a_{n}}{a_{n+1}}=1$ there exists some
$M>N$ such that
$$
\frac{a_{M}}{a_{M+1}}> b
$$
Finally, since
$$
\lim_k \frac{a_{M}}{a_{M+k}} =0
$$
there exists some $k \geq 2$ such that
$$
\frac{a_{M}}{a_{M+k}} < b \,.
$$
Pick the minimal such $k$. Then
$$
\frac{a_{M}}{a_{M+k-1}} \geq b \\
\frac{a_{M+k-1}}{a_{M+k}} > \frac{b}{a} \qquad \mbox{ by } (*) \,.
$$
Multiplying gives $\frac{a_{M}}{a_{M+k}} >a$ which completes the proof.
P.S. Intuitivelly the solution is as follows: for $n$ large enough $\frac{a_n}{a_{n+1}}$ is arbitrary closed to $1$, but smaller than one. Multiplying consecutive terms of this form, you get telescopic products converging to $0$ is very small steps.


text:
Q: Should I be attempting to return an array, or is there a better solution? A problem set for people learning C++ is

Write a short program to simulate a ball being dropped off of a tower. To start, the user should be asked for the initial height of the tower in meters. Assume normal gravity (9.8 m/s2), and that the ball has no initial velocity. Have the program output the height of the ball above the ground after 0, 1, 2, 3, 4, and 5 seconds. The ball should not go underneath the ground (height 0).

Before starting C++ I had a reasonable, but primarily self taught, knowledge of Java. So looking at the problem it seems like it ought to be split into

*

*input class

*output class

*calculations class

*Physical constants class (recommended by the question setter)

*controller ('main') class

The input class would ask the user for a starting height, which would be passed to the controller. The controller would give this and a number of seconds (5) to the calculations class, which would create an array of results and return this to the controller. The controller would hand the array of results to the output class that would print them to the console.
I will put the actual code at the bottom, but it's possibly not needed.
You can probably already see the problem, attempting to return an array. I'm not asking how to get round that problem, there is a workaround here and here. I'm asking, is the problem a result of bad design? Should my program be structured differently, for performance, maintenance or style reasons, such that I would not be attempting to return an array like object?
Here is the code (which works apart from trying to return arrays);
main.cpp
/*
 * Just the main class, call other classes and passes variables around
 */
#include <iostream>
#include "dropSim.h"
using namespace std;

int main()
{
    double height = getHeight();
    int seconds = 5;
    double* results = calculateResults(height, seconds);
    outputResults(results);
    return 0;
}

getHeight.cpp
/*
 *  Asks the user for a height from which to start the experiment
 *  SI units
 */
#include <iostream>
using namespace std;

double getHeight()
{
    cout << "What height should the experiment start at; ";
    double height;
    cin >> height;
    return height;
}

calculateResults.cpp
/*
 * given the initial height and the physical constants, the position of the ball
 * is calculated at integer number seconds, beginning at 0
 */

#include "constants.h"
#include <cmath>
#include <iostream>
using namespace std;

double getPosition(double height, double time);

double* calculateResults(double height, int seconds)
{

    double positions[seconds + 1];
    for(int t = 0; t < seconds + 1; t++)
    {
        positions[t] = getPosition(height, t);
    }
    return positions;
}

double getPosition(double height, double time)
{
    double position = height - 0.5*constants::gravity*pow(static_cast<double>(time), 2);
    if( position < 0) position = 0;
    //Commented code is for testing
    //cout << position << endl;
    return position;
}

outputResults.cpp
/*
 *      Takes the array of results and prints them in an appropriate format
 */

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void outputResults(double* results){
    string outputText = "";
    //The commented code is to test the output method
    //Which is working
    //double results1[] = {1,2,3,4,5};
    //int numResults = sizeof(results1)/sizeof(results1[0]);
    int numResults = sizeof(results)/sizeof(results[0]);
    //cout << numResults; //= 0 ... Oh
    for(int t = 0; t < numResults; t++)
    {
        ostringstream line;
        line << "After " << t << " seconds the height of the object is " << results[t] << "\r";
        outputText.append(line.str());

    }
    cout << outputText;
}

And finally a couple of headers;
dropSim.h
/*
 * dropSim.h
 */

#ifndef DROPSIM_H_
#define DROPSIM_H_

double getHeight();

double* calculateResults(double height, int seconds);

void outputResults(double* results);

#endif /* DROPSIM_H_ */

constants.h
/*
 *      Contains physical constants relevant to simulation.
 *      SI units
 */

#ifndef CONSTANTS_H_
#define CONSTANTS_H_

namespace constants
{
    const double gravity(9.81);
}

#endif /* CONSTANTS_H_ */

A: I would say that you're over-engineering a big solution to a little problem, but to answer your specific question:

Should my program be structured differently, for performance, maintenance or style reasons, such that I would not be attempting to return an array like object?

Returning an array-like object is fine. But that doesn't mean returning an array, nor does it mean allocating raw memory with new.
And it's not restricted to return values either. When you're starting out with C++, it's probably best to just forget that it has built-in arrays at all. Most of the time, you should be using either std::vector or std::array (or another linear collection such as std::deque).
Built-in arrays should normally be viewed as a special-purpose item, included primarily for compatibility with C, not for everyday use.
It may, however, be worth considering writing your computation in the same style as the algorithms in the standard library. This would mean writing the code to receive an iterator to a destination, and writing its output to wherever that iterator designates.
I'd probably package the height and time together as a set of input parameters, and have a function that generates output based on those:
struct params {
    double height;
    int seconds;
};

template <class OutIt>
void calc_pos(params const &p, OutIt output) {
    for (int i=0; i<p.seconds; i++) {
        *output = get_position(p.height, i);
        ++output;
    }
}

This works somewhat more clearly along with the rest of the standard library:
std::vector<double> results;

calc_pos(inputs, std::back_inserter(results));

You can go a few steps further if you like--the standard library has quite a bit to help with a great deal of this. Your calc_pos does little more than invoke another function repeatedly with successive values for the time. You could (for example) use std::iota to generate the successive times, then use std::transform to generate outputs:
std::vector<int> times(6);

std::iota(times.begin(), times.end(), 0);

std::vector<double> distances;

std::transform(times.begin(), times.end(), compute_distance);

This computes the distances as the distance dropped after a given period of time rather than the height above the ground, but given an initial height, computing the difference between the two is quite trivial:
double initial_height = 5;

std::vector<double> heights;

std::transform(distances.begin(), distances.end(),
    std::back_inserter(heights),
    [=](double v) { return max(initial_height-v, 0); });

At least for now, this doesn't attempt to calculate the ball bouncing when it hits the ground--it just assumes the ball immediately stops when it hits the ground.

A: You should get rid of self-allocated double * and use std::vector<double> instead. It's not difficult to learn and a basic step in modern C++

A: This is how I would solve the problem:
#include <cmath>
#include <iostream>
#include <iomanip>

using std::cin;
using std::cout;
using std::endl;
using std::sqrt;
using std::fixed;
using std::setprecision;
using std::max;
using std::setw;

static const double g = 9.81;

class Calculator {
public:
   Calculator(double inh) : h(inh)
   {
   }

   void DoWork() const {
      double tmax = sqrt(h / ( g / 2));
      for (double t=0.0; t<tmax; t+=1.0) {
         GenerateOutput(t);
      }
      GenerateOutput(tmax);
   }
private:
   void GenerateOutput(double t) const {
      double x = g * t * t / 2;
      double hremaining = max(h - x, 0.0);
      cout << fixed << setprecision(2) << setw(10) << t;
      cout << setw(10) << hremaining << endl;
   }

   double h;
};

int main() {
   double h(0.0);

   cout << "Enter height in meters: ";
   cin >> h;
   if (h > 0.0) {
      const Calculator calc(h);
      calc.DoWork();
   } else {
      return 1;
   }

   return 0;
}


text:
Q: Remove last column from large CSV file I have a large CSV file that I would like to upload to postgres using datagrip. When I upload it I get the following error for a few records:
11807:98: actual: value separator (,), expected: record separator (\n)

The problem is that there are only 19 columns recognized and that in a very few records there are 20 values. For those records it does not import the record at all. I do want to have all rows in my database.
I thought this would be a peace of cake in python. So I started to work with pandas and loaded the data with the following line:
 df = pd.read_csv('filename.csv', sep='delimiter', header=None)

That does contain the file. It is however way more difficult than I expected to either remove all values that are on lines behind the 19 comma, or to just add a full 20th column that I can later delete. It feels like this is a trivial question and I need a push in the right direction.

A: This generates a dataframe with 30 columns then drops all columns after column 20.
df = pd.DataFrame({f"col{i}":[1,2,3] for i in range(30)})

df = df.drop(columns=[c for c in df.columns[20:]])

A: Reading it into a dataframe that way buys you nothing since each cell will contain a row of your file.
Use the csv module, instead, because it does not try to read the file as a table of fixed width.
import csv

with open('filename.csv', 'r') as i, open('fixed.csv', 'w') as o:
    cr = csv.reader(i)
    cw = csv.writer(o)
    for row in cr:
        cw.writerow(row[0:19])


text:
Q: Javascript: Setting all array values to the same I want to make a new array (of X elements) with all the elements set to 0.
X is set before.
Anyone could make the most compact and easy code for that? Thank you for your
help.

A: Just create a function:
function makeArray(size, defaultValue) {
    var arr = [];
    for (var i = 0; i < size; i++) arr.push(defaultValue);
    return arr;
}

var myArr = makeArray(10, 0);


text:
Q: Segmentation fault 11 is this related to Obj-C-bridge.h? I'm migrating to Swift 3.0 and keep coming across the Segmentation fault 11:
CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
    cd "/Users/kekearif/Documents/MyApp/MyApp Dev/ios-app"
    export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk
    export TOOLCHAINS=com.apple.dt.toolchain.XcodeDefault
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -incremental -module-name SA_Dev -Onone -D COCOAPODS -DDEV -DDEBUG -sdk /......./MyApp\ DEV.build/Objects-normal/arm64/SA_Dev-Swift.h -import-objc-header /Users/kekearif/Documents/MyApp/MyApp\ Dev/ios-app/MyApp/Obj-C-bridge.h -Xcc -working-directory/Users/kekearif/Documents/MyApp/MyApp\ Dev/ios-app

<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: compile command failed due to signal (use -v to see invocation)
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: compile command failed due to signal (use -v to see invocation)
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: compile command failed due to signal (use -v to see invocation)
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: compile command failed due to signal (use -v to see invocation)

The long path ends with:
SA_Dev-Swift.h -import-objc-header /Users/kekearif/Documents/MyApp/MyApp\ Dev/ios-app/MyApp/Obj-C-bridge.h -Xcc -working-directory/Users/kekearif/Documents/MyApp/MyApp\ Dev/ios-app
Is this likely to be an issue with either my Obj-C-bridge.h or pods?

A: This is a bug in the SWIFT compiler, which Apple has to fix. You should report it to Apple.
Until Apple has fixed the bug, you should try to isolate the piece that triggers the bug and then make some changes so the bug isn't triggered. Sometimes, changing the order of a few things or changing the white space is enough. Sometimes, you have to remove the triggering code and replace it with an alternative implementation.
And yes, the place to start is Obj-C-bridge.h. Remove everything there and then start to add things piece by piece until you have identified the triggering code or line.


text:
Q: Django: Accessing queryset in ModelMultipleChoiceField from template I'm creating a panel where a user can assign an assignment to other users. I'm attempting to build this with the ModelMultipleChoiceField and a form called AssignedUsersForm
forms.py
class AssignedUsersForm(ModelForm):
    class Meta:
        model = Assignment
        fields = ['users']

    custom_users = CustomUser.objects.all()
    users = forms.ModelMultipleChoiceField(queryset=custom_users, widget=forms.CheckboxSelectMultiple())

template
  <form method="post" id="assigned_users_form">
      {% csrf_token %}
      {{ assigned_users_form.errors }}
      {{ assigned_users_form.non_field_errors }}

          {{ assigned_users_form.content.errors }}
          {% for user in assigned_users_form.users %}

              {{ user }}

          {% endfor %}

        <input class="input-btn" type="submit" value="Save" name='submit_assigned_users_form'>

  </form>

I've successfully rendered each of the options for CheckboxSelectMultiple individually in my HTML.
Unfortunately, each iteration of 'user' renders CustomUser object (#) - the default name for the object.
From what I understand, the Checkbox widget does not pass the original queryset to the template. Thus, I'm unable to access the model attributes of each user and render information such as name, profile picture, etc.
Is there a method of accessing the actual object that's represented in the checklist, instead of the _ str _ value?
I've considered running a parallel iteration of queryset in the template, but I'm not sure if that's possible in Django.
I've also considered creating custom template tags to access each object based on the id in str, but that seems like overkill?
Is there a more intuitive method that I'm missing here?

A: I found a work around by creating a template_filter that takes the checkbox value and returns the corresponding object to the template.
template_tags.py
@register.filter(name='get_user')
def get_user(user_id):
    user = CustomUser.objects.get(pk=user_id.value)
    return user

template
 <form method="post" id="assigned_users_form">
      {% csrf_token %}
      {{ assigned_users_form.errors }}
      {{ assigned_users_form.non_field_errors }}

          {{ assigned_users_form.content.errors }}
          {% for user in assigned_users_form.users %}

              {% with customuser=user.data.value|get_user %}
              {{user.tag}} {{customuser.first_name }}
              {% endwith %}

          {% endfor %}

        <input class="input-btn" type="submit" value="Save" name='submit_assigned_users_form'>

  </form>

Essentially, this code looks at the checkbox widget iteration (user) and gets the value, passes that value to the template tag and then returns the associated object back to the page.
Not the best solution given that you're repeating the query search for each object, rather than gathering them all in one go. But this is the best I could come up with.


text:
Q: Update specific column within the same table and add limit - PostgreSQL I would like to update the value of a column within the same table by transforming its former value, but I would like to first test it with the first 10 data according to its created date.
I am getting this error though
ERROR:  syntax error at end of input
LINE 6: limit 10

Here is my sample code:
UPDATE posts p1
SET cooked = (select entity2char(strip_tags(p2.cooked))
FROM posts p2
WHERE p1.id = p2.id
ORDER BY p2.created_at ASC
LIMIT 10

Any syntax that would make this work?

A: Hmmm . . . I don't see why you are using a self-join.  If you just want to delete the top 10 entities, you can use:
UPDATE posts p
    SET cooked = entity2char(strip_tags(p.cooked))
    WHERE p.id IN (SELECT p2.id
                   FROM posts p2
                   ORDER BY p2.created_at ASC
                   LIMIT 10
                  );


text:
Q: Coding Competitions: How to store large numbers and find its all combination modulus P I have started doing competitive programming and most of the time i find that the input size of numbers is like
     1 <= n <=  10^(500).

So i understand that it would be like 500 digits which can not be stored on simple int memory. I know c and c++.
I think i should use an array. But then i get confused on how would i find
   if ( (nCr % P) == 0 )  //for all (0<=r<=n)//

I think that i would store it in an array and then find nCr. Which would require coding multiplication and division on digits but what about modulus.
Is there any other way?
Thanks.

A: I think you don't want to code the multiplication and division yourself, but use something like the GNU MP Bignum library http://gmplib.org/

A: Regarding large number libraries, I have used ttmath, which provides arbitrary length integers, floats, etc, and some really good operations, all with relatively little bulk.
However, if you are only trying to figure out what (n^e) mod m is, you can do this for very large values of e even without extremely large number calculation. Below is a function I added to my local ttmath lib to do just that:
/*!
        mod power this = (this ^ pow) % m
        binary algorithm (r-to-l)

        return values:
        0 - ok
        1 - carry
        2 - incorrect argument (0^0)
    */
    uint PowMod(UInt<value_size> pow, UInt<value_size> mod)
    {
        if(pow.IsZero() && IsZero())
        // we don't define zero^zero
        return 2;

        UInt<value_size> remainder;
        UInt<value_size> x = 1;

        uint c = 0;

        while (pow != 0)
        {
            remainder = (pow & 1 == 1);
            pow /= 2;
            if (remainder != 0)
            {
                c += x.Mul(*this);
                x = x % mod;
            }

            c += Mul(*this);
            *this = *this % mod;
        }

        *this = x;
        return (c==0)? 0 : 1;
    }

I don't believe you ever need to store a number larger than n^2 for this algorithm. It should be easy to modify such that it removes the ttmath related aspects, if you don't want to use those headers.
You can find the details of the mathematics online by looking up modular exponentiation, if you care about it.

A: If we have to calcuate nCr mod p(where p is a prime), we can calculate factorial mod p and then use modular inverse to find nCr mod p. If we have to find nCr mod m(where m is not prime), we can factorize m into primes and then use Chinese Remainder Theorem(CRT) to find nCr mod m.
#include<iostream>
using namespace std;
#include<vector>

/* This function calculates (a^b)%MOD */
long long pow(int a, int b, int MOD)
{
    long long x=1,y=a;
    while(b > 0)
    {
        if(b%2 == 1)
        {
            x=(x*y);
            if(x>MOD) x%=MOD;
        }
        y = (y*y);
        if(y>MOD) y%=MOD;
        b /= 2;
    }
    return x;
}

/*  Modular Multiplicative Inverse
    Using Euler's Theorem
    a^(phi(m)) = 1 (mod m)
    a^(-1) = a^(m-2) (mod m) */
long long InverseEuler(int n, int MOD)
{
    return pow(n,MOD-2,MOD);
}

long long C(int n, int r, int MOD)
{
    vector<long long> f(n + 1,1);
    for (int i=2; i<=n;i++)
        f[i]= (f[i-1]*i) % MOD;
    return (f[n]*((InverseEuler(f[r], MOD) * InverseEuler(f[n-r], MOD)) % MOD)) % MOD;
}

int main()
{
    int n,r,p;
    while (~scanf("%d%d%d",&n,&r,&p))
    {
        printf("%lld\n",C(n,r,p));
    }
}

Here, I've used long long int to stote the number.

A: In many. many cases in these coding competitions, the idea is that you don't actually calculate these big numbers, but figure out how to answer the question without calculating it. For example:
What are the last ten digits of 1,000,000! (factorial)?

It's a number with over five million digits. However, I can answer that question without a computer, not even using pen and paper. Or take the question: What is (2014^2014) modulo 153? Here's a simple way to calculate this in C:
int modulo = 1;
for (int i = 0; i < 2014; ++i) modulo = (modulo * 2014) % 153;

Again, you avoided doing a calculation with a 6,000 digit number. (You can actually do this considerably faster, but I'm not trying to enter a competition).


text:
Q: Shortcuts do not work on android studio I recently installed android studio after long time using eclipse
I have properly configured the ide and it works, but I have a problem with keyboard shortcuts.
I have setup shortcuts that comes by default and, for example, want to collapse or expand all code, this is the shortcut:

However, using that shortcut creates a comment in my code.
/ ** /

I looking setup, see the shortcut is correct:

This happens to me most keyboard shortcuts, tried different ways but do not know how to work properly.
I appreciate any help.
Thanks!


text:
Q: how to add a new field on description page Hello everyone i am using Magento 2.x.x , and i want to add a new field to product description "Date to ship" to let the customer chose a specific date like the quantity, and also i want to display that value with his equivalent row on admin sales grid can anyone help me to do this please i am new on Magento ?

A: In order to have the info on admin sales grid it must be set on the order. You must add an extra checkout field.
Please check the following question as it will surelly suit your case:
How to Add Custom fields to Checkout page in Magento2

A: You may create a UI component just like you would in the case of adding custom fields for any page.
For reference have a look at this: https://www.mageplaza.com/devdocs/how-to-add-custom-fields-in-product-edit-pages-in-magento-2.html

A: You can add block file catalog_product_view.xml
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product.info.main">
            <block class="Module\Name\Block\Catalog\ProductView" name="product.info.custom_block" template="Module_Name::custom_block.phtml" after="product.info.price"/>
        </referenceBlock>
    </body>
</page>

Block file
<?php
namespace Module\Name\Block\Catalog\Product;
use Magento\Catalog\Block\Product\AbstractProduct;
class View extends AbstractProduct
{

}

custom_block.phtml
Dat to ship


text:
Q: How to signal between process/containers in cpp in efficient way? Background:
We have a clock process which needs to signal other non child processes[cpp code] on each clock tick. Each of the process lives in its on container (containerd).
Besides doing brute force of scanning a shared memory on a change(which is very bad in terms of computing resource). Any other effective ways for a near real-time system to send a signal for other processes?
Desired behavior:

*

*Make all process to sleep for a time x or until they received a tick single from the main clock

*The latency of each process should be small, less than a milisecond.

Questions:
Is it possible to wait_event_interruptible_timeout in the userspace. Will it help for the scenario above? Any other solution ?


text:
Q: cannot run thinkorswim behind corporate firewall: "unable to find valid certification path to requested target" In windows, when I install and run thinkorswim inside company network (with its own self-signed ssl cert), it cannot connect via https to tdameritrade's server.  How do I update tos's java runtime with the self-signed cert?

A: open command prompt in windows and run the following command to install company's cacert into thinkorswim's jre:
cd C:\<thinkorswim-install-dir>\jre\bin\
keytool.exe -import -trustcacerts -noprompt -storepass changeit -alias mycertificate -keystore ..\lib\security\cacerts -file c:\mycert.cer

For MacOS
cd /Applications/thinkorswim/.install4j/jre.bundle/Contents/Home/jre/bin
./keytool -import -trustcacerts -noprompt -storepass changeit -alias mycertificate -keystore ../lib/security/cacerts -file /path/to/mycert.cer


text:
Q: Does PHP's FILTER_VALIDATE_EMAIL provide adequate security? I have a page where I want to accept an email address in the GET parameters. If I use FILTER_VALIDATE_EMAIL, am I still vulnerable to xss and javascript injection attacks, and the like?
I'm not asking if it's a good, or good enough, validator of email addresses. I want to know if one can still inject bad web code through arbitrary strings passed through it -- do I need to do additional filtering to prevent that?

A: Yes, a valid email address can easily be used as the container for some carefully crafted strings that can be used to attack you.
Get out of the "filtering" mindset and get into the "escaping" mindset. A universal "make it safe" filter simply doesn't exist. It cannot exist, because all escaping must be done in a context-specific manner.
For example, if the email address will be output to a plain text document, then nothing is needed to be done. If it's being output into an html document, as a text node, then it needs to be escaped for an html context, so escape html special characters and entities. If it's being put into an html document, and it's value will be inside of an html attribute, then very very careful escaping would need to be performed, and it would depend on which html attribute. If it's being used in an sql query, then it needs to be escaped via a database specific escaping function, and even then you must escape differently if you're using it as a parameter value (i.e., where someColumn = '$paramVal'), vs a symbol name like a table name, a column name (i.e., order by $myEscapedColumnName DESC). and so on.
It's all about context of use, not content of the string. This goes for everything (not just emails or other user input), and it's not just a matter of security, but it's a matter of programming and syntax correctness. Proper escaping is complicated, and takes a lot of time to learn, and careful thought and consideration when you code. Many coders don't bother doing it due to the effort, and they are the ones who cause the company to get hacked.
fyi, the email address spec allows quoted strings, so something you could inject strings like "<script>alert('xss')</script>"@example.com. The possibilities are obvious.

A: That should be good enough, but naturally you should still escape it when entering it into a database, etc. You never know what kind of bug may exist in PHP or Apache, etc, that may allow an attack to happen anyway.


text:
Q: PHP display random n images from directory I want to display random n number of images from a folder. Currently i am using this script to display images
<?php
$dir = './images/gallery/';
foreach(glob($dir.'*.jpg') as $file) { ?>

<img src="<?php=$file;?>">

<?php } ?>

I want only 10 (or n number) images, that too randomly. How to do this?

A: The shuffle() method will put the elements of a given array in a random order:
<?php
$dir = './images/gallery/';

function displayImgs($dir, $n=10){
$files = glob($dir.'*.jpg');
shuffle($files);
$files = array_slice($files, 0, $n);
foreach($files as $file) { ?>

<img src="<?php=$file;?>">

<?php }
} ?>

Usage:
displayImgs("/dir/temp/path", 20);

A: Well, this might be overkill, but you can also use a directory iterator and some randomness to achieve this. I used a modified version of the random numbers generation function from this answer.
make sure that the path you give to the function is relative to the directory in which the script resides, with a slash at the beginning. The __DIR__ constants will not change would you happen to call this script from different places in your file hierarchy.
<?php

function randomImages($path,$n) {

    $dir = new DirectoryIterator(__DIR__. $path);

    // we need to know how many images we can range on
    // but we do not want the two special files . and ..
    $count = iterator_count($dir) - 2;

    // slightly modified function to create an array containing n random position
    // within our range
    $positionsArray = UniqueRandomNumbersWithinRange(0,$count-1,$n);

    $i = 0;
    foreach ($dir as $file) {

        // those super files seldom make good images
        if ($file->getFilename() === '.' || $file->getFilename() === '..') continue;

        if (isset($positionsArray[$i])) echo '
getPathname().'">
';

        $i++;
        // change the count after the check of the filename,
        // because otherwise you might overflow
    }
}

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_flip(array_slice($numbers, 0, $quantity));
}

A: Let us first create a array and push some random numbers into it. And as per you let $n be 10.
$n = 10;
$arr = array();
for($i = 1; $i <= $n; $i++){
    /* Where $n is the limit */
    $rand = rand($n);
    array_push($arr, $rand);
}

So now we have an array containing the random digits and now we have to echo out the images by iterating over the array:
foreach($arr as $image){
    $intToStr = (string) $image;
    foreach(glob($dir. $intToStr . '.jpg') as $file){
        echo "
$file
";
    }
}

This would echo out your images.


text:
Q: The setenv command is not found when trying to run a shell script. How do I fix this? I have a problem with a shell script, which looks like:
#!/bin/csh -f
setenv Test

The problem is that it worked until I installed Ubuntu 12.04.
The respond tells me that the command setenv is not found.
My idea is that the bash does not change to the csh but how can I fix it?

A: This happens because the line
#!/bin/csh -f

is not the very first line in your script file. If it is the first line, then please post the exact error message that is being printed in terminal when you execute the script.
Please verify also that csh/tcsh is actually installed. You can do this by typing the following into terminal:
dpkg -l | grep csh

If this command produces no output at all, then you can install tcsh by entering following command:
sudo apt-get install tcsh


text:
Q: React: Fetched data, but no access to object properties I successfully fetched data from an API call, in console I see the result, but I can't access object properties or display them.
interface Data {
    data: []
    isLoading: boolean
}
function About() {

    const  [ dataUser, setDataUser ] = useState<Data>({data: [], isLoading: false})

    useEffect(() => {
        setDataUser({data: [], isLoading: true})

        fetch('https://jsonplaceholder.typicode.com/users')
        .then(response => {
            if (!response.ok) {
                throw new Error("Failed with HTTP code " + response.status);
            }
            return response;
        })
        .then(response => response.json())
        .then(data => setDataUser( {data: data, isLoading: false} ))
        .catch((err) => {console.log(err)})
    }, [])

    const user = dataUser.data.map(item => {
        console.log(item)        //works
        console.log(item.id)     //doesn't work (error: "Property 'id' does not exist on type 'never'.")
        return (
{item.name}
)   //another error ("Objects are not valid as a React child...")
    })

    return (

            {user}

    )
}

export default About

EDIT
console.log(dataUser.data) ->

I added code for checking if response was ok and everything is fine with that.
console.log(item) ->

A: Your issue is your interface.  I hadn't realized this was a compile-time error, not a run-time error.
interface Data {
    data: any[],
    isLoading: boolean,
}

The issue is that you're defining Data.data to be an empty array, and the elements of an empty array are of type never.  That means that item in your map() callback is of type never, and never has no properties.
You probably want Data.data to be something other than any[] so that item has strongly-typed values, but this should unblock you.


text:
Q: Rails: How to cache a field of a has_many relationship in an array Here is what I'm doing right now:
m = Merchant.find(1)
ebay_item_id_array = []
active_items = m.active_items
active_items.each { |item|
  # Fill the array containing what items are already in the DB based on ebay item id
  ebay_item_id_array.push(item.external_product_id)
}

The goal here is so that when I ping eBay's API for the latest products, I can check if I already have that ebay item id in my database. Thus, it would be skipped. The problem is that when the DB gets big, this operation above is not very efficient. How can I cache the external_product_field into an array that I can bring up without looping across all my active records?

A: You should consider polling the eBay API for products added after the last update of your database that would be less computationally expensive. You can do this by using itemFilters
See the documentation for more info:
http://developer.ebay.com/DevZone/finding/CallRef/findItemsByKeywords.html#Request.aspectFilter


text:
Q: Reading a SQL variable from a Visual Studio project I have a third party database created by someone else for use in a third party application that is limited in its customisability (using Microsoft SQL Server) so I am trying to create a small Visual Basic application to update a single value, using a button click.
I have found how to update the value, but now I am trying to display the value on my form, but I'm not succeeding.
This is my code so far:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using sqlcon = New SqlConnection("Data Source=(localdb)\xxx;Initial Catalog=IpposnifDB240;Integrated Security=True")
            sqlcon.Open()
            Dim sqltext = "UPDATE newcount SET Count = Count + 1"
            Dim cmd = New SqlCommand(sqltext, sqlcon)
            cmd.ExecuteNonQuery()
            cmd = New SqlCommand("SELECT Count from newcount", sqlcon)
            Label1.Text = cmd.ExecuteReader(1)
        End Using

    End Sub

I expect you can guess that the ExecuteReader does not return the string that I am looking for, how do I obtain a string from my SQL query?

A: It sounds like you want ExecuteScalar() instead.  https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=dotnet-plat-ext-3.1
Modify your code like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using sqlcon = New SqlConnection("Data Source=(localdb)\xxx;Initial Catalog=IpposnifDB240;Integrated Security=True")
        sqlcon.Open()
        Dim sqltext = "UPDATE newcount SET [Count] = [Count] + 1"
        Dim cmd = New SqlCommand(sqltext, sqlcon)
        cmd.ExecuteNonQuery()
        cmd = New SqlCommand("SELECT [Count] from newcount", sqlcon)
        Label1.Text = cmd.ExecuteScalar().ToString()
    End Using

End Sub

Also btw, Count is a reserved word and might give you problems if you don't escape it with square brackets (see above).


text:
Q: Device file vanishes after a reboot When I connected a USB modem to my machine, it complained that /dev/sr1 does not exist. So, after a bit of Googling, I used the following commands to create this device.
ls -l /dev/sr*
brw-rw----+ 1 root cdrom 11, 0 Aug 16 08:05 /dev/sr0

sudo mknod /dev/sr1 b 11 0
sudo chown -v :cdrom /dev/sr1
sudo chmod -v g+w /dev/sr1
ls -l /dev/sr*
brw-rw----+ 1 root cdrom 11, 0 Aug 16 08:05 /dev/sr0
brw-rw-r--+ 1 root cdrom 11, 0 Aug 16 08:10 /dev/sr1

Then my modem worked without any problem. However, after a reboot, I find that the device has vanished, and I have to create the device again.
Please tell me,

*

*Why such a strange thing like a device vanishing is happening?

*How do I get rid of the situation?

I am using Ubuntu 15.04.
(As I am going to hit the Post button, I notice that creation date-time of /dev/sr0 coincides with the boot time this morning.
Are the devices being created at boot time?
Looks like the answer is, yes, indeed,
ls -l /dev/
total 0
lrwxrwxrwx  1 root root           7 Aug 16 08:14 atttyUSB1 -> ttyUSB1
crw-------  1 root root     10, 235 Aug 16 08:05 autofs
drwxr-xr-x  2 root root         640 Aug 16 08:14 block
drwxr-xr-x  2 root root         120 Aug 16 08:14 bsg
crw-------  1 root root     10, 234 Aug 16 08:05 btrfs-control
drwxr-xr-x  3 root root          60 Aug 16  2015 bus
lrwxrwxrwx  1 root root           3 Aug 16 08:14 cdrom -> sr0
lrwxrwxrwx  1 root root           3 Aug 16 08:14 cdrw -> sr0
drwxr-xr-x  2 root root        4300 Aug 16 08:14 char
crw-------  1 root root      5,   1 Aug 16 08:06 console
lrwxrwxrwx  1 root root          11 Aug 16  2015 core -> /proc/kc

<snipped>

So, if I ask, which list do I update to cause  /dev/sr1 created at boot time?, can we move in the right direction?
)

A:
Are the devices being created at boot time?

Yes.

So, if I ask, which list do I update to cause /dev/sr1 created at boot time?

makedev
DESCRIPTION

   MAKEDEV is a script that will  create  the  devices  in  /dev  used  to
   interface with drivers in the kernel.

   Note  that  programs  giving  the  error  ``ENOENT:  No  such  file  or
   directory'' normally means that the device  file  is  missing,  whereas
   ``ENODEV:  No such device'' normally means the kernel does not have the
   driver configured or loaded.

Regarding your sr1:
CDROM DEVICES

   sr or scd or scd-all
          Creates scd{0..16} SCSI CD players and  sr{0..16}  symlinks  for
          these  devices.   cdrom is a symlink which can be created by the
          user to the active CD device.  It is not created by MAKEDEV.


text:
Q: Edit / add comment to question submitted while not logged in I posted a question from another deve's computer so I did not login to SO.  Now I need to edit and\or comment on an answer.
Is there a way to do this?
emp

A: As long ask you have 50 rep, you don't need to be the question author to comment. Being the question author doesn't give you any special ability to edit answers, either (you still need 2k rep).
You ought to have the accounts merged so that you can accept  a correct answer when you receive one, however. Email team@stackoverflow.com and ask them to merge your account with your anonymous account. Note that you might have to edit your profile on the other dev's computer to prove that the other account is yours.


text:
Q: What Software to Use for Tagging/Annotating/Commenting/Highlighting Video Footage? My Question in a Nutshell
I'm looking for a tool with which I can easily organize/manage the video footage I have recorded. I don't want to only tag the video clip files themselves, though; I would rather like to add notes to different positions in the videos so that I can more easily find the highlights of my shots later.
I'm not looking for solutions which change the videos themselves. It's really just about adding metadata on the frame level.
What I have Found
As far as I can see, most existing media management tools only allow to tag on the file level but for videos it would be very helpful to add tags/markers on the timeline (or frame level) of each video.
The only tool that I have found which comes close to what I'm looking for is Advene – suggested in this AskUbuntu answer. Unfortunately, I couldn't get Advene to display any of my videos.
With Blender I could somehow do what I need, however, it'd be overkill and cumbersome to use for this task.
What I have in Mind as the Ideal Solution
The ideal tool would be a GUI program like Totem or VLC in which I can easily add notes to the video which is currently being played. A note would either be tied to a single timecode or to a span between two timecodes. Adding a note would be done with a keyboard shortcut which automatically pauses the video and then provides a text field in which a comment can be added.
The tool would store the notes in a text-based format in a somewhat configurable way. That way, notes could easily be searched later across files with the help of existing tools like grep.
Since I'm using Ubuntu 14.04 LTS, I would somehow want to be able to run the tool there.
Less ideal but still useful: a tool as described above which can only add highlight markers at certain timecodes (i.e., without text notes).

A: Best Solution: Totem
In Totem you can create custom chapters. By choosing "Chapters" from the "View", you get a sidebar for working with chapters:

By clicking the "Add New Chapters" button in the sidebar and then using the buttons at the bottom of the sidebar, chapter markers can be added, deleted and saved:

Saving creates a new file with the same name as the video file (but with a different suffix) right next to the video file. The new file is in the XML-based Continuous Media Markup Language (CMML) format, i.e., it can be easily searched with for example grep.
Since the CMML format is open, such chapter files can also be created by other tools and loaded into Totem. This might become handy, for example, when extracting HiLight tags from GoPro cameras and converting them to CMML for viewing in Totem.
Honorable Mention: VLC
VLC has a "Custom Bookmarks" item in the "Playback" menu that can be used for marking positions in videos. These boomarks can be saved into a playlist from where they can also be loaded again.
Unfortunately the feature seems to have been partly broken for a while now.


text:
Q: SELECT lastest row based on recent ID filter by certain criteria I have tried a few ways to get the distinct results based on recent id. But still cannot get the correct/valid result because of there are still other criteria to be taken care which I do not know how to get it done.
I tried with a few methods but somehow the group by method will ruin the valid data due to I also need to take care of the uid.
**With this method I failed to get the correct and valid data from my record.**
select *
from record
WHERE id in (SELECT max(id) FROM record GROUP BY vip_id)

TABLE:RECORD
id  company   vip_id    uid   status
1    a        1000      888    pass
2    b        1000      888    pass
3    c        1000      888    pass
4    d        2000      888    pass
5    e        2000      888    fail
6    b        2000      777    pass

Expected RESULT
id  company   vip_id    uid   status
3    c        1000      888    pass
5    e        2000      888    fail

Final Outcome
uid count(pass)
888     1

A: Try this:
SELECT * FROM RECORD WHERE id IN (
  SELECT max(id) FROM RECORD WHERE uid = 888 GROUP BY vip_id
);

The output is:
| id | company | vip_id | uid | status |
|----|---------|--------|-----|--------|
|  3 |       c |   1000 | 888 |   pass |
|  5 |       e |   2000 | 888 |   fail |

View the attached fiddle.


text:
Q: Can (or should) I use ActionLink() in controller I need to add error message to ModelState like below:
ModelState.AddModelError(string.Empty, string.Format("An account with the mobile or email you have specified already exists. If you have forgotten your password, please {0} it.", Html.ActionLink("Reset", "Reset", "Account")));

First of all how to do this? and btw, is doing this way appropriate in MVC pattern?
Or should I add a key to ModelState and let the view pick it up and generate the error message?

A: The view should do stuff like that IMO, you set your model to reflect what happened and let your view make the decision about how to present the UI. After all you may decide to change how the link is displayed and you don't really want to change your controller when it's just a UI change.


text:
Q: how to correctly pass data structures between custom llvm passes I have a Function pass, called firstPass, which does some analysis and populates:
A a;

where
typedef std::map< std::string, B* > A;
class firstPass : public FunctionPass {
   A a;
}

typedef std::vector< C* > D;
class B {
   D d;
}

class C {
   // some class packing information about basic blocks;
}

Hence I have a map of vectors traversed by std::string.
I wrote associated destructors for these classes. This pass works successfully on its own.
I have another Function pass, called secondPass, needing this structure of type A to make some transformations. I used
bool secondPass::doInitialization(Module &M) {
  errs() << "now running secondPass\n";
  a = getAnalysis<firstPass>().getA();
  return false;
}

void secondPass::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.addRequired<firstPass>();
  AU.setPreservesAll();
}

The whole code compiles fine, but I get a segmentation fault when printing this structure at the end of my first pass only if I call my second pass (since B* is null).
To be clear:
opt -load ./libCustomLLVMPasses.so -passA < someCode.bc

prints in doFinalization() and exits successfully
opt -load ./libCustomLLVMPasses.so -passA -passB < someCode.bc

gives a segmentation fault.
How should I wrap this data structure and pass it to the second pass without issues? I tried std::unique_ptr instead of raw ones but I couldn't make it work. I'm not sure if this is the correct approach anyway, so any help will be appreciated.
EDIT:
I solved the problem of seg. fault. It was basically me calling getAnalysis in doInitialization(). I wrote a ModulePass to combine my firstPass and secondPass whose runOnModule is shown below.
bool MPass::runOnModule(Module &M) {
  for(Function& F : M) {
    errs() << "F: " << F.getName() << "\n";
    if(!F.getName().equals("main") && !F.isDeclaration())
      getAnalysis<firstPass>(F);
  }

  StringRef main = StringRef("main");
  A& a = getAnalysis<firstPass>(*(M.getFunction(main))).getA();

  return false;
 }

This also gave me to control the order of the functions processed.
Now I can get the output of a pass but cannot use it as an input to another pass. I think this shows that the passes in llvm are self-contained.

A: I'm not going to comment on the quality of the data structures based on their C++ merit (it's hard to comment on that just by this minimal example).
Moreover, I wouldn't use the doInitialization method, if the actual initialization is that simple, but this is a side comment too. (The doc does not mention anything explicitly about it, but if it is ran once per Module while the runOn method is ran on every Function of that module, it might be an issue).
I suspect that the main issue seems to stem from the fact A a in your firstPass is bound to the lifetime of the pass object, which is over once the pass is done. The simplest change would be to allocate that object on the heap (e.g. new) and return a pointer to it when calling getAnalysis<firstPass>().getA();.
Please note that using this approach might require manual cleanup if you decide to use a raw pointer.


text:
Q: Can I place my script in /usr/bin? I wrote a small bash script for starting, stopping and restarting my java applications and I want to make it available to all users so they could run it.
Should I just place it in /usr/bin to do that? Is it the right place for my scripts? Isn't that for like installed package script and stuff only?

A: I would recommend putting it in /opt. You can create directory with your application name under /opt and then bin directory under it, so your path will look like that:
/opt/<your_app_name>/bin

Then you create two scripts in /etc/profile.d - <your_app_name>.sh and <your_app_name>.csh and in those scripts you add the path above to global $PATH variable to make executables of your app available to all users. That's all.
I think that this approach is cleaner then putting it in /usr/local/bin since all your changes to the system are localized to a single directory (with exception of two scripts in /etc/profile.d), it is easy to remove your app manually and your files do not mix with files of other applications (which may be the case with /usr/local). This approach is also compliant with "Filesystem Hierarchy Standard".

A: Correct, [/usr]/[s]bin is for the distro creator's use. Local user scripts belong under /usr/local, specifically /usr/local/bin in this case.
Filesystem Hierarchy Standard

A: There is certainly nothing preventing you from placing a script in /usr/bin, giving it world-execute permissions (something like chmod 755) and allowing users to run it.  If you want to conform with "The UNIX way" there are more appropriate locations.  I'm sure I'll start a trail of comments on why this is wrong, but I'd learn towards storing it in /usr/local/bin/ instead.  The /usr/local directory is typically for software not managed by the distribution directly, such as third party applications or scripts.


text:
Q: Input radio checking I'm trying to set the Input called iva displayed only when #azienda is selected but i don't understand why the code just doesn't set the display to block
This is the code:

        <input type="radio" id="azienda" name="radio" value="Azienda/Impresa/Società">
         Azienda/Impresa/Società

 <input type="number" class="iva" name="iva" id="iva" placeholder="Inserire P.IVA...">

I'll give an hug at everyone who will help me please

A: You swiched from class to id with iva :)

        <input type="radio" id="azienda" name="radio" value="Azienda/Impresa/Società">
         Azienda/Impresa/Società
 <input type="number" class="iva" name="iva" id="iva" placeholder="Inserire P.IVA...">


text:
Q: Mac hangs after Snow Leopard installation I have a white 2007 MacBook, 2.16 GHz, 3GB RAM.
 It was happily running OS X.6.1 for a while but a friend borrowed it and left a lot of rubbish on it, so thought I'd reinstall Snow Leopard and then up to Lion again. Tried OS X.5.1, X.6, & X.6.3, all Apple original DVDs.
After they say "Installed successfully", when I must input info: name, address, postcode, phone No., where will the computer be used?, job description etc.  click is held continuously  and I get the spinning ball and the machine hangs. Any ideas?


text:
Q: Are there workarounds to System.Zip which allow progress to be displayed? I am attempting to use Delphi's built in System.Zip tool for compression. However, many of the situations with which I would use compression have significant number and sizes of files. Is there a way to hook into System.Zip to obtain and display progress?

A: The built in library exposes no mechanism for progress callbacks. There are no opportunities for you to hook into the compression (or decompression) process. Without modifying the built in library, you have no opportunity to receive progress.
So, modifying the built in library is one option, but probably not the best. The most attractive option, in my view, would be to use a library that did support compression. I think that tpAbbrevia is the most full featured Delphi compression library.


text:
Q: Apply Js to show or hide elements I'm trying to show a select option and then show a input to filter
here's my js code
function showSearch(id) {
    if (id == "statusSearch") {
          $("#statusSearch").show();
          $("#monthSearch").hide();
          $("#employeeSearch").hide();
    }
}

But it doesn't work, it doesn't show anything. Only my first select option
       <select id="status" name="status" onChange="showSearch(this.value);">
            <option selected disabled>Select</option>
            <option name="statusSearch">Estado de OT</option>
            <option name="monthSearch">Mes</option>
            <option name="employeeSearch">Empleado</option>
        </select>
        <button type="submit">Ver todo</button>

Example, if I choose "statusSearch"

Estado de OT

        <select type="text" name="searchByStatus">
                <option selected disabled>Elegir</option>
                <option name="open">Abierta</option>
                <option name="closed">Cerrada</option>
        </select>

And it's my view
$req3=$request;

if($req3) {
            $query = trim($req3->get('statusSearch'));
            $search = MaintenanceTasks::select('Employee_Id_created','Task_Id','Machine_Id',
            'Request_date')//etc
            ->get();
        }

Well, I don't know what I'm doing wrong

A: use value="statusSearch" than name="statusSearch" on your options
example :
<option selected disabled>Select</option>
<option value="statusSearch">Estado de OT</option>
<option value="monthSearch">Mes</option>
<option value="employeeSearch">Empleado</option>

like here https://codepen.io/JUSEN/pen/dyOperB?editors=1010

A: Your selector is not correct:
function showSearch(id) {
   $( "#statusSearch option" ).each(function( index ) {

    if (id == "statusSearch") {
          $("#statusSearch option).each(function(  ) {
            if($this).attr('name') == "statusSearch"){
               $(this).show();

            }else if($this).attr('name') == "monthSearch"){
               $(this).hide();

            }else if {
              //and so on
             :
         });//end each


text:
Q: Method is not compatible with method intelephense(1038) VSCode doesn't accept a child and parent method with the same name but they have the same purpose.
The book I use doesn't use different name for this exercise and I don't understand why it doesn't work with me.
I found a solution by giving a different name to the child method but it doesn't help me to understand the problem.
Index.php
function monAutoLoad($class) {
    include(str_replace("\\", "/", $class). ".php");
}

spl_autoload_register('monAutoLoad');

use MesProduits\Produit;
$ordinateur = new Produit("ordinateur",10,1200,false);
echo $ordinateur . "
";
echo $ordinateur->supprimerProduit(5) . "
";

use MesProduits\ProduitParLots;
$cartouchesEncre=new ProduitParLots("Cartouches d'encre",3,50,false);
$cartouchesEncre->setNbArticlesParLot(10);
$cartouchesEncre->ajouterProduit(6);
echo $cartouchesEncre . "
";

Produit.php (parent class file)
namespace MesProduits; //donner le même nom que le dossier parent

class Produit{
    protected $nom = "mon produit";
    protected $quantite = 10;
    protected $prix = 120;
    protected $rupture = false;

    function __construct($nom,$quantite,$prix,$rupture)
    {
       $this->nom=$nom;
       $this->quantite=$quantite;
       $this->prix=$prix;
       $this->$rupture=$rupture;
    }

    function __toString(){
        return "nom: " . $this->nom . "
".
                "quantité: " . $this->quantite . "
".
                "prix: " . $this->prix . "
".
                (($this->rupture)? "no stock
" : "in stock
");
    }

    function ajouterProduit($quantite){ //parent method and I want the same name in the child file
        $this->quantite+=$quantite;
        if($this->quantite >=0){
            $this->rupture = false;
        }
        return "a product has been add
" .
                "there is: " . $this->quantite . " in stock
";
    }

    function supprimerProduit($quantite){
        $this->quantite-=$quantite;
        if($this->quantite <=0){
            $this->rupture = true;
        }
        return "a product has been removed
" .
                "there is " . $this->quantite . " in stock
";
    }
}

ProduitParLots.php (child file class)
namespace MesProduits;

class ProduitParLots extends Produit{
    private $nbArticlesParLot;

    function getNbArticlesParLot(){
        return $this->nbArticlesParLot;
    }

    function setNbArticlesParLot($valeur){
        if(!is_integer($valeur)){
            echo "the property must be an integer
";
        }else{
            $this->nbArticlesParLot=$valeur;
        }
    }

    function ajouterProduit2(){ //need to choose a different name for the child method
        $this->quantite+=$this->nbArticlesParLot;
        if($this->quantite>0) $this->rupture=false;
    }
}

A: This is because the "child" method has not the same signature as the parent method. You missed the $quantite parameter.
class ProduitParLots extends Produit
{
    function ajouterProduit($quantite) { /* ... */ }
}


text:
Q: Ideal Length of a java method I am working on a functionality and have confuded about the length of the method.There are certain points are read but not sure what is best or a standard

*

*A method should be as long as required to perform the task for which it is designed.

*can read the whole method without the need for scrolling and it fits onto the page.

There are others points also.
I have a static helper method and whose lengths is getting increased, so i have the option of either to create more static helper methods and distribute the tasks to those methods but than it seems like i am creating unnecessary static methods.
Other approach is to create another helper class and delegate some work to methods defined in the helper class
I am not sure what is best way/standard way to do this.

A: In general, both of those points are very good things to consider. One of the main reasons you already mentioned:  It makes the code more readable and easier to digest.
The other benefit from splitting up your methods and creating helper methods is one that won't manifest itself immediately. Instead, one day you'll be working on a system where you have users who are Customers, and you'll need to implement a feature where you'll need to create admin users, or Vendors, or some other abstract version of a person.
You'll find yourself thinking about how you're going to save the vendor's orders, or the vendor's whatever, to the database and you'll need to generate some form of something or other that is used to identify the order, and you'll realize that the code you wrote to do this same action for the customer will work with a Vendor object just as well as a Customer object.
However, if all of that code was strong together in the same method that handles everything related to Customers, you'd be using what we call cut and paste reusability. Which involves going through your previously-written code and cutting and pasting relevant parts and creating a copy that is mostly similar but with very subtle differences. (Note: This is generally considered a bad practice.)
But when you write small, concise methods that do one thing only and one thing really well, you find that you're able to take those building blocks you've already built and then use them to build other things, saving you time, saving QA time, and in general lowering the maintenance costs of the project, allowing the product to move forward, and allowing you to move forward and do cooler stuff.
However, one last point to consider is that it is possible to overdo it, or over-architect. There is a fine line between too long and too short, and you may be tempted to split your methods up too much. If you get to the point where splitting up your methods makes it too hard to work with, then consider that you may be taking it a little too far. Good luck!


text:
Q: why does "pkg_info -Q bash" on OpenBSD give me an "empty" result? i installed a fresh OpenBSD server on a Linux - Proxmox server with kvm.
I tried to to install bash but pkg_info returns "empty":
root@openbsd:~# echo $PKG_PATH
https://cdn.openbsd.org/pub/OpenBSD

root@openbsd:~# ping -c 1 cdn.openbsd.org
ping: Warning: dualstack.osff.map.fastly.net has multiple addresses; using
151.101.2.217
PING dualstack.osff.map.fastly.net (151.101.2.217): 56 data bytes
64 bytes from 151.101.2.217: icmp_seq=0 ttl=60 time=5.810 ms

--- dualstack.osff.map.fastly.net ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/std-dev = 5.810/5.810/5.810/0.000 ms

root@openbsd:~# pkg_info -v -Q bash
PKG_PATH=https://cdn.openbsd.org/pub/OpenBSD
https://cdn.openbsd.org/pub/OpenBSD/: empty
root@openbsd:~#

DNS / reverse DNS is good.
how can i debug this?

A: The PKG_PATH variable is not set to the correct value.
In modern OpenBSD versions, you no longer need to specify a PKG_PATH, but if you want to, you need to include the full path to the packages, something like:
https://cdn.openbsd.org/pub/OpenBSD/7.0/packages/amd64/


text:
Q: Read in scientific notation with numpy loadtxt I have a datafile containing 3 columns with floats in scientific notation,
20346.7353    0.139945D+04    0.922215D+03
20347.0689    0.139958D+04    0.922340D+03
20347.4024    0.139970D+04    0.922464D+03
20347.7360    0.139983D+04    0.922589D+03
...           ...             ...

, which I want to read using a python script in order to plot the data with pyplot. However the numpy loadtxt command
x, y1, y2 = np.loadtxt(sys.argv[1], unpack=True, dtype=float, usecols=(0, 1, 2))
does not recognise the floats due to the scientific notation. How could I read in this file (with approximately 30000 lines)?
Thank you

A: The python scientific notation uses E, not D. So you can replace them before reading the data:
# reading from string here, read from file in your case
data = '''20346.7353    0.139945D+04    0.922215D+03
20347.0689    0.139958D+04    0.922340D+03
20347.4024    0.139970D+04    0.922464D+03
20347.7360    0.139983D+04    0.922589D+03'''

import io

np.loadtxt(io.StringIO(data.replace('D', 'E')))

output:
array([[20346.7353,  1399.45  ,   922.215 ],
       [20347.0689,  1399.58  ,   922.34  ],
       [20347.4024,  1399.7   ,   922.464 ],
       [20347.736 ,  1399.83  ,   922.589 ]])


text:
Q: Sustainsys Saml2 start authentication for ASP.NET Web Forms Example I found the information below to start auth for web forms from Anders Abel. I can't find any actual example code anywhere on how to use the HttpModule to start the auth redirect. Can someone provide some please? I have multiple idps, so I would need a way to specify one.

You should use the HttpModule with Web forms. To start authentication
redirect the user to /Saml2/SignIn.
Or protect the entire application with automatic redirection by
settings in web.config:
Authentication mode Forms with a login url of /Saml2/SignIn Set
Authorization rules in web.config to disallow anonymous access to all
pages.

A: You can download the code from github...
https://github.com/Sustainsys/Saml2
and still there but you need to go back a little bit in time to commit
62552e250cccd8a7663d9ce29b3239eae51ce498
to get the example


text:
Q: add remeber me to Symfony 4.2 Security with custom User Entity I'm working with Symfony 4.2,
I'm working with Security Component and I'm trying to add remember me.
At first Remember Me worked for me, but when my User Entity Became Customized, the remember me doesn't work anymore,
My Custom User:
I'm connected to a wordpress DB that I can't do any change on it ( I must Read Only ),
And I need to add some field to the User, So I have to create a new table User OneToOne with WpUsers (wordpress Users),
So, I use doctrine to create entity from the existing DB, I didn't touch to those entities, I just create my User Entity just to add roles field to the User System:
Wordpress pass is hashed with phpass.
Entity\WpUsers (generated by doctrine):
/**
 * WpUsers
 *
 * @ORM\Table(name="wp_users", indexes={@ORM\Index(name="user_nicename", columns={"user_nicename"}), @ORM\Index(name="user_login_key", columns={"user_login"}), @ORM\Index(name="user_email", columns={"user_email"})})
 * @ORM\Entity(repositoryClass="App\Repository\WpUsersRepository")
 */
class WpUsers
{
    /**
     * @var int
     *
     * @ORM\Column(name="ID", type="bigint", nullable=false, options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="user_login", type="string", length=60, nullable=false)
     */
    private $userLogin = '';

    /**
     * @var string
     *
     * @ORM\Column(name="user_pass", type="string", length=255, nullable=false)
     */
    private $userPass = '';

    /**
     * @var string
     *
     * @ORM\Column(name="user_nicename", type="string", length=50, nullable=false)
     */
    private $userNicename = '';

    /**
     * @var string
     *
     * @ORM\Column(name="user_email", type="string", length=100, nullable=false)
     */
    private $userEmail = '';

    /**
     * @var string
     *
     * @ORM\Column(name="user_url", type="string", length=100, nullable=false)
     */
    private $userUrl = '';

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_registered", type="datetime", nullable=false, options={"default"="0000-00-00 00:00:00"})
     */
    private $userRegistered = '0000-00-00 00:00:00';

    /**
     * @var string
     *
     * @ORM\Column(name="user_activation_key", type="string", length=255, nullable=false)
     */
    private $userActivationKey = '';

    /**
     * @var int
     *
     * @ORM\Column(name="user_status", type="integer", nullable=false)
     */
    private $userStatus = '0';

    /**
     * @var string
     *
     * @ORM\Column(name="display_name", type="string", length=250, nullable=false)
     */
    private $displayName = '';

Entity\User.php:
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="json_array")
     */
    private $roles = [];

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\WpUsers", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="wp_user_id", referencedColumnName="ID",nullable=false)
     */
    private $wpUser;

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return $this->getWpUser()->getUserLogin();
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword()
    {
        return $this->getWpUser()->getUserPass();
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed for apps that do not check user passwords
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getWpUser(): ?WpUsers
    {
        return $this->wpUser;
    }

    public function setWpUser(WpUsers $wpUser): self
    {
        $this->wpUser = $wpUser;

        return $this;
    }

}

security.yaml:
security:
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    # encoders:
    #         App\Entity\WpUsers:
    #             algorithm: bcrypt
    providers:
        # in_memory: { memory: ~ }
        app_user_provider:
            entity:
                class: App\Entity\User
                property: wpUser.userLogin
firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator

            remember_me:
                secret:   '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds

Security\LoginFormAuthenticator:

namespace App\Security;
// use ...
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    // private $passwordEncorder;
    private $router;

    public function __construct(
            EntityManagerInterface $entityManager,
            UrlGeneratorInterface $urlGenerator,
            CsrfTokenManagerInterface $csrfTokenManager,
            // UserPasswordEncoderInterface $passwordEncorder,
            // PasswordHash $passwordHash
            RouterInterface $router
            )
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        // $this->passwordEncorder = $passwordEncorder;
        $this->router = $router;
        $this->passwordHash = new PasswordHash(8,false);
    }

    public function supports(Request $request)
    {
        return 'app_login' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'userLogin' => $request->request->get('userLogin'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['userLogin']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $wpUser = $this->entityManager->getRepository(WpUsers::class)->findOneBy(['userLogin' => $credentials['userLogin']]);

        if (!$wpUser) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('User Login could not be found.');
        }

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['wpUser' => $wpUser ]);

        if(!$user){
            $user = new USER();
            $user->setWpUser($wpUser);
            $this->entityManager->persist($user);
            $this->entityManager->flush();
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {

        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        // return $this->passwordEncorder->isPasswordValid($user, $credentials['password']);
        return $this->passwordHash->CheckPassword($credentials['password'],$user->getPassword());

        // Check the user's password or other credentials and return true or false
        // If there are no credentials to check, you can just return true
        throw new \Exception('TODO: check the credentials inside '.__FILE__);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
        // throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
        return new RedirectResponse($this->router->generate('commandes'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('app_login');
    }

}

login.twig.html:
{% extends 'myBase.html.twig' %}

{% block title %}Log in!{% endblock %}

{% block body %}
<form method="post">
    {% if error %}

{{ error.messageKey|trans(error.messageData, 'security') }}

    {% endif %}

Please sign in

    User Login
    <input type="text" value="{{ last_username }}" name="userLogin" id="inputUserLogin" class="form-control" placeholder="User Login" required autofocus>
    Password
    <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>

    <input type="hidden" name="_csrf_token"
           value="{{ csrf_token('authenticate') }}"
    >

            <input type="checkbox" name="_remember_me"> Remember me

    <button class="btn btn-lg btn-primary" type="submit">
        Sign in
    </button>
</form>
{% endblock %}

A: I believe what you are missing is a supportsRememberMe() Guard Authenticator method. As you can read in the documentation:
supportsRememberMe()
    If you want to support "remember me" functionality, return true from this method. You will still
    need to activate remember_me under your firewall for it to work...

So the solution should be adding above mentioned method to your authenticator:
public function supportsRememberMe()
{
    return true;
}

A: The Answer is that I have to implement a custom User Provider because my loading User Process is not related to direct Entity.

bin/console make:user

And choose that the user shouldn't be saved in the DB, So that the CLI will create for you the UserProvider.


text:
Q: Autoresizing UITableViewCell I wan to know how can I resize my table view cell, and see all the message
My app is obtaining the messages from an xml on my server, and then it shows them, but if the message is longer than the text field it just display 3 dots
here is my code:
 - (NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section {
return ( messages == nil ) ? 0 : [messages count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 37;
}

- (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"ChatListItem"];
if (cell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChatListItem" owner:self options:nil];
    cell = (UITableViewCell *)[nib objectAtIndex:0];
}

NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
UILabel *textLabel = (UILabel *)[cell viewWithTag:1];
textLabel.text = [itemAtIndex objectForKey:@"text"];
UILabel *stextLabel = (UILabel *)[cell viewWithTag:3];
stextLabel.text = [itemAtIndex objectForKey:@"text"];

UILabel *userLabel = (UILabel *)[cell viewWithTag:2];
userLabel.text = [itemAtIndex objectForKey:@"user"];
UILabel *suserLabel = (UILabel *)[cell viewWithTag:4];
suserLabel.text = [itemAtIndex objectForKey:@"user"];

if ([usernameText.text isEqualToString:userLabel.text]){
    UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat1@2x.png"]];
    [cell setBackgroundView:img];
    [img release];

    textLabel.hidden=NO;
    stextLabel.hidden=YES;

    userLabel.hidden=NO;
    suserLabel.hidden = YES;

}
else{
    UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat2@2x.png"]];
    [cell setBackgroundView:img];
    [img release];

    textLabel.hidden=YES;
    stextLabel.hidden=NO;

    userLabel.hidden=YES;
    suserLabel.hidden = NO;
}

return cell;

}

Thanks

A: You have to pass by heightForRowAtIndexPath like this logic (isn't a code ready):
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
NSString *text = [itemAtIndex objectForKey:@"text"];
if(text is larger then what ever you want) {
    return yourSpecificCellHeight;
}
return 37;

}
To calculate the size of text see this post on stackOverflow


text:
Q: Display multiple graphics with Seaborn I have a csv file that I open with Pandas. It looks like this:
"Patient","Visit","Feature1","Feature2","Feature3"
"P1",0,?,?,?
"P1",1,?,?,?
"P2",0,?,?,?
"P2",1,?,?,?
"P2",2,?,?,?
"P3",0,?,?,?
"P3",1,?,?,?

? being a numerical value.
I know how to display one feature at a time (because they have various ranges) and separated per patient:
seaborn.stripplot(y="Feature1", x="Patient", data=features)

I would like to display ALL the plots inside a single image, like a mapping. How can I do it?

A: Seaborn usually prefers the "long form" of the dataframe, which can be obtained via pandas' melt.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame({"Patient": ["P1", "P1", "P2", "P2", "P2", "P3", "P3"],
                   "Visit": [0, 1, 0, 1, 2, 0, 1],
                   "Feature1": np.random.normal(10, 2, 7),
                   "Feature2": np.random.normal(12, 2, 7),
                   "Feature3": np.random.normal(15, 2, 7)})
df_melted = df.melt(value_vars=["Feature1", "Feature2", "Feature3"], id_vars=["Patient", "Visit"],
                    var_name="Feature", value_name="Value")
sns.stripplot(data=df_melted, x="Patient", y="Value", hue="Feature", dodge=True)

plt.tight_layout()
plt.show()

To get each feature in separate subplots, you can use catplot on the melted dataframe (use sharey=True if all features are in about the same range; use col_wrap=3 to start a new row every 3 columns):
sns.catplot(kind="strip", data=df_melted, x="Patient", y="Value", col="Feature", sharey=False)
plt.tight_layout()


text:
Q: Sharing .NET application pools On an server running multiple ASP.NET sites, is it better to use one application pool per site or for sites to share a single application pool?  What are the advantages or disadvantages inherent to each setup?  Or is there a hard and fast rule here?

A: This really depends on what the requirements are of the site, as well as your concern regarding risks.
When two applications run inside the same application pool they have the same security level, so there is a security concern here for some as in theory each could have access to files of the other.  Also, if one site starts having issues and using memory it could cause recycles or freezes that could impact both.
Although there is not a "hard and fast" rule to this, some of the things that I consider and that cause "automatic" decisions for me are the following.

*

*Is the application mission critical?  (If so, separate app pool)

*Is this a third party application?  (If so, and unsure of what all it does, separate app pool)

*Will this application see major spikes in activity?  (If so, it might be best to isolate)

There is a lot out there, but the keys are isolation and ability to troubleshoot single applications.  Here is a Microsoft article that touches on it a bit as well.

A: One of the advantages of separate AppPools is that in the event that you need to recycle the AppPool you can do so for one site without affecting the performance (or caching) of the others.

A: One critical rule to remember:
DO NOT put .Net 1.1 and .Net 2.0 applications in the same application pool. It will mess things up really fast.

A: It would depend a lot on if certain sites need more reliability than others, what your expected load per site is, etc.
Sharing a pool will be more efficient in general, but a single misbehaving application can more rapidly cause problems for other sites. Additionally you can recycle or update separate app pools separately which may make maintenance schedules easier.

A: There's no hard and fast rule. I tend to use one app pool per site (and IIS7 even defaults to creating one per site) because I like to play it safe in case I have a memory leak in one site/pool, I don't want it affecting and taking down other sites. But I've also got some servers where 100 sites share a single pool without issue. So, as always, it depends.

A: I would strongy prefer single application - single application pool - unles you have performance concerns. An exception in background thread (once someone starts playing async) can bring down the whole app pool. And unless you have automatic recycling enabled this may cause lot of trouble.


text:
Q: Install a custom ASPX file as part of a ListTemplate definition I am using VSeWSS 1.3 to create a custom list definition scoped to 'Site'.
    <Elements Id="8924acef-84ef-4584-ade4-e3eaeb8df345" xmlns="http://schemas.microsoft.com/sharepoint/">

  <ListTemplate Name="MyListDefinition"
                DisplayName="MyList"
                Description=""
                BaseType="0"
                Type="10888"
                OnQuickLaunch="TRUE"
                SecurityBits="11"
                Sequence="410"
                Image="/_layouts/images/itgen.gif" />

  <CustomAction
    Id="MyList.Print"
    Location="Microsoft.SharePoint.StandardMenu"
    GroupId="ActionsMenu"
    Title="Print MyItem"
    Description="Print Empty copies of this form."
    RegistrationType="List"
    ControlAssembly="MyList, Version=1.0.0.0, Culture=neutral, PublicKeyToken=de6e0316a726abcd, processorArchitecture=MSIL"
    ControlClass="MyList.PrintActionMenu" />

  <Module Name="ActionPages" Url="">
    <File Url="PrintForm.aspx" Type="Ghostable" Path="MyListDefinition\PrintForm.aspx" />
  </Module>
</Elements>

The file 'PrintForm.aspx' is correctly installed on the server under ...\12\TEMPLATE\Features... , but it doesn't show up under the expected URL http://localhost/site/lists/listname/PrintForm.aspx after installing the list template and creating a new list instance using this template.
I suspect I am missing the correct properties in the  and/or  tags in my ListDefinition.xml file (shown above).

A: You should also have a schema.xml and in the schema.xml there should be something like this:
<Forms>
  <Form Type="DisplayForm" Url="DispForm.aspx" WebPartZoneID="Main" />
  <Form Type="EditForm" Url="EditForm.aspx" WebPartZoneID="Main" />
  <Form Type="NewForm" Url="NewForm.aspx" WebPartZoneID="Main" />
  ...... your form here
</Forms>

P.S. try the SharePoint Solution Generator to export an existing List (Comes with VSeWSS), it'll give you a complete xml definition. You can use that as a reference.
P.P.S. in the link posted in the comment it states that files should be registered in the feature like so:
<ElementFile Location="GenericList\schema.xml" />
<ElementFile Location="GenericList\DispForm.aspx" />
<ElementFile Location="GenericList\EditForm.aspx" />
<ElementFile Location="GenericList\NewForm.aspx" />
<ElementFile Location="GenericList\AllItems.aspx" />

A: If it is anywhere, I would expect PrintForm.aspx to show up in the root folder of your website when the Url of your Module element is blank. Try this:
  <Module Name="ActionPages" Url="lists/listname">
        <File Url="PrintForm.aspx" Type="GhostableInLibrary" Path="MyListDefinition\PrintForm.aspx" />
  </Module>

Also, try GhostableInLibrary instead of Ghostable as the File Type.
Finally, you mention that PrintForm.aspx does show up somewhere in Features, but did not give the complete path. Make sure it is in ...\12\TEMPLATE\Features\YourFeaturesName\MyListDefinition\PrintForm.aspx. Based on the value of the Path attribute, PrintForm.aspx needs to be in a directory named MyListDefinition within your Feature.


text:
Q: Java 8, how to compose (Bi)Function from (Bi)Predicate I don't believe this question is specific to the Bi versions of these Java 8 classes, hence the parens in the question title.
I composed a function to create an Apache Commons Lang3 Pair object with the following requirements:

*

*If both Left and Right are null, then the Pair should be null

*If Left and Right are equal to one another, then the Pair should be null

*Otherwise, a Pair should be created, either side of which may be null

I did this within a method as follows:
BiPredicate<String,String> valuesExist = (pre, post) -> pre != null || post != null;

final BiPredicate<String, String> valuesDiffer = valuesExist.and((pre, post) ->
            (pre != null) ? ! pre.equals(post) : true);

BiFunction<String, String, Pair<String,String>> createPair =
            (pre, post) -> (valuesDiffer.test(pre, post)) ?
                            ImmutablePair.of(pre, post) : null;

// usage looks like:
Pair<String, String> myPair = createPair.apply(myValue1, myValue2)

I had 3 questions:

*

*Is there a way to avoid the 2 BiPredicates?  The second one is only needed because referencing inside the BiFunction requires it to be final

*Is there a way to move this out of the method and into the surrounding class?

*Is there obvious "clean-up" I missed?

Update
Based upon one of the answers below, a solution without any Java-8 features also seems practical:
static boolean filterPairArgs(String pre, String post) {
    return (pre != null || post != null) && ((pre == null) || !pre.equals(post));
}

static Pair<String, String> createPair(String v1, String v2) {
    if (filterPairArgs(v1, v2)) {
       return new Pair<>(v1, v2);
    }
    return null;
}

// usage looks like:
Pair<String, String> myPair = createPair(myValue1, myValue2);

A: The null-safe handling of Objects.equals() method will clean things up here.
Personally, I'd put this in a helper function. You can use it functionally as a tidy method reference or simply call it as a method.
static Pair<String, String> toPair(String pre, String post) {
  return Objects.equals(pre, post) ? null : ImmutablePair.of(pre, post);
}

A: You can join the predicates:
BiPredicate<String,String> valuesExist = (pre, post) -> (pre != null || post != null) && ((pre == null) || !pre.equals(post));
BiFunction<String, String, Pair<String,String>> createPair =
        (pre, post) -> (valuesExist.test(pre, post)) ?
                new Pair<>(pre, post) : null;

Personally I would create 2 methods/functions instead:
boolean filterPairArgs(String pre, String post) {
    return (pre != null || post != null) && ((pre == null) || !pre.equals(post));
}

Pair<String, String> createPair(String v1, String v2, BiPredicate<String, String> pred) {
    if(pred.test(v1, v2)) {
        return new Pair<>(v1, v2);
    }
    return null;
}

// usage looks like:
Pair<String, String> myPair = createPair(myValue1, myValue2, this::filterPairArgs);


text:
Q: drupal_validate_form not validating more than one time on listing page i am using drupal_validate_form on a node listing page .
it is validating it correctly only for 1st item after that it is not checking validation.
here is my code
     foreach($result as $r){
        $node_form = (object) array(
          'uid' => $user->uid,
          'type' => 'MY_CONTENT_TYPE',
          'language' => LANGUAGE_NONE,
        );
        $form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
        $form['#submit'] = array('#type' => 'submit', '#value' => t('Next'));

        $old_fs = @unserialize($r->form_state);
        $old_fs['values']['uid'] = $user->uid;
        $node = (object) array(
          'uid' => $user->uid,
          'type' => 'MY_CONTENT_TYPE',
          'language' => LANGUAGE_NONE,
        );
        node_object_prepare($node);
        $form_state = array();
        $form_state['build_info']['args'] = array($node);
        $form_state['values'] = $old_fs['values'];
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
        unset($form['#token']);
        drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);
        $errors = form_get_errors();
        $noOfError = 'empty';
        if (!empty($errors)) {
          $noOfError = count($errors);
        }
        form_clear_error();
    }

thank You in advance

A: Finally i have to reset need_validation in $form .
Because every time form get for validation it will chack $form['#needs_validation'] in _form_validate();
so i  added another line after
$form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
$form['#needs_validation'] = TRUE;

and it will validate every form in that loop