text:
Q: Rejecting peripheral touch inputs Given a nested view structure such as:

How do I disable input on the grey periphery, such that even as the user holds a finger on it, but touches the yellow view, the touch event would register in dispatchTouchEvent() for that view unhindered?
EDIT:
To explain a bit further, I need some kind of palm rejection system in the grey area. In the yellow area the user is able to draw with his finger. All of that works fine, but on some phones with border-less displays you might accidentally touch the grey area, which registers as input and the drawing is ruined.
This happens only when the user is touching the screen in multiple places at once. One might blame the user at this point for buying into the gimmick, but I've tried it myself and it's really easy to accidentally touch the edge, and prevent events from flowing properly.
After I've posted this question, I have come up with a somewhat hacky solution that uses multi-touch events. It works better than before, but because it's not really a multi-touch event, sometimes it goes stale and stops registering inputs altogether. Besides, it would be nice to be able to capture real multi-touch events in the yellow box eventually (for example to make zoom-into-your-drawing gesture).
The basic premise of my solution so far is:

*

*Setup the view. In this test case I just got one View, that draws all the areas in its onDraw().

*Capture the MotionEvent in dispatchTouchEvent()

*Pick out the portion of the event with the x,y inside the yellow area:

Then:
// ... event:MotionEvent, pointerCoordsOut:MotionEvent.PointerCoords
for (pidx in 0 until event.pointerCount) {
    event.getPointerCoords(pidx, pointerCoordsOut)
    if (inYellowArea(pointerCoordsOut.x, pointerCoordsOut.y)) {
         //pointerCoordsOut now has (x,y) that I need
    }
}

Finally, adjust the code to accept ACTION_* and ACTION_POINTER_* events, and make them do something reasonable. This was easy enough in the demo case, but I think this is where the solution will ultimately fail.
So I would still love for there to be a proper solution for palm rejection on borders as-if that event was not there at all, as opposed to in my case part of a complicated gesture that I am trying to decipher.
EDIT:
Still open for suggestions.

A: UPDATED:
layout:
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/orange"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="64dp"
        android:layout_marginEnd="64dp"
        android:layout_marginStart="64dp"
        android:layout_marginTop="64dp"
        android:background="@android:color/holo_orange_dark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

code:
class MainActivity : AppCompatActivity() {

    private val touchableRect = Rect()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        root.post {
            orange.getGlobalVisibleRect(touchableRect)
        }

        root.setOnTouchListener { v, event ->
            Log.d("logi", "root touched : ${event.actionMasked}")
            false
        }

        orange.setOnTouchListener { v, event ->
            Log.d("logi", "orange touched : ${event.actionMasked}")
            true
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        val isConsumed = ev?.let {
            if (touchableRect.contains(it.x.toInt(), it.y.toInt())) {
                orange.dispatchTouchEvent(it)
            } else {
                true
            }
        }

        return isConsumed ?: true
    }
}

A: The underlying problem is two-fold: First, a touch outside of the drawing area will fail to ever reach the drawing area for the duration of the gesture unless coding is in place to redirect the gesture. Second, there may be several pointers on the screen, so they have to be kept straight.
In the following solution, dispatchTouchEvent() is called for the drawing area from the main activity. This insures that the drawing area sees all events even those that are intiated outside of its boundaries. MainActivity does a blanket call to the drawing area although it could be made smarter to dispatch the call under certain circumstances.
The drawing area is a simple custom view that sorts through the events and acts on ones that are germane while ignoring others. See the comments in the code. The custom view simply permits the user to draw with a finger.
The main activity, the layout and the custom view all work together as a simple app if you want to try it out.
MainActivity.java
public class MainActivity extends AppCompatActivity {
    private View mDrawingArea;
    private final int[] mDrawingAreaLocation = new int[2];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View layout = findViewById(R.id.layout);
        mDrawingArea = findViewById(R.id.drawing_area);

        layout.post(new Runnable() {
            @Override
            public void run() {
                mDrawingArea.getLocationOnScreen(mDrawingAreaLocation);
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // Everything goes to the drawing area. We could do some bounds checking and send
        // everything within the bounds to the drawing area and everything else to
        // super.dispatchTouchEvent().

        // Adjust location to be view-relative.
        event.offsetLocation(-mDrawingAreaLocation[0], -mDrawingAreaLocation[1]);
        return mDrawingArea.dispatchTouchEvent(event);
    }
}

MyView.java
public class MyView extends View {
    private final Rect mViewBounds = new Rect();
    private static final int NO_POINTER_CAPTURED = -1;
    private int mCapturedPointer = NO_POINTER_CAPTURED;
    private final Path mPath = new Path();
    private final Paint mPaint = new Paint();

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.STROKE);
    }

    @Override
    public void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mViewBounds.left = 0;
        mViewBounds.top = 0;
        mViewBounds.right = w;
        mViewBounds.bottom = h;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Coordinates will be relative to the view.

        switch (event.getActionMasked()) {

            case MotionEvent.ACTION_DOWN:
                // This is the start of the gesture and the first pointer down.
                // Check to see if it is in our drawing area and capture it if it is.
                if (mViewBounds.contains((int) event.getX(), (int) event.getY())) {
                    mCapturedPointer = event.getPointerId(event.getActionIndex());
                    mPath.reset();
                    mPath.moveTo(event.getX(), event.getY());
                }
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
                // This is the second, third, etc. pointer down. We are just going to
                // consider capturing it if we don't have another pointer already captured.
                if (mCapturedPointer == NO_POINTER_CAPTURED) {
                    int x = (int) event.getX(event.getActionIndex());
                    int y = (int) event.getY(event.getActionIndex());
                    // The pointer must be within the drawing area.
                    if (mViewBounds.contains(x, y)) {
                        mPath.reset();
                        mPath.moveTo(x, y);
                        mCapturedPointer = event.getPointerId(event.getActionIndex());
                    }
                }
                break;

            case MotionEvent.ACTION_MOVE:
                // See if our captured pointer is moving. If it is, do some prep for drawing.
                if (mCapturedPointer != NO_POINTER_CAPTURED) {
                    int pointerCount = event.getPointerCount();
                    for (int ptrIndex = 0; ptrIndex < pointerCount; ptrIndex++) {
                        if (event.getPointerId(ptrIndex) == mCapturedPointer) {
                            mPath.lineTo(event.getX(ptrIndex), event.getY(ptrIndex));
                            invalidate();
                            break;
                        }
                    }
                }
                break;

            case MotionEvent.ACTION_POINTER_UP:
                // Release the captured pointer when it leaves the surface.
                if (event.getPointerId(event.getActionIndex()) == mCapturedPointer) {
                    mCapturedPointer = NO_POINTER_CAPTURED;
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mCapturedPointer = NO_POINTER_CAPTURED;

            default:
                break;
        }

        // We want to look at everything.
        return true;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(mPath, mPaint);
    }
}

activity_main.xml
<FrameLayout
    android:id="@+id/parentGroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_light"
    android:padding="32dp"
    tools:context=".MainActivity">

    <com.example.android.rejectperipheraltouches.MyView
        android:id="@+id/drawing_area"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        android:background="#FDD835"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</FrameLayout>

Using a touch listener
The code above redirects events within dispatchTouchEvent() in the activity but may need additional logic for more complicated layouts. An alternative is to call the drawing view's onTouchEvent() directly from a touch listener for the parent view. Thus, if the drawing view is touched directly, all events flow normally. However, if the initial touch is to the enclosing view, those touches will be redirected to the drawing view. This is probably cleaner than the dispatchTouchEvent() solution.
MainActivity.java (alternative)
public class MainActivity extends AppCompatActivity {
    private View mDrawingArea;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawingArea = findViewById(R.id.drawing_area);
        findViewById(R.id.parentGroup).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                event.offsetLocation(-mDrawingArea.getLeft(), -mDrawingArea.getTop());
                return mDrawingArea.onTouchEvent(event);
            }
        });
    }
}


text:
Q: If div has class remove class or else add a new class I have a '-' button on my WordPress website that I want to use to add a class to the  of my page to increase font size. I also have a '+' button, which will decrease the size of font.
Plus button HTML:

+

Minus button HTML:

-

In the stylesheet I have styles for 'biggerText' and 'smallerText'. What I want to avoid is having both these classes as a  class (hence I cannot just add/remove/toggle class.
How would I do this with jQuery? For the '-' button I've tried this, but it does not work.
    jQuery('smallerTextButton').click(function (){
        if ( jQuery('body').hasClass('biggerText')) {
            jQuery('body').removeClass('biggerText');
        } else {
            jQuery('body').addClass('smallerText');
        }
    });
});

I think I am incorrectly using if/else statements, but cannot see why it does not work. Obviously, the above text would online apply to clicking the 'smallerTextButton', but would I use the same solution for 'biggerTextButton', with appropriate classes? :)

A: Firstly note that your jQuery selector was missing the . prefix for the class.
With regard to your issue, the simplest way to achieve this would be to remove both classes from the body before you add the relevant one from the clicked div. All you need to do is add a 'normal size' option to enable users to revert the font size back to normal.
I would also suggest you change the trigger elements to buttons. As you're doing this for accessibility reasons, you should build the HTML to best standards for screen readers. They can still be styled to not look like buttons, if you prefer.

let $body = $('body');

$('.textAmendmentButton').on('click', function() {
  $body.removeClass('biggerText smallerText').addClass(this.dataset.bodyclass);
});
body { font-size: 1em; }
body.smallerText { font-size: 0.7em; }
body.biggerText { font-size: 2em; }

<button type="button" class="textAmendmentButton" data-bodyclass="biggerText">+</button>
<button type="button" class="textAmendmentButton" data-bodyclass="">N</button>
<button type="button" class="textAmendmentButton" data-bodyclass="smallerText">-</button>

Foo bar

Lorem ipsum dolor sit amet consectetur adipscing elit. Lorem ipsum dolor sit amet consectetur adipscing elit. Lorem ipsum dolor sit amet consectetur adipscing elit. Lorem ipsum dolor sit amet consectetur adipscing elit. Lorem ipsum dolor sit amet consectetur adipscing elit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java or Scala maven installed jar using CLASSPATH Finding maven with pom.xml files confusing.
Dependencies can be added to the pom file which can be installed using the following command:
mvn dependency:resolve

The result is, by default, dependencies installed into the .m2 directory with the caller's home directory.
Each maven package might have one or more of its own dependencies each having a jar file.
After the installation, you'll end up with many packages installed beyond the jars defined as dependencies in the pom file.
I want to import jars in applications using the CLASSPATH environment variable; however, it seems that including just the jar of a dependency defined in my pom file will leave out its own dependencies.
Having trouble understanding the scope of a dependency jar and how to make those dependencies available to applications using the CLASSPATH environment variable.
How can I accomplish this?

A: Maven dependency plugin can be used to get the classpath as explained here.
This would print the classpath in the console:
mvn dependency:build-classpath

or classpath can be written to a file:
mvn dependency:build-classpath -Dmdep.outputFile=cp.txt

Output from these commands can be used to setup your CLASSPATH environment variable.


text:
Q: Building own recursive power function I'm pretty new to python as a whole so apologies, but i'm tasked with building a standalone power function for exponents upto 4.
So far i have;
def power(x,n):
    if(n==1):
        return x
    if(n==2):
        return square(x)
    if(n==3):
        return cube(x)
    if(n==4):
        return hypercube(x)

with the square, cube and hypercube functions being;
def square(x):
    return x*x

def cube(x):
    return x*x*x

def hypercube(x):
    return x*x*x*x

I'm trying to replace the square, cube and hypercube functions with calls to the power function itself, but i'm having trouble understanding recursive call. I tried the following thinking you just have to call from within directly to the end result. I'm struggling just being able to visualise this
def power(x,n):
    if(n==1):
        return x
    if(n==2):
        return power(x^)
    if(n==3):
        return power(x^n)
    if(n==4):
        return power(x^n)

A: You can use direct recursion like so
def power(x, n):
    if n == 0:
        return 1
    return x * power(x, n - 1)


text:
Q: cakephp 3 upload photo with Josegonzalez/Upload I want to have some photos for my products and tried to use :
Josegonzalez/Upload.Upload

but I have some problem with this .
The field that I specified for image is became required .
and this is the error I get when leave the field empty :

This field cannot be left empty

when comment the  Josegonzalez/Upload.Upload configurations that field is became optional as it should be !!
this is my configuration :
$this->addBehavior('Josegonzalez/Upload.Upload' ,
            [
                'image' => [
                    'path'              => 'webroot{DS}img{DS}dynamic' ,
                    'nameCallback' => function ($data) {
                        $ext = pathinfo($data['name'], PATHINFO_EXTENSION);
                        return rand(100000,999999).time().rand(10000 , 99999).".".$ext;
                    } ,
                    'keepFilesOnDelete' => false,
                ] ,
            ]);

I also deleted default validation for the field in the table but it doesn't work.
thanks a lot for your help
UPDATE :
This is the input  for the photo field before submit

                    chose pic
                     edit
                    <input value="" name="..." type="hidden">
                    <input name="image" id="image" image="" height="150" width="200" type="file">

         حذف

and this is after i hit submit and the page refreshes with error "This field cannot be left empty"

                    chose pic
                     edit
                    <input value="" name="..." type="hidden">
                    <input name="image" required="required" id="image" val=" 4   0" class="form-error" image="" height="150" width="200" type="file">

         حذف

A: I found the answer
  $validator
        ->allowEmpty('image');

adding the code above to the table will solve the problem.


text:
Q: Only main page being found So I just started making a new website, or rather modifying an old one. All the code is the same, the only difference is I changed some text here and there. The old website worked perfectly, so this one should as well, so I'm not sure why this is happening, but only the main page can be found using the URLs that I wish to be used. Try going to, for example, the projects page, and not only is the file not found, but my custom not found page won't even be shown. First I'll show some examples then I will show some code.

*

*Main page that works: teivodov.com

*Projects page that worked on old site, but not on this one: teivodov.com/projects

*Projects page that works, but ugly url form https://teivodov.com?page=projects

*Not found page working only if ?page= used: https://teivodov.com?page=blahblah
Here is my htaccess file:

//deny access to this file
  <Files ~ ".htaccess">
      deny from all
  </Files>
//start RewriteEngine
  RewriteEngine On
//if the called file is NOT a directory, file or link, we call index.php?page=
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
//disable file listing
  Options -Indexes
//set error page 403 (no permission) and 404 (page not found) to our notfound page
  ErrorDocument 403 /notfound
  ErrorDocument 404 /notfound
  order deny,allow

(# replaced with //)
My index.php:
<?php
function dump_error_to_file($errno, $errstr) {
    file_put_contents('/errors.log', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler('dump_error_to_file');

//load needed settings, constants, page array and functions
include 'variables.php';
include 'constants.php';
include 'functions.php';

//setting timezone to America/Chicago, needed by some functions
date_default_timezone_set('America/Chicago');

//gets changed to the return of the include file
$ret = 1;

/*
 * The include file has to contain the following values:
 *   Array('filename' => string, -- Filename for template
 *         'data' => Array())    -- Array with data for the template
 * - At an exception
 *   string  -- Errormessage.
 */

//if no page was called, include the main page
if (!isset($_GET['page'])) {
    $ret = include 'includes/' . $files['main'];
} else {

  if (isset($_GET['page'])) {
      $page = trim($_GET['page']);
  } else {
      $page = 'main';
  }

  if (isset($files[$page])) {
      //if the file exists include it, else print error message
      if (file_exists('includes/' . $files[$page])) {
          $ret = include 'includes/' . $files[$page];
      } else {
          $ret = "Include-File was not found: 'includes/" . $files[$page] . "'";
      }
  } else {
      $ret = include 'includes/' . $files['notfound'];
  }
}

//include header template
include 'templates/header.html';

//if the include returns an array, it contains the templatestring and the data array, try to include the template
if (is_array($ret) && isset($ret['filename'], $ret['data']) && is_string($ret['filename']) && is_array($ret['data'])) {
    //if the template exists include it, else print error message
    if (file_exists($file = 'templates/' . $ret['filename'])) {
        $data = $ret['data'];
        include $file;
    } else {
        $data['msg'] = 'Template "' . $file . '" was NOT found.';
        include 'templates/error.html';
    }
//if the include file returns a string, it returned an exception. So we print it
} else if (is_string($ret)) {
    // Exception
    $data['msg'] = $ret;
    include 'templates/error.html';

//the defualt value of $ret didnt change, so the include didnt return anything. Print error message
} else if (1 === $ret) {
    //No return array
    $data['msg'] = 'No return in the template!';
    include 'templates/error.html';
} else {
//include file has a complete other return like a boolean or something, print error
    //everything left
    $data['msg'] = 'Include file has an invalid return.';
    include 'templates/error.html';
}

//include footer template
include 'templates/footer.html';

Variables.php:
<?php

$files = array();
$files['main'] = 'main.php';
$files['projects'] = 'projects.php';
$files['projects/jda-extended'] = 'projects/jda-extended.php';
$files['contact'] = 'contact.php';
$files['about'] = 'about.php';
$files['notfound'] = 'notfound.php';

An example include file, projects.php:
<?php

$a = array();
$a['filename'] = 'projects.html';
$a['data'] = array();

return $a;

Example template file, projects.html:

    This website is still under construction.

      JDA Extended - Extension to the JDA API. Allows for quick and easy discord bot development.

I believe that should be all the code someone might ask for, but feel free to ask for more if need be. The only difference between my last site and this one, is that the last site was hosted on shared web hosting. This one is hosted on my vps using apache2. It really confuses me as the site is able to find for example includes/main.php and templates/main.html, but not any other files in those folders. The only thing I can think of is something went wrong in the htaccess file as ?page=projects works but /projects does not, but I can't see anything wrong with it?

A: After playing around, I realized it was an issue with Apache2. By default in /etc/apache2/apache2.conf AllowOverrides is set to None when I needed it to be All. I had done all my testing of the website in windows, which I did not need to bother changing that.


text:
Q: 7zip - Command Line: how to set output path? I want to compress all HTM files in D:\HTM\ to an archive called comp.7z which is created in D:\HTM\ directory, so I do the following:
7z a -o "D:\HTM" comp.7z "D:\HTM"

and get an error, exactly as below:
Error:
Incorrect command line

Why am I getting error, what is the correct way/syntax of using -o switch?
I have tried:
7z a -o"D:\HTM" comp.7z "D:\HTM"

And:
7z a -o{"D:\HTM"} comp.7z "D:\HTM"

It creates comp.7z in CWD.

A: 7z a D:\HTM\comp.7z D:\HTM\*.htm

You don't need the -o since you're creating an archive. You also fail to specify which files need to be included in the archive (D:\HTM\*.htm). The output is the complete name of the archive (D:\HTM\comp.7z). The quotes aren't needed here, since there are no spaces in the filename(s).


text:
Q: Javascript closures : Loop inside Loop I already know how to loop thanks to closure like this :
for (var i = first; i <= last; i++) {
    document.getElementById(more + i).onmouseover = (function(arg1) {
        return function() {
            document.getElementById(arg1).style.display = "block";
        }
    })(i);
}

But I'd like now to do a look inside the loop.
I've got elements of the DOM which must be dynamically attached to other elements. The elements are of the type: '1text1', '1text2', '1text3',... and '2text1', '2text2', '2text3', '3text4'...
I've tried something like this:
var text;
var ktext;
for (var k = 1; k <= last_number; k++) {
    for (var i = first; i <= last; i++) {
        ktext = k + text;
        document.getElementById(ktext + i).onmouseover = (function(arg1, arg2) {
            return function() {
                document.getElementById(arg1 + arg2).style.display = "block";
            }
        })(ktext, i);
    }
}

But the loop is partially lost. If I put alert(ktext + i) just at the beginning of the var i loop, I see: 1text1, 1text2, 1text3, 1text4 then 2text1 (as expected), but not 2text2, 2text3... as if the second pass of the var k loop stops too early.

A: Your use of closures is unnecessary:
for( k=1; k<=last_number; k++) {
  for( i=first; i<=last; i++) {
    document.getElementById(k+text+i).onmouseover = function() {
      this.style.display = "block";
    }
  }
}

Anyway, your loop may be stopping early if one of the elements doesn't exist on the page. You should check for the element's existence before attempting to assign to it.


text:
Q: What are the standard method known to secure WCF services or web services in general? What I am looking for is a set of article that can help me understand the basics, so I can be sure of what I am doing.
Methods regarding secure authentification are the most welcome.
Thanks.

A: see this article about Securing WCF Services with Authentication Service.
also this one on Certificate based Authentication.
take a look at Programming WCF Security in msdn library


text:
Q: Redirecting SSH on login, however SFTP does not work I'm trying to set up a SSH proxy for our users using an automated jumpbox.  The user logs in and gets automatically SSHed off to his container/vm, which works great.  Regretfully, SFTP which tunnels over it does not.  I'm sure this has to do with how I've set it up as it's basically just piping term back and not doing the tunneling properly.
/etc/passwd
redtest:x:1002:1002::/home/redtest:/usr/bin/redtest

/usr/bin/redtest
#!/bin/bash
/usr/bin/ssh redtest -t -F ~/.ssh/config

/home/redtest/.ssh/config
Host redtest
        HostName redtest1
        User root
        IdentityFile ~/.ssh/id_rsa

What's the correct way to set something like this up, or is this even possible?  The logins are one to one with the containers.  Appreciate a nudge in the right direction!

A: When a remote ssh client requests to run a command on the server, the OpenSSH server launches the local user's shell with the "-c" option to run the command. It runs the equivalent of this:
$SHELL -c 'the requested command'

Eg, if the remote user ran:
ssh user@somehost 'rm -rf /'

and "user@somehost" had /bin/bash as his shell, then the server would run the equivalent of:
/bin/bash -c 'rm -rf /'

SFTP is a little more complicated, but you end up in the same place. The remote client requests the server to run the "sftp" subsystem. In the server's sshd_config file, you probably have a line like this:
Subsystem sftp /path/to/sftp-server

That line says "When a client requests the 'sftp' subsystem, run /path/to/sftp-server" sftp-server is a program included with OpenSSH which implements the server part of the SFTP protocol. So when an ssh client connects and requests the sftp subsystem, the server ends up running:
$SHELL -c /path/to/sftp-server

(There is a special case called "internal-sftp" which I won't go into here.)
Now, you've written a script named /usr/bin/redtest and set it to be the user's shell. So when a remote user tries to run sftp, the server will end up running:
/usr/bin/redtest -c /path/to/sftp-server

Your redtest script ignores its command line and just starts a plain ssh session to the target server. It never runs the sftp-server program on the target server.
To make this work, you need to make redtest start sftp-server on the target host when redtest is run in this fashion. If you're not too picky about what the user runs on the target host, then something like this ought to work:
#!/bin/bash
if [ "$1" = "-c" ]
then
    /usr/bin/ssh redtest -F ~/.ssh/config "$2"
else
    /usr/bin/ssh redtest -t -F ~/.ssh/config
fi

This will pass through any command requested by the client, not just sftp. This shouldn't be a problem, since users apparently have root command-line access to the target servers anyway.
You may run into a problem here if the jump host and the target host don't have the sftp-server program in the same place. The ssh server on the jump host will try to run sftp-server using the path from the jump host's config, which may not be correct for the target host. You'll have to make sure sftp-server can be invoked on the target host, using the path in the jump host's sshd_config.
If you want to make the redtest script more sophisticated, you could arrange for it to run something like this when the remote user tries to run sftp:
/usr/bin/ssh redtest -F ~/.ssh/config -s sftp

The -s and sftp arguments specifically request to run the sftp subsystem on the target host.


text:
Q: Difference between these 3 shopping cart calls? I read these 3 snippets from the Internet of obtaining shopping cart contents.
Snippet 1
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
    // get item details here
}

Snippet 2
$cartItems = Mage::getModel("checkout/cart")->getItems();
foreach($cartItems as $item) {
    // get item details here
}

Snippet 3
$cartHelper = Mage::helper('checkout/cart');
$cartItems = $cartHelper->getCart()->getItems();
foreach($cartItems as $item) {
    // get item details here
}

What are the difference the snippets above? All of them return the same items.

A: 1.
$cartItems = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();

Will return all visible items in the cart. For more info on visible / not visible items look here. (In short, this kind of function would return a configurable but not its simple)
2.
$cartItems = Mage::getModel("checkout/cart")->getItems();
Mage_Checkout_Model_Cart
public function getItems()
{
    if (!$this->getQuote()->getId()) {
        return array();
    }
    return $this->getQuote()->getItemsCollection();
}

Under the hood it is getting the quote and getting the items collection, so will not be doing visible filtering as scenario 1. (In short, this kind of function would return a configurable AS WELL AS its simple)
3.
$cartItems = Mage::helper('checkout/cart')->getCart()->getItems()
Mage_Checkout_Helper_Cart
/**
 * Retrieve cart instance
 *
 * @return Mage_Checkout_Model_Cart
 */
public function getCart()
{
    return Mage::getSingleton('checkout/cart');
}

Under the hood this calls getSingleton('checkout/cart'), from there it's the same as scenario 2.
So the main difference is in 1, where it filters for visible items.

A: Snippet 1
$quote = Mage::getSingleton('checkout/session')->getQuote(); give Current cart Object.It provide.
Snippet 2
$cartItems = Mage::getModel("checkout/cart")->getItems();

Snippet 3
$cartHelper = Mage::helper('checkout/cart');
$cartItems = $cartHelper->getCart();

Here:
Mage::getSingleton('checkout/cart')=$cartHelper->getCart()

Mage::getSingleton('checkout/cart') give singleton object of  Class Mage_Checkout_Model_Cart.
and  $cartItems->getItems() give null value if current session  did not have any cart items.
please check  on this class
public function getItems()
    {
    //  !$this->getQuote() =Mage::getSingleton('checkout/session')->getQuote()
        if (!$this->getQuote()->getId()) {
            return array();
        }
        return $this->getQuote()->getItemsCollection();
    }

** More details will provide soon


text:
Q: Ignore case in email address used in a form For users that forget their login credentials I have a form they can fill out that includes their email address. It is compared to a list of email addresses that is all in lower case.
Can I.. have the case of the email address ignored if the user uses caps?
I recently used strtolower() to ignore the case of my login which worked great but am having troubles trying to implement the same in my form.
Thank you for any advice or help.
   <form action="../pages/send_mail.php" method="post">

<left>
Please type in your email address as listed in the Shareholders list

    Email address    >>>
    <input type="text" name="email_address" />

    <input type="submit" name="submit" value=" Click this bar to have an email sent to the address above with your username and password " style="font-size:11px;" />


text:
Q: What is fragment?How to add a frgament to an existing activity?And how to modify layout of a fragment I am new to android,and i want to create a fragment which has listview in it and i want to add that fragment to my main activity.I am trying but i cant add it to my activity and also cant define my own layout to it.So please help me.
Thanks in advance.
This is my MainActivity.java
package com.example.sample;

import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

String[] codeLearnChapters = new String[] { "Android Introduction","Android Setup/Installation","Android Hello World","Android Layouts/Viewgroups","Android Activity & Lifecycle","Intents in Android"};

ArrayAdapter<String> codeLearnArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codeLearnChapters);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ListView codeLearnLessons = (ListView) findViewById(R.id.idListView1);
    setContentView(R.layout.activity_main);
    codeLearnLessons.setAdapter(codeLearnArrayAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

And its xml is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<fragment
    android:layout_width="wrap_content"
    android:layout_height="300dp"
    android:name="com.example.sample.myFragment"
    android:id="@+id/fragment"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true" />
</RelativeLayout>

My fragment java is myFragment.java
package com.example.sample;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * Created  on 11/4/2015.
*/
public class myFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle
                                 savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.act_fragment,
            container, false);
    return view;
}
}

Its xml i.e act_fragment.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/idListView1">
</ListView>

</RelativeLayout>

A: A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
In my words, a fragment is a sub-activity.
You can read more about what a fragment is http://developer.android.com/guide/components/fragments.html
There is also a sample which you could use (and will be helpful as you will learn something new). The sample is http://developer.android.com/training/basics/fragments/index.html
You can also look it up on youtube (once you have read about it and understood what fragment is). There is also a video tutorial to start you with. Just search "Android Fragment Lifecycle Part 1: Android Application Development Tutorial [HD 1080p]" - sorry, Stackoverflow is not allowing me to add more than two links.
They have five tutorials and I would recommend it as it will help you start better by yourself.

A: You can read more about what a fragment is
link
Code :
public class Tab2Fragment extends Fragment {

    EditText fromdate;
    EditText todate;

    // List view
    private ListView lv;

    // Listview Adapter
    ArrayAdapter<String> adapter;

    // Search EditText
    EditText inputSearch;

    // ArrayList for Listview
    ArrayList<HashMap<String, String>> productList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View V = inflater.inflate(R.layout.tab2_view, container, false);

        EditText fromdate=(EditText)V.findViewById(R.id.fromdate);
        EditText todate=(EditText)V.findViewById(R.id.todate);

        fromdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        // Listview Data
        String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
                "iPhone 4S", "Samsung Galaxy Note 800",
                "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};

        lv = (ListView) V.findViewById(R.id.list_view);

        // Adding items to listview
        adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);

        return V;
    }

}

A: hope this link helpful you
http://developer.android.com/guide/components/fragments.html
Place this in your activity class
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
and place below code in activitylayout code

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/fragment_container"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:ignore="MergeRootFrame" />


text:
Q: require file as string I'm using node + express and I am just wondering how I can import any file as a string. Lets say I have a txt file all I want is to load it into a variable as such.
var string = require("words.txt");

I am against
modules.exports = function(){

    var string = "whatever";

    return string;

}

A: The selected answer is deprecated and not recommended anymore.
NodeJS documentation suggests other approaches like:

loading modules via some other Node.js program

but it does not expand any more.

*

*You can use a very simple library like this: require-text

*Or implement it yourself ( like from the package above: )

var fs = require('fs');
module.exports = function(name, require) {
   return fs.readFileSync(require.resolve(name)).toString();
};

A: you'll have to use readFile function from filesystem module.
http://nodejs.org/docs/v0.3.1/api/fs.html#fs.readFile

A: To read the CSS file to String, use this code. It works for .txt.
const fs = require('fs')
const path = require('path')

const css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')

ES6:
import fs from 'fs'
import path from 'path'

let css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')

A: My simplest solution is
var string = require("fs").readFileSync("file.txt", 'utf8')
console.log("string = ", string);

A: If it's for a (few) specific extension(s), you can add your own require.extensions handler:
var fs = require('fs');

require.extensions['.txt'] = function (module, filename) {
    module.exports = fs.readFileSync(filename, 'utf8');
};

var words = require("./words.txt");

console.log(typeof words); // string

Otherwise, you can mix fs.readFile with require.resolve:
var fs = require('fs');

function readModuleFile(path, callback) {
    try {
        var filename = require.resolve(path);
        fs.readFile(filename, 'utf8', callback);
    } catch (e) {
        callback(e);
    }
}

readModuleFile('./words.txt', function (err, words) {
    console.log(words);
});

A: you can require .json files, both with node.js and TypeScript. That's the only format that support being required() suitable for serializing text. YOu can use a compile-time tool to pack your files into a json, such as https://github.com/cancerberoSgx/fs-to-json


text:
Q: sockaddr value changes unexpectedly after calling getaddrinfo() I am programming an UDP client. I want to bind the socket to a given port on the client machine, so that the same port is always used for all sends. I get the sockaddr for the server using getaddrinfo, and I do the same to get the sockaddr which I pass to the call to getaddrinfo. However, after the second call to getaddrinfo the address of the server machine changes, and I end up sending the packet from the client machine to the client machine itself.
The following code is a standalone example that reproduces the error:
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SERVER_HOST "www.google.com"
#define UDP_PORT "4000"

static struct sockaddr_in *destination_addr = NULL;
static int client_port;

int main(){

    uint8_t bytes[5] = { 0xaa, 0xab, 0xac, 0xad, 0xaf}; //some data to send

    uint16_t length = 5;
    int status;

    //initialize socket and bind
    if (destination_addr == NULL) {
        struct addrinfo hints;
        struct addrinfo *servinfo, *p;
        srand(time(NULL));
        memset(&hints, 0, sizeof hints);
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_flags = AI_PASSIVE;

        if ((status = getaddrinfo(SERVER_HOST, UDP_PORT, &hints, &servinfo)) != 0) {
            printf("Unable to send UDP. Reason: %s", gai_strerror(status));
            return 0;
        }

        for (p = servinfo; p != NULL; p = p->ai_next) {
            if (p->ai_addr != NULL)
                destination_addr = (struct sockaddr_in *) p->ai_addr;
        }
        client_port = 1027 + rand()%50000;
        freeaddrinfo(servinfo);
        printf("Created destination_addr with IP %s\n",  inet_ntoa(destination_addr->sin_addr));
    }

    int send_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (send_socket_fd == -1) {
        printf("Unable to create UDP socket. Reason: %s", strerror(errno));
        return 0;
    }
    printf("IP after socket creation is %s\n", inet_ntoa(destination_addr->sin_addr));
    int yes = 1;
    if (setsockopt(send_socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (int)) == -1) {
        perror("setsockopt");
        return 0;
    }
    printf("IP after sockopt is %s\n", inet_ntoa(destination_addr->sin_addr));

    // bind to local address
    char str_client_port[6];
    snprintf(str_client_port, 5, "%d", client_port);
    struct addrinfo *source_addr_info;
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;

    // ***** destination_addr changes after this call *****
    getaddrinfo (NULL, str_client_port, &hints, &source_addr_info);

    printf("IP after getaddrinfo is %s\n", inet_ntoa(destination_addr->sin_addr));
    bind(send_socket_fd, source_addr_info->ai_addr, source_addr_info->ai_addrlen);
    printf("IP after binding is %s\n", inet_ntoa(destination_addr->sin_addr));

    // send
    int bytes_sent = sendto(send_socket_fd, bytes, length, 0, (struct sockaddr *)destination_addr, sizeof *destination_addr);
    printf("Sent to IP %s\n", inet_ntoa(destination_addr->sin_addr));
    if (bytes_sent != length){
        if (bytes_sent == -1){
            printf("UDP send failed. Reason: %s", strerror(errno));
        }
        else {
            printf("UDP: not all bytes could be sent.");
        }
    }

    close(send_socket_fd);
    return 1;

}

The output generated by the execution of this program in my machine is:
Created destination_addr with IP 64.233.167.105
IP after socket creation is 64.233.167.105
IP after sockopt is 64.233.167.105
IP after getaddrinfo is 0.0.0.0
IP after binding is 0.0.0.0
Sent to IP 0.0.0.0

I am rather new to socket programming in C, and pretty sure I am doing some silly mistake, but after googling a lot and trying many things, I am still stuck with this. Any idea?

A: Solved. As @molbdnilo pointed out, the error was caused by the call to freeaddrinfo. To fix it I now copy the value pointed by p->ai_addr, so that it is not lost when freeing. I substituted:
if (p->ai_addr != NULL)
    destination_addr = (struct sockaddr_in *) p->ai_addr;

with
if (p->ai_addr != NULL){
    destination_addr = malloc(sizeof *destination_addr);
    memcpy(destination_addr, (struct sockaddr_in *)p->ai_addr, sizeof *p->ai_addr);
}

and it worked.


text:
Q: Why does a @Query annotated method require a body? I'm new to Spring.
I wrote a class:
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Kontroller
{
  @Query( value="select * from teszt"
        , nativeQuery = true
        )
  List<Teszt> osszesSor();  // <-- error
//.....
  @RequestMapping("/szam")
  public @ResponseBody String szamossag()
  {
    List<Teszt> sokasag = osszesSor();
    return("számosság="+sokasag.size());
  }

}

And it says (it = the IDE (STS), and at runtime when I call osszesSor()):
This method requires a body instead of a semicolon.
The Teszt class is:
import java.io.Serializable;
import javax.persistence.*;

@Entity
@IdClass(Teszt.class)
public class Teszt implements Serializable {

  @Id
  private String kulcs;
  @Id
  private String ertek;

//getters, setters

}

It's a very simple table (that's why it becomes very complex in spring, because it has not a one-column key):
create table TESZT
(
    KULCS VARCHAR2(2000) not null,
    ERTEK VARCHAR2(2000) not null,
    constraint TESZT_UN
        unique (KULCS, ERTEK)
)

A: Now I know.
I had to create a repo interface:
public interface TesztRepo extends Repository<Teszt, Teszt>
{
  @Query( value="select * from teszt"
        , nativeQuery = true
        )
  List<Teszt> sokasag();
//...
}

and autowire it in the controller.
  @Autowired
  TesztRepo dao;
//...
    List<Teszt> sokasag = dao.sokasag();

Not that complex.


text:
Q: count occurrence of a words in a csv file in python using nltk I tried to count the number of occurrence of the word "the" in a .csv file, but when I run
the following code, it returns 0.  (test.csv is located here)
I just search the first column of this file.
import csv
import nltk

tweet = []

for t in csv.DictReader(open('test.csv'), delimiter=','):
    tweet.append(t['text'])

tweet_text = nltk.Text(tweet)
print tweet_text.count("the")

Thanks in advance for your help.

A: Split text field into words using str.split, and use list.extend accordingly.   And make lowercase unless you only want lowercase the.
>>> nltk.Text(['the world The words']).count('the')
0
>>> nltk.Text(['the', 'world', 'The', 'words']).count('the')
1

Complete code:
import csv
import nltk

tweet = []

for t in csv.DictReader(open('test.csv'), delimiter=','):
    tweet.extend(t['text'].lower().split()) # <-----------

tweet_text = nltk.Text(tweet)
print tweet_text.count('the')


text:
Q: Issue when running ng build I just finished my first Angular 4 project, only utilizing user login. However, when I run ng build --prod, I get the following errors:
Versions of @angular/compiler-cli and typescript could not be determined.
The most common reason for this is a broken npm install.

Please make sure your package.json contains both @angular/compiler-cli and typescript in
devDependencies, then delete node_modules and package-lock.json (if you have one) and
run npm install again.

However, I do the above suggested things, and I still get the same error.  I'm not sure where to begin.
Angular is installed locally on my MacBook Pro, and the API is a backend API call that is all setup.
EDIT EDIT EDIT
Contents of package.json
    {
  "name": "angular2-registration-login-example",
  "version": "1.0.0",
  "repository": {
    "type": "git",
    "url": "https://github.com/cornflourblue/angular2-registration-login-example.git"
  },
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "license": "MIT",
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.2.0",
    "systemjs": "^0.19.47",
    "zone.js": "^0.8.5"
  },
  "devDependencies": {
    "@angular/cli": "^1.4.3",
    "@angular/compiler-cli": "^4.4.3",
    "@types/node": "^6.0.60",
    "concurrently": "^3.1.0",
    "lite-server": "^2.3.0",
    "typescript": "^2.2.2"
  }
}

EDIT
After doing the suggested install angular/compiler-cli --save-dev, I get this:
ng build --prod

To disable this warning run "ng set --global warnings.typescriptMismatch=false".

Cannot read property 'config' of null
TypeError: Cannot read property 'config' of null
    at Class.run (/Users/adamcampbell/Documents/Development/appDir/member/node_modules/@angular/cli/tasks/build.js:15:56)
    at Class.run (/Users/adamcampbell/Documents/Development/appDir/member/node_modules/@angular/cli/commands/build.js:204:26)
    at resolve (/Users/adamcampbell/Documents/Development/appDir/member/node_modules/@angular/cli/ember-cli/lib/models/command.js:273:20)
    at Class.validateAndRun (/Users/adamcampbell/Documents/Development/appDir/member/node_modules/@angular/cli/ember-cli/lib/models/command.js:251:12)
    at Promise.resolve.then.then (/Users/adamcampbell/Documents/Development/appDir/member/node_modules/@angular/cli/ember-cli/lib/cli/cli.js:154:24)

A: Your package.json do not have complier-cli installed. By running this command -> install it.
npm install @angular/compiler-cli --save-dev

A: You need to copy your .angular-cli.json file to the root folder of your application.
Trace your error code from line 15 of /node_modules/@angular/cli/tasks/build.js
const config = config_1.CliConfig.fromProject().config;

tracing it further, we find config_1, which is defined on line 9
const config_1 = require("../models/config");

so we head over to ../models/config.js where we find that fromProject() returns null if it can't find the config file, which points here:
exports.CLI_CONFIG_FILE_NAME = '.angular-cli.json';
const CLI_CONFIG_FILE_NAME_ALT = 'angular-cli.json';

So if you don't see .angular-cli.json in the root directory of your app, you need to copy it there.

A: Well, this error may come in many situations like.
aot/prod build problem
add/install reflect-metadata will resolve the problem. Any one facing the issue after angular 4 and have cli may help this.
npm i --save-dev reflect-metadata

you upgraded your node and npm in system
In this case, the node modules are old and it will show error in your project. You can delete node_modules folder and package-lock.josn and do a npm install will work.
some problem in node module or sync
Just delete node_modules folder and package.json file and do a npm i some time resolves the problem.
their is problem with cli version, missing dependencies, etc.
Check all the version like node, npm cli etc and see if they are compartable.
This kind of problem mostly happens when we upgrade something.


text:
Q: How to change multiple column names in pandas according to a criteria I have a dataframe like this -
Country|1980 YR1980|1981 YR1981|1982 YR 1982|...
     A | 1         |  -        |   2        |...
     B | -         |  1        |   2.5      |...
     c | -         |  0.433    |   4.7      |...

My aim is to remove from the column names: YR.... part. Actually I want to visualise the data and have years on my Y axis and countries on X axis and map the datapoints to the table.
Another idea is to plot a world map and make a slider below for years.
And my understanding is that for either case, we need the years to be integers.
My table has years in range - 1980 to 2013 (total 33)
I tried doing this:
list1= [i for i in range(33)]
new_Index=[str(i) for i in list1]
df = df.iloc[:,1:34].columns= new_Index

But got error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-6cf1843506e9> in <module>()
      1 list1= [i for i in range(33)]
      2 new_Index=[str(i) for i in list1]
----> 3 df = df.iloc[:,1:34].columns= new_Index

AttributeError: 'list' object has no attribute 'iloc'

Can anyone help me please.

A: If need values of columns before first space use str.split with selecting by str:
df.columns = df.columns.str.split().str[0]

If need set values use lists joined by +:
#exclude 2013
df.columns = df.columns[:1].tolist() + list(range(1980, 2013))

#include 2013
#df.columns = df.columns[:1].tolist() + list(range(1980, 2014))

A: I think this should do it:
x = df.columns.tolist()
new_cols = [x.split()[-1].strip('YR') for x in x]


text:
Q: Function doesn't want to return string slice using function arguments I tried making a function that returns a string slice. The function takes three arguments:

*

*a the start of the slice

*b the end of slice

*txt a reference to a string literal

fn main() {
    let text = String::from("My name is Ivan");

    fn get_slice(a: u8, b: u8, txt: &String) -> &str {
        &txt[a..b]
    }

    println!("{}", get_slice(4, 8, &text));
}

The compiler tells me:
error[E0277]: the type `String` cannot be indexed by `std::ops::Range<u8>`
 --> src/main.rs:5:10
  |
5 |         &txt[a..b]
  |          ^^^^^^^^^ `String` cannot be indexed by `std::ops::Range<u8>`
  |
  = help: the trait `Index<std::ops::Range<u8>>` is not implemented for `String`

If I replace the range [a..b] with [2..7] or any other number range it works.

A: Two things to take into consideration, slices use usize instead of u8. Also you would probably want to use &str instead of &String:
fn get_slice(a: usize, b: usize, txt: &str) -> &str {
    &txt[a..b]
}

Playground


text:
Q: Increment a number in the name of textbox public void test()
    {
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        for (int i = 1; i <= list.Count; i++)
        {

            textBx.Text = list[i].ToString();
            // I want it to be textBx1.Text = list[1].ToString();
                               textBx2.Text = list[2].ToString();
                               textBx3.Text = list[3].Tostring();
                               etc.
              // I can't create textbox dynamically as I need the text box to be placed in specific places in the form . How do I do it the best way?

        }

    }

A: Sounds like a job for Controls.Find(). You could dynamically build your string and search for the TextBox with that name:
 var textBox = this.Controls.Find("textBx" + i, true) as TextBox;
 textBox.Text = list[i].ToString();

This is a bit ugly as it's predicated on your naming convention for the TextBoxes. Perhaps a better solution would be to cache a list of the TextBoxes before your loop:
var textBoxes = new[] { textBx1, textBx2, textBx3 };

Then you can simply index into the array:
textBoxes[i].Text = list[i].ToString();

A: +1 to Matt. Here's a complete solution that works:
        string TextBoxPrefix = "textBx";
        foreach (Control CurrentControl in this.Controls)
        {
            if (CurrentControl is TextBox)
            {
                if (CurrentControl.Name.StartsWith(TextBoxPrefix)) {

                    int TextBoxNumber = System.Convert.ToInt16(CurrentControl.Name.Substring(TextBoxPrefix.Length));

                    if (TextBoxNumber <= (list.Count - 1))
                    {
                        CurrentControl.Text = list[TextBoxNumber].ToString();
                    }
                }
            }
        }


text:
Q: Div not displaying over video I have few simple divs and a video as a background:

                        <video width="1024" height="704" id="vid" loop>
                            <source src="images/reverse.mp4" type="video/mp4">
                        </video>

        #vid {
            width: 100%;
            height: 100%;
        }
        #overlay {
            position: absolute;
            display:block;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            z-index: 1000;
        }
        #man-photo {
            position: absolute;
            top: 200px;
            left: 300px;
            z-index: 1200;
            display: block;
        }

All are inside a indagerous swiper slide.
The video is shown correctly, image is positioned correctly but its not visible!
First time such thing ever happened to me: when I inspect it in developer tools and change any of its property, suddenly it gets drawn as expected.
Any idea how to overcome this?

A: Apparently chrome has some problems with redrawing images over video.
But:
setInterval(function(){$('#man-photo').hide().show(0)},100);

fixed it.
Not the tidiest solution but it is working.


text:
Q: What does the notation $\mathbb{P}V$ mean for a vectorspace $V$? In algebraic geometry, I keep seeing the notation $\mathbb{P}V$ when $V$ is given as a vectorspace. My best guess is that $\mathbb{P}V$ is to mean the projective closure of $V$. But it would be nice to know if this notation is standard, and if so, what the precise definition is so there is no confusion on my part.

A: I would expect this to mean the projective space defined by $V$: the space nonzero vectors modulo the relation $r\vec{v} \sim \vec{v}$ whenever $r \neq 0$.
So, for example, $\mathbb{P} \mathbb{R}^3$ is the usual real projective plane.

A: The symbol $\mathbb{P}V$ stands for the projectivisation of the vector space $V$. The one-dimensional linear subspaces of $V$ are the elements of $\mathbb{P}V$.
If $V$ is a vector space over the field $\mathbb{K}$, then the projectivisation $\mathbb{P}V$ of $V$ is the quotient space $(V \setminus \{0\}) /\sim$ where, given $u,v \in V \setminus \{0\}$ we have $u \sim v$ if and only if there exists a non-zero $\lambda \in \mathbb{K}$ for which $u = \lambda v$.
For a fixed $v \in V \setminus \{0\}$, the set of all $u \in V \setminus \{0\}$ with $u \sim v$ are of the form $\lambda v$. This set of vectors can be identified with the span of $v$.

A: In algebraic geometry, the projective space $\mathbb P(V)$ associated to a vector space $V$ is $\mathrm{Proj}(\mathrm{Sym}(V))$, see EGA, II.4.1.1. In particular, the $k$-rational points of $\mathbb P(V)$ are the linear forms modulo $k^*$:
$$ \mathbb P(V)(k) = (V^{\vee} \setminus \{ 0\})/k^*.$$
In other words, they are hyperplanes of $V$. A good reason is that if you want to generalize to projective scheme associated to a coherent sheaf $\mathscr E$ over a scheme $S$, you take $\mathrm{Proj}(\mathscr Sym(\mathscr E))$. If you take $ \mathrm{Proj}(\mathscr Sym(\mathscr E)^{\vee})$ instead, you lose much information from $\mathscr E$ because, for instance, taking the dual kills the torsions of $\mathscr E$.
Edit Another reason over a field. Consider the projective space $\mathrm{Proj}(k[t_0, \dots, t_n])$. It is natural to consider it as $\mathbb P(V)$ where $V=kt_0+\cdots+kt_n$. Now if you have surjective homomorphism
$$ \phi: k[t_0, \dots, t_n] \to k[s_0, \dots, s_m]$$
of homogeneous $k$-algebras, you have a surjective linear map
$$ \phi_1: V \to E=ks_0+\cdots +ks_m.$$
We know that $\phi$ induces a morphism
$$ \mathbb P(E) = \mathrm{Proj}k[s_0, \dots, s_m]\to \mathbb P(V).$$
On the level of rational points, with EGA's definition, it corresponds to
$$ E^{\vee} \setminus \{ 0\} /k^* \to V^{\vee} \setminus \{ 0\} /k^* $$
which is correct (given by the injective $\phi_1^*$). But if use the defintion of lines, you need a linear map
$V\setminus  \{ 0\}\to E\setminus \{ 0\}$ and this is impossible if $\phi_1$ is not injective.
Of course, over a field, people usually do not notice the difference between $V$ and its dual, and this is harmless in general if you only work over fields.


text:
Q: How can I harness a loading gif from a different page? I'd be really grateful for some help to solve this brain teasing problem!

*

*We have a website which is hosted on one server.

*We also have a web-based application which is hosted on a different server because it uses different technology (QlikView).

What we've done is make the application look like it's part of the website by using an iFrame to pull in the application.  The code we've used to do this is shown below:

This works fine.  But the application takes a good 20 seconds to load.  During that time, the user is presented with the header and footer of the website but other than that it's just blank.  There's no sign that anything's happening or that the application's loading.
The application does have a loading gif whilst it's loading if you view it directly rather than through the iFram, but it's positioned at the top right corner of the page, so it's completely out of view of the iFrame.  The loading gif appears in a div with id="InitialLoader".
We don't have control over the code of the application (e.g. to move the loading gif).  But we can edit the code in the website.  I wondered if it would be possible to harness that loading symbol somehow and display our own loading symbol (or indeed the same symbol) as long as that is visible in the application?
One idea I've had is to use jQuery .load, but not sure whether this is feasible?  The loading symbol is not permanently displayed, only when the page is loaded.  I want to display it on our web page when it is being loaded by a specific user.  Here's an example of the code I was thinking of:
jQuery

Html

I'm very open to suggestions if there are other methods!  It would also be good to know whether the above is feasible?  It's difficult for me to test in the website as I get charged by our agency, so want to be sure before committing!
Many thanks,
Katie

A: Ok, I believe the problem you are having is that you are doing the following:
1) You are loading a iframe with a img tag all ready set in it...
2) Asking with jquery if the img has loaded, or applying a onload attribute to it will only fail as the tag has allready been rendered and the DOM does not support this logic it seems.
An option I found is to manually set the source once the document has loaded for the img (if it is possible), the jFiddle gives a quick example.
$(document).ready(function(){
    $('img').attr('src', 'http://onerahi.cabu.school.nz/files/2012/09/goes-12-firstimage-large081701.jpg').load(function() { alert('loaded'); });
}
);

http://jsfiddle.net/7E6zQ/

#

Ok so, take the existing image and remake it and add it onto the dom with a new onload function, I think this achieves your result, new fiddle attached.
http://jsfiddle.net/yNGV7/
$('document').ready(function(){
    var newimg = new Image();
    newimg.src = $('img').attr('src');
    newimg.onload = function() {
         //remove loading msg
        $('.ctx-menu-text').remove();

            //hide the div
        $('#InitialLoader').fadeOut(1000);
    }

    $('img').replaceWith(newimg);
});

A: Thanks John for your example - it's great to be able to see it on jsfiddle!
From what I understand, you've created some code which displays an alert when the image has finished loading.  Perhaps this can be used for my purposes with a little tweaking?  I'm not sure how.  Here's what I'd need to achieve:
Whilst application is loading
Whilst the application is loading, the loading gif container div on www.application-blah.co.uk looks like this:

Loading...

I would like a loading message to be displayed on www.mysite.com whilst this div is visible on www.application-blah.co.uk.
Once the application has finished loading
Once the application has loaded, the style of the div containing the loading gif changes to style="display:none" as below.

Loading...

I would like the loading message on www.mysite.com to disappear when this happens.
Hope that makes sense!  I know it's not an ideal scenario!
Thanks again!
Katie

A: You can actually try to move the DIV in the frame itself.
The DIV "InitialLoader" is controlled by CSS in Qlikview.
It's possible to edit the CSS to position the DIV at the center of the page.
Then you can edit the "Loading..." text to something else in "opendoc.htm".


text:
Q: Scheduling method run at exact time I'm looking to schedule a method to run at an exact time selected by the user, and end at a time selected by the user. The user selects a time in the setup phase of my application and that value is stored in NSUserDefaults.
I then want the application to execute the method at the selected time which will also then end at a selected time.
I have seen a lot of people suggesting using UILocalNotifications but that is now deprecated in iOS 10. NSTimer is also suggested quite frequently but more often than not it is shot down for not being accurate enough.
What would be my best approach to implement this?


text:
Q: Change Wrap Strategy in Google Sheets with Ruby Is it possible to change Wrap Strategy programmatically? I've already tried with
batch_update_spreadsheet documentation
service.batch_update_spreadsheet

and
stackoverflow question
batch_update

but neither worked.
It always return Invalid Request.
My request, as I understand from here, is just
service.batch_update_spreadsheet([{ 'wrapStrategy': 'WRAP' }])
What am I doing wrong? I want to change all cells from my sheet.
Thanks

A: From service.batch_update_spreadsheet([{ 'wrapStrategy': 'WRAP' }]) and I want to change all cells from my sheet., I guessed that your goal is as follows.

*

*You want to reflect 'wrapStrategy': 'WRAP' to a sheet in a Google Spreadsheet using googleapis for ruby.

*You have already been able to get and put values to Google Spreadsheet with Sheets API.

In this case, how about the following sample script?
Sample script:
spreadsheet_id = '###' # Please set your Spreadsheet ID.
sheet_id = '###' # Please set your sheet ID.

request_body = {
  requests: [{repeat_cell: {
    range: {
      sheet_id: sheet_id,
    },
    cell: {
      user_entered_format: {
        wrap_strategy: 'WRAP'
      }
    },
    fields: 'userEnteredFormat.wrapStrategy'
  }}]
}
service.batch_update_spreadsheet(spreadsheet_id, request_body, {})

*

*When this script is run, the wrapStrategy of sheet_id is set as WRAP.

*In this case, please use the snake case for the keys instead of the camel case. Please be careful about this.
Note:

*

*In this sample script, it supposes that your client of service can be used for updating the spreadsheet. Please be careful about this.

References:

*

*Method: spreadsheets.batchUpdate

*RepeatCellRequest


text:
Q: console command: log data to a specyfic file (Symfony3 and monolog) I have a console command as a service.
I would like to log, that the command was executed in a log file called foo.log - and no other logs to be placed there.
I have almost done it, but:
in case A, I get all logs to my specyfic file (not only the one i want)
in case B, I get my specyfic log to foo.log file, but other logs i get on console screen when run consol command.
command file
class A extends command
{
    (...)
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        (...)
        $this->logger->info('done it');
    }
}

services.yml
sender.command.fetch.and.send:
    class: ReportsBundle\Command\SendReports
    arguments:
      - "@sender.reports.worker"
      - "@logger"
    tags:
      - { name: console.command }
      - { name: monolog.logger, channel: sender}

case A (config.yml) - when i get all logs to foo.log
monolog:
    handlers:
        sender:
            type:     stream
            path:     '%kernel.logs_dir%/foo.log'
            channels: ~

case B (config.yml) when i get unwanted logs on screen
monolog:
    channels: ['sender']
    handlers:
        sender:
            type:     stream
            path:     '%kernel.logs_dir%/foo.log'
            channels: sender

unwanted logs:
(...)
[2016-10-11 20:48:28] doctrine.DEBUG: SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED [] []
[2016-10-11 20:48:28] doctrine.DEBUG:  [] []
[2016-10-11 20:48:28] event.DEBUG: Notified event "{event}" to listener "{listener}". {"event":"console.exception","listener":"Staffim\\RollbarBundle\\EventListener\\RollbarListener::onConsoleException"} []
(...)

A: I believe you just need to level down your verbosity level
See in documentation:
# app/config/config.yml

monolog:
    handlers:
        console:
            type:   console
            verbosity_levels:
                VERBOSITY_NORMAL: NOTICE
            channels: sender


text:
Q: Invalid read of size 4 Hello there I have the following code:
struct Edge
{
    Node * nodeA, * nodeB;
    int weight;
};
.
.

This is typedef'd to simply Edge elsewhere.
.
.

int cmp(const void *b, const void *a)
{
    Edge * e1 = (Edge*)a;
    Edge * e2 = (Edge*)b;
    printf(" %d++", getWeight(e1));
    printf(" %d++", getWeight(e2));
    if (getWeight(e1) != getWeight(e2))
        return (getWeight(e1) < getWeight(e2)) ? -1 : 1;
    return 0;
}

void sortEdges(Edge ** edgeList, int numEdges)
{
    qsort(edgeList, numEdges, sizeof(Edge*), cmp);
}

Valgrind tells me that I have an Invalid read of size 4, and when I output the value for the the edge weights I get totally unexpected results. I can only conclude that there is something wrong with my cast to an Edge* or that the sizeof is somehow not doing what I think it is. If you need any information please let me know.

A: There are two ways to correct your code.
1. if edgeList is a array of (Edge *).
int cmp(const void *b, const void *a)
{
    Edge ** e1 = (Edge**)a;//notice
    Edge ** e2 = (Edge**)b;//notice
    printf(" %d++", getWeight(*e1));//notice
    printf(" %d++", getWeight(*e2));//notice
    if (getWeight(*e1) != getWeight(*e2))//notice
        return (getWeight(*e1) < getWeight(*e2)) ? -1 : 1;//notice
    return 0;
}

void sortEdges(Edge ** edgeList, int numEdges)
{
    qsort(edgeList, numEdges, sizeof(Edge*), cmp);
}

2, if edgeList is a array of Edge.
int cmp(const void *b, const void *a)
{
    Edge * e1 = (Edge*)a;
    Edge * e2 = (Edge*)b;
    printf(" %d++", getWeight(e1));
    printf(" %d++", getWeight(e2));
    if (getWeight(e1) != getWeight(e2))
        return (getWeight(e1) < getWeight(e2)) ? -1 : 1;
    return 0;
}

void sortEdges(Edge * edgeList, int numEdges)//notice
{
    qsort(edgeList, numEdges, sizeof(struct Edge), cmp);//notice
}


text:
Q: Android Studio error in Environment.java cannot resolve symbol com.google.android I downloaded and install Java Version 8 JDK.
Android Studio is at latest update.
My build.gradle file has:
android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')
    }

The android manifest has:
    uses-adk android:minSdkVersion="9"
It also has:
    "android:targetSdkVersion="10""
In the Environment.java, the: import com.google.android.collect.Lists;
shows "android" in red with cannot resolve symbol 'android'.
Should I, perhaps, uninstall Java JDK 8 and re-install Java JDK 7?

A: Android Studio currently supports only java 6 and 7. Try to use java 7. See android studio installation specs.
For java 7 use compile options in your gradle project.
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}


text:
Q: Check if memory is on the Heap? I have a class who's constructor takes the address of an object as a parameter.
MyClass(OtherClass * otherClass);

In the Destructor of this class I try to delete the instance of OtherClass.
~MyClass() {
    if(otherClass != nullptr) {
        delete otherClass;
    }
}

The issue I'm having is when I call this constructor I call it with an element from the stack instead of from the heap, thus I call it as below:
MyClass myClass(&otherObject);
so when the myClass object goes out of scope I get an exception. How can I fond out if my OtherObject variable was declared on the stack or the heap? Or in other words, how can I know if I can delete the object?

A: While there are system specific approaches which will probably be able to tell whether memory is from heap or from a stack, that actually doesn't really help: you may have got a pointer to a member of another object on the heap. The memory would be on the heap but you are still not responsible for deleting the object. Put differently: do not go down the path you are on!
The proper way to deal with the problem is to make the ownership semantics blatantly clear in the interface and go with that. There are essentially two directions you can take:

*

*Your class can deliberately not take over responsibility for the pointer passed in the constructor! Instead, it is the responsibility of the user of your class to deal with these objects and to guarantee that they are valid while your objects exists. If you can get pointers to stack (or member) objects the user already has to guarantee the validity of these objects anyway and for other ways it may be entirely trivial for the user to deal with them, e.g., by managing them via a std::unique_ptr<OtherClass>.

*Your class takes responsibility of all objects passed and it will delete all of them. It becomes the responsibility of the caller to not pass pointers to objects managed elsewhere, e.g., to objects on the stack or member objects.

There is sort of a hybrid approach where your class takes responsibility of objects some times but not always. However, the implementations of such an approach is really a combination of the two approaches above: you'd take a suitable smart pointer as constructor argument and it is the user's responsibility to make sure that the smart pointer is constructed appropriately by the user of your class. For example, your class could take a std::shared_ptr<OtherClass> for which the normal construction will delete the object. When the user wants to pass in a pointer to an otherwise owned object the std::shared_ptr<OtherClass> would be constructed with a deleter which does not delete the pointer. Here is a simple program demonstrating the two different management strategies for std::shared_ptr:
#include <iostream>
#include <memory>

struct foo {
    char const* name;
    foo(char const* name)
        : name(name) {
        std::cout << "foo::foo(" << name << "): " << this << "\n";
    }
    ~foo() {
        std::cout << "foo::~foo(" << name << "): " << this << "\n";
    }
};

int main() {
    std::shared_ptr<foo>(new foo("heap"));
    foo f("stack");
    std::shared_ptr<foo>(&f, [](auto){});
}


text:
Q: How can I change Checkbox color when I click and unclick? When I click on checkbox color change of that checkbox and rest of check box remain another color so how can I change the color of checkbox ?
if (CountryList.get(pos).getSelected()) {
    CountryList.get(pos).setSelected(false);
    holder.country.setBackgroundResource(R.color.btnbckgrd);
} else {
    CountryList.get(pos).setSelected(true);
    holder.country.setBackgroundResource(R.color.lightgreen);
}

A: try this:
mSelectedItem = -1;
holder.country.setBackgroundResource(mSelectedItem == position ?
R.color.lightgreen: R.color.btnbckgrd);

A: you can use style for this
<style name="yourStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">your_color</item> <!-- for uncheck state -->
    <item name="android:textColorSecondary">your color</item> <!-- for check state -->
</style>

set it in xml like this
<CheckBox
     android:theme="@style/yourStyle"
/>

A: Have you tried android:tint="@color/your_color" in your layout file??

A: Correct answer which is working on all API would be:
Create style:
<style name="CheckBox">
        <item name="colorControlNormal">@color/light_grey</item>
        <item name="colorControlActivated">@color/ts_white</item>
    </style>

and use it like this:
   <androidx.appcompat.widget.AppCompatCheckBox
                  .....
                    android:theme="@style/Bonus.CheckBox"
                  ..... />

after setting style you wont going to need to check views background programmaticaly

A: try this:
  final CheckBox cbox= (CheckBox) findViewById(R.id.cb_flash);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Set the Flash CheckBox Text Color
            cbox.setTextColor(Color.BLUE);

            // Set the Flash CheckBox Background Color
            cbox.setBackgroundColor(Color.parseColor("#cbff75"));
        }
    });

 if(checkbox.isChecked()){
   cbox.setTextColor(Color.BLUE);

            // Set the Flash CheckBox Background Color
            cbox.setBackgroundColor(Color.parseColor("#cbff75"));

  }else{
 //chenge color
   }

refer this link another method


text:
Q: How to publish a (csv, xlsx, etc) file from SAS DIS via email So I have some SAS DIS jobs which create "kickout" data when run - by this I mean that if things run smoothly, none of the "kickout" data is generated, but it is known that there will be exceptions and I would like to have those exceptions put into a table and automatically emailed to me so that I am notified when something is behaving in a non-ideal manner.
I can create a transformation which will send an email containing the data I'm looking for, but the data is formatted as html and thus not in a form conducive to analysis. I'd like the transformation to email a .csv file which is more easily manipulated.
There is the option to send a .spk file but I'm having issues getting that to work and in any case am not sure it really suits my needs.
Is what I want possible, with or without the standard Publish to Email transformation provided by SAS DIS? Looking at the SAS DIS user guide I'm guessing that there is no pre-built transformation which does what I want, but can the base SAS code accomdate this requirement?
Thanks much!

A: The "Publish to Email transformation" uses ODS HTML to generate the output so you'll get a HTML output. If you want an XLS output then there is a way. You could change the extension of the output file to xls to generate xls file from the ODS HTML. This is an old way of generating xls from ODS HTML.
Now coming to the SPK file. This is something you should look into. Since you are looking into getting an xls/csv attachement which you can open and do some manipulation etc. SPK file is like a ZIP file. You can right click and unzip spk file. Basically you can put in all your files within a archive/spk file and get that emailed as attachement using the "Publish to Email Transformation"
To get this done, go to the properties of the "Publish to Email Transformation" and Under Publishing option=>

*

*select Send report in an archive (.spk) file as an email attachment in the Select viewer file/attachment option field

*provide folder/path where the spk file would be stored under Select path of where to store archive file containing report

*provide the name of the spk file under Specify filename of archive file containing report

*provide name=value pair of the package under Specify one or more desired package name/value pairs for package. For example this transformation is generating a PROC PRINT of an INPUT data set and the output file is c:\sushil\test.html then enter myname=(test.html) . The myname is for labeling purpose when you unzip the spk you should get test.html

Now Under REPORT SPECIFICATION option in the "Publish to Email Transformation"  transformation select "Generate PROC PRINT from input table" and then enter the path and filename of generated report which based on our previous entry should be c:\sushil\test.html
Also, to select "Generate PROC PRINT from input table" you would need to right click the "Publish to Email Transformation" and select Ports -> Add Input Port. This how you can connect a table with the transformation. Now this is the minimum settings required to generate spk package from the transformation. Let me know if it helps!!
Note: This information is as per SAS DI Studio 4.6. I don't know if the transformation is updated in the newer version of DI Studio.


text:
Q: Can't update view/function 'cte' because it contains aggregates, when calculating times over 24 hours I have a datatable alarms with columns, two of which are: tmStartTime and tmEndtime. I want to calculate the total active time tmTotals in hours, this can be over 24 hours. So for example 24:00:04
my datatable Alarms (I used data type TIMEhere which worked fine for times less than 24 hour):
tmStarttime               tmEndTime                 tmTotals
--------------------------------------------------------------
2018-12-03 00:00:19.257   2018-12-04 00:00:23.288   00:00:04  (is actually 24:00:04)
2018-12-03 23:59:16.817   2018-12-04 00:01:42.942   00:02:26
2018-12-03 23:59:45.005   2018-12-04 00:07:03.650   00:07:18
2018-12-03 23:11:57.645   2018-12-04 00:07:16.785   00:55:19
2018-12-04 00:03:52.086   2018-12-04 00:07:37.991   00:03:45
2018-12-04 00:07:16.787   2018-12-04 00:08:14.302   00:00:57
2018-12-04 00:08:30.430   2018-12-04 00:08:34.480   00:00:04

With times over 24 hours I found I should do:
UPDATE Messages_History
SET tmTotals
= right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 3600 )),2) + ':'
+ right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 60 ) % 60 ),2) + ':'
+ right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) %60 )),2)

Here I got the error:
An aggregate may not appear in the set list of an UPDATE statement.

I then found I should do:
    WITH cte

    AS (SELECT new_tmTotals
    = right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 3600 )),2) + ':'
    + right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 60 ) % 60 ),2) + ':'
    + right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) %60 )),2), tmTotals
    FROM Messages_History
    GROUP BY tmTotals)

    UPDATE cte
    SET tmTotals = new_tmTotals

When executing the Stored Procedure I got the error:
Cannot update the view or function 'cte' because it contains aggregates, or a DISTINCT or GROUP BY clause, or PIVOT or UNPIVOT operator.

I'm a bit lost what I have to do now, I found something about deleting duplicate rows, but I need to keep duplicates.

A: As an alternative, you may try updating using a join:
UPDATE mh1
SET tmTotals = mh2.new_tmTotals
FROM Messages_History mh1
INNER JOIN
(
    SELECT
        tmTotals,
           RIGHT('0' + convert(varchar(9),
           (sum(datediff(second,tmStartTime,tmEndTime)) / 3600 )),2) + ':' +
           RIGHT('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 60 ) % 60 ),2) + ':' +
           RIGHT('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) %60 )),2) AS new_tmTotals
    FROM Messages_History
    GROUP BY tmTotals
) mh2
    ON mh1.tmTotals = mh2.tmTotals;

The basic issue with the error is that you are trying to update a derived (aggregated) table, and SQL Server is refusing to decide how the original underlying table should be updated.

A: Add Primary or Unique key to the Table to get resolved from this issue. And then use below one...
WITH cte

AS (SELECT UniqueID 'Uniq_ID',new_tmTotals = right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 3600 )),2) + ':'
+ right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) / 60 ) % 60 ),2) + ':'
+ right ('0' + convert(varchar(9),(sum(datediff(second,tmStartTime,tmEndTime)) %60 )),2), tmTotals
FROM Messages_History
GROUP BY tmTotals)

UPDATE cte
SET tmTotals = new_tmTotals
WHERE UniqueID = Uniq_ID


text:
Q: Fixed issue when using send-crypto module I've found the issues when I tried to send btc from one wallet to another using withdraw function. I built withdraw function using send-crypto
 const CryptoAccount = require("send-crypto");
 const withdrawWallet = async () => {
       ............................
       const walletAddress = ".........";
       const account = new CryptoAccount(privateKey);
       const walletBalance = await account.getBalance("BTC");
       const txHash = await account`your text`
        .send(walletAddress, walletBalance, "BTC", {
          subtractFee: true,
        })
        .on("transactionHash", console.log)
        .on("confirmation", console.log);
 }

It works well on localside,so I hosted the project online. but unfortunately, the function makes errors online. like that "expected property "1" of type BigInteger, got n"
Please let me know the btc withdraw function that used bitcoinjs-lib or others.


text:
Q: Hide all Divs except last 2. Number of Divs can increase I want to hide all the Divs except Last 2. Number of Divs can increase in my case.
I have searched some topics, so now i became able to hide all except last 1 div.
Here is my Code so far: http://jsfiddle.net/D83ZC/11/
HTML:

 This is Div 1

 This is Div 2

 This is Div 3

 This is Div 4

 This is Div 5

CSS:
.container{
    border:black 1px solid;
}

Jquery:
$('.container').not(':last').hide();

A: Use the .slice() method.
$(".container").slice(0, -2).hide();

This behaves the same as Array.prototype.slice, where the second index you provide may be a negative number which counts back from the end.
This will be very fast, and has the benefit of not relying on non-standard selectors included with jQuery (via Sizzle), which means the browser's native selector engine will do the initial DOM selection.

A: You can use the CSS3 selector nth-last-child
$('.container:nth-last-child(n+3)').css('background-color', 'red');

updated demo
This will select all items that match n+3 for n begining from 0, so this is the third, fourth, and so on; begining from the last


text:
Q: How to draw checkbox without 3d frame I use the DrawFrameControl function to draw a checkbox:
DrawFrameControl(hdc, &r, DFC_BUTTON,  DFCS_CHECKED);

and this is result:

But I do not need a 3d frame, I need a simple 1-pixel frame like this:

if I pass to DrawFrameControl function a DFCS_FLAT flag, then I get a bold frame:

Is there a way to draw a checkbox with a 1-pixel border?

A: Use DrawThemeBackground to draw check box in different states.
See also
Parts and States
Visual Styles Reference
HTHEME htheme = OpenThemeData(hwnd, L"BUTTON");
if(htheme)
{
    DrawThemeBackground(htheme, hdc, BP_CHECKBOX, CBS_CHECKEDNORMAL, &rc, 0);
    CloseThemeData(htheme);
}

Required headings and libraries:
<Uxtheme.h>
<vsstyle.h>
"Uxtheme.lib"

A: I need to draw a checkbox image exactly the same as it looks in the network adapter properties window, for example:

Why I don't want to use the DrawThemeBackground function? First, I need to draw the appearance of the checkbox exactly the same as described above. Secondly, the DrawThemeBackground function will only works if the Windows theme is enabled, and the checkbox will look themed.
DrawFrameControl function draws the 3d border with the checkbox. This does not fit.
so I decided to write checkbox drawing code using Rectangle, MoveToEx and LineTo functions:
HPEN old_pen = (HPEN)SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(128, 128, 128)));
HBRUSH old_brush = (HBRUSH)SelectObject(hdc, CreateSolidBrush(RGB(255, 255, 255)));

Rectangle(hdc, 0, 0, 11, 11);
DeleteObject(SelectObject(hdc, old_pen));
DeleteObject(SelectObject(hdc, old_brush));

old_pen = (HPEN)SelectObject(hdc, CreatePen(PS_SOLID, 2, RGB(0, 0, 0)));

MoveToEx(hdc, 1, 4, NULL);
LineTo(hdc, 5, 8);
MoveToEx(hdc, 4, 7, NULL);
LineTo(hdc, 9, 2);

DeleteObject(SelectObject(hdc, old_pen));
old_pen = (HPEN)SelectObject(hdc, CreatePen(PS_SOLID, 1, RGB(255, 255, 255)));

MoveToEx(hdc, 1, 3, NULL);
LineTo(hdc, 1, 6);
MoveToEx(hdc, 1, 6, NULL);
LineTo(hdc, 4, 9);
MoveToEx(hdc, 4, 9, NULL);
LineTo(hdc, 9, 4);
MoveToEx(hdc, 9, 4, NULL);
LineTo(hdc, 9, 1);

DeleteObject(SelectObject(hdc, old_pen));

And I got the desired result:


text:
Q: Invalid Syntax for CTE what in the world could be wrong, the syntax looks fine:
With photos(PhotoID, MemberID) as
(
    select  photoID,
            memberID
    from MemberPhotos
)
select PhotoID, MemberID from photos

A: If the CTE follows from another query, you should add a semi-colon before the WITH keyword.
;With photos(PhotoID, MemberID) as
(
    select  photoID,
            memberID
    from MemberPhotos
)
select PhotoID, MemberID from photos


text:
Q: Как сделать открытие модального окна через метод .sheet для ipad и через .fullScreenCover для iPhone? Хочу сделать расширение для SwiftUI View которое открывает модальное View через метод .sheet для iPad и через метод .fullScreenCover для iPhone.
Пробовал так:
extension View {

    public func modal<Item, Content>(
        item: Binding<Item?>,
        content: @escaping (Item) -> Content) ->
        some View where Item : Identifiable, Content : View {
        if UIDevice.current.userInterfaceIdiom == .pad {
            return sheet(item: item, content: content)
        } else {
            return fullScreenCover(item: item, content: content)
        }
    }

}

Но получаю ошибку:
Function declares an opaque return type, but the return statements in its body do not have matching underlying types

A: Заверните в AnyView:
extension View {

    public func modal<Item, Content>(
        item: Binding<Item?>,
        content: @escaping (Item) -> Content) ->
        some View where Item : Identifiable, Content : View {
        if UIDevice.current.userInterfaceIdiom == .pad {
            return AnyView(sheet(item: item, content: content))
        } else {
            return AnyView(fullScreenCover(item: item, content: content))
        }
    }

}


text:
Q: Cannot enter input in cgdb on Linux Ubuntu 14.04 Here is my very simple program that I am trying to debug with cgdb. Problem is once I get to the "scanf" line, it prompts for an input, but once I press enter after entering the input (2 in the example below) it seems to enter into an infinite loop. It works fine in gdb though.
#include <cstdio>
using namespace std;

int main()
{
    int n;
    scanf("%d", &n);
    printf("%d\n", n);
    return 0;
}

Here is the execution trace in terminal:
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...done.
(gdb) start
Temporary breakpoint 1 at 0x400585: file test.cpp, line 7.
Starting program: /home/Alex/Desktop/test
Temporary breakpoint 1, main () at test.cpp:7
(gdb) next
2 (this is my input)
Infinite loop starts here.

A: According to the info page of cgdb, you need to either:

*

*start the program on one terminal, and attach to it with CGDB from another terminal

*or pass arguments using the tty window

To invoke the tty window, hit 'T' in command mode (escape)
Extracted from the info page:

Sending I/O to the program being debugged
This technique is similar to getting in and out of "GDB mode".  The tty window is not
visible by default.  This is because it is only needed if the user
wishes to send data to the program being debugged. To display the tty
window, hit `T' while in command mode.


text:
Q: After Triggering the code, the Master workbook also getting closed without saving the file Option Explicit

Sub combine()

Dim wbk As Workbook
Dim wb As Workbook
Dim lr As Long
Dim ln As Long
Dim i As Integer

Application.AskToUpdateLinks = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set wbk = ThisWorkbook

wbk.Activate

lr = wbk.Sheets("Gov 1.01 Report").Cells(Rows.Count, "A").End(xlUp).Row
ln = wbk.Sheets("Gov 1.01 Report").Cells(Rows.Count, "A").End(xlUp).Row

    Dim fDialog As FileDialog
    Dim filename As String

    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    With fDialog
        .AllowMultiSelect = True
        .Title = "Please select the files"
        .Filters.Clear
        .Filters.Add "All supported files", "*.xls*"
        .Filters.Add "Excel files", "*.xls*"

        If .Show = True Then
            For i = 1 To .SelectedItems.Count
            'Opening selected file
        filename = .SelectedItems(i)

    Set wb = Workbooks.Open(filename)

    Dim lrow As Long
    Dim lrows As Long
     lrow = wb.Sheets("Gov 1.01 Report").Cells(Rows.Count, 1).End(xlUp).Row
     lrows = wb.Sheets("Gov 1.02 Report").Cells(Rows.Count, 1).End(xlUp).Row

     wb.Activate

     wb.Sheets("Gov 1.01 Report").Range("A2:X" & lrow).Copy

      wbk.Sheets("Gov 1.01 Report").Activate
     wbk.Sheets("Gov 1.01 Report").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
     ActiveSheet.Paste

     wb.Activate
     wb.Sheets("Gov 1.02 Report").Range("A2:X" & lrows).Copy

    wbk.Sheets("Gov 1.02 Report").Activate
    wbk.Sheets("Gov 1.02 Report").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
    ActiveSheet.Paste

     wb.Close True

    Next i
    End If
    End With
wbk.Save
Application.AskToUpdateLinks = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

the above code is for to pull the data from multiple workbooks and paste in the Master workbook within respective sheets. However, when I ran the code, it is closing all the workbooks even Master workbook ( I code it as wbk=thisworkbook). Could you please help me to resolve the issue?

A: I can't see anything in your code that would cause wbk to be closed however try this.
Option Explicit

Sub combine()

    Dim wbMaster As Workbook, wb As Workbook
    Dim ws As Worksheet, rngSrc As Range
    Dim fDialog As FileDialog, files, filename As String
    Dim lastrow As Long, i As Long, msg As String

    ' get list of files
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    With fDialog
        .AllowMultiSelect = True
        .Title = "Please select the files"
        .Filters.Clear
        .Filters.Add "All supported files", "*.xls*"
        .Filters.Add "Excel files", "*.xls*"

        If .Show = True Then
            Set files = .SelectedItems
        Else
            Exit Sub
        End If
    End With

    ' copy files to master
    Set wbMaster = ThisWorkbook
    Application.ScreenUpdating = False
    For i = 1 To files.Count
        filename = files(i)

        ' open workbook and copy sheets
        Set wb = Workbooks.Open(filename, False, True) ' no link update, readonly
        For Each ws In wb.Sheets
            If ws.Name Like "Gov 1.0[12] Report" Then
                lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
                Set rngSrc = ws.Range("A2:X" & lastrow)

                With wbMaster.Sheets(ws.Name)
                    lastrow = .Cells(ws.Rows.Count, "A").End(xlUp).Row
                    rngSrc.Copy .Range("A" & lastrow + 1)
                End With

                msg = msg & vbLf & wb.Name & " " & ws.Name & " " & rngSrc.Address
            End If
        Next
        wb.Close False
    Next
    Application.ScreenUpdating = True

    MsgBox "Copied:" & msg, vbInformation

End Sub