text:
Q: What does it mean that the current returns through the ground? What does it mean that the current returns through the ground? I mean, the current comes from the transformers to our house and then back through "ground".So if you return by "land" to complete the circuit. Is there a way to "intercept" this circuit or worse still is there the possibility of an accident?

A: There is no "returning to the ground" or "return by land" as such, since for current to flow, all you need is a potential difference and current will flow through the circuit, from one point to another of lower electrical potential.
The term ground simply refers to a reference point where the potential is taken to be zero (usually, but you can choose a number other than zero). Voltages are then measured relative to this reference point.
Originally (and commonly these days), in just about all of home and building wiring and electricity, the term "ground" referred to the actual physical earth, which is at a relatively constant potential. In this case, electrical cabling was physically connected to a rod that is pushed into the earth.
But nowadays, as pointed out in the comment by Jageber, the term "ground" is used in a lot of electrical appliances and products, even though they have no physical connection to the earth/ground. For example, if you look at the circuit diagrams (or even the circuit board) of your mobile phone or tablet device, you may find the term "ground" appear.
The possibility of harm from household devices or overhead cables etc., arises when a live wire finds path to the ground through your body (if you touch a live wire or electrified part of a device while another part of you touches the ground or wire/part connected to ground).


text:
Q: TaskCompletionSource cancellation with CancellationTokenSource does not update Task.Status? This seems unintuitive to me:
var cts = new CancellationTokenSource();
cts.Cancel();
var tcs = new TaskCompletionSource<int>();
try
{
    tcs.Task.Wait(cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine(tcs.Task.Status); //TaskStatus.WaitingForActivation
}

I'd expect it to update the status to TaskStatus.Canceled. What is the rationale behind leaving it in TaskStatus.WaitingForActivation?

A: You're misunderstanding Wait().
Wait(CancellationToken) allows you to cancel the wait operation.
It has no effect on the underlying task.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I set my window manager in Fedora 20 without using a graphical login prompt? I'm using Fedora 20 and I've disabled the graphical login so now when I boot I'm presented with a standard console to log into. When I log in and run startx I get Metacity. How can I change this on a per-user basis to be, say, Xfce or the Awesome window manager?
I figured I would have to edit .xinitrc but it's either getting ignored or I've got some syntax problems. I haven't found a lot of documentation on this; it seems like Fedora expects you to keep the GUI. Before I disabled the graphical login, I was able to change the window manager successfully so I know the other window managers do work.
Update: I've determined that either .xinitrc or .xsession is being looked at, and if neither of these files exist, then the default window manager is loaded. I believe I'm encountering some syntax problems. Consider this question solved.

A: Is there a startxfce command?
On one server I work with, startx would boot some ghetto Window Manager, but startxfce4 would start XFCE.
EDIT: fvwm is the name of the desktop environment that would start with startx


text:
Q: Oculus Virtual Desktop I would like to use Oculus Virtual Desktop with my work laptop so I could use Oculus to have several monitors when working remotely.
However, my company laptop only allows to install a restricted list of software, not including anything related to Oculus or Virtual Desktop.
Is there any workaround to this? Maybe installing Oculus Virtual Desktop in a 2nd device and connect it with an HDMI to my work laptop?


text:
Q: Upload Multiple Image when code moved to another laptop it shows error I did my best to debug this code in my first laptop and successfully worked it out but now when i move it to another laptop it suddenly began to show some errors again which i cannot understand the reason why.
Controller
public function uploadCollateralImage_Front()
{
    $config['upload_path'] = './uploads/files';
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = '2408';
    $config['max_width'] = '2408';
    $config['max_height'] = '2408';
    $this->load->library('upload', $config);
    if ( !$this->upload->do_upload('userfile1')){
        $error = array('error'.'hey' => $this->upload->display_errors());
        var_dump( $error); die;
    }else{
        $fileName = $this->upload->data();
        $post_image = $fileName['file_name'];
        // var_dump($post_image); die;
        return $post_image;
    }
}

View
<?php
     $attributes = array('name' => 'applicationform');
     $hidden = array('userfile1' => 'userfile1');
     echo form_open_multipart("Client_Dashboard/applicationPost",$attributes, $hidden);
    ?>

Front-view Image

        <input type="file" name="userfile1" class="w3-margin-left w3-col s10 w3-teal w3-medium w3-hover-white w3-wide " required/>

and my main method
public function applicationPost(){
 $data_vehicleinformation = array();
 $data_vehicleinformation['FrontImage'] = $this->uploadCollateralImage_Front();
 check_insert_user = $this->foo_app->apply_loan($data_log, $data_user,
 $data_loanapplication, $data_collateraldetails_app, $data_vehicleinformation ,
 $data_paymentdetails, $data_loanpayment, $data_loanapproval,
 $data_loanrequest);
}

it show some error like
array(1) { ["errorhey"]=> string(43) "
You did not select a file to upload.
" }
which totally means it did not end up saving in database. and i thought that my DB is the error maybe because of the collation or what other matter but its not it only show the error from function uploadCollateralImage()

A: as by your comment:

moved CI installation from PHP Version 5.6.23-windows8 to PHP Version
  5.5.11-Windows7 Ultimate

the Codeigniter 3.x manual says:

Server Requirements
PHP version 5.6 or newer is recommended.

please check all server requirements here


text:
Q: Setup a linked table in Access for a path which doesn't exist yet? How can we setup a linked table where the path doesn't exist yet?
We need to setup a linked table in Access for eventual use in a customer environment which doesn't have MS Access installed (the Access database is simply utilised as a backend via Jet).
We can use Jet & DDL on the customer's site to create/edit/drop tables in their .mdb but as far as I can tell you can't create linked tables using DDL.
In theory we can create the linked table here (where we have Access) and specify the "invalid" path using VBA like so (assume Kilimanjaro is the customer's server which doesn't exist on our network):
Function SetLinkedTablePath(tableName As String)
    Dim cdb As DAO.Database
    Set cdb = CurrentDb
    cdb.TableDefs(tableName).Connect = ";DATABASE=\\Kilimanjaro\Foo-Data.mdb"
    cdb.TableDefs(tableName).RefreshLink
    Set cdb = Nothing
End Function

However the .RefreshLink line attempts to validate the path so fails on our network.
If we comment out the .RefreshLink line and run it it executes fine, but checking Linked Table Manager in Access the new path hasn't taken.
Any solution to this? We'd prefer not to use a mapped drive.

A: If you don't have an actual server named Kilimanjaro on your local network then you could edit the hosts file on your machine to "fool" it into thinking that there is one. I just tried this with Access 2010 and it worked for me:
I opened a Windows command prompt "as Administrator" and issued the command
notepad C:\Windows\System32\drivers\etc\hosts

I added a line at the end of the file like so
192.168.1.109   Kilimanjaro

where 192.168.1.109 is the IPv4 address of my local test server (whose real name is something different). I saved the changes and exited Notepad.
Then in Access I was able to tweak the .Connect property of a linked table to point to \\Kilimanjaro like so:
Dim cdb As DAO.Database, tbd As DAO.TableDef
Set cdb = CurrentDb
Set tbd = cdb.TableDefs("TableX")
tbd.Connect = ";DATABASE=\\Kilimanjaro\Public\Database1.accdb"
tbd.RefreshLink
Set tbd = Nothing
Set cdb = Nothing

Since there really was a file named Database1.accdb on that UNC path Access had no problem with it, and I could open the linked table in Datasheet view as usual.

A: In the end we took a spare virtual machine on our network and temporarily renamed it to match our client's server (call it \\Kilimanjaro for example). Then we could create the linked table without any problem at all.
It's unsatisfactory and inelegant. But I'm going to accept this answer as it was our solution but if anyone ever comes up with a neater trick, I'd love to hear it.


text:
Q: Assign ArrayList to File[] in java How to assign ArrayList of String to File[] in java. I have tried as shown below
ArrayList<String> fileList;

File[] file;

for (int i = 0; i < fileList.size(); i++) {
    file = new File (fileList.get(i));
}

But I am getting file cannot be converted to File[]. Please correct me.

A: First, you need to initialize the array like
File[] file = new File[list.size()];

Now, you need to access the indexes of the array, like
for(int i = 0;i<fileList.size();i++) {
    file[i] = new File(list.get(i));
}


text:
Q: Create a fading animation using cairo.h i'm trying to make a function that can switch a window from dark mode to light mode and vice-versa. I managed to do it but now i want to add a sort of transition to the colors, where the white gets darker, and the grey gets lighter.
I've got this so far:
void paint_fade(cairo_surface_t* surface){

    cairo_t*cr=cairo_create(surface);

    if(darkmode){
        for(int i=1; i>0.2; i-=0.005){
            cairo_set_source_rgb(cr, i, i, i);
            cairo_rectangle(cr, 0, GUI_Y, getX_SizeWindow(), getY_SizeWindow()-GUI_Y);
            cairo_fill(cr);
            sleep(0.1);
        }
    }
    else{
        for(int i=0.2; i<1; i+=0.005){
            cairo_set_source_rgb(cr, i, i, i);
            cairo_rectangle(cr, 0, GUI_Y, getX_SizeWindow(), getY_SizeWindow()-GUI_Y);
            cairo_fill(cr);
            sleep(0.1);
        }
    }

    cairo_destroy(cr);
}

But this doesn't seem like it works, does anyone know why?

A: Pango does not update the contents of the window immediately. It waits till it is in the main event loop. Your requests are put in a queue, and that queue can only by processed in the event loop. To fix this, include GTK+, if you have not already, and put that code inside of a timout. Then you will have to use static variables so you can save you variables state from timeout call to call. Here is a possible revision:
void paint_fade(cairo_surface_t* surface){

    static cairo_t* cr = cairo_create(surface);
    static int i = 1;
    if(darkmode){
       i-=0.005;
       cairo_set_source_rgb(cr, i, i, i);
       cairo_rectangle(cr, 0, GUI_Y, getX_SizeWindow(),
       getY_SizeWindow()-GUI_Y);
       cairo_fill(cr);
       if ( i <= 0.2) {
         cairo_destroy(cr);
         return FALSE; // Abort the timeout.
       }
    }
    else
    {
        i+=0.005
        cairo_set_source_rgb(cr, i, i, i);
        cairo_rectangle(cr, 0, GUI_Y, getX_SizeWindow(),
        getY_SizeWindow()-GUI_Y);
        cairo_fill(cr);
        if (i => 1) {
          cairo_destroy(cr);
          return FALSE; // Abort the timeout.
        }
    }
    return TRUE;

}


text:
Q: Ubuntu 16.04 DVD Playback I am currently setting up a kodi PVR which is all finished apart from DVD playback.
I have ubuntu 16.04 on my desktop which I set up about a year ago and the dvds play fine on there. When I set this up I did this which has always worked.
sudo apt-get install ubuntu-restricted-extras
sudo apt-get install libdvdcss2 libdvdnav4 libdvdread4 libdvd-pkg
sudo apt-get install libdvd-pkg
sudo dpkg-reconfigure libdvd-pkg

I have repeated these steps on my PVR (even did a clean install with and without updates) and I can only play non-encrypted DVDs. (None of the ones I have purchased legally work)!
What has changed and how can I get it to work?
I installed windows 10 and libdvdcss for windows on the same hardware (both computers) and all my DVDs play fine (the ones I had time to try anyway). But I don't want to use windows! Everything else works in ubuntu just not DVDs!
I have tried two dvd drives and same problem on both (both work on my desktop PC)

A: For 14.04 (and possibly others but IDK)
Run the following commands:
$ sudo apt-get install libdvdread4
$ sudo /usr/share/doc/libdvdread4/install-css.sh

After they finishes executing, encrypted DVDs should work right away, but if they don't, try rebooting.  This worked perfectly for me - before I did it, encrypted DVDs would crash the Videos program and give an error report.  After, they play flawlessly.
For 16.04
Reference
Enter the following commands:
$ sudo apt install libdvdnav4 libdvdread4 gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly libdvd-pkg -y
$ sudo dpkg-reconfigure libdvd-pkg

After that you should be able to play encrypted DVDs (reboot may be necessary)


text:
Q: Remove unexisting annotations in kubectl apply -f When applying an update to a kubernetes resource with kubectl -f apply and in the applied configuration I removed some annotations that currently exists in the deployed resource, these annotations are not being removed (but the changes in the existing ones are being properly updated). How can I force to delete the removed annotations in the update process?
BTW, I want avoid to delete and recreate the resource

A: As @Matt mentioned

Did you use kubectl apply to create this data on the resource? apply stores previous state in an annotation. If that annotation doesn't exist then it can't detect what data to delete

More about it here

You can use kubectl edit to delete those annotations.

Edit a resource from the default editor.
The edit command allows you to directly edit any API resource you can retrieve via the command line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. You can edit multiple objects, although changes are applied one at a time. The command accepts filenames as well as command line arguments, although the files you point to must be previously saved versions of resources.
Editing is done with the API version used to fetch the resource. To edit using a specific API version, fully-qualify the resource, version, and group.
The default format is YAML. To edit in JSON, specify "-o json".
The flag --windows-line-endings can be used to force Windows line endings, otherwise the default for your operating system will be used.
In the event an error occurs while updating, a temporary file will be created on disk that contains your unapplied changes. The most common error when updating a resource is another editor changing the resource on the server. When this occurs, you will have to apply your changes to the newer version of the resource, or update your temporary saved copy to include the latest resource version.

I made an example with nginx pod and some annotation
apiVersion: v1
kind: Pod
metadata:
  name: annotations-demo
  annotations:
    delete: without-restart
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort: 80

I used

*

*kubectl describe to check if the annotation is added.

Annotations:        delete: without-restart

*kubectl edit to delete this annotation, it's empty now.

Annotations:


text:
Q: Why is valgrind limited to 32 Gb on 64 bit architectures? I'm trying to valgrind a heisenbug on a process which uses more than 32 Gb of ram and hitting this valgrind limitation, is this an arbitrary one that could be avoided by recompiling valgrind or is it a hard one?

A: The limit is arbitrary and can be changed by recompiling valgrind.
Valgrind keeps track of memory using a 2-level sparse array.  16 bits of the address are used to index into a 65536-entry table containing a pointer to a second-level map, which tracks a range of the address space (normally 2¹⁶ bytes = 64KB for 32-bit processes, 2¹⁹ bytes = 512KB for 64-bit processes).  So the total amount of memory that can be tracked by this 2-level sparse array is 65536 × this chunk size.  By modifying the code, the size of these chunks can be increased to a larger power of 2, at the cost of using more memory to track most partial chunks.
In this message on the valgrind-users mailing list, Julian Seward explains how to increase the limit from 32GB to 128GB:

*

*in memcheck/mc_main.c change N_PRIMARY_BITS from 19 to 21

*change the assertions at the end of memcheck/mc_main.c accordingly:

*

*MAX_PRIMARY_ADDRESS →  4 * (existing value + 1) - 1

*for the MASK(1/2/4/8) assertions, set to zero the rightmost two
  '1' bits in the block of leading 1 bits, eg
  MASK(8) → 0xFFFFFFE000000007ULL  I think

*in coregrind/m_aspacemgr/aspacemgr-linux.c change aspacem_maxAddr from
  (Addr)0x800000000 - 1 to (Addr)0x2000000000ULL - 1.

Update:
The maximum amount of memory that Valgrind can use has increased in recent versions:

*

*32 GB prior to Valgrind 3.9

*64 GB in Valgrind 3.9 through 3.12

*128 GB in Valgrind 3.13


text:
Q: Unit Testing window.location.assign using Karma/Mocha/Sinon/Chai I am attempting to unit test a function using Karma as my test runner, Mocha as my testing framework, Sinon as my mocking/stubbing/spying library, and Chai as my assertion library. I am using Chromium as my headless browser in my Karma configuration.
I am totally baffled, however, as to why I am getting the following error:
TypeError: Cannot redefine property: assign

...when I run npm test on this:
function routeToNewPlace() {
  const newLoc = "/accountcenter/content/ac.html";
  window.location.assign(newLoc);
}
describe('tests', function() {
  before('blah', function() {
    beforeEach('test1', function() {
          window.onbeforeunload = () => '';
      });
    });
  it('routeToNewPlace should route to new place', function() {
    expectedPathname = "/accountcenter/content/ac.html";
    routeToNewPlace();
    const stub = sinon.stub(window.location, 'assign');
    assert.equal(true, stub.withArgs(expectedUrl).calledOnce);
    stub.restore();
  });
});

As you can see, I am attempting to assign an empty string to window.location, but this doesn't seem to help.
Here is my karma.config.js:
module.exports = function(config) {
    config.set({
      frameworks: ['mocha', 'chai', 'sinon'],
      files: ['jstests/**/*.js'],
      reporters: ['progress'],
      port: 9876,  // karma web server port
      colors: true,
      logLevel: config.LOG_INFO,
      //browsers: ['Chrome', 'ChromeHeadless', 'MyHeadlessChrome'],
      browsers: ['ChromeHeadless'],
      customLaunchers: {
        MyHeadlessChrome: {
          base: 'ChromeHeadless',
          flags: ['--disable-translate', '--disable-extensions', '--remote-debugging-port=9223']
        }
      },
      autoWatch: false,
      // singleRun: false, // Karma captures browsers, runs the tests and exits
      concurrency: Infinity
    })
  }

Any thoughts would be greatly appreciated.

A: The problem you are seeing is that window.location.assign is a native function that is non-writable and non-configurable. See the discussion of property descriptors on MDN.
See this screenshot and it may help you understand:

What this means is that sinon cannot spy on the assign function since it cannot overwrite its property descriptor.
The simplest solution is to wrap all calls to window.location.assign into one of your own methods, like this:
function assignLocation(url) {
  window.location.assign(url);
}

And then in your tests, you can do:
const stub = sinon.stub(window, 'assignLocation');

A: Try this:
Object.defineProperty(window, 'location', {
    writable: true,
    value: {
        assign: () => {}
    }
});
sinon.spy(window.location, 'assign');


text:
Q: Javascript trigger event based on data-selector attribute I have a nav bar with following items

  Blog

  Home

When i hover the item the class of the corresponding link will be hover like if i hover on Blog the list will be

  Blog

  Home

When i click on it the class will change from hover to open.
I want to listen the event of click to know that  with data-selector="nav a" is clicked. Whether it is Blog or Home whatever it be i want to call a single function. If  with data-selector="nav a" is clicked and class is open i want to do some other task.

A: Use document.querySelectorAll('li a') to get all your links, then with forEach, add the proper event listener to your links with link.addEventListener(event, handler).
You can use the mouseenter and mouseleave events to add and remove the hover class using the classList property of your links.
And you can use the click event to handle the clicks, then with link.getAttribute('data-selector') you can query your data-selector attribute and do something with it:

const links = document.querySelectorAll('li a');

links.forEach(link => {
  link.addEventListener('mouseenter', event => {
    if (!link.classList.contains('open')) {
      link.classList.add('hover');
    }
  });
  link.addEventListener('mouseleave', event => {
    link.classList.remove('hover');
  });
  link.addEventListener('click', event => {
    link.classList.remove('hover');
    link.classList.toggle('open');
    const dataSelector = link.getAttribute('data-selector');
    if (dataSelector === 'nav a') {
      console.log('this is a [nav a] link');
    } else {
      console.log('this is NOT a [nav a] link');
    }
  });
});
.hover {
  color: blue;
}
.open {
  color: green;
}

  Blog

  Home


text:
Q: How I can export analytic data from iTunes Connect I have iTunes Connect account, I want to export the analytics from iTunes Connect and then generate a report in my own system. I read many article but haven't been able to find any api to connect to iTunes Connect remotely. Any help in this regards will be greatly appreciated.

A: Navigate to Analytics for the appropriate app, then select the Metrics tab, then select a metric. There is a download icon (the box with the down arrow in the screenshot below) which you can click on for a CSV file. You can also select an option from the View By dropdown. As far as I know, there is no download all stats functionality sadly. Also, the analytics functionality is available for the iTunes Connect Admin, Finance, and Sales roles.

A: If you want to download your app store data automatically without navigating manually to iTunes Connect, Apple offers the Reporter Tool which is an API. It takes some programming skills but is a reliable interface that can be adapted to your needs. We are currently developing a Google Sheets Add-on that will import your app statistics directly into Sheets. This includes all available reports and a schedule function on a daily, weekly, or monthly basis. If you are interested in a free trial sign up for beta testing on www.appstoremetrix.com.


text:
Q: How to make Gulp wait until dest file is finished? I want to run gulp-sass and after that check, what is the size of the generated css file.
If I have the following in my gulpfile:
gulp.task('sass', function () {

  gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
});

gulp.task('css.size', ['sass'], function() {
  gulp.src(buildPath+'css/style.css')
      .pipe(filesize())
})

gulp.task('default', ['clear','copy', 'sass', 'connect'], function() {

  gulp.watch(['./src/**/*.js', './src/*/**.html'], ['copy', 'reload']);
  gulp.watch('./src/**/*.scss', ['sass']);
  gulp.watch(buildPath+'css/style.css', ['css.size']);
});

I end up in the never ending limbo of building css file, apparently because the css.size task has to wait for the sass task to finish. Correct me if I am wrong. For me it does not make sense, but I have not found any other explanation, especially because if I comment the style.css watch task, the sass task is ran only once, as expected.
Now, if I modify the gulpfile like this:
gulp.task('sass', function () {

  gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
});

gulp.task('css.size', ['sass'], function() {
  gulp.src(buildPath+'css/style.css')
      .pipe(filesize())
})

gulp.task('default', ['clear','copy', 'sass', 'connect'], function() {

  gulp.watch(['./src/**/*.js', './src/*/**.html'], ['copy', 'reload']);
  gulp.watch('./src/**/*.scss', ['sass', 'css.size']);
});

or like this
gulp.task('sass', function () {

  gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
  gulp.src(buildPath+'css/style.css')
      .pipe(filesize())
});

gulp.task('default', ['clear','copy', 'sass', 'connect'], function() {

  gulp.watch(['./src/**/*.js', './src/*/**.html'], ['copy', 'reload']);
  gulp.watch('./src/**/*.scss', ['sass']);
});

I get the wrong results. The file is apparently not compiled yet and I get the file size of the old file.
How should I arrange my tasks so I could get the file size of freshly built css file?

A: Make your sass task return the stream. Like this:
gulp.task('sass', function () {
  return gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
});

Note the return before the gulp.src. That way, the css.size task will know when the sass task finishes, and start after it.


text:
Q: How do I shrink the root logical volume (LV) on LVM? I don't need to actually shrink the MBR partition, just the logical volume that contains the root "/" filesystem. It's ~200GB now, and I need to shrink it to ~150GB to make room for a new logical volume. How do I go about this?

A: Any partition and LV resizing should be done on unmounted partitions, so you have to boot from Ubuntu installation disk or USB stick, run it as live CD, connect to Internet, install lvm2
sudo apt-get install lvm2

...or you can use any Linux rescue CD which already has lvm2 available. Then make sure, that your root LV is not installed, by
mount

and unmount it when necessary, then do filesystem check
e2fsck -f /dev/yourVG/yourLV

on this LV. Then shrink filesystem
resize2fs /dev/yourVG/yourLV 150G

and reduce LV
lvreduce -L -50G /dev/yourVG/yourLV

Reboot to your system, enjoy!

A: Both lvresize and lvreduce now support re-sizing the filesystem prior to shrinking the logical volume.
This is a snippet from a man page on CentOS 6.5
-r, --resizefs
       Resize underlying filesystem together with the logical volume using fsadm

A: BEFORE YOU CHANGE ANYTHING MAKE SURE YOU HAVE A CURRENT BACKUP. This all worked for me, but it might not work for you. If it blows up for some reason, you don't want to lose anything that you can't recover. Continuing on…
It is not possible (to my knowledge) to shrink a filesystem while it is mounted, so we need to do the actual resizing from a Live CD. All the following instructions assume you have booted off of the 11.10 Desktop Install CD.
After the Live CD boots up to the desktop, open up the Terminal.
The LVM tool are not built-in to the Live CD, so first we must install them:
sudo apt-get install lvm2

Find the name of the Volume Group (henceforth "somevg") that contains the root Logical Volume:
sudo lvs

(If it's not showing up, try running sudo lvmdiskscan and sudo pvscan then try again.)
If you run ls /dev/mapper/ you may see that the Logical Volumes is not showing up. If it's not there, you need to run the following command to make the kernel aware of the logical volumes:
sudo vgchange --available y <somevg>

Since we haven't mounted the root filesystem, it should be safe to resize. Proceed to perform the actual resizing of the Logical Volume. Note that this command (--size -50G) shrinks the volume by 50GB — read the lvreduce(8) man page to learn how to specify a different size.
sudo lvreduce --resizefs --size -50G /dev/<somevg>/root

(My Logical Volume is called "root", but yours may be named something different.)
This command will first shrink the filesystem, then shrink the Logical Volume that contains it, which is the only safe way to do it.
You can now restart the system and boot into your now-resized root filesystem.

A: Have a look into this http://ubuntuforums.org/showthread.php?t=1537569


text:
Q: How to delete 5 to 10 records in sqlite in android? How can I delete records from 5 to 10?
I have used code below but all the records are being deleted instead.
SQLiteDatabase db = dbHandler.getWritableDatabase();

for (int i = 5; i <= 10; i++) {
    db.delete(DbHandler.TABLE_USERS, i+"", null);
}
db.close();

A: What your loop is really doing is this:
db.delete(DbHandler.TABLE_USERS, 5+"", null);
db.delete(DbHandler.TABLE_USERS, 6+"", null);
db.delete(DbHandler.TABLE_USERS, 7+"", null);
db.delete(DbHandler.TABLE_USERS, 8+"", null);
db.delete(DbHandler.TABLE_USERS, 9+"", null);
db.delete(DbHandler.TABLE_USERS, 10+"", null);

which is equivalent say for the first:
delete from DbHandler.TABLE_USERS WHERE '5'

This WHERE '5' is interpreted by SQLite as WHERE true, so it deletes all the rows and all the next iterations do the same but there are no rows to delete.
If you want to delete rows with a column value of 5 up to 10, do this without loop:
db.delete(DbHandler.TABLE_USERS, columnname between ? and ?, new String[]{"5", "10"});

A: You need to pass the whereClause and whereArgs
Ex.
delete(String table, String whereClause, String[] whereArgs)

A: Supposing the row number is stored on column _id. If you have a different column name, just replace by proper column.
SQLiteDatabase db = dbHandler.getWritableDatabase();
db.delete(DbHandler.TABLE_USERS, "_id >= 5 AND _id <= 10", null);
db.close();

or
SQLiteDatabase db = dbHandler.getWritableDatabase();
db.delete(DbHandler.TABLE_USERS, "_id >= ? AND _id <= ?", new String[] {"5", "10"});
db.close();


text:
Q: ReorderableListView throws when Slider in item list I've got a ReorderableListView where the ListTile contains a Slider() widget.  If I don't touch any of the Slider() widgets, I can reorder the ListTiles with no issue.  But, as soon as you click-on or interact with any of the Slider() widgets, then attempting to reorder the items throws() with this error in the debug console (many of them):
════════ Exception caught by scheduler library ═════════════════════════════════
Assertion failed:
../…/rendering/layer.dart:2498
leader._lastOffset != null
"LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse was true."

On Flutter 2.8.1, Stable Channel.
Here is the code to duplicate.  I used the example code from the ReorderableListView widget documentation, and the only things I changed was the Text() to a Slider() as well as autogenerate some values for the Slider().  Other than that it's the same example as the documentation.  This works fine with a Text() widget, but the Slider() fails.  Is there a way to use a Slider() inside a ReorderableListView()?:
import 'dart:math';
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: ListViewTestWidget(),
        ),
      ),
    );
  }
}

class ListViewTestWidget extends StatefulWidget {
  const ListViewTestWidget({Key? key}) : super(key: key);

  @override
  _ListViewTestWidgetState createState() => _ListViewTestWidgetState();
}

class _ListViewTestWidgetState extends State<ListViewTestWidget> {
  final List<int> _items = List<int>.generate(50, (int index) => index);
  final List<double> _values =
      List<double>.generate(50, (int index) => Random().nextDouble() * 100);

  _changeValue(int index, double newValue) {
    if (newValue < 1 || newValue > 100) return;
    setState(() {
      _values[index] = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    final ColorScheme colorScheme = Theme.of(context).colorScheme;
    final Color oddItemColor = colorScheme.primary.withOpacity(0.05);
    final Color evenItemColor = colorScheme.primary.withOpacity(0.15);

    return ReorderableListView(
      padding: const EdgeInsets.symmetric(horizontal: 40),
      children: <Widget>[
        for (int index = 0; index < _items.length; index += 1)
          ListTile(
            key: Key('$index'),
            tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
            title: Slider(
              min: 1,
              max: 100,
              value: _values[index],
              onChanged: (newValue) =>
                  setState(() => _changeValue(index, newValue)),
            ),
          ),
      ],
      onReorder: (int oldIndex, int newIndex) {
        setState(() {
          if (oldIndex < newIndex) {
            newIndex -= 1;
          }
          final int item = _items.removeAt(oldIndex);
          _items.insert(newIndex, item);
        });
      },
    );
  }
}

A: This is a known issue on the flutter framework itself. You can track the progress of this issue on GitHub: https://github.com/flutter/flutter/issues/97292
Meanwhile (before they fix it), you can perhaps try to use CupertinoSlider to replace the (Material) Slider. The issue does not occur on the Cupertino widget. And yes, they look a little different but the main functionalities are the same. Or you can write your own slider widget and customize it however you want.


text:
Q: How do I set up a route to access nested objects in mongodb The route to get our forms is setup correctly and returns something similar to this. In the questions array I have stored question objects but I can't figure out how to access them. My code currently looks like:
router.route('/:post_id/:q_id')

.get(function (request, response)
{

forms.findById(request.params.post_id,function(error,form)
{
    if (error)
    {
        response.send({error: error});
    }
   else
   {
        for (var i in form.questions)
        {
            if (form.questions[i] == request.params.q_id)
            {
                questions = form.questions[i];
                response.json({singleQuestion: questions});
            }
        }
    }
});
})

This returns this
I am wondering how to get the object and read the fields in the object.

A: Looks like you are trying to do the following:

router.get('/:formId/:questionId', (req, res) => {
  Form.findOne({
    _id: req.params.formId,
    questions: req.params.questionId
  }).populate('questions').then(form => {
   if (!form) {
      return res.status(404).json({error: 'Form not found'});
   };
   res.json({
      singleQuestion: form.questions.find(q => q._id.toString() == req.params.questionId)
   });
  }).catch(err => res.status(500).json({error: 'Internal error'}));
});

However, it seems this route is set up to retrieve question objects given a form. It may be smarter to make the following modification to your Form 'get' request:

router.get('/form/:formId', (req, res) => {
  Form.findById(req.params.formId).populate('questions').exec((err, data) => {
    if (err || !data) {
      res.status(404).json({error: 'Form not found'});
    } else {
      res.json({data});
    }
  });
});

Have a look at mongoose's docs for populate - essentially, it'll swap the questionIds for the question objects themselves. Consider it an application-side join.


text:
Q: how to insert multiple row of listview into mssqlserver using c# This code is working but I think something is missing because it only works if I add one row at a time. How can I store many rows at a time?
foreach (ListViewItem item in listView1.Items)
{
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        SqlConnection con = new SqlConnection("Data Source=ZON-PC;Initial Catalog=RestaurantPOSSOC;Integrated Security=True");

        con.Open();

        SqlCommand _sqlcommand = new SqlCommand("insert into OrderInfo (ProductName,Quantity,Price)values('" + listView1.Items[i].SubItems[0].Text + "','" + listView1.Items[i].SubItems[1].Text + "','" + listView1.Items[i].SubItems[2].Text + "')", con);

        SqlDataReader _sqldatareader = _sqlcommand.ExecuteReader();
        _sqldatareader.Read();

       con.Close();
    }
}

A: There are a couple of things I would change for your routine:

*

*As gmiley commented, you don't need the foreach loop and the for loop, you are doing n*n inserts this way

*Connections can be expensive, I would create the connection outside of the foreach loop.

*When I am doing updates, I use SqlCommand.ExecuteNonQuery, instead of SqlCommand.ExecuteReader(), since I don't actually expect any rows to come back.

So in pseudocode:
using (connection = new(...))
    con.open
    foreach(item)
        command = new command()
        command.ExecuteNonQuery()

    con.close

A: Look Here
basically:
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

A: Not an answer, but you really should change your starting code to at least this:
SqlConnection con = new SqlConnection("Data Source=ZON-PC;Initial Catalog=RestaurantPOSSOC;Integrated Security=True");
con.Open();

foreach (ListViewItem item in listView1.Items)
{
    SqlCommand _sqlcommand = new SqlCommand("insert into OrderInfo (ProductName,Quantity,Price)values('" + item.SubItems[0].Text + "','" + item.SubItems[1].Text + "','" + item.SubItems[2].Text + "')", con);

    SqlDataReader _sqldatareader = _sqlcommand.ExecuteReader();
    _sqldatareader.Read();
}

con.Close();

And you really also need to parameterize your query and add some exception handling.

A: First: regardless of what method is used, you really need to clean up the external resources. Both the SqlConnection and SqlCommand objects have a .Dispose() method and should be used in a using() construct / macro. The using handles both the .Dispose() as well as a basic try / finally to ensure that the .Dispose() method is called, even if an error occurs.
Second: if you are using SQL Server 2008 or newer, you should check out Table Valued Parameters (TVPs) as they will eliminate the SQL Injection issues and increase performance.
I have examples of doing this in the following answers:

*

*Pass Dictionary<string,int> to Stored Procedure T-SQL

*How can I insert 10 million records in the shortest time possible?

A: Add this under button click or any, before that you should open a SqlConnection
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

foreach (ListViewItem item in lvPOItem.Items)
{
    SqlCommand cmd = new SqlCommand("INSERT INTO PurchasePOItems (PO_ItemName, PO_Specs, PO_PONumber)values(@PO_ItemName, @PO_Specs,@PO_PONumber)", conn);
    conn.Open();
    cmd.Parameters.AddWithValue("@PO_ItemName", item.SubItems[0].Text);
    cmd.Parameters.AddWithValue("@PO_Specs", item.SubItems[1].Text);
    cmd.Parameters.AddWithValue("@PO_PONumber", cbPurchaseOrderNo.Text);
    cmd.ExecuteNonQuery();
    conn.Close();
}


text:
Q: Ng-include partial not rendering with phantomjs So, I am using the MEAN stack and my landing page includes a number of Angular ng-include's. For example:
<div data-ng-include="'/modules/landing/views/sections/features.client.view.html'">

I'm also using mean-seo: https://github.com/meanjs/mean-seo. This essentially just uses phantomjs to render the page if a crawler is detected via ?_escaped_fragment_=.
My problem is that the partials being included via the ng-include are not rendered by mean-seo, i.e. by phantomjs.
If you have any ideas why this might be it would be terrific if you could share them!

A: I managed to get this to work using prerender.io. I'm still not certain why it wasn't working when I was taking a DIY approach...


text:
Q: How to port encrypt (AES192) method from nodejs to java correctly? I'm trying to port this nodejs code to java
const crypto = require("crypto");

const encrypt = (data, key) => {
    const cipher = crypto.createCipher('aes192', key)

    let crypted = cipher.update(data, 'utf8', 'hex')
    crypted += cipher.final('hex')

    return crypted;
}

I've tried to use this solution:
import org.springframework.security.crypto.codec.Hex;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public String encrypt(String data, String key) {
    try {
        var cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));

        var cipherText = cipher.update(data.getBytes());
        cipherText = ArrayUtils.addAll(cipherText, cipher.doFinal());

        return new String(Hex.encode(cipherText));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Cons:

*

*encrypt method for Java returns a different value than the method for nodejs (for the same data and key).

*In nodejs, I can put a short key (5 characters long), at the same time in java I'm catching an exception e.g. "java.security.InvalidKeyException: Invalid AES key length: 5 bytes"
Could you suggest the right solution or point on a mistake in the existing one? Thank you in advance!
Note: I'm unable to change encrypt/decrypt method in nodejs, so I need to port this to java correctly.

A: Your encrypt java version doesn't use the same logic as the javascript version.
The encrypt javascript function takes a password (the argument name key is misleading) and then passes it to createCipher. createCipher doesn't use the password directly, but derives a key from it. It's the derived key that is used to encrypt the message. From NodeJs documentation :
The password is used to derive the cipher key and initialization vector (IV). The value must be either a 'latin1' encoded string, a Buffer, a TypedArray, or a DataView.

The encrypt java function, on the other hand, expects a ready to use key, so you have to do the key derivation from the password yourself.
AES keys have a fixed size. They can only be 128, 192 or 256 bits long. (in bytes 8, 16, 32 bytes long). If you use a key with a different size, you'll get the exception InvalidKeyException. NodeJS didn't complain about an "invalid key length" because in actuality you were using a password, not a key. NodeJS derives a key from the password before encrypting the data.
(as mentioned in the docs) NodeJs uses OpenSSL to encrypt the data and derives the key using a function specific to OpenSSL : EVP_BytesToKey.
Luckily this SO answer has an implementation of EVP_BytesToKey in Java. (The code is originally from this blog entry)
I adapted your code to use it. I added the final result to the end of the answer. I rarely write security code, and in this case I just adapted an existing solution, so you should review the code (or have someone else review it if you have a security team in your company) if you decide to use it.
One final comment : createCipher is deprecated. But you said in your question that you can't change the implementation of the javascript encrypt version. (If you're not the maintainer of encrypt) You should discuss the deprecation issue with the maintainer to understand their reasons for still using createCipher (which uses EVP_BytesToKey). EVP_BytesToKey is considered a weak key derivation function and OpenSSL recommends using more modern functions for newer applications.
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.crypto.codec.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class Main {
    public static void main(String[] args){
        System.out.println("Result : " + encrypt("my secret message","pass"));
    }

    public static byte[][] EVP_BytesToKey(int key_len, int iv_len, MessageDigest md, byte[] salt, byte[] data, int count) {
        byte[][] both = new byte[2][];
        byte[] key = new byte[key_len];
        int key_ix = 0;
        byte[]  iv = new byte[iv_len];
        int iv_ix = 0;
        both[0] = key;
        both[1] = iv;
        byte[] md_buf = null;
        int nkey = key_len;
        int niv = iv_len;
        int i = 0;
        if(data == null) {
            return both;
        }
        int addmd = 0;
        for(;;) {
            md.reset();
            if(addmd++ > 0) {
                md.update(md_buf);
            }
            md.update(data);
            if(null != salt) {
                md.update(salt,0,8);
            }
            md_buf = md.digest();
            for(i=1;i<count;i++) {
                md.reset();
                md.update(md_buf);
                md_buf = md.digest();
            }
            i=0;
            if(nkey > 0) {
                for(;;) {
                    if(nkey == 0) break;
                    if(i == md_buf.length) break;
                    key[key_ix++] = md_buf[i];
                    nkey--;
                    i++;
                }
            }
            if(niv > 0 && i != md_buf.length) {
                for(;;) {
                    if(niv == 0) break;
                    if(i == md_buf.length) break;
                    iv[iv_ix++] = md_buf[i];
                    niv--;
                    i++;
                }
            }
            if(nkey == 0 && niv == 0) {
                break;
            }
        }
        for(i=0;i<md_buf.length;i++) {
            md_buf[i] = 0;
        }
        return both;
    }

    public static String encrypt(String data, String password) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            var cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            var keySizeBits = 192 / Byte.SIZE; //AES with 192 bits key = 16 bytes
            var ivSize = cipher.getBlockSize();
            final byte[][] keyAndIV = EVP_BytesToKey(keySizeBits, ivSize, md5, null, password.getBytes(StandardCharsets.US_ASCII), 1);
            SecretKeySpec key = new SecretKeySpec(keyAndIV[0], "AES");
            IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);

            cipher.init(Cipher.ENCRYPT_MODE, key, iv);

            var cipherText = cipher.update(data.getBytes());
            cipherText = ArrayUtils.addAll(cipherText, cipher.doFinal());

            return new String(Hex.encode(cipherText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
Q: Form creation issue in Mozilla FireFox I'm working on a project in MVC.NET 5. In this project I have a table which has some checkboxes in it. I want to send these checkboxes value to the server and I don't have a form element. But I create a form element with jQuery. Here is the form creation code:
$("#setNewRoles").click(function (evt) {
        evt.preventDefault();
        var checkbox = $(".checkbox:checked");
        var form = $("<form />").attr({ "action": "/Admin/Account/AddnewRolesForUser", "method": "post" });
        alert(form);
        for(var i=0;i<checkbox.length;i++){
            if ($(checkbox[i]).attr("disabled") != "disabled") {
                $(form).append("<input type='checkbox' name='rolesValue[]' value='" + $(checkbox[i]).val() + "' checked />");
            }
        }
        $(form).submit();
    });

This code works correctly in Chrome but it doesn't work on Mozilla. What is the matter with the code?

A: I found it by some tests,
We can Replace above code with this code :
$("#setNewRoles").click(function (evt) {
        evt.preventDefault();
        var checkbox = $(".checkbox:checked");
        var form = $("<form />").attr({ "action": "/Admin/Account/AddnewRolesForUser", "method": "post", "id": "setRolesForUserForm", "style": "visibility: hidden;" });
        for(var i=0;i<checkbox.length;i++){
            if ($(checkbox[i]).attr("disabled") != "disabled") {
                $(form).append("<input type='checkbox' name='rolesValue[]' value='" + $(checkbox[i]).val() + "' checked />");
            }
        }
        $('body').append(form);
        $('#setRolesForUserForm').submit();
    });


text:
Q: Initiate different chat buttons on a single page application (React) Our website is a single-page application build on React and we would like to have different buttons based on different state:

*

*If the user is not logged in (button A)

*If the user is logged in (button B)

*if the user is logged in and in the Sales funnel

*if the user is not logged in and is in the Sales funnel

Therefore we defined 4 States and we reinitialize the init function when the app change state out init function looks something like:
embedded_svc.init(
            'https://selina2.my.salesforce.com',
            'https://selinaoperations.secure.force.com/liveAgentSetupFlow',
            gslbBaseURL,
            '00D8d000003SrEh',
            'Logged_In',
            {
                baseLiveAgentContentURL: 'https://c.la1-c2-lo2.salesforceliveagent.com/content',
                deploymentId: '5728d000000H0AF',
                buttonId: '5738d000000H0NN',
                baseLiveAgentURL: 'https://d.la1-c2-lo2.salesforceliveagent.com/chat',
                eswLiveAgentDevName: 'EmbeddedServiceLiveAgent_Parent04I8d0000008SzzEAE_180fb6579d4',
                isOfflineSupportEnabled: false
            }
        );
    };

for some reason out init is not reinitialized so if for example the user get to our website the button A will initialize. Then when the user log in and it changes state then the user should be proposed the button B.
However it is still the Button A that is displayed until we RELOAD the page and then the button B get initialized
Could you please help me figure out how to display a specific button when a state change
Thx you


text:
Q: How can I associate a new entity with an existing entity in EF4? I've got a Patient entity (storing up-to-date information about a patient) and a TreatmentPlanPatient entity (a copy of a patient's date as it was when the "treatment plan", another entity not relevant to this question, was created):

I'm using Table-per-Type in this case. Now when I try to add a new TreatmentPlanPatient that's pointing to the Patient it was created from, EF4 actually does this:

*

*It retrieves the existing patient from the database

*Creates a copy of that patient

*Assigns it a new ID GUID (despite StoreGeneratedPattern = None!)

*Inserts the new patient into the Patients table

*Rewrites the ID in my TreatmentPlanPatient instance to point to this new Patient

*Inserts the new treatment plan patient in to the TreatmentPlanPatients table.

This is my code causing above behavior:
using(var container = new SmartTherapyContainer()) {

  // Look up the patient in the current container to make sure EF4 recognizes it
  var patient = container.Patients.First(r => r.Id == selectedPatient.Id);

  var treatmentPlanPatient = new TreatmentPlanPatient() {
    Id = Guid.NewGuid(),
    FirstName = patient.FirstName,
    LastName = patient.LastName,
    Street = patient.Street,
    ZipCode = patient.ZipCode,
    City = patient.City,
    BirthDate = patient.BirthDate,
    Telephone = patient.Telephone,
    Email = patient.Email,
    ClonedPatient = patient
  };

  // EF4 doesn't generate a separate .TreatmentPlanPatients collection :-/
  container.Patients.AddObject(treatmentPlanPatient);
  container.SaveChanges();

}

What is going on? How can I get EF4 to just insert a treatment plan patient into the TreatmentPlanPatients table and associate it with the existing patient in the Patients table?

A: I am not sure I completely understand what you are trying to do but according to your schema, the Patient table is a parent of TreatmentPlanPatients table (one to many relationship). Hence, you should add the TreatmentPlan to the Patient itself and not the Patients table. So rather than doing container.Patients.AddObject(treatmentPlanPatient), you should do patient.TreatmentPlanPatients.Add(treatmentPlanPatient). In this case, TreatmentPlanPatients should be a navigational property on the Patient table/entity.
OR, if you really want to use inheritance, then you have to use the same primary key (Id in this case) in both tables and have a one-to-one relationship.


text:
Q: Hooking Function Constructor (JavaScript) Does anyone know of a way to detect when a new function is created?
I know you can hook the function class constructor but that will only detect new Function() calls, not function func(){} declarations.
I assume the JS engine just creates a default function class when it sees a function declaration instead of looking at the global Function class.
Does anyone know if this is the case or if you can intercept function declarations.
Example function to hook :
function add(x,y){return x+y}

A hook should get the function when it is defined and hopefully redefine it to be able to capture the arguments, this, and return value.

A: (V8 developer here.)
No, there is no way to intercept all function declarations.
FWIW, this isn't up to individual engines to decide; the JavaScript language provides no way to accomplish this, and engines aim to implement the language without any custom deviations (i.e. neither adding nor removing features).
I can offer two alternative ideas that may or may not serve your purposes:
(1) V8 has a --trace flag which logs all function entries and returns to stdout. Be warned: this tends to produce a lot of output.
(2) You could feed the source of the app you are interested in to a JavaScript parser, and then run whatever analysis (and/or transformation) you want over the AST it produces. This won't catch dynamically generated and eval-ed functions, but it will find all function func() {...} declarations.

The need is game hacking.

In the interest of helping you ask better questions (so that you may get more helpful answers), I'd like to point out that that's not the level of detail that @Bergi was asking for: the general area in which you are active does not provide any hints for possible alternative approaches. Wanting to hook function declarations so that you can capture their arguments and return values is a search for a specific solution. @Bergi's question is: what is the specific problem that you are trying to solve by intercepting all functions?
That said, "game hacking", while being very vague, does sound sufficiently shady that I'd like to humbly suggest that you not only think about whether you could, but alse give sufficient thought to whether you should.


text:
Q: How to replace words outside double and single quotes For a custom script parser in PHP I would like to replace some words in a multiline string that contain double and single quotes.
However, only the text that is outside the quotes can be replaced.
Many apples are falling from the trees.
"There's another apple over there!"
'Seedling apples are an example of "extreme heterozygotes".'

For example, I would like to replace 'apple' with 'pear', but only outside the quote sentences. So in this case only 'apple' inside 'Many apples are falling from the trees' would be targeted.
The above would give the following output:
Many pears are falling from the trees.
"There's another apple over there!"
'Seedling apples are an example of "extreme heterozygotes".'

How can I achieve this?

A: This function does the trick:
function str_replace_outside_quotes($replace,$with,$string){
    $result = "";
    $outside = preg_split('/("[^"]*"|\'[^\']*\')/',$string,-1,PREG_SPLIT_DELIM_CAPTURE);
    while ($outside)
        $result .= str_replace($replace,$with,array_shift($outside)).array_shift($outside);
    return $result;
}

How it works It splits by quoted strings but includes these quoted strings, this gives you alternating non-quoted, quoted, non-quoted, quoted etc strings in an array (some of the non-quoted strings may be blank). It then alternates between replacing the word and not replacing, so only non-quoted strings are replaced.
With your example
$text = "Many apples are falling from the trees.
        \"There's another apple over there!\"
        'Seedling apples are an example of \"extreme heterozygotes\".'";
$replace = "apples";
$with = "pears";
echo str_replace_outside_quotes($replace,$with,$text);

Output
Many pears are falling from the trees.
"There's another apple over there!"
'Seedling apples are an example of "extreme heterozygotes".'

A: I came up with this:
function replaceOutsideDoubleQuotes($search, $replace, $string) {
    $out = '';
    $a = explode('"', $string);
    for ($i = 0; $i < count($a); $i++) {
        if ($i % 2) $out .= $a[$i] . '"';
        else $out .= str_replace($search, $replace, $a[$i]) . '"';
    }
    return substr($out, 0, -1);
}

The logic is: you explode string by double-quotes, so the odd elements of the returning string-array represent text outside quotes, and even ones represents text inside double-quotes.
So, you can build your output by concatenating original parts and replaced parts alternatively, ok?
Working example here: http://codepad.org/rsjvCE8s

A: Just a thought: create a temporary string by removing quoted parts, replace what you need to, then add the quoted parts you removed.

A: You can use preg_replace, using a regular expression to replace the words inside " "
$search  = array('/(?!".*)apple(?=.*")/i');
$replace = array('pear');
$string  = '"There\'s another apple over there!" Seedling apples are an example of "extreme heterozygotes".';

$string = preg_replace($search, $replace, $string);

You can add more possible searchable objects by adding another RegEx in $search, and another replace string in $replace
This RegEx uses a lookahead and lookbehind to find out if the searched string is inside of " "


text:
Q: XQuery - is it possible to generate non-XML document? I would like to use XQuery to generate Java source code from my XML document, for instance:
<configuration package="my.package.name">

    <property>
        <name>First</name>
        <value>0</value>
        <description>First description</description>
    </property>

    <property>
        <name>Second</name>
        <value>2</value>
        <description>Second description</description>
    </property>
...

Should generate:
package my.package.name;

class MyClass {
    // First description
    private String first;

    // Second description
    private String second;
}

I was trying to start like this:
xquery version "1.0";

"package "+$doc/@package
"class "+$doc/@classname
{
for $property in $doc//property
    return {
        "private String "+$property/name::text()
    }
}

The syntax is obviously incorrect and I wonder whether it is even feasible. Thanks!

A: The details depend a bit on your query processor. It should be possible to return a query result as a string, and it may also be possible to use the text serialization method as in XSL; but the way you invoke this varies from one query processor to another. (The difference between the two approaches is that the text serialization method will automatically turn anything in the query result into a string, and then concatenate the strings).
Here's how to do it in the form of a query returning a single string:
declare variable $nl "= '
';
concat(
  "package ", $doc/@package, $nl,
  "class ", $doc/@classname, $nl,
  string-join(
    (for $property in $doc//property
     return {
        concat("private String ", $property/name)
     }), $nl)
)

A: XQuery:
declare function xf:XML2Java($configuration as element(configuration))
    as xs:string {
    let $package := string($configuration/@package)
    let $newline := "
"
       for $property in $configuration/property
       let $variable := data($property/name)
       let $javadoc := data($property/description)
       return
        fn:concat($package,$newline,"class MyClass{",$newline,"//",$javadoc,$newline,"private String ",$variable,";",$newline," }")
};

Input:
<configuration package="com.test">
    <property>
        <name>Test</name>
        <value>somevalue</value>
        <description>This is test variable</description>
    </property>
</configuration>

Output:
com.test
class MyClass{
//This is test variable
private String Test;
 }

Did this in WebLogic workshop XQuery designer.


text:
Q: Git Re-Clone an existing repository from origin? So I've been running into some issues when I try to pull down changes from a bit bucket repo, I believe its something about the permissions on a shared folder that I do not have access to change. I have no problems editing or moving files or anything, and I can clone a new repository with no problem, and I can delete my existing repo and then clone it again. When I try to pull I get an "Unable to write new index file"
Is it possible to just re-clone my local repo from its origin?


text:
Q: Adding file to the database I am trying to add file to my database but for some reason its not working can someone tell me why. This is what I've sofa:
        $(document).on("click", "#BUTTON", function () {
        var FILE= $('#name').val();

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "@Url.Action("File", "Controller")",
            data: JSON.stringify(FILE),
        contentType: "application/json; charset=utf-8",
        success: function () {

        }
    });
    });

This is what happens in my controller:
public ActionResult File(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(Server.MapPath("~/path"), pic);
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return Index();
    }
}

When I place a brakepoint in line HttpPostedFileBase file then file has null value I dont know why? If i do alert(FILE); then I am getting full file path e.g. G:/filename/imagename.jpg but in controller the path is no being passed?

A: You will not be able to post a file that way, the only thing you do is post the text value, in this case the file name.
Maybe this can help you out (another example on stack overflow)

A: You can do this if you will use files collection of your input, so try it. And i hope it will help
$(document).on("click", "#BUTTON", function(){

//Create form data
var data = new FormData();

//attach your file
data.append('file', document.getElementById("fileHere").files[0]);

//and send it on server
$.ajax({
    url: "@Url.Action("File", "Controller")",
    data: data,
    cache: false,
    contentType: 'multipart/form-data',
    processData: false,
    type: 'POST',
    success: function(data){
            }
        });
    });


text:
Q: Replacement group includes part of other group I have this text:
<ITEM>PART 23 m1,
<ITEM>PART 49b
;

I want the output to be:
PART 23 m1, PART 49b;

I'm using this pattern: <ITEM>(.*?)(?=<|\n|$)
Which results in this:
PART 23 m1,
PART 49b
;

(notice the semi-colon)
If I change the pattern to this: <ITEM>(.*?)(<|\n|$)
The output will be this:
PART 23 span class='sub'>m1,
PART 49b;

(notice the missing < in the span>
What am I missing?

A: This seems to work with your limited sample:
var match = @"<ITEM>([^<\n]+)\n?";
var replace = @"$1";

var ans = Regex.Replace(src, match, replace);


text:
Q: How to get the count of array of images i m parsing a json feed .using async image download I m downloading images (around 18 images) and storing it in UIImage.how to get the count of the images so that i can iterate in a loop.below is the code
- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage    *)image
{   UIImage *boom=image;
//download the image and storing it in UIImage

}

A: In your delegate callback you should be adding the processed element to an NSMutableArray. Something like this:
// MainViewController.h
...
{
  NSMutableArray *synced;
}

@property (nonatomic, retain) NSMutableArray *synced;

And:
// MainViewController.m

@synthesize synced;

...

- (void)viewDidLoad
{
  [super viewDidLoad];
  self.synced = [NSMutableArray array];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage    *)image
{
  [self.synced addObject:image];
  self.syncedLabel.text = [NSString stringWithFormat:@"%i images", [self.synced count]];
}


text:
Q: Writing five other iterated integrals that are equal to the given iterated integral The given integral is $$\int_{0}^{1}\int_{0}^{x^2}\int_{0}^{y} f(x,y,z) dz dy dx$$
I'm looking at the solution and I understand how to switch the order so that I have $dz dx dy$
The full solution:

I'm mainly confused on how to set up the graphs for (2)-(5). I understand how to do (1) but I'm unsure how to set up the integrals for the remaining combinations

A: The main idea is to reduce the problem to a double integral problem. There are two parts.
Part I. The inner pair.
Let us begin with something you understand already:
$$
\int_{0}^{1} \int_{\sqrt{y}}^{1} \int_{0}^{y} f(x, y, z)\; d z d x d y\tag{1}
$$
So you want to switch the order in the "inner pair" to get $dxdzdy$ as in (2). First, write (1) as
$$
\int_{0}^{1}\left( \int_{\sqrt{y}}^{1} \int_{0}^{y} f(x, y, z)\; d z d x \right)d y\tag{1a}
$$
Note that for each fixed value of $y\in[0,1]$, the inner part is a double integral
$$
\int_{\sqrt{y}}^{1} \int_{0}^{y} f(x, y, z)\; d z d x\tag{1b}
$$
This is a double integral on the $zx$-plane where the region that you integrate on is a rectangle, $[0,y]\times[\sqrt{y},1]$. Again remember that $y$ is a fixed number here (which means you should think it as a constant). So (1b) is equal to (by the Fubini theorem)
$$
\int_{\sqrt{y}}^{1} \int_{0}^{y} f(x, y, z)\; d z d x= \int_{0}^{y} \int_{\sqrt{y}}^{1} f(x, y, z)\; d x d z\tag{1c}
$$
Combining (1c) and (1a) you get (2):
$$
\int_{0}^{1}  \int_{0}^{y}\int_{\sqrt{y}}^{1} f(x, y, z)\; d x d z d y\tag{2}
$$
Part II. The outer pair.
Now you want to switch the order in the "out pair" to get $dxdydz$. Rewrite (2) as
$$
\int_{0}^{1} \int_{0}^{y} \left(\int_{\sqrt{y}}^{1} f(x, y, z)\; d x\right) d z d y\tag{2a}
$$
Note that after integrating with respect to $x$, the inner part is a function in $z$ and $y$. Let us write it as $g(z,y):=\left(\int_{\sqrt{y}}^{1} f(x, y, z)\; d x\right)$ so (2a) is
$$
\int_{0}^{1} \int_{0}^{y} g(z,y) d z d y\tag{2a}
$$
which is nothing but a double integral on the $zy$-plane now! Now you use the diagram below the formula (2) in your solution to switch the order
$$
\int_{0}^{1} \int_{0}^{y} g(z,y) d z d y=\int_{0}^{1} \int_{z}^{1} g(z,y) d y d z\tag{2c}
$$
Combining (2a)-(2c) you get (3):
$$
\int_{0}^{1} \int_{z}^{1} \int_{\sqrt{y}}^{1} f(x, y, z) d x d y d z
\tag{3}
$$
You can now proceed similarly to get (4) and then (5).


text:
Q: Reducing convex QCQP to SDP or something better I am trying to solve the following QCQP
$$\begin{array}{ll} \underset{x}{\text{minimize}} & x^T P_0 x + q_0^Tx + r_0\\ \text{subject to} & x^T P_1 x + r_1< 0\end{array}$$
where symmetric matrices $P_0, P_1$ are positive semi-definite and . I would like to know when this problem has a solution and in this case what the minimizer $x^*$ is.
On Wikipedia, I read that in my case the problem is convex and "can be readily solved using interior point methods, as done with semidefinite programming". The only problem is that my optimization courses go back a long way and I don't know how to write my problem in the form of a semidefinite program. Maybe there is a much more effective method, I don't know.
Any help would be most welcome. Thank you very much!


text:
Q: How is "I don't think you answered..." different from "I think you didn't answer..."? I come from Brazil, and many times in my day, I find myself saying phrases like

I think you didn't answer that question. (1)

which, in our language, is totally fine in all aspects. However, in English, very few times have I seen or listened to (1). What I normally see, though, is

I don't think you answered that question. (2)

Now, both (1) and (2) are correct from a grammar standpoint. Then, why is (2) used more than (1)? Simply because that's the way things are? Is there a difference in meaning?

A: Both forms in the edited answer are indeed correct grammatically. (2) does somehow feel more natural to me, and I would probably be more likely to use it than (1), but I can't specify any clear reason, nor would I call (1) wrong or think it odd if I heard it.
I suppose this must just be a matter of language fashion or style, and might be different in other major varieties of English.


text:
Q: XML Tag grouping in RTF Template to suppress duplicates My XML Tag generated is as follows-
<P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>

When I am using these tag like below in the RTF template-
DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>

This is giving an output like -
DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1

I want the repeated values in division and district to be suppressed and the output to look like -
DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
                                                      Laboratory Services                11
                                                      Corporate                          3
                      S District                      Corporate Administration           6
                                                      Corporate Technology               1

How can this be achieved ? I am not being able to use for-each-group properly to group the tags. Can someone please help ?

A: You can also use variables. Something like this:
RTF

Make sure you put your "if" logic in the alt-text/field properties, else, it may not work. I took it out so you could see it better here.
Output

A: I'd use nested tables and for-each-group functionality.
RTF:

Output


text:
Q: SMBus v1.1 voltage threshhold value I am planning to use PIC18F26K83 and communicate with a smart battery that uses SMBus ver 1.1. So from the datasheet of PIC it says I need to choose appropriate input threshhold for SMBus from RxyI2C register. Bit 0 and 1 are being used for choosing that threshold but there is no information for SMBus ver 1.1 (See below.).

TH<1:0>: I2C Input Threshold Selection bits
11 = SMBus 3.0 (1.35 V) input threshold
10 = SMBus 2.0 (2.1 V) input threshold
01 = I2C specific input thresholds
00 = Standard GPIO Input pull-up, enabled via INLVLxy registers

And over the internet I couldn't find input threshold for SMBus v1.1. So my question is:
What is the input threshold voltage for SMBus v1.1? Or how should I set related bits in order to use SMBus v1.1 from RxyI2C register?

A: The datasheet of the IC PIC18F26K83.
States that the IC supports SMBus v2.0 and v3.0.
Comparing SMBus v2.0 and v1.1, there are some differences regarding voltage's, but the electrical differences on SMBus v1.1 and v2.0 should be close enough to work together.
As for backwardscompatibility, pay attention to the pull-up resistance for SMBus v1.1. Recommended Pull-up restitance of SMBus v2.0 is close to standard I2C and will therefore not work on SMBus v1.1.
Using the Microcontroller in configuration for SMBus 2.0 with pull-up resistance compatible with SMBus v1.1 should therefore work fine.
Following you have Link's to the documentation I've used to implement SMBus v1.1.
Smart batteryData
SMBus datasheet for each version of SMBus
ReadThis <- Implementing the SMBus Interface


text:
Q: copying 14gb file from ftp to azure data lake store using ADF I am trying to copy 14gb file from FTP to my azure data lake store using Azure data factory. When I executed the pipeline it started copying the file and copied almost 13.9 gb within half hour.
Remaining data is not copied even after running the pipeline for 8 hours and finally failed by providing message that file not available. Reason for file not available is the source team removed the file for next file.
Increased the integration unit to 250
{
    "name": "job_fa",
    "properties": {
        "activities": [
            {
                "name": "set_parameters_adh_or_sch",
                "description": "validate and set the parameter values based on the runtype sch or adh",
                "type": "Lookup",
                "dependsOn": [
                    {
                        "activity": "br_bs_loggin",
                        "dependencyConditions": [
                            "Succeeded"
                        ]
                    }
                ],
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "userProperties": [
                    {
                        "name": "CheckLookup1",
                        "value": "1"
                    }
                ],
                "typeProperties": {
                    "source": {
                        "type": "SqlSource",
                        "sqlReaderStoredProcedureName": "[dbo].[usp_FeedParameters_main]",
                        "storedProcedureParameters": {
                            "FeedName_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_FeedName",
                                    "type": "Expression"
                                }
                            },
                            "RunType_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_RunType",
                                    "type": "Expression"
                                }
                            },
                            "SrcEnddate_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_SrcEndDate",
                                    "type": "Expression"
                                }
                            },
                            "SrcStartdate_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_SrcStartDate",
                                    "type": "Expression"
                                }
                            },
                            "TgtDate_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_TargetDate",
                                    "type": "Expression"
                                }
                            },
                            "SrcHour_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_SrcHour",
                                    "type": "Expression"
                                }
                            },
                            "TgtHour_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_TgtHour",
                                    "type": "Expression"
                                }
                            }
                        }
                    },
                    "dataset": {
                        "referenceName": "AzureSql_cdpconfiguser",
                        "type": "DatasetReference"
                    },
                    "firstRowOnly": true
                }
            },
            {
                "name": "br_bs_loggin",
                "description": "insert into the batch run and update the batch scheduler to started in case of sch run",
                "type": "Lookup",
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "typeProperties": {
                    "source": {
                        "type": "SqlSource",
                        "sqlReaderStoredProcedureName": "[dbo].[usp_BatchRun]",
                        "storedProcedureParameters": {
                            "FeedName_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_FeedName",
                                    "type": "Expression"
                                }
                            },
                            "RunType_in": {
                                "type": "String",
                                "value": {
                                    "value": "@pipeline().parameters.p_RunType",
                                    "type": "Expression"
                                }
                            },
                            "Status_in": {
                                "type": "String",
                                "value": "Started"
                            }
                        }
                    },
                    "dataset": {
                        "referenceName": "AzureSql_cdpconfiguser",
                        "type": "DatasetReference"
                    },
                    "firstRowOnly": true
                }
            },
            {
                "name": "Check if file exists in target",
                "type": "GetMetadata",
                "dependsOn": [
                    {
                        "activity": "Copy Data WT to ADLS",
                        "dependencyConditions": [
                            "Succeeded"
                        ]
                    }
                ],
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "typeProperties": {
                    "dataset": {
                        "referenceName": "AzureDataLakeStoreFile_wt_tgt_path_and_name",
                        "type": "DatasetReference",
                        "parameters": {
                            "TgtFilePath": "@activity('set_parameters_adh_or_sch').output.firstrow.TgtFileName_wt_dt_out",
                            "TgtFileName": {
                                "value": "@activity('set_parameters_adh_or_sch').output.firstrow.TgtFileName_wt_dt_out",
                                "type": "Expression"
                            }
                        }
                    },
                    "fieldList": [
                        "exists",
                        "size"
                    ]
                }
            },
            {
                "name": "Copy Data WT to ADLS",
                "type": "Copy",
                "dependsOn": [
                    {
                        "activity": "set_parameters_adh_or_sch",
                        "dependencyConditions": [
                            "Succeeded"
                        ]
                    }
                ],
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "userProperties": [
                    {
                        "name": "Source",
                        "value": "@{activity('set_parameters_adh_or_sch').output.firstrow.SrcFilePath_wo_dt_out}/@{activity('set_parameters_adh_or_sch').output.firstrow.SrcFileName_wt_dt_out}"
                    },
                    {
                        "name": "Destination",
                        "value": "@{activity('set_parameters_adh_or_sch').output.firstrow.TgtFilePath_wt_dt_out}/@{activity('set_parameters_adh_or_sch').output.firstrow.TgtFilePath_wt_dt_out}"
                    }
                ],
                "typeProperties": {
                    "source": {
                        "type": "FileSystemSource",
                        "recursive": true
                    },
                    "sink": {
                        "type": "AzureDataLakeStoreSink"
                    },
                    "enableStaging": false,
                    "dataIntegrationUnits": 0
                },
                "inputs": [
                    {
                        "referenceName": "FTP_SRC_FA",
                        "type": "DatasetReference",
                        "parameters": {
                            "SrcFileName": "@activity('set_parameters_adh_or_sch').output.firstrow.SrcFileName_wt_dt_out",
                            "SrcFilePath": "@activity('set_parameters_adh_or_sch').output.firstrow.SrcFilePath_wo_dt_out"
                        }
                    }
                ],
                "outputs": [
                    {
                        "referenceName": "AzureDataLakeStoreFile_wt_tgt_path_and_name",
                        "type": "DatasetReference",
                        "parameters": {
                            "TgtFilePath": "@activity('set_parameters_adh_or_sch').output.firstrow.TgtFileName_wt_dt_out",
                            "TgtFileName": {
                                "value": "@activity('set_parameters_adh_or_sch').output.firstrow.TgtFileName_wt_dt_out",
                                "type": "Expression"
                            }
                        }
                    }
                ]
            },
            {
                "name": "br_bs_update_failed",
                "type": "SqlServerStoredProcedure",
                "dependsOn": [
                    {
                        "activity": "Copy Data WT to ADLS",
                        "dependencyConditions": [
                            "Failed"
                        ]
                    }
                ],
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "typeProperties": {
                    "storedProcedureName": "[dbo].[usp_BatchRunUpdate]",
                    "storedProcedureParameters": {
                        "BatchId": {
                            "value": {
                                "value": "@activity('br_bs_loggin').output.firstrow.Batchid_out",
                                "type": "Expression"
                            },
                            "type": "String"
                        },
                        "FeedID": {
                            "value": {
                                "value": "@activity('br_bs_loggin').output.firstrow.FeedId_out",
                                "type": "Expression"
                            },
                            "type": "Int32"
                        },
                        "FeedRunId": {
                            "value": {
                                "value": "@activity('br_bs_loggin').output.firstrow.BatchRunId_out",
                                "type": "Expression"
                            },
                            "type": "Int32"
                        },
                        "Status": {
                            "value": "Failed",
                            "type": "String"
                        }
                    }
                },
                "linkedServiceName": {
                    "referenceName": "AzureSqlDatabase1_cdp_dev_sql_db_appconfig",
                    "type": "LinkedServiceReference"
                }
            },
            {
                "name": "If Condition1",
                "type": "IfCondition",
                "dependsOn": [
                    {
                        "activity": "Check if file exists in target",
                        "dependencyConditions": [
                            "Succeeded"
                        ]
                    }
                ],
                "typeProperties": {
                    "expression": {
                        "value": "@equals(activity('Check if file exists in target').output.Exists,true)",
                        "type": "Expression"
                    },
                    "ifFalseActivities": [
                        {
                            "name": "Stored Procedure_failed",
                            "type": "SqlServerStoredProcedure",
                            "policy": {
                                "timeout": "7.00:00:00",
                                "retry": 0,
                                "retryIntervalInSeconds": 30,
                                "secureOutput": false,
                                "secureInput": false
                            },
                            "typeProperties": {
                                "storedProcedureName": "[dbo].[usp_BatchRunUpdate]",
                                "storedProcedureParameters": {
                                    "BatchId": {
                                        "value": {
                                            "value": "@activity('br_bs_loggin').output.firstrow.Batchid_out",
                                            "type": "Expression"
                                        },
                                        "type": "String"
                                    },
                                    "FeedID": {
                                        "value": {
                                            "value": "@activity('br_bs_loggin').output.firstrow.FeedId_out",
                                            "type": "Expression"
                                        },
                                        "type": "Int32"
                                    },
                                    "FeedRunId": {
                                        "value": {
                                            "value": "@activity('br_bs_loggin').output.firstrow.BatchRunId_out",
                                            "type": "Expression"
                                        },
                                        "type": "Int32"
                                    },
                                    "Status": {
                                        "value": "Failed",
                                        "type": "String"
                                    }
                                }
                            },
                            "linkedServiceName": {
                                "referenceName": "AzureSqlDatabase1_cdp_dev_sql_db_appconfig",
                                "type": "LinkedServiceReference"
                            }
                        }
                    ],
                    "ifTrueActivities": [
                        {
                            "name": "Stored Procedure1",
                            "type": "SqlServerStoredProcedure",
                            "policy": {
                                "timeout": "7.00:00:00",
                                "retry": 0,
                                "retryIntervalInSeconds": 30,
                                "secureOutput": false,
                                "secureInput": false
                            },
                            "typeProperties": {
                                "storedProcedureName": "[dbo].[usp_BatchRunUpdate]",
                                "storedProcedureParameters": {
                                    "BatchId": {
                                        "value": {
                                            "value": "@activity('br_bs_loggin').output.firstrow.Batchid_out",
                                            "type": "Expression"
                                        },
                                        "type": "String"
                                    },
                                    "FeedID": {
                                        "value": {
                                            "value": "@activity('br_bs_loggin').output.firstrow.FeedId_out",
                                            "type": "Expression"
                                        },
                                        "type": "Int32"
                                    },
                                    "FeedRunId": {
                                        "value": {
                                            "value": "@activity('br_bs_loggin').output.firstrow.BatchRunId_out",
                                            "type": "Expression"
                                        },
                                        "type": "Int32"
                                    },
                                    "Status": {
                                        "value": "Succeeded",
                                        "type": "String"
                                    }
                                }
                            },
                            "linkedServiceName": {
                                "referenceName": "AzureSqlDatabase1_cdp_dev_sql_db_appconfig",
                                "type": "LinkedServiceReference"
                            }
                        }
                    ]
                }
            }
        ],
        "parameters": {
            "p_FeedName": {
                "type": "String",
                "defaultValue": "fa_cpsmyid_vdumcap1"
            },
            "p_BatchType": {
                "type": "String",
                "defaultValue": "RAW"
            },
            "p_RunType": {
                "type": "String",
                "defaultValue": "sch"
            },
            "p_SrcStartDate": {
                "type": "String"
            },
            "p_SrcEndDate": {
                "type": "String"
            },
            "p_TargetDate": {
                "type": "String"
            },
            "p_SrcHour": {
                "type": "String"
            },
            "p_TgtHour": {
                "type": "String"
            }
        },
        "variables": {
            "v_StartDate": {
                "type": "String"
            },
            "v_EndDate": {
                "type": "String"
            }
        },
        "folder": {
            "name": "Batch_load"
        }
    },
    "type": "Microsoft.DataFactory/factories/pipelines"
}

A: Based on your description,all concern is about improving transfer performance,i think.
Firstly,referring to the Data integration units statements, DIU only applies to Azure Integration Runtime, but not Self-hosted Integration Runtime.Your source data is from FTP,so i think it is not affected by the DIU even though you already set the largest number.(Of course,it is referred by the official document,you still could get the verification from ADF team)
Then maybe you could get some clues to improve the copy performance from this document.
Such as:
1. Try to use the parallelCopies property to indicate the parallelism that you want Copy Activity to use. But it also has some restrictions from the statements.
2.Try to set the sink dataset as Azure SQL Data Warehouse,because it seems that it has better performance than ADL.

3.Try to compression the file from the source dataset to reduce the file size.
4.Consider to use Azure Cloud Service as source dataset such as Azure Blob Storage,as i know, the performance of copy activity between azure services is better commonly.