text:
Q: How to disable back swipe gesture in UINavigationController on iOS 7 In iOS 7 Apple added a new default navigation behavior. You can swipe from the left edge of the screen to go back on the navigation stack. But in my app, this behavior conflicts with my custom left menu. So, is it possible to disable this new gesture in UINavigationController?

A: swift 5, swift 4.2 can use the code in the below.
// disable
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
// enable
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

A: I found a solution:
Objective-C:
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

Swift 3+:
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

A: I found out setting the gesture to disabled only doesn't always work. It does work, but for me it only did after I once used the backgesture. Second time it wouldn't trigger the backgesture.
Fix for me was to delegate the gesture and implement the shouldbegin method to return NO:
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Disable iOS 7 back gesture
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    // Enable iOS 7 back gesture
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return NO;
}

A: EDIT
If you want to manage swipe back feature for specific navigation controllers, consider using SwipeBack.
With this, you can set navigationController.swipeBackEnabled = NO.
For example:
#import <SwipeBack/SwipeBack.h>

- (void)viewWillAppear:(BOOL)animated
{
    navigationController.swipeBackEnabled = NO;
}

It can be installed via CocoaPods.
pod 'SwipeBack', '~> 1.0'

I appologize for lack of explanation.

A: it works for me in ios 10 and later :
- (void)viewWillAppear:(BOOL)animated {
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }

}

it doesnt work on viewDidLoad() method.

A: My method. One gesture recognizer to rule them all:
class DisabledGestureViewController: UIViewController: UIGestureRecognizerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController!.interactivePopGestureRecognizer!.delegate = self
    }

    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        // Prevent going back to the previous view
        return !(navigationController!.topViewController is DisabledGestureViewController)
    }
}

Important: don't reset the delegate anywhere in the navigation stack: navigationController!.interactivePopGestureRecognizer!.delegate = nil

A: This is the way on Swift 3
works for me
    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

A: Just remove gesture recognizer from NavigationController. Work in iOS 8.
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    [self.navigationController.view removeGestureRecognizer:self.navigationController.interactivePopGestureRecognizer];

A: All of these solutions manipulate Apple's gesture recognizer in a way they do not recommend. I've just been told by a friend that there's a better solution:
[navigationController.interactivePopGestureRecognizer requireGestureRecognizerToFail: myPanGestureRecognizer];

where myPanGestureRecognizer is the gesture recognizer you are using to e.g. show your menu. That way, Apple's gesture recognizer doesn't get turned back on by them when you push a new navigation controller and you don't need to rely on hacky delays that may fire too early if your phone is put to sleep or under heavy load.
Leaving this here because I know I'll not remember this the next time I need it, and then I'll have the solution to the issue here.

A: As of iOS 8 the accepted answer no longer works.  I needed to stop the swipping to dismiss gesture on my main game screen so implemented this:
- (void)viewDidAppear:(BOOL)animated
{
     [super viewDidAppear:animated];

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }

}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
     return NO;
}

A: I've refined Twan's answer a bit, because:

*

*your view controller may be set as a delegate to other gesture recognisers

*setting the delegate to nil leads to hanging issues when you go back to the root view controller and make a swipe gesture before navigating elsewhere.

The following example assumes iOS 7:
{
    id savedGestureRecognizerDelegate;
}

- (void)viewWillAppear:(BOOL)animated
{
    savedGestureRecognizerDelegate = self.navigationController.interactivePopGestureRecognizer.delegate;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.delegate = savedGestureRecognizerDelegate;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == self.navigationController.interactivePopGestureRecognizer) {
        return NO;
    }
    // add whatever logic you would otherwise have
    return YES;
}

A: This works in viewDidLoad: for iOS 8:
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      self.navigationController.interactivePopGestureRecognizer.enabled = false;
  });

Lots of the problems could be solved with help of the good ol' dispatch_after.
Though please note that this solution is potentially unsafe, please use your own reasoning.
Update
For iOS 8.1 delay time should be 0.5 seconds
On iOS 9.3 no delay needed anymore, it works just by placing this in your viewDidLoad:
(TBD if works on iOS 9.0-9.3)
navigationController?.interactivePopGestureRecognizer?.enabled = false

A: None of the given answers helped me to resolve the issue. Posting my answer here; may be helpful for someone
Declare private var popGesture: UIGestureRecognizer? as global variable in your viewcontroller. Then implement the code in viewDidAppear and viewWillDisappear methods
override func viewDidAppear(animated: Bool) {

    super.viewDidAppear(animated)

    if self.navigationController!.respondsToSelector(Selector("interactivePopGestureRecognizer")) {

        self.popGesture = navigationController!.interactivePopGestureRecognizer
        self.navigationController!.view.removeGestureRecognizer(navigationController!.interactivePopGestureRecognizer!)
    }
}

override func viewWillDisappear(animated: Bool) {

    super.viewWillDisappear(animated)

    if self.popGesture != nil {
        navigationController!.view.addGestureRecognizer(self.popGesture!)
    }
}

This will disable swipe back in iOS v8.x onwards

A: It worked for me for most of the viewcontrollers.
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

It wasn't not working for some viewcontrollers like UIPageViewController. On UIPageViewController's pagecontentviewcontroller below code worked for me.
override func viewDidLoad() {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}

On UIGestureRecognizerDelegate,
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
   if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
      return false
}
      return true
}

A: For Swift:
navigationController!.interactivePopGestureRecognizer!.enabled = false

A: Please set this in root vc:
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

A: For Swift 4 this works:
class MyViewController: UIViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.interactivePopGestureRecognizer?.gesture.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

        self.navigationController?.interactivePopGestureRecognizer?.gesture.isEnabled = false
    }

}

A: self.navigationController.pushViewController(VC, animated: Bool)

call
self.navigationController.setViewContollers([VC], animated: Bool)

setViewControllers replaces all the VCs on the stack, instead of adding a new controller on top. This means that the new set VC is the root VC, and the user cannot go back.
This is most effective when you only want to disable the swipe on a single VC and keep the swipe-to-back for the other VC.
If you want users to be able to go back, just not through swiping, do not use this method as it will disable all backs (as there is no VC to go back to)


text:
Q: Could not download metadata for numpy 1.19.1 using pip I am trying to install the dependencies necessary for a diy teaching library for machine learning engineers (Minitorch), but I get an error after it tries to install a specific version of numpy (1.19.1).
(env) C:\Users\pytho\OneDrive\Documentos\Minitorch\minitorch>python -m pip install -r requirements.txt
Collecting numpy==1.19.1
  Downloading numpy-1.19.1.zip (7.3 MB)
     ---------------------------------------- 7.3/7.3 MB 2.3 MB/s eta 0:00:00
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error

× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─\> \[242 lines of output\]
Running from numpy source directory.
\<string\>:470: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
C:\\Users\\pytho\\AppData\\Local\\Temp\\pip-install-alzx9eh\_\\numpy_1923ad9693a54691aa73f3e3cd16576b\\tools\\cythonize.py:73: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
required_version = LooseVersion('0.29.21')
C:\\Users\\pytho\\AppData\\Local\\Temp\\pip-install-alzx9eh\_\\numpy_1923ad9693a54691aa73f3e3cd16576b\\tools\\cythonize.py:75: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
if LooseVersion(cython_version) \< required_version:
Processing numpy/random_bounded_integers.pxd.in
Processing numpy/random\\bit_generator.pyx
Processing numpy/random\\mtrand.pyx
Processing numpy/random_bounded_integers.pyx.in
Processing numpy/random_common.pyx
Processing numpy/random_generator.pyx
Processing numpy/random_mt19937.pyx
Processing numpy/random_pcg64.pyx
Processing numpy/random_philox.pyx
Processing numpy/random_sfc64.pyx
Cythonizing sources
blas_opt_info:
blas_mkl_info:
No module named 'numpy.distutils.\_msvccompiler' in numpy.distutils; trying from distutils
customize MSVCCompiler
libraries mkl_rt not found in \['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib'\]
NOT AVAILABLE

The error message I get is pretty long and I don't know how to interpret it. Here's the rest:
      atlas_3_10_blas_threads_info:
      Setting PTATLAS=ATLAS
        libraries tatlas not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      atlas_3_10_blas_info:
        libraries satlas not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      atlas_blas_threads_info:
      Setting PTATLAS=ATLAS
        libraries ptf77blas,ptcblas,atlas not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      atlas_blas_info:
        libraries f77blas,cblas,atlas not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      accelerate_info:
        NOT AVAILABLE

      C:\Users\pytho\AppData\Local\Temp\pip-install-alzx9eh_\numpy_1923ad9693a54691aa73f3e3cd16576b\numpy\distutils\system_info.py:1914: UserWarning:
          Optimized (vendor) Blas libraries are not found.
          Falls back to netlib Blas library which has worse performance.
          A better performance should be easily gained by switching
          Blas library.
        if self._calc_info(blas):
      blas_info:
        libraries blas not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      C:\Users\pytho\AppData\Local\Temp\pip-install-alzx9eh_\numpy_1923ad9693a54691aa73f3e3cd16576b\numpy\distutils\system_info.py:1914: UserWarning:
          Blas (http://www.netlib.org/blas/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [blas]) or by setting
          the BLAS environment variable.
        if self._calc_info(blas):
      blas_src_info:
        NOT AVAILABLE

      C:\Users\pytho\AppData\Local\Temp\pip-install-alzx9eh_\numpy_1923ad9693a54691aa73f3e3cd16576b\numpy\distutils\system_info.py:1914: UserWarning:
          Blas (http://www.netlib.org/blas/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [blas_src]) or by setting
          the BLAS_SRC environment variable.
        if self._calc_info(blas):
        NOT AVAILABLE

      non-existing path in 'numpy\\distutils': 'site.cfg'
      lapack_opt_info:
      lapack_mkl_info:
        libraries mkl_rt not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      openblas_lapack_info:
        libraries openblas not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      openblas_clapack_info:
        libraries openblas,lapack not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      flame_info:
        libraries flame not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      atlas_3_10_threads_info:
      Setting PTATLAS=ATLAS
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries tatlas,tatlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries lapack_atlas not found in C:\
        libraries tatlas,tatlas not found in C:\
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries tatlas,tatlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries lapack_atlas not found in C:\ProgramData\Anaconda3\Library\lib
        libraries tatlas,tatlas not found in C:\ProgramData\Anaconda3\Library\lib
      <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
        NOT AVAILABLE

      atlas_3_10_info:
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries satlas,satlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries lapack_atlas not found in C:\
        libraries satlas,satlas not found in C:\
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries satlas,satlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries lapack_atlas not found in C:\ProgramData\Anaconda3\Library\lib
        libraries satlas,satlas not found in C:\ProgramData\Anaconda3\Library\lib
      <class 'numpy.distutils.system_info.atlas_3_10_info'>
        NOT AVAILABLE

      atlas_threads_info:
      Setting PTATLAS=ATLAS
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries ptf77blas,ptcblas,atlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries lapack_atlas not found in C:\
        libraries ptf77blas,ptcblas,atlas not found in C:\
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries ptf77blas,ptcblas,atlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries lapack_atlas not found in C:\ProgramData\Anaconda3\Library\lib
        libraries ptf77blas,ptcblas,atlas not found in C:\ProgramData\Anaconda3\Library\lib
      <class 'numpy.distutils.system_info.atlas_threads_info'>
        NOT AVAILABLE

      atlas_info:
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries f77blas,cblas,atlas not found in C:\Users\pytho\.conda\envs\env\lib
        libraries lapack_atlas not found in C:\
        libraries f77blas,cblas,atlas not found in C:\
        libraries lapack_atlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries f77blas,cblas,atlas not found in C:\Users\pytho\.conda\envs\env\libs
        libraries lapack_atlas not found in C:\ProgramData\Anaconda3\Library\lib
        libraries f77blas,cblas,atlas not found in C:\ProgramData\Anaconda3\Library\lib
      <class 'numpy.distutils.system_info.atlas_info'>
        NOT AVAILABLE

      lapack_info:
        libraries lapack not found in ['C:\\Users\\pytho\\.conda\\envs\\env\\lib', 'C:\\', 'C:\\Users\\pytho\\.conda\\envs\\env\\libs', 'C:\\ProgramData\\Anaconda3\\Library\\lib']
        NOT AVAILABLE

      C:\Users\pytho\AppData\Local\Temp\pip-install-alzx9eh_\numpy_1923ad9693a54691aa73f3e3cd16576b\numpy\distutils\system_info.py:1748: UserWarning:
          Lapack (http://www.netlib.org/lapack/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [lapack]) or by setting
          the LAPACK environment variable.
        return getattr(self, '_calc_info_{}'.format(name))()
      lapack_src_info:
        NOT AVAILABLE

      C:\Users\pytho\AppData\Local\Temp\pip-install-alzx9eh_\numpy_1923ad9693a54691aa73f3e3cd16576b\numpy\distutils\system_info.py:1748: UserWarning:
          Lapack (http://www.netlib.org/lapack/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [lapack_src]) or by setting
          the LAPACK_SRC environment variable.
        return getattr(self, '_calc_info_{}'.format(name))()
        NOT AVAILABLE

      numpy_linalg_lapack_lite:
        FOUND:
          language = c
          define_macros = [('HAVE_BLAS_ILP64', None), ('BLAS_SYMBOL_SUFFIX', '64_')]

      C:\Users\pytho\AppData\Local\Temp\pip-build-env-r4qjpa7c\overlay\Lib\site-packages\setuptools\_distutils\dist.py:265: UserWarning: Unknown distribution option: 'define_macros'
        warnings.warn(msg)
      running dist_info
      running build_src
      build_src
      building py_modules sources
      creating build
      creating build\src.win-amd64-3.10
      creating build\src.win-amd64-3.10\numpy
      creating build\src.win-amd64-3.10\numpy\distutils
      building library "npymath" sources
      C:\Users\pytho\AppData\Local\Temp\pip-build-env-r4qjpa7c\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py:539: UserWarning: Fallback spawn triggered. Please update distutils monkeypatch.
        warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
      creating build\src.win-amd64-3.10\numpy\core
      creating build\src.win-amd64-3.10\numpy\core\src
      creating build\src.win-amd64-3.10\numpy\core\src\npymath
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npymath\npy_math_internal.h
        adding 'build\src.win-amd64-3.10\numpy\core\src\npymath' to include_dirs.
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npymath\ieee754.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npymath\npy_math_complex.c
      None - nothing done with h_files = ['build\\src.win-amd64-3.10\\numpy\\core\\src\\npymath\\npy_math_internal.h']
      building library "npysort" sources
      creating build\src.win-amd64-3.10\numpy\core\src\common
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\common\npy_sort.h
        adding 'build\src.win-amd64-3.10\numpy\core\src\common' to include_dirs.
      creating build\src.win-amd64-3.10\numpy\core\src\npysort
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\quicksort.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\mergesort.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\timsort.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\heapsort.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\radixsort.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\common\npy_partition.h
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\selection.c
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\common\npy_binsearch.h
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\npysort\binsearch.c
      None - nothing done with h_files = ['build\\src.win-amd64-3.10\\numpy\\core\\src\\common\\npy_sort.h', 'build\\src.win-amd64-3.10\\numpy\\core\\src\\common\\npy_partition.h', 'build\\src.win-amd64-3.10\\numpy\\core\\src\\common\\npy_binsearch.h']
      building library "npyrandom" sources
      building extension "numpy.core._multiarray_tests" sources
      creating build\src.win-amd64-3.10\numpy\core\src\multiarray
      conv_template:> build\src.win-amd64-3.10\numpy\core\src\multiarray\_multiarray_tests.c
      building extension "numpy.core._multiarray_umath" sources
      BUILD_ARCHITECTURE: 'AMD64', os.name='nt', sys.platform='win32'
      error:
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I tried installing a slightly different version of numpy, but then when I had to install torch it told me there was no compatible version with my previous installations. I already tried using venv instead of conda to create a virtual environment or resetting my computer and installing everything again, but none of that made any difference.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compile Cmake with SFML I was trying to compile Cmake with SFML and try several things from different sites, but no result.
This same code is from my teammate that works for him in Fedora 29 while me for Ubuntu doesn't work, and I have no idea what to try more.
cmake_minimum_required(VERSION 3.16)
project(indie)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "-W -Wall -Wextra -I./$(INCLUDE_PATH) -Wno-long-long -lsfml-graphics -lsfml-window -lsfml-system -lIrrlicht")

include_directories(src
        include)

add_executable(indie
        src/Indie.cpp
        include/Indie.hpp
        src/Player.cpp
        include/Game.hpp
        include/Player.hpp
        src/Game.cpp
        include/Menu.hpp
        src/Menu.cpp
        include/Structures.hpp
        src/Structures.cpp
        include/Macros.hpp
        main.cpp)


text:
Q: where is /etc/xinetd.d/telnet in fedora 23 I'm studying linux server book.
I'm now seeing telnet.
they say after install telnet, I should modify telnet configure in /etc/xinetd.d/telnet
but there is no telnet file. but install is well finished.

A: Fedora 23 is based on Systemd. The Fedora 23  telnet-server (that's what you installed) uses sytemd service units to manage the telnetd service. To enable it, run systemctl enable telnetd.socket and to start it, systemctl start telnetd.socket. Use this /usr/lib/systemd/system/telnet.socket instead for checking configuration.


text:
Q: Collapse ControlP5 DropdownList I am having issues collapsing a  ControlP5 DropdownList object.
I select the item that I want, the arrow points up as if it wanted to collapse....but all of the choices are still there! It never collapses after a selection is made.
I have looked at the isOpen() function and it is telling me that the list is closed. I have also explored the isCollapse() function and it is telling me that the list is already collapsed......
Here is my code for instantiating the object:
    SimilarityChoices = P5Controller.addDropdownList("SimChoices").setPosition((float)(width * .7), 450);
    SimilarityChoices.addItem("Euclidian", 1);
    SimilarityChoices.addItem("Manhattan", 2);
    SimilarityChoices.setValue(2);
    this.SimilarityChoices.enableCollapse();
    this.SimilarityChoices.setItemHeight(20);
    this.SimilarityChoices.actAsPulldownMenu(true);

If anybody can give me a hint on how to make this work, I'd be much obliged. (And I'm happy to supply more information as well)

A: You'll notice that the dropdownlist example sketch includes this:
void draw() {
  background(128);
}

which draws over the pixels previously rendered while the list was expanded. I wrote a sketch using your code to illustrate the difference more clearly:
import controlP5.*;

ControlP5 P5Controller;
DropdownList SimilarityChoices;

void setup() {
  size(500, 500);
  P5Controller = new ControlP5(this);
  SimilarityChoices = P5Controller.addDropdownList("SimChoices").setPosition((float)(width * .7), 450);
  SimilarityChoices.addItem("Euclidian", 1);
  SimilarityChoices.addItem("Manhattan", 2);
  SimilarityChoices.setValue(2);
  this.SimilarityChoices.enableCollapse();
  this.SimilarityChoices.setItemHeight(20);
  this.SimilarityChoices.actAsPulldownMenu(true);
}
void draw() {
  //background(128);
}

Uncommenting the background(128); line makes it behave as expected. I hope that helps! Note that some of the settings you coded in may no longer be necessary.


text:
Q: Use a standard single sql to group data (SQL Server) Raw data with 2 columns:
0 33
2 null
0 44
2 null
2 null
2 null
0 55
2 null
2 null
.....

Results I want:
2 33
2 44
2 44
2 44
2 55
2 55
....

Can I use a SQL statement to accomplish this? (return the rows with 2 only but fill with values come from the previous row that is 0), there could be many '2 null' between 0.

A: This way
with s as (
    select *
    from
    (values
        (1,0,33  ),
        (2,2,null),
        (3,0,44  ),
        (4,2,null),
        (5,2,null),
        (6,2,null),
        (7,0,55  ),
        (8,2,null),
        (9,2,null)
    ) T(id,a,b)
)
select s1.a, t.b
from s s1
cross apply (
    select top(1) s2.b
    from s s2
    where s2.id < s1.id and s2.b is not null and s2.a = 0
    order by s2.id desc ) t
where s1.a = 2
order by s1.id;

I use CROSS APPLY so the query may be easily extended to get other columns from  the relevant '0' row.

A: First of all, select value for every row with null:
SELECT col2 FROM (SELECT MAX(ID) FROM your_tbl t WHERE t.ID < ID AND col2 IS NOT NULL);

Then write a condition for your table with that subquery:
SELECT col1, (
    SELECT col2 FROM your_tbl where id = (SELECT MAX(ID) FROM your_tbl t
    WHERE t.ID < tbl.ID AND col2 IS NOT NULL))
FROM your_tbl tbl WHERE col1 <> 0;


text:
Q: Constraints Foregin Key allows null? I have these two tables:
 Table1
ID,int(Key) not null
Name,nvarchar not null

Table2
MyCode, int(key) not null
Year, int(key) not null
ExternalCode,int(Fkey) null

Constraints
ALTER TABLE "Table2" WITH CHECK
ADD CONSTRAINT"FK_Table2_Table1_ExternalCode" CHECK ([ExternalCode] IS NOT NULL) REFERENCES [Table1] (ID)
ALTER TABLE "Table2" CHECK CONSTRAINT "FK_Table2_Table1_ExternalCode";

SQL server reports syntax error in REFERENCES, how can I create the constraint? Or rather, is it possible to insert a costraint on a foreign key if my key (ExternalCode) is nullable?
Edit...
The Table2 index is MyCode,year,ExternalCode, in certain conditions decided by a configuration parameter from the application, Table1 can be empty and in no way can a record be written to it and therefore ExternalCode can be null in those cases, in other cases or when Table1 has records (why not base as soon as I modify that condition a record is written on Table1)


text:
Q: Google OAuth to remember chosen account I've implemented Google OAuth 2.0 login on a site that I'm working on. It works fine, except in situations when the user is logged with two or more different accounts on the same browser. It's asking him to choose which one he want's to use. But it's asking the user every time to choose the account. Is there a way to remember this, so the user can choose the account only the first time and later automatically to log him with that account?
You can put hd=domain.com parameter in the request to Google, but that only helps if the two logged accounts are from different domains and it can than log the user in with @domain.com account.
I read somewhere that you can send user_id account as a parameter to Google (I guess that would be the email address), but in this case I don't know the users email address before he logs in.
I think this behavior is the same if you use OpenID.
I'm using Google's PHP OAuth library.
Thanks,
Andrej

A: Google should have a cookie set that enables OAuth applications to tell what account to currently use.

A: If you know the email address you want to log in with, you can use the login_hint parameter and they won't see the account chooser.  See https://developers.google.com/accounts/docs/OAuth2Login#sendauthrequest


text:
Q: Get Description of Columns Returned In SQL Server and/or its C# API, is there a mechanism by which I can get a description (i.e. column names and data types) of the result of executing arbitrary SQL/prepared statement/stored procedure without actually executing it?
Example...
select * from my my_table

Desired result...
col_1        col_2        col_3        ...        col_n
integer      float        varchar(32)             datetime2

Or some equivalent information?

A: SET FMTONLY is what you're looking for:

Returns only metadata to the client. Can be used to test the format of the response without actually running the query.

E.g.:
SET FMTONLY ON
GO
select * from my my_table
GO
SET FMTONLY OFF
GO

Will produce an empty result set.

In C#, with an SqlCommand object, you can specify the SchemaOnly CommandBehaviour and you'll similarly get an empty result set that you can then examine.

A: I think you might get use out of this:
EXEC sp_help my_table

Or see my question/answer here: How do I get a list of columns in a table or view?


text:
Q: Access nodejs application from URL on VPS I have a VPS running apache on CentOS 6.5. I'm currently writing a node application to run on port 1234.
My question is that, how to access the node application via URL. Like http://IP_ADDRESS:1234 or http://MYDOMAIN:1234?

A: It was not actually a node issue. It was a firewall that was blocking all requests to the port 1234.
I found that advanced policy firewall (APF) was installed on my machine. All I had to do to allow connections to the required port is to edit APF config file located in /etc/apf/conf.apf.
Then add the required ports to the variable IG_TCP_CPORTS=
Finally, restart APF to apply effects
$ /usr/local/sbin/apf -r


text:
Q: Using a macro to define an include file To make a long story short, I'm working on some code that needs different header files based on various configuration options. I could do something like this:
#if OPTION == A
#include "relative/path/to/file/a.hpp"
#elseif OPTION == B
#include "relative/path/to/file/b.hpp"
#elseif OPTION = ...
...
#endif

This would work, but it seems like a really ugly solution for what could potentially be more than a handful files. I could also simply include all the various header files, but that, too, seems like a bit of an ugly solution, and it could pose problems in the future if files (for some horrible reason) start redefining the same objects. The idea I had was that something like the following would be nice, particularly in the context of how the rest of the code is written:
#define QUOTE(str) #str
#define STRINGIFY(A,B) QUOTE(A##B)
...
#include STRINGIFY(relative/path/to/option/,OPTION)

The problem with this seems to be two-fold:

*

*The OPTION definition doesn't expand properly inside STRINGIFY.

*If there are any forward slashes in the path name, STRINGIFY fails altogether, with g++ giving me an error along the lines of the following:

error: pasting "/" and "OPTION" does not give a valid preprocessing token

I can't seem to find any real information on why / is a bad character for the C++ preprocessor, just a few articles saying that you should just put "/" in and rely on automatic C++ string concatenation (which doesn't work in an #include statement). I'm willing to consider design alternatives if I'm just trying to do something really dumb, but I'd also like to figure out why this isn't working.
EDIT: I should make the clarification that I'm working on a codebase originally designed by a group of scientists. Reasonable coding conventions and typical expectations for how a code gets used go completely out the window. This code will probably be modified at least as many times as it gets used, often by people who have spent their entire careers writing Fortran 77 and think object-oriented programming is some new-fangled invention that just makes your code harder to understand.

A: When writing macros it is essential to look at the output after preprocessing. With gcc thats the -E option.
To include different files I would rely on your build tools rather than macro voodoo. For example when the code is
include option

Then gcc -E -option=\"foo.h\" yields
include "foo.h"

Note that I ommitted the # here, otherwise preprocessing would fail due to not finding "foo.h".

A: I wanted to do something similar, searched around and found this post, and after trying few things I think I can help you.
So, your approach:
#define QUOTE(str) #str
#define STRINGIFY(A,B) QUOTE(A##B)
...
#include STRINGIFY(relative/path/to/option/,OPTION)

As I understand from https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html doesn't work because when using ## to paste tokens, the result must be a valid token, where something like path/to/file.hpp is not a valid preprocessing token.
Now, I think that you only need to have a macro which holds the path plus the token to be replaced. Well, you don't really need to add the relative path if you are using the -I flag. Your macro could look like #define myMacro relative/path/to/file/OPTION.hpp, then you just need to define OPTION and pass it to one macro so OPTION gets replaced with its value and then another macro to stringize. These two levels of macros are described here https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html#Stringizing
The following example will ilustrate both cases (with/without -I flag).
Consider this directory structure:
.
|-- a.c
|-- headers
|   |-- A.hpp
|   `-- B.hpp
`-- makefile

Where a.c:
#define header OPTION.hpp
#define xstr(x) #x
#define str(x) xstr(x)
#include str(header)

makefile:
PATH_OPTION ?= headers/A
OPTION ?= A

.PHONY: all
all: a.c
        cpp -D OPTION=${PATH_OPTION} $<
        cpp -I./headers -D OPTION=${OPTION} $<

A.hpp
#warning Including A.hpp
1

B.hpp
#warning Including B.hpp
2

With this, you can call make which by default will include headers/A.hpp and you should be able to see both approaches (with/without -I flag) working and printing to stdout the corresponding warning.
To include headers/B.hpp you would do make OPTION=B or make PATH_OPTION=headers/B depending on the approach you take.
I also tried with g++ instead of cpp and it works as well.


text:
Q: Transfer function of an H bridge circuit Hey guys I'm trying to find the transfer function of the given circuit. It is an H bridge motor driver circuit. I have tried to find a spice model for these chips but could not find anything. Any help related would be really appreciated.

A: Here is a simplified SPICE "circuit" for a IDEAL "bridge" model.
E1 & E2 are the driving "functions".
Bridge has "direction" and "enable" functions (PWM driven).
Can be modified to include some "defects" ...

Here another circuit with "analog" inputs (based on a sawtooth wave -> PWM).


text:
Q: Convert UIView to UIImage to save as binary data in Core Data I am trying to save a UIView as a UIImage to save in the Core Data database. My code is causing a compile error at self.canVasView.image stating:

Value of type 'UIView' has no member 'image'.

I think part of this code works in Swift 4 but it is not working in Swift 5.
var canVasView = UIView()

@objc func hhh() {
    let photo = self.canVasView.image
    let data = UIImagePNGRepresentation(photo!)

    if cdHandler.saveObject(pic:  data!){
    }
}

A: You need to use a specific subclass of UIView.
Try using:
var canVasView = UIImageView()

Of course, you need to actually set the .image property to some UIImage in order for the call to UIImagePNGRepresentation to actually work.


text:
Q: What is the difference between idn and idn2? what is the difference between idn and idn2? (why two that do almost the same. why the output is different. Which one should be used)
infile:
Amazon.com
ama--zon.com
a--mazon.com
--amazon.com
amazon--.com
amazon-.com

cat infile | idn
Amazon.com
ama--zon.com
a--mazon.com
--amazon.com
amazon--.com
amazon-.com

cat infile | idn2
amazon.com
ama--zon.com
a--mazon.com
idn2: toAscii: string start/ends with forbidden hyphen

(for 3 last entry)
THK
Update: This is the answer what i'm looking for. Thanks. Vote close.
GNU IDN Library - Libidn
Please be aware that GNU libidn2 is the successor of GNU libidn. It comes with IDNA 2008 and TR46 implementation and also provides a compatibility layer for GNU libidn.


text:
Q: Android: Singleton DefaultHttpClient will not keep session I am using a singleton instance of a DefaultHttpClient in my Android application so that the session with my website remains authenticated across multiple activities after logging in.
This is the singleton class for the DefaultHttpClient:
public class Client {
  private static DefaultHttpClient instance = null;
  //handler for current response in UI thread after receiving it in AsyncTask
  private static HttpResponse currentResponse = null;

  //I also tried this without "synchronized"
  public synchronized static DefaultHttpClient getInstance()
  {
  if(instance == null)
    {
      instance = new DefaultHttpClient();
    }
    return instance;
  }
  public static void setCurrentResponse(HttpResponse response)
  {
    currentResponse = response;
  }
  public static HttpResponse getCurrentResponse()
  {
    return currentResponse;
  }
}

I call the client each time it is used in an AsyncTask using Client.getInstance().
I have tried:
ClientInstance = Client.getInstance();
Client.setCurrentResponse(ClientInstance.execute(HttpPost to execute));

I have tried:
Client.setCurrentResponse(Client.getInstance().execute(HttpPost to execute));

And numerous other ways of going about it that I have found through searches.
I have also tried using a CookeStore and HttpContext, which produces the same result.
Using consumeContent() on the entity when I get it from the response also does not fix the issue.
Everything I have found has said that using a singleton instance of DefaultHttpClient allows it to maintain its session, but every time I execute a post to perform an action for which my website requires users to be logged in, the response body I get back displays the error indicating that the 'user_id' session variable is not set (so the user is not logged in). I have searched Google and Stack Overflow exhaustively to no avail. Can somebody please point out what I'm doing wrong?

A: Sorry for the question, guys.
After almost losing my sanity, I looked my php code over one more time. It turns out the problem was on my webpage - I was not allowing the php to call session_start() when receiving the mobile HttpPost. Who knows, maybe my question/answer will help somebody else.


text:
Q: Use symlink to provide access to a specific file under a restricted directory My home directory's permissions allow only myself access to it.
Is it possible to put a file inside my home directory with.. say.. full permissions, and create a symlink to it so other users can access that file alone inside my home folder?
System is Ubuntu Karmic.

A: It's possible, but not with symbolic links. It's called Hard links. Usage:
ln /home/you/the-file /some/public/folder/

A reference to the file "the-file" will be created in /some/public/folder/the-file.
Hard links points to the same inode (file, directory, ...). Symbolic links have their own inode, and will not work in chroots for example. Since hard links links to a inode instead of a path, it can only be used on the same filesystem.
Another way would be bind mounts. This will require root permissions for running the mount command and can only be used for directories. Usage:
sudo mount --bind /home/you/the-folder-to-be-shared/ /some/public/folder

/some/public/folder should be an existent folder. It does not have to be empty, although it's recommended because the contents will not be visible after mounting /home/you/the-folder-to-be-shared on /some/public/folder.
If you decide to remove this shared folder from /some/public/folder, run:
sudo umount /some/public/folder

A: An easier way is to make a dir in your home directory, set it to whatever permission for the users you want to read to do so, then set your home dir to 701 permission.
With directories the read permission is needed to list the contents, execute to enter (as in to traverse, as done in the /path/to/dir part of the ls), and write to create files (when together with execute).

ls /home/[user] -- permission denied
ls /home/[user]/[shared dir] -- allowed

Anyone know of a down side to this? Please comment.


text:
Q: Extjs 4.0.7 How do I re render my treepanel to see changes I am creating an item selector with two boxes that move things back and forth within an extjs application. On the right box, I am creating buttons  that serve to move items up and down. Essentially I am swapping the item with one above or below it. So, my code is straight forward in that regard
MoveUp: function(button, event, eOpts){
  var theChosen = Ext.getStore('storeId').getRootNode().findChild('text', 'Chosen folder');
  var chosenPanel = Ext.ComponenetQuery.query('#chosenTreePanel')[0];
  var selected = chosenPanel.getSelectionModel().getSelection();

  for( var i = 1; i < theChosen.childNodes.length; i++){
    if(Ext.Array.contains(selected, theChosen.childNodes[i]) && (!Ext.Array.contains(selected, theChosen.childNodes[i-1]){
      var temp = theChosen.childNodes[i];
      theChosen.childNodes[i] = theChosen.childNodes[i-1];
      theChosen.childNodes[i-1] = temp;

    }

  }
}

All of this code seems to work fine, because after clicking my button, and checking the DOM in firebug, I can see that the selected nodes have moved in the array correctly, however, this effect is never shown within my treepanel. ???How do I make the treepanel update when it's elements change. ???
TreePanel heirarchy looks like this just to clarify
Root Node
'Chosen Folder Node'
Array of items I am moving up and down within the 'folder'
I am USING VERSION 4.0.7
Attempting to use replaceChild() to fire an event to rerender does not behave as I expected
Changing:
var temp = theChosen.childNodes[i];
theChosen.childNodes[i] = theChosen.childNodes[i-1];
theChosen.childNodes[i-1] = temp;

To:
var temp = theChosen.childNodes[i];
theChosen.replaceChild(theChosen.childNodes[i-1], theChosen.childNodes[i]);
theChosen.replaceChild(temp, theChosen.childNodes[i-1]);

Results in odd behavior in which some nodes go missing. Certaintly not what I was looking for. Where am I going wrong here?
Tried the following code using the datachanged and (undocumented)refresh event:
Ext.getStore('storeId').fireEvent('datachanged', Ext.getStore('chosen') );
Ext.getStore('storeId').fireEvent('datachanged', Ext.getStore('chosen') );

This does not reload anything...
SOLUTION:
Use the insertChild method of nodeInterface....
I have noticed something strange in how insertChild works in that I need to change my index more based on moving up or down will explain with code below.
To move Up:
theChosen.insertChild( (i-1), theChosen.childNodes[i]);

To move down:
theChosen.insertChild( (i+2), theChosen.childNodes[i]);

Although the -1 vs +2 they both effectively move the item by one in the appropriate direction.

A: If you want to update the view of the nodes, I recommend using yourTree.getView().refresh();
But you can avoid that by using parentNode.insertChild(index, childNode); where index is where you want the node to show up and parentNode is the parent to the nodes you are reordering.  ChildNode can be a config for a new node or any other nodeinterface that already exists.  If the node does already exist and you use the insertChild method to insert it, it will automatically remove that node from whereever else it is.
So as you provided in your question in response to my answer, your code will work with something like (this is probably how I'd do it, but this is untested):
MoveUp: function(button, event, eOpts){
    var chosenPanel = Ext.ComponenetQuery.query('#chosenTreePanel')[0];
    var selectedNodes = chosenPanel.getSelectionModel().getSelection();
    for( var i = 0; i < selectedNodes.length; i++){
        var currentNode = selectedNodes[i];
        if(!currentNode.isFirst())
        {
            var parentNode = currentNode.parentNode;
            var newIndex = parentNode.indexOf(currentNode) - 1;
            parentNode.insertChild(newIndex, currentNode);
        }
    }
}

A: Edit:
Back to the the responsible event question...
You need to fire the
'datachanged'
'refresh'

Events on the store with the store as only param. That should cause a UI update. But please note that I just had a glimpse into the sourcecode and I am sure this can all be done much smarter. At least a DD solution for this exists already.
If I find some time I my look into this again, but I guess you should be fine with these events for the first.
You never see anything cause you just do it without the appropriate methods that then fire the responsible events that cause rerender. Take a look at

*

*appendChild()

*removeChild()

*replaceChild()
There may also be more methods that can help on the Ext.data.NodeInterface. I recommend you to use these instead of doing it under hood without any responsible event fired.
In addition to my second comment (just a wild guess without knowing if that is exactly what you want):
MoveUp: function(button, event, eOpts){
    var target = Ext.getStore('storeId').getRootNode().findChild('text', 'Chosen folder');
    var selected = chosenPanel.getSelectionModel().getSelection();
    target.appendChild(selected);
}


text:
Q: Making HTTPS requests using a provided x509 certificate on Google App Engine I'm interested if Google App Engine provides a way to use a X.509 Certificate to create a HTTPS connection (the server where I have to connect provides the public certificate - to encrypt data that I send and the private key to decrypt the data received from that server).
According to this post https://groups.google.com/forum/?fromgroups#!topic/google-appengine-python/C9RSDGeIraE it's not possible but 3 years passed since this answer was posted.

A: AppEngine has the ability to work with SSL certificate on your custom domain, that means the you can assign a certificate to a domain that is running on the AppEngine.
You cannot AFAIK make a request and provide a custom certificate per request.
Documentation on AppEngine SSL.

A: SSL client certificates are not currently supported. The feature request is here.


text:
Q: iOS Parse RSS Feed Retrieve dc:creator Tag Recently Enclosed By CDATA I have an iPhone app that is parsing a WordPress default RSS feed. It is parsing various tags including title, pubDate, dc:creator and link.
dc:creator tag used to be like its written below. The Wordpress sites that i haven't updated still shows this tag as below:
<dc:creator>Andy RR</dc:creator>

I am using NSXMLParser. I was able to successfully get this text using the following code in my didStartElement method:
if ([elementName isEqual:@"dc:creator"])
    {
        currentString = [[NSMutableString alloc] init];
        [self setCreator:currentString];
    }

But with the updated WordPress sites, the default feed that is found under http ://sitename.com/feed shows the dc:creator tag enclosed inside CDATA as follow:
<dc:creator>
<![CDATA[ Andy RR ]]>
</dc:creator>

So the previous code is not getting the text inside dc:creator since its enclosed by CDATA block now.
Now i want to get this CDATA block under dc:creator. I can use the following method of NSXMLParser:
-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    currentString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    NSLog(@"CDaTa text %@", currentString);
}

But the problem is that this method gets all the text from CDATA from other tags as well that are enclosed under CDATA tag. Remember other than dc:creator, there are other tags like "category" and "description" that also have the text enclosed under CDATA block.
What i want is how can the NSXMLParser's foundCDATA method can get only the text under dc:creator tag and ignores other CDATA tags like category and description. How can i achieve that?

A: Solved it my self by using the following:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
     if ([elementName isEqual:@"dc:creator"])
     {
          currentString = [[NSMutableString alloc] init];
          [self setCreator:currentString];
    }
}

and in the cdata method of NSXMLParser, just appending string worked:
    -(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
    {
          NSString *someString1 = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
         [currentString appendString:someString1];
    }


text:
Q: Oracle to Sql server Migration is very slow SSIS package Details
SOURCE- ORACLE database
Connection Manager:- Native oledb\Microsoft OLE DB Provider For Oracle

Destination SQL SERVER database
Connection Manager:-Native oledb\SQL SERVER Native Client 10.0

Currently, the Data migration is very slow, Kindly let me know any suggestions to speedup the migration.

A: This can be down to many things, and you will just have to check loads of stuff.

*

*Network Speed (more below)

*Load on Oracle server - CPU, Disk, Network

*Load on SQL Server - CPU, Disk, Network

I did a large Oracle to SQLServer migration a few years ago, using SSIS. When I ran the SSIS packages on my desktop machine, the data path was from my desktop to the Oracle Server in the Data Centre over a fast WAN, data back to my desktop, data out to the SQL Server in a different Data Centre. The speed was not good.
We ended up running the SSIS packages on the the SQL Server machine.This was far, far faster - by about an order of between 10 and 100 as I remember. Making the network path be DC <-> DC instead of DC <-> Desktop -> DC was the difference.
Cheers -

A: Lots of potential bottlenecks here. Hard to know with so few details provided in the question. Can you post more details and maybe a screenshot of your SSIS package data flow? In general, these can help you rule out a few things:

*

*Rule out SQL Server destination as an issue

*

*Remove the SQL Server destination from your data flow

*Add a Union All transformation

*Connect your Oracle source to the Union All

*Do not connect the Union All transformation to a destination

*Execute your data flow

*If its slow, you know that you have an issue with your Oracle source

*If its fast, you know you have an issue with your SQL Server destination

*Are there indexes on your SQL Server destination table?

*

*Consider removing them prior to the insert and rebuilding them after

*OLE DB Destination Editor setting (these are probably your defaults)

*

*Data access mode: Table or view - fast load

*Table lock (check)

*Maximum insert commit size: 2147483647


text:
Q: How do you import discord.py on ubuntu terminal? So I've been using windows 10 for quite a while but my windows has many problems so I am now using ubuntu.
pip install discord

used to always work;
but I just can't find any tutorial about installing discord.py on ubuntu.
The following all don't work:
Pip install discord
And
Pip install discord.py

A: Maybe pip isn't added to your path. Try python3 -m pip install discord.


text:
Q: How can I convert "YYYY-MM-DD HH:mm:ss.SSS" string to a Java Date object? I have a date string coming from database resultset like this 2022-07-21 16:19:23.209 I need to convert this string to a java date object. I am using java-11.
Note: I am using Spring JpaRepository with nativeQuery for fetiching records from db. Since I am not using an entity class type, it returns result set with List<Object[]>. One of the elements from the resultset object is a db timestamp (java.sql.Timestamp; example: obj[1] is 2022-07-21 16:19:23.209). I need to map this to a pojo.


text:
Q: Problems getting Auth:: user() I'm new to Laravel. I want to get an authorized user using the Auth::user () facade, in order to extract its ID, in the logout() method this is obtained and the authorized user is returned as an array with its data, but in the store() method Auth:: user () returns null. Tell me, please, what is the problem?
AuthController (here is logout()):
<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserLoginRequest;
use Egulias\EmailValidator\Exception\AtextAfterCFWS;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;

class AuthController extends Controller
{
    public function store(UserCreateRequest $request){
        $user               = new User();
        $user->login        = $request->get('login');
        $user->password     = Hash::make($request->get('password'));
        $user->email        = $request->get('email');
        $user->number_phone = $request->get('number_phone');
        $user->assignRole('user');

        if (!$user->save()) {
            return response()->json(['message'=>'Регистрация не удалась']);
        }

        return response()->json(['message'=>$user->jsonSerialize()]);
    }

    public function login(UserLoginRequest $request){

        $user = User::query()->where('login', $request->get('login'))->first();
        if (!$user || !Hash::check($request->get('password'), $user->password)) {
            return response()->json(['message'=>'Попытка входа не удалась'], 400);
        }

        $token = $user->createToken('api_token')->plainTextToken;
        $user->api_token = $token;
        $user->save();
        $user = Auth::login($user);

        return response()->json(['message'=>Auth::user()->api_token], 200);
    }

    public function logout(Request $request) {
        dd(Auth::user());
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Вы вышли из системы'], 200);
    }

AuthController (here is store()):
<?php

namespace App\Http\Controllers;

use App\Http\Requests\ApplicationCreateRequest;
use Illuminate\Http\Request;
use App\Models\Application;
use App\Models\Status;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class ApplicationController extends Controller
{
    public function showById($id) {
        return response()->json(Application::find($id), 200);
    }

    public function show() {
        return response()->json(Application::all(), 200);
    }

    public function store(ApplicationCreateRequest $request){
        dd(Auth::user());
        //$application                = new Application();
        //dd(Auth::user()->api_token);
        //$application->user_id       = Auth::id();
        //$application->status_id     = 1;
        //$application->description   = $request->get('description');
//
        //if (!$application->save()) {
        //    return response()->json(['message'=>'Заявка не отправлена'], 500);
        //}
//
        //return response()->json(['message'=>$application->jsonSerialize()]);
    }

    public function delete(Application $application) {
        if ($application->delete()) {
            return response()->json('Заявка удалёна', 200);
        }

        return response()->json(['message' => 'Заявка не удалёна'], 500);
    }

//    public function updateStatus(Application $application)
//    {
//        if ($application->status_id)
//    }
}

api.php:
<?php

use App\Http\Controllers\ApplicationController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ReviewController;
use App\Http\Controllers\AdminController;
use App\Http\Requests\UserLoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group(['middleware' => ['role:admin']], function () {

});

Route::post('login', [AuthController::class, 'login']);
Route::post('authStore', [AuthController::class, 'store']);
Route::get('authLogout', [AuthController::class, 'logout'])->middleware('auth:sanctum');

Route::get('application/{id}', [ApplicationController::class, 'showById']);
Route::get('application', [ApplicationController::class, 'show']);
Route::post('applicationStore', [ApplicationController::class, 'store'])->middleware('auth:sanctum');
Route::post('applicationDelete/{application}', [ApplicationController::class, 'delete'])->middleware('auth:sanctum');

//Route::post('userDelete/{user}', [AdminController::class, 'delete']);
Route::post('userStore', [AdminController::class, 'store']);
Route::get('user', [AdminController::class, 'show']);
Route::get('user/{id}', [AdminController::class, 'showById']);
Route::post('userDelete/{user}', [AdminController::class, 'delete'])->middleware('auth:sanctum');

Route::get('review', [ReviewController::class, 'showReview']);
Route::get('review/{id}', [ReviewController::class, 'showReviewById']);
Route::post('reviewStore', [ReviewController::class, 'store'])->middleware('auth:sanctum');
Route::post('reviewUpdate/{id}', [ReviewController::class, 'updateReview'])->middleware('auth:sanctum');
Route::post('reviewRatingUpdate/{id}', [ReviewController::class, 'updateReviewRating'])->middleware('auth:sanctum');
Route::get('reviewRating', [ReviewController::class, 'showReviewRating'])->middleware('auth:sanctum');
Route::get('reviewRating/{id}', [ReviewController::class, 'showReviewRatingById']);

Route::get('authUser', [AuthController::class, 'user']);

A: Define middleware in the constructer of your controller and it will do the trick here
public function __construct()
{
    $this->middleware('auth:api');
}

Or  moved the route into Route::middleware it will work
Route::middleware('auth:api')->group( function () {
Route::post('authStore', [AuthController::class, 'store']);

});

A: Use
   public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

at the start
register method
   public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
            'mobile' => 'required|min:10',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors()->toJson(), 400);
        }

        $user = User::create(array_merge(
            $validator->validated(),

            [
                'password' => bcrypt($request->password),

            ]
        ));

        return response()->json([
            'message' => 'User successfully registered',
            'user' => $user
        ], 201);
    }


text:
Q: Django Object filter expected id (int) but get str I make Django blog project and I've implemented a function to filter posts by their tag. There is a possibility to select a certain tag and to see all posts with this specific one. But I have trouble when I want to filter all posts by this tag. I get an error that Django expects int number but not str. How to solve this problem?
This is my code
 models.py

class Tag(models.Model):
    name = models.CharField(max_length=200, null=True)
    slug = models.SlugField(max_length=250, unique=True, editable=False)

class ProjectPost(models.Model):
    tag = models.ForeignKey(Tag, on_delete=models.PROTECT)

url.py

urlpatterns = [
    ...
    path("projects/", views.projects, name='projects'),
    path('projects/<slug:tag>/',views.projects, name='projects_tag'),
]

views.py

def projects(request, tag=None):

    if tag is not None:
        ProjectPost.objects.filter(tag=tag)
    else:
        posts = ProjectPost.objects.all()

    tags = Tag.objects.all()
    context = {'posts':posts, 'tags':tags}
    return render(request, 'website/projects.html', context)

THis is error
ValueError at /projects/romania/
Field 'id' expected a number but got 'romania'.
Request Method: GET
Request URL:    http://127.0.0.1:8000/projects/romania/
Django Version: 3.2.5
Exception Type: ValueError
Exception Value:
Field 'id' expected a number but got 'romania'.
Exception Location: /home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/db/models/fields/__init__.py, line 1825, in get_prep_value
Python Executable:  /home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/bin/python
Python Version: 3.8.5
Python Path:
['/home/cristian/Desktop/GreatEcology my project/ecosite/ecowebsite',
 '/home/cristian/Anaconda3/lib/python38.zip',
 '/home/cristian/Anaconda3/lib/python3.8',
 '/home/cristian/Anaconda3/lib/python3.8/lib-dynload',
 '/home/cristian/Desktop/GreatEcology my '
 'project/ecosite/venvecosite/lib/python3.8/site-packages']
Server time:    Wed, 21 Jul 2021 14:36:51 +0000

A: I gues you get name of tag in your tag variable so just filter with this name
def projects(request, tag=None):
    if tag:
        posts = ProjectPost.objects.filter(tag__name=tag)
    else:
        posts = ProjectPost.objects.all()
    ...

A: You likely are filtering with something like Model.objects.filter(id=tag), with tag is a variable that now contains romania now. Probably the error is located in the view in line
ProjectPost.objects.filter(tag=tag)

Instead Just access name of tag by dunderscore.
ProjectPost.objects.filter(tag__name=tag)

A: ty this in your views.py
posts = ProjectPost.objects.filter(tag__name=tag)


text:
Q: What is the PowerShell equivalent of the Unix shell `export` command? What is the equivalent in PowerShell of:
export pwtst=777; bash -c 'echo xxx${pwtst}xxx'

?
I want to expose the variables set in PowerShell to traditional Unix shells.
When I run this is in zsh, for example, I get:
xxx777xxx

but in PowerShell
export $pwtst=777; bash -c 'echo xxx${pwtst}xxx'

results in
export: The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I tried
$global:pwtst='777'; bash -c 'echo xxx${pwtst}xxx'

but that returns
xxxxxx

and I tried
$global:pwtst=777; Export-ModuleMember -Variable pwtst; bash -c 'echo xxx${pwtst}xxx'

which resulted in
Export-ModuleMember: The Export-ModuleMember cmdlet can only be called from inside a module.

PS- I am trying to pass values to sub shells, this is just a test for me. I know I could do bash -c "echo xxx${pwtst}xxx" but then it'll be PowerShell doing the variable substitution and not the sub shell (ie Bash). My use case is porting over an existing collection of shell scripts to PowerShell since it's more cross-platform friendly and top-down is easier than bottom up because it means means the difficult niche scripts can be left for last.

A: Use the env: scope or drive:
$env:pwtst='777'; bash -c 'echo xxx${pwtst}xxx'

xxx777xxx

Using env: as a drive example:
set-content env:foo 'hi'; bash -c 'echo $foo'

hi


text:
Q: delete from jsp view. can't get the table id while deleting it's row My task:            I have to delete operation over the table "testtable"  each row  from jsp view.
My problem:         not able to get the table id while deleting it's row.
Application technology used:        jsp as view , servlet as controller, setter and getter method as model and jdbc code for database  operation.
Backend mysql:=I have two table one "userinfo"  for aurtherntication and  another table "testtable".
For the two table connection I have used hidden field input in jsp as  instead of  using foreign key relation.
In the console print we can see after clicking the delete button
com.mysql.jdbc.JDBC4PreparedStatement@1f4bcaf: delete from testtable where id=0 and email='myswagt@yahoo.com'
at home servlet
userid is 0

please help me according to jsp,servlet,model,jdbc post below:

//expense model
package com.intermediateDemo.home.dto;
public class ItemBean {
private  int id;
private  String email;
private String itemName;
private Double itemPrice;
private String transactionTime;
private  int userid;

public ItemBean() {
}
public ItemBean(int id, String email, String itemName, Double itemPrice, String    transactionTime) {
    this.id = id;
    this.itemName = itemName;
    this.itemPrice = itemPrice;
    this.transactionTime = transactionTime;
    this.email = email;
}
public String toString() {

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");
    stringBuilder.append("Id: " + id);
    //stringBuilder.append("\tName: " + firstName + ' ' + middleName + ' ' + lastName);
    stringBuilder.append("\titemname: " + itemName);
    stringBuilder.append("\titemprice: " + itemPrice);

    stringBuilder.append("\ttime: " + transactionTime);
       stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");

    return stringBuilder.toString();

}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
public int getUserid() {
    return userid;
}

public void setUserid(int userid) {
    this.userid = userid;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getItemName() {
    return itemName;
}

public void setItemName(String itemName) {
    this.itemName = itemName;
}

public Double getItemPrice() {
    return itemPrice;
}

public void setItemPrice(Double itemPrice) {
    this.itemPrice = itemPrice;
}

public String getTransactionTime() {
    return transactionTime;
}

public void setTransactionTime(String transactionTime) {
    this.transactionTime = transactionTime;
}
}

//user model
package com.intermediateDemo.login.dto;
public class LoginBean {

private int userid;
private String email;
private String password;
public boolean valid;
private String lastName;
private String firstName;

public LoginBean() {
}

public LoginBean(String email, String lastname, String firstname) {
    this.email = email;
    this.firstName = firstname;
    this.lastName = lastname;

}

public int getUserid() {
    return userid;
}

public void setUserid(int userid) {
    this.userid = userid;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public boolean isValid() {
    return valid;
}

public void setValid(boolean valid) {
    this.valid = valid;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getLastName() {
    return lastName;
}

public String getFirstName() {
    return firstName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
}

//delete servlet
package com.intermediateDemo.home.controller;
import com.intermediateDemo.home.dao.ItemDao;
import com.intermediateDemo.home.dao.ItemDaoFactory;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class DeleteExpense extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, ServletException, IOException {
ItemBean item = new ItemBean() ;

    try {
        ItemDao dao = ItemDaoFactory.getItemDao();
        HttpSession session = request.getSession(false);
        LoginBean user = (LoginBean) session.getAttribute("user");
        item.setId(Integer.parseInt(request.getParameter("id")));
        item.setEmail(user.getEmail());
        dao.deleteItem(item, user);
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        response.sendRedirect("homeservlet");
    }

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher view;
    view = request.getRequestDispatcher("/home/home.jsp");
    view.forward(request,response);
}
}

//jdbc code
 public void deleteItem(ItemBean item, LoginBean user) throws Exception {

   try {
        JdbcConnection connection =   new JdbcConnection();
        String query = "delete from testtable where id=? and email=?";
        Connection con = connection.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
        pstm.setInt(1, item.getId());
        pstm.setString(2, user.getEmail());
        System.out.println(pstm);
        pstm.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

//jsp view
<%--
Created by IntelliJ IDEA.
User: Dell
Date: 3/13/14
Time: 8:12 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page import="com.intermediateDemo.home.dto.ItemBean" %>
<%@ page import="java.util.List" %>
<%@ page import="com.intermediateDemo.login.dto.LoginBean" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<title>home</title>
<link rel="stylesheet" type="text/css" href="style_css/mystylesheet.css">
<link rel="stylesheet" href="resource/css/bootstrap.css"  type="text/css"/>

<jsp:include page="../includes/header.jsp"/>

Welcome <%=session.getAttribute("email")%>

your id is  <%=session.getAttribute("userid")%>
your firstname is  <%=session.getAttribute("firstname")%>

Your Financial Management

    <form action="homeservlet" method="post">

        <legend>

Expense list

        </legend>

                    Expense title
                    Expense amount
                    Expense Date

                <c:forEach var="item"  items="${requestScope.itemList}" >

                        <c:out value="${item.getItemName()}"> </c:out>
                        <c:out value="${item.getItemPrice()}"> </c:out>
                        <c:out value="${item.getTransactionTime()}"> </c:out>

                        <form method="post" action="/deleteexpense">
                            <input type="hidden" name="id" value="${item.id}">
                            <input class="btn btn-mini btn-danger " type="submit" value="Delete"/>
                        Edit
                         </form>

                </c:forEach>

    </form>

<jsp:include page="../includes/footer.jsp"/>

//DAO where I retrieve the data of ItemBean
    public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
    List<ItemBean> itemList = new ArrayList<ItemBean>();
    JdbcConnection connecton = new JdbcConnection();
    //String query = "select * from testtable where userid = ?";
     String query = "select  * from testtable where  email = ?";
    ResultSet rs;
    try {
        Connection con = connecton.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
       // pstm.setInt(1, user.getUserid());
        pstm.setString(1,user.getEmail());
        rs = pstm.executeQuery();
        while (rs.next()) {
            ItemBean item = new ItemBean();
            item.setItemName(rs.getString("itemname"));
            item.setItemPrice(rs.getDouble("itemprice"));
            item.setTransactionTime(rs.getString("transactiontime"));
           // item.setUserid(rs.getInt("userid"));
            item.setEmail(rs.getString("email"));
            itemList.add(item);

        }

        System.out.println("at jdbc code");
        for (ItemBean item1 : itemList) {
            System.out.println(item1.getItemName());
            System.out.println(item1.getItemPrice());
            System.out.println(item1.getTransactionTime());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return itemList;
}

//jdbc code for item insert,retrieve and delete like operation in one page is
package com.intermediateDemo.home.dao.mysql;
import com.intermediateDemo.common.JdbcConnection;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcItemMysql {
public void itemtodb(ItemBean item, LoginBean user) throws Exception {
    JdbcConnection connection = new JdbcConnection();
    //String query = "insert into testtable    (itemname,itemprice,transactiontime,userid) values (?,?,?,?)";
   String query = "insert into testtable (itemname,itemprice,transactiontime,email) values (?,?,?,?)";
    try {
        Connection con = connection.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
        pstm.setString(1, item.getItemName());
        pstm.setDouble(2, Double.parseDouble(String.valueOf(item.getItemPrice())));
        pstm.setString(3, item.getTransactionTime());
        pstm.setString(4, user.getEmail());
       // pstm.setInt(4,user.getId());
        pstm.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
    List<ItemBean> itemList = new ArrayList<ItemBean>();
    JdbcConnection connecton = new JdbcConnection();
    //String query = "select * from testtable where userid = ?";
     String query = "select  * from testtable where  email = ?";
    ResultSet rs;
    try {
        Connection con = connecton.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
       // pstm.setInt(1, user.getUserid());
        pstm.setString(1,user.getEmail());
        rs = pstm.executeQuery();
        while (rs.next()) {
            ItemBean item = new ItemBean();
            item.setItemName(rs.getString("itemname"));
            item.setItemPrice(rs.getDouble("itemprice"));
            item.setTransactionTime(rs.getString("transactiontime"));
           // item.setUserid(rs.getInt("userid"));
            item.setEmail(rs.getString("email"));
            itemList.add(item);

        }

        System.out.println("at jdbc code");
        for (ItemBean item1 : itemList) {
            System.out.println(item1.getItemName());
            System.out.println(item1.getItemPrice());
            System.out.println(item1.getTransactionTime());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return itemList;
}

public void deleteItem(ItemBean item, LoginBean user) throws Exception {

   try {
        JdbcConnection connection =   new JdbcConnection();
        String query = "delete from testtable where id=? and email=?";
        Connection con = connection.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
        pstm.setInt(1, item.getId());
        pstm.setString(2, user.getEmail());
        System.out.println(pstm);
        pstm.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

A: You are not passing the record id to the jsp page from your method. Your getItemFromdb() should be some thing like this
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {

    //  whatever you are doing comes here
    while (rs.next()) {
        ItemBean item = new ItemBean();
        item.setId(rs.getInt("id");  //  you need to have this, here id is the the primary key of the table
        item.setItemName(rs.getString("itemname"));
        item.setItemPrice(rs.getDouble("itemprice"));
        item.setTransactionTime(rs.getString("transactiontime"));
     // item.setUserid(rs.getInt("userid"));
        item.setEmail(rs.getString("email"));
        itemList.add(item);
    }

    //  rest of the code
}

so that in the jsp page you can use this id to identify the record do whatever operation you want to do


text:
Q: Android TCP client receive messages and bmp I use the common tcp client to receive string messages through TCP.
I want after the reception of a specific message e.g. "XXX" my client to be ready to receive a bmp image.
My server in C++ sends the messages but the client does not receive the image...
After some suggestions .. se below I udated the code...
Here is my code:
TCP client:
public class TCPClient {

private String serverMessage;
public static final String SERVERIP = "192.168.1.88"; //your computer IP
public static final int SERVERPORT = 80;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter out;
private BufferedReader input;
private DataInputStream dis;
/**
 *  Constructor of the class. OnMessagedReceived listens for the messages received from server
 */
public TCPClient(OnMessageReceived listener) {
    mMessageListener = listener;
}

/**
 * Sends the message entered by client to the serveraddress
 * @param message text entered by client
 */
public void sendMessage(String message){
    if (out != null && !out.checkError()) {
        out.println(message);
        out.flush();
    }
}

public void stopClient(){

    mRun = false;
    if (out != null) {
        out.flush();
        out.close();
    }

    mMessageListener = null;
    input = null;
    input = null;
    input = null;
    serverMessage = null;
}

public void run() {

    mRun = true;
    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVERIP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVERPORT);

        try {

            //send the message to the server
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            Log.e("TCP Client", "C: Sent.");

            Log.e("TCP Client", "C: Done.");

            //receive the message which the server sends back

            dis = new DataInputStream(socket.getInputStream());
            // The buffer reader cannot can't wrap an InputStream directly. It wraps another Reader.
            // So inputstreamreader is used.
            input = new BufferedReader(new InputStreamReader(dis, "UTF-8"));

            Log.d("MyApp","We are here");
            //this.input = new DataInputStream(in);

            //in this while the client listens for the messages sent by the server
            while (mRun) {
                Log.d("MyApp", "We are here 2");
                serverMessage = input.readLine();

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(serverMessage);

                    Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
                }

                if ("XXX".equals(serverMessage)) {
                    Log.d("MyApp", "We are here 3");
                    serverMessage = null;
                    while (mRun) {
                        WriteSDCard writeSDCard = new WriteSDCard();

                        writeSDCard.writeToSDFile(serverMessage);

                        }
                    }
                }
              } finally {
                socket.close();
        }
            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.

}

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
    public void messageReceived(String message);
}
}
public class WriteSDCard extends Activity {

private static final String TAG = "MEDIA";
private TextView tv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//(not needed)        setContentView(R.layout.main);
//(not needed)           tv = (TextView) findViewById(R.id.TextView01);
    checkExternalMedia();
    String message =null;
  }

 /** Method to check whether external media available and writable. This is adapted from
 http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */

private void checkExternalMedia(){
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Can't read or write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }
    tv.append("\n\nExternal Media: readable="
            +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}

  /** Method to write ascii text characters to file on SD card. Note that you must add a
   WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
 a FileNotFound Exception because you won't have write permission. */

   void writeToSDFile(String inputMsg){

    // Find the root of the external storage.
    // See http://developer.android.com/guide/topics/data/data-  storage.html#filesExternal

    File root = android.os.Environment.getExternalStorageDirectory();
    tv.append("\nExternal file system root: "+root);

    // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

    File dir = new File (root.getAbsolutePath() + "/download");
    dir.mkdirs();
    Log.d("WriteSDCard", "Start writing");
    File file = new File(dir, "myData.txt");

    try {
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        pw.println(inputMsg);
        pw.flush();
        pw.close();
        f.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.i(TAG, "******* File not found. Did you" +
                " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
    } catch (IOException e) {
        e.printStackTrace();
    }
    tv.append("\n\nFile written to "+file);
}

/** Method to read in a text file placed in the res/raw directory of the application. The
 method reads in all lines of the file sequentially. */

}
And the server side:
Code:
void sendBMP( int cs, int xs, int ys)
{
int imgdataoffset = 14 + 40;     // file header size + bitmap header size
int rowsz = ((xs) + 3) & -4; // size of one padded row of pixels
int imgdatasize = (((xs*3) + 3) & -4) * ys;    // size of image data
int filesize = imgdataoffset + imgdatasize;
int i, y;

HTLM_bmp_H HTLM_bmp_h;
HTLM_bmp_h.bmfh.bfSize = filesize;
HTLM_bmp_h.bmfh.bfReserved1 = 0;
HTLM_bmp_h.bmfh.bfReserved2 = 0;
HTLM_bmp_h.bmfh.bfOffBits = imgdataoffset;

HTLM_bmp_h.bmih.biSize = 40;
HTLM_bmp_h.bmih.biWidth = xs;
HTLM_bmp_h.bmih.biHeight = ys;
HTLM_bmp_h.bmih.biPlanes = 1;
HTLM_bmp_h.bmih.biBitCount = 24;
HTLM_bmp_h.bmih.biCompression = 0;
HTLM_bmp_h.bmih.biSizeImage = imgdatasize;
HTLM_bmp_h.bmih.biXPelsPerMeter = 1000;
HTLM_bmp_h.bmih.biYPelsPerMeter = 1000;
HTLM_bmp_h.bmih.biClrUsed = 1 << 24;
HTLM_bmp_h.bmih.biClrImportant = 0;

printf("Start Sending BMP.\n");

send(cs,(unsigned char *)"BM",2,0);

send(cs,(unsigned char *)&HTLM_bmp_h,sizeof(HTLM_bmp_h),0);

printf("Sending...\n");

Buff_ptr = 0;

send(cs, (unsigned char *)Rbuffer, BUFF_SIZE,0 );
send(cs, (unsigned char *)Gbuffer, BUFF_SIZE,0 );
send(cs, (unsigned char *)Bbuffer, BUFF_SIZE,0 );
send(cs, (unsigned char *)"\n",1,0);
send(cs, (unsigned char *)"END\n",4,0);
printf("Done\n\n");
}

typedef struct {
//       char    bfType1;
//       char    bfType2;
int     bfSize;
short   bfReserved1;
short   bfReserved2;
int     bfOffBits;
} BMFH;

typedef struct {
unsigned int    biSize;
int    biWidth;
int    biHeight;
short    biPlanes;
short    biBitCount;
unsigned int    biCompression;
unsigned int    biSizeImage;
int    biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int    biClrUsed;
unsigned int    biClrImportant;
} BMIH;

typedef struct {
BMFH bmfh;
BMIH bmih;
} HTLM_bmp_H;

main()
{
TSK_Handle tsk_cam;
tsk_cam=TSK_create( (Fxn)TSK_webview, NULL);
TSK_setpri(tsk_cam, 8);
}

char buffer[2048];

Void TSK_webview()
{

int s,cs;
struct sockaddr_in    addr;    /* generic socket name */
struct sockaddr    client_addr;
int sock_len = sizeof(struct sockaddr);
int frame = 0;
LgUns i=0;
int len;
int x = DSKeye_SXGA_WIDTH, y = DSKeye_SXGA_HEIGHT;

DSKeye_params CAM_params = {
....
};

lwIP_NetStart();

/**************************************************************
    *     Main loop.
***************************************************************/

s = socket( AF_INET, SOCK_STREAM, 0 );

addr.sin_port = htons(80);
addr.sin_addr.s_addr = 0;
memset(&(addr.sin_zero), 0, sizeof(addr.sin_zero));
printf("start\n");
if( bind(s, (struct sockaddr*)&addr, sizeof(struct sockaddr)))
{
    printf("error binding to port\n");
    return ;
}
printf("xx1\n");
if(DSKeye_open(&CAM_params)) {
    printf("xx2\n");
    SYS_abort("DSKcam_CAMopen");
printf("xx3\n");  fflush(stdout);}

printf("xx4\n");

while(1==1) {
    printf("Waiting for client to be connected ... \n");
    listen(s, 10);
    cs  = accept(s, &client_addr, &sock_len);
    printf("Client connected.\n");
    send(cs,(unsigned char *)"Server connected\n",17,0);
    recv(cs, (unsigned char*)buffer, 17, 0);

    switch (*(buffer)){
        case 'A' :
        ...
        case 'B' :
        ...
    }
    REG32(0xA0000080)=REG32(0xA0000080) - 0x800000; ///Disable stepper controller vhdl Quartus Block

    for(frame = 0; frame < 4; frame++){ // Allow AEC etc to settle

       SrcFrame=DSKeye_getFrame();
    }

    printf("Demosaicing of %d x %d image is ongoing \n", x, y);
    demosaic(SrcFrame, x, y);
    break;

}

    printf("Demosaicing completed ...\n");
    send(cs,(unsigned char *)"Demosaicing completed\n",22,0);
    send(cs,(unsigned char *)"XXX\n",4,0);
    sendBMP(cs, x, y);
    fflush(stdout);
    lwip_close(cs);

}
the send : lwip_send
int lwip_send(int s, void *data, int size, unsigned int flags)
{
  struct lwip_socket *sock;
  struct netbuf *buf;
  err_t err;

  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d, data=%p, size=%d, flags=0x%x)\n", s, data, size, flags));

  sock = get_socket(s);
  if (!sock) {
    set_errno(EBADF);
    return -1;
  }

  switch (netconn_type(sock->conn)) {
  case NETCONN_RAW:
  case NETCONN_UDP:
  case NETCONN_UDPLITE:
  case NETCONN_UDPNOCHKSUM:
    /* create a buffer */
  buf = netbuf_new();

  if (!buf) {
     LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) ENOBUFS\n", s));
      sock_set_errno(sock, ENOBUFS);
      return -1;
  }

  /* make the buffer point to the data that should
   be sent */
  netbuf_ref(buf, data, size);

  /* send the data */
  err = netconn_send(sock->conn, buf);

 /* deallocated the buffer */
 netbuf_delete(buf);
 break;
case NETCONN_TCP:
   err = netconn_write(sock->conn, data, size, NETCONN_COPY);
 break;
default:
  err = ERR_ARG;
  break;
 }
 if (err != ERR_OK) {
  LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) err=%d\n", s, err));
  sock_set_errno(sock, err_to_errno(err));
  return -1;
 }

 LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) ok size=%d\n", s, size));
 sock_set_errno(sock, 0);
 return size;
  }

A: You can't mix a buffered reader and a data input stream on the same socket. The buffered reader will read-ahead and steal data you expect to read via the data input stream. You will have to use the data input stream for everything. And correspondingly at the sender.

A: You're doing incorrect comparison for string equality.
In Java, string comparison for equality is done using String.equals(Object anObject)
You're using if (serverMessage == "XXX") {....
You should use if ("XXX".equals(serverMessage)) {....


text:
Q: MySQL Query Problem with Alias and Aggregate Functions I have a troublesome MySQL query as follows:
SELECT camera_id, ((avg(low_price) + avg(high_price)) / 2) as avg_price
FROM camera_general, camera_products
WHERE camera_id = ir_camera_id
AND dp_post_dt IS NOT NULL
AND dp_post_dt NOT LIKE '0000%'
AND currently_manufactured = 'Yes'
AND ((no_of_sellers >= 0) OR ((TO_DAYS(CURRENT_DATE) - TO_DAYS(dp_post_dt)) < 120))
AND avg_price < 150
AND camera_id != 1411
AND camera_id != 9
ORDER BY rand();

This one produced the "Unknown column 'avg_price' in 'where clause'" error. I understand this is because column aliases are not allowed in the WHERE clause. (Correct me if I'm wrong with any of this as I go, please.)
So, I tweaked the query like so:
SELECT camera_id, ((avg(low_price) + avg(high_price)) / 2) as avg_price
FROM camera_general, camera_products
WHERE camera_id = ir_camera_id
AND dp_post_dt IS NOT NULL
AND dp_post_dt NOT LIKE '0000%'
AND currently_manufactured = 'Yes'
AND ((no_of_sellers >= 0) OR ((TO_DAYS(CURRENT_DATE) - TO_DAYS(dp_post_dt)) < 120))
AND ((avg(low_price) + avg(high_price)) / 2) < 150
AND camera_id != 1411
AND camera_id != 9
ORDER BY rand();

Replacing the alias with the actual calculation and this query produced the error: "Invalid use of group function". I understand this is because the avg() can't happen until after the WHERE clause has done its processing.
So then I tried:
SELECT camera_id, ((avg(low_price) + avg(high_price)) / 2) as avg_price
FROM camera_general, camera_products
ORDER BY rand();
HAVING camera_id = ir_camera_id
AND dp_post_dt IS NOT NULL
AND dp_post_dt NOT LIKE '0000%'
AND currently_manufactured = 'Yes'
AND ((no_of_sellers >= 0) OR ((TO_DAYS(CURRENT_DATE) - TO_DAYS(dp_post_dt)) < 120))
AND avg_price < 150
AND camera_id != 1411
AND camera_id != 9;

Replacing the WHERE with the HAVING and it produced this error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'HAVING camera_id = ir_camera_id'".
And at this point, I feel like I am shooting in the dark trying to make this query work. Would someone guide me in the right direction to make this a functioning query?
Thanks!

A: *

*Even though you can use WHERE to specify join condition, it's better to do in LEFT[INNER] JOIN clause.

*If you want to filter by non-aggregate field, put the filter into WHERE, if you need to filter by aggregate, move condition into HAVING

*While using aggregate and non-aggregates in the same query, don't forget GROUP BY.
SELECT camera_id, ((avg(low_price) + avg(high_price)) / 2) as avg_price
FROM camera_general
INNER JOIN camera_products ON (camera_id = ir_camera_id)
WHERE  dp_post_dt IS NOT NULL
AND dp_post_dt NOT LIKE '0000%'
AND currently_manufactured = 'Yes'
AND ((no_of_sellers >= 0) OR ((TO_DAYS(CURRENT_DATE) - TO_DAYS(dp_post_dt)) < 120))
AND camera_id != 1411
AND camera_id != 9
GROUP BY camera_id
HAVING avg_price < 150
ORDER BY rand();

A: ORDER clause should go after HAVING clause. (besides you put a semicolon ; after ORDER BY rand() then continued with HAVING, which is actually a start of another query, since the first got ended with the ;).


text:
Q: Updating post data on save (save_post vs wp_insert_post_data) I am trying to modify post data on post save action.
Firstly I tried to use save_post hook like that
function post_save_action($post_id, $post, $update)
    {
        if ($this->is_temp_saving_post($post, $post_id)) {
            return;
        }
        // Check user permissions
        if (!current_user_can('edit_post', $post_id))
            return;
        // Update post
        if (!$this->is_proper_post_type($post)) {
            return;
        }
        $processed_content = $this->process_post_data($post);
        $update_data = [
            self::POST_ID => $post_id,
            self::POST_CONTENT => $processed_content
        ];
        // Prevent infinite loop
        remove_action('save_post', array($this, 'post_save_action'), 99);
        // Update the post into the database
        wp_update_post($update_data);
        // Add hook again
        add_action('save_post', array($this, 'post_save_action'), 99);
    }

The problem here is that wp_update_post($update_data); triggers save_post action again for other plugins, so all plugins except mine are being executed twice, and that is bad.
Then I found another hook wp_insert_post_data and add my processing logic
public function post_insert_filter($data, $postattr)
    {
        $post_id = $postattr['ID'];
        $post_object = $this->convertToObject($data);
        $post_object->ID = $post_id;
        if ($this->is_temp_saving_post($post_object, $post_id)) {
            return $data;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return $data;
        }
        // Update post
        if (!$this->is_proper_post_type($post_object)) {
            return $data;
        }
        $processed_content = $this->process_post_data($post_object);
        $data[self::POST_CONTENT] = $processed_content;
        return $data;
    }

It works hook is not called twice, but the problem for the time wp_insert_post_data is triggerd, data already has been escaped(parentheses) somewhere, but I need raw data here.
Please suggest the right way to modify data considering all requirements.

A: At first, Data was sanitized here (line 2997).
If you don't want any plugin/theme run on action save_post. User  function remove_all_actions to remove all functions hooked to action save_post.
function post_save_action($post_id, $post, $update)
 {
    if ($this->is_temp_saving_post($post, $post_id)) {
        return;
    }
    // Check user permissions
    if (!current_user_can('edit_post', $post_id))
        return;
    // Update post
    if (!$this->is_proper_post_type($post)) {
        return;
    }
    $processed_content = $this->process_post_data($post);
    $update_data = [
        self::POST_ID => $post_id,
        self::POST_CONTENT => $processed_content
    ];
    // Backup actions
    global $wp_filter, $merged_filters;
    $backup_wp_filter = $wp_filter;
    $backup_merged_filters = $merged_filters;
    // Remove all functions which hooked to this action, to prevent run twice.
    remove_all_actions('save_post');
    // Update the post into the database
    wp_update_post($update_data);
   // restore actions
    $wp_filter = $backup_wp_filter;
    $merged_filters = $backup_merged_filters;
 }