text:
Q: Does the implicit type conversion change the size of the variable for example,
#include <stdio.h>

int main (void) {

    int x = 5;
    double y = 6;
    int z = x+y;

    printf("size of z = %d bytes",sizeof(z));

    return 0;
}

The output is 4 bytes, why doesn't it converted to double and takes 8 bytes of memory as a double.

A: No, sizeof z will always be sizeof(int)
When you do:
int z = x+y;

The value of x will be converted to double since y is double, but this won't change x. And the result of x+y(type double) will be converted to int, and assigned to z.

A: You have defined z to be integer. While doing "x+y", the addition does happen on double size but when assigning it performs implicit conversion and truncate the result to fit in size of z.

A: Since you declared z being int it' ll be int. And every possible conversion will be from whatever type to int:
  int z = whatever (legal) formula you put here;
  sizeof(z); /* <- 4 */

on the contrary temporal value of x + y is double which is finally converted to int
  int x = 5;
  double y = 6;
  int z = x+y; /* x + y = 11.0 since y = 6.0; which is converted to 11*/

A: Read the comments which describe your code behavior:
#include <stdio.h>

int main (void) {

int x = 5;
double y = 6;
int z = x+y; // 5 (int, 4 bytes) + 6 (double, 8 bytes)
             // converting `int` to `double` when adding them ()
             // 5.0 (double, 8 bytes) + 6.0 (double, 8 bytes)
             // 11.0 (double, 8 bytes)
             // But! `z` is of type `int`, so it will not convert to `double`
             // Then 11.0 converts to 11 because `z`... is of type `int`!
            /// read "Double-precision floating-point format" and you'll see why.
             // So,  z = 11 (`z` is of type `int`, so it's size is *4* bytes )
             // Here is your 4 bytes instead of 8! ;)

printf("size of z = %d bytes",sizeof(z));
return 0;

}

A: Your output is 4 because you are declaring int z. z will always be of type int.
Even if the expression x+y is of type double because y is a double, this expression will be implicitly converted to int because you try to assign int to and int.
Check this code :
#include <stdio.h>

int main()
{
    int x = 4;
    double y = 5;
    int z = x+y;

    printf( "%d %d \n", sizeof(z), sizeof( x + y ) );
    return 0;
}

The output will be 4 8 because z is of type int and the expression x+y of type double. Example


text:
Q: Format for iname in Find operation When using find what is the correct format to say "Find files that end in .jpg OR .png"?
Is it as simple as using the | operator/character?
find -iname "*.jpg|*.png"

A: No.
You need to use -o (OR) in find like:
find \( -iname '*.jpg' -o -iname '*.png' \)

Your one would be close to correct if you are matching Regex:
find -iregex ".*\(jpg\|png\)"

Or using extended Regex:
find -regextype posix-extended -iregex ".*(jpg|png)"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to install autodock vina (potentially due to boost) As part of a script I am writing, I need to install the package autodock vina for the purpose of ligand and protein binding. Every time I attempt to "pip install vina", I recieve an error message " ValueError: Boost library location was not found!". Upon attempting to install boost manually, I have been unable to run the bootstrap file, as it does not make the b2 folder that online tutorials say it will make.
To resolve this issue, I installed conda, and made an active environment with every single prerequisite, including boost, installed. I have checked for the version of all of these prerequisites and confirmed their existence, as well as double and triple-checking that I am in the write active environment. Upon installation, I either get the same issue (using conda install vina) or when using "conda install -c bioconda autodock-vina", I get a message saying that the package does not exist (despite adding cforge and bioconda as active package handlers, and the existence of said package is clearly documented online). Does anyone have any suggestions? I've been attempting to install this piece of software for 3 days and I've completely exhausted the documentation, as well as all other similar question answers, with nothing working.
Full error message:
Collecting vina
  Using cached vina-1.2.3.tar.gz (95 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [56 lines of output]
      Version found 1.2.3 (from __init__.py)
      running egg_info
      creating vina.egg-info
      writing vina.egg-info\PKG-INFO
      writing dependency_links to vina.egg-info\dependency_links.txt
      writing requirements to vina.egg-info\requires.txt
      writing top-level names to vina.egg-info\top_level.txt
      writing manifest file 'vina.egg-info\SOURCES.txt'
      Boost library is not installed in this conda environment.
      Traceback (most recent call last):
        File "C:\Users\chris\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 363, in <module>
          main()
        File "C:\Users\chris\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 345, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "C:\Users\chris\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 130, in get_requires_for_build_wheel
          return hook(config_settings)
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\build_meta.py", line 177, in get_requires_for_build_wheel
          return self._get_build_requires(
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\build_meta.py", line 159, in _get_build_requires
          self.run_setup()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\build_meta.py", line 174, in run_setup
          exec(compile(code, __file__, 'exec'), locals())
        File "setup.py", line 346, in <module>
          setup(
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\__init__.py", line 87, in setup
          return distutils.core.setup(**attrs)
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 148, in setup
          return run_commands(dist)
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 163, in run_commands
          dist.run_commands()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 967, in run_commands
          self.run_command(cmd)
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\dist.py", line 1214, in run_command
          super().run_command(command)
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\command\egg_info.py", line 308, in run
          self.find_sources()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\command\egg_info.py", line 315, in find_sources
          mm.run()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\command\egg_info.py", line 550, in run
          self.add_defaults()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\command\egg_info.py", line 587, in add_defaults
          sdist.add_defaults(self)
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\command\sdist.py", line 228, in add_defaults
          self._add_defaults_ext()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\command\sdist.py", line 311, in _add_defaults_ext
          build_ext = self.get_finalized_command('build_ext')
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 299, in get_finalized_command
          cmd_obj.ensure_finalized()
        File "C:\Users\chris\AppData\Local\Temp\pip-build-env-r7vbpka4\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 107, in ensure_finalized
          self.finalize_options()
        File "setup.py", line 247, in finalize_options
          raise ValueError(error_msg)
      ValueError: Boost library location was not found!
      Directories searched: conda env, /usr/local/include and /usr/include.
      [end of output]

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

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

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

A: I also get this error. I asked ResearchGate how to solve this problem and Cheng Shen adviced to use WSL/WSL2 to simulate a Linux environment and then run conda install -c bioconda vina (or another command like this)
What I did.

*

*Install WSL and Ubuntu on Windows 2. Run code . in WSL terminal (for installing VS Code [recommended])

*Install Anaconda/Miniconda following this guide

*Type conda install -c bioconda vina in Ubuntu terminal (bioconda channel will download all required packages - boost, swig, etc.)

*Vina should be successfully installed ( vina --version in WSL Terminal to check)
I found it much easier to install packages for docking via WSL and use VS Code to run scripts there. It's VERY easier than trying to solve this problem by configuring boost for Windows. If you have any questions you can ask me in ResearchGate.


text:
Q: is it possible to use jquery after() and load() together I want to make an ajax call but the data returned i want it inserted in the html after a tag

A: I think you will need a container for this:
$('

').after('#element').load('ajax.php')

A: The below code will help you enter the code after a p tag:
  $('p').after(function() {
    $('#result').load('ajax/test.html', function() {
      alert('Load was performed.');
    });
  });

A: You would first have to use the load event and after a result (either success or error) of the AJAX gets returns you can append it to the page using after(). The after() would have to be used inside the success and/or error result.


text:
Q: Angular 8 Jasmine Karma: TypeError: Cannot read property 'abiertos' of undefined Estaba desarrollando una App en Angular 8 con TypeScript como lenguaje de Script, y me ha surgido el siguiente error testeando uno de los componentes.

EscaparateTerminalesComponent > abiertos defaults to: []
TypeError: Cannot read property 'abiertos' of undefined

El código de mi componente sería el siguiente:
export class EscaparateTerminalesComponent implements OnInit, OnDestroy {

...

  cerrarCaracMov() {
    // console.log('titulos', this.titulos);
    for (let e = 0; e < this.titulos.length; e++) {
      this.abiertos.push(false);
    }
    // console.log(this.abiertos);
  }

  caerrarAbrirCarac(i) {
    if (this.abiertos[i] === false) {
      this.abiertos[i] = true;
    } else {
      this.abiertos[i] = false;
    }
    for (let t = 0; t < this.titulos.length; t++) {
      if (this.abiertos[t] !== true) {
        this.abiertos[t] = false;
      }
    }
...
}

Y el código correspondiente al archivo spec.ts sería el que podéis ver a continuación debajo de vuestras pantallas justo aquí debajo de esta línea de aquí:
  it('abiertos defaults to: []', () => {
    expect(component.abiertos).toEqual([]);
  });

Espero podáis ayudar en el caso de que sepáis por donde van los tiros, y si ese es el caso, muchas gracias de ante mano!

A: Debes declarar tu variable abiertos como vacío
public abiertos:any[] = []


text:
Q: Find a string and replace it the whole database I have a wordpress website and I'm going to change it's URL. The problem is that when I search for its actual URL in the database, I have like 200 results.
I would like to search in the whole database for the actual url and replace it with the new one.
I know that if I have the exact table and exact column, I can do :
UPDATE
    Table
SET
    Column = Replace(Column, 'find value', 'replacement value')

But how can I generalize this code to my whole database ?
Thank You !

A: Perhaps not the best, one solution is to export the whole database, open the sql file in a text editor, perform the search-replace and importing again.


text:
Q: How to handle images with unknown dimension for CLS To improve the CLS (Cumulative Layout Shift) you are supposed to set the width and height attribute of images. Is there any other proper way to handle images, if it's dimension is unknown?
On my website there is a section were brand logos are displayed. The logo can be different on every page and there is no way to get the size of the image in the backend and set the attributes accordingly.
Is there any other way to handle that properly? The image should not be stretched.
That's the current code:

img {
  max-height: 100px;
  max-width: 150px;
}

EDIT:
I now came up with this solution (don't know if it's best practice, but at least google PageSpeed Insights is not complaining anymore):

a {
  display: block;
  height: 100px;
  width: 150px;
  position: relative
}

img {
  position: absolute;
  top: 0;
  bottom: auto;
  left: 0;
  right: auto;
  max-height: 100px;
  max-width: 150px;
}


text:
Q: Angular 4 Component ngOnInit not called on each route request I just recently started diving into Angular 4 coming from Angular 1.5.  I'm working with user routes and pulling API data from a service into a user component.
The component seems to stay static unlike controllers in 1.* where they were refreshed on each request.
Is there anyway to have the ngOnInit function called on each new route request?
My user component class:
// url structure: /user/:id
export class UserComponent implements OnInit {

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {

      // doesn't log new id on route change
      let id = this.route.snapshot.params['id'];
      console.log(id);

      this.route.params
        .switchMap(params => this.userService.getUser(params['id']))
        .subscribe(user => {
          // logs new id on route change
          let id = this.route.snapshot.params['id'];
          console.log(id);

          this.user = user
        });
    }
}

UPDATE:
Found a solution that I think works best for my scenario.  Based on several answers and comments to my question and further investigation, subscribing to the route seems to be the way to go.  Here is my updated component:
export class UserComponent {

  user;
  id;

  constructor(
    private userService: UserService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.params
      .subscribe(params => this.handleRouteChange(params));
  }

  handleRouteChange(params) {
    this.id = params['id'];

    switch (this.id) {
      case '1':
        console.log('User 1');
        break;

       case '2':
        console.log('User 2');
        break;

       case '3':
        console.log('User 3');
        break;
    }

    this.userService.getUser(this.id).
      subscribe(user => this.user = user);
  }

}

A:
Angular prefers -by default- to reuse the same component instead of instanciating a new one if the route is the same but the parameters change.
Good news ! this is a customizable behavior, you can force instanciating a new component instance by implementing your own RouteReuseStrategy:
export class MyRouteReuseStrategy extends DefaultRouteReuseStrategy {
  shouldReuseRoute(next: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
    let name = next.component && (next.component as any).name;
    return super.shouldReuseRoute(next, current) && name !== 'UserComponent';
  }
}

in your module:
@NgModule({
  ...
  providers:[{
      provide: RouteReuseStrategy,
      useClass: MyRouteReuseStrategy}]
  ...
})
export class AppModule {}

(this code is more or less taken from this article, especially the check for the name property which might not be very accurate...)
Note that ther might be some performance drawback when reinstanciating the same component. So maybe you'd better use the observables properties instead of the snapshot.

A: I realize that this is quite after the fact, but I thought it best not to leave the an incomplete solution that newcomers might implement into their projects.
In response to the original post's update: it is important that you unsubscribe from Observables once you're done using them, otherwise you risk leaving references in memory. Here's a bare example.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Subscription, Observable } from 'rxjs';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss']
})
export class Example implements OnInit, OnDestroy {
  protected _routeChangeSubscription: Subscription;

  constructor(
    protected _activatedRoute: ActivatedRoute,
  ) { }

  ngOnInit(): void {
    this._routeChangeSubscription = this._activatedRoute.params.subscribe(this._routeChangeHandler);
  }

  ngOnDestroy(): void {
    this._routeChangeSubscription.unsubscribe();
  }

  public _routeChangeHandler = (params: Observable<Params>) => {
    // check params here
  }
}

A: Hi you have to use switchMap like this:
this.sub = this.route.paramMap
  .switchMap((params: ParamMap) =>
  this.firebaseService.getProductsByCategory(params.get('category'))).subscribe(products => {
  this.products = products;
  this.count = products.length;
});

This work for me.

A: Does the url look like "...?id=1" or "../:id" and you want the component to log the id each time the GET param changes?  The problem is talked about here.  A better solution I found is here.  I haven't tested it myself but this should work.
The second link shows how to subscribe to a route change within a component, which I think is essentially what you're trying to do.  It will allow you to handle a GET param change within ngOnInit.  I'm not sure if the route subscribe will run when you initally navigate to the URL, so you might want to have the function that handles the route event call a doCheck(), and change ngOnInit to ngAfterContentInit
ngOnInit only operates on change detection, and a GET change seems not to trigger it, which is surprising to me.
Tl;dr - Subscribe to the route change event in the constructor and create a function that handles an emitted event.  The function should hold the logic you have in ngOnInit().


text:
Q: Generate random floating value I need to generate random floating numbers between 0 and 1 in the field of attribute table for ArcGIS 10.3 version.

A: You can vary parameter in expression below, depending on what distribution is required:
def aRand():
 return arcgis.rand("Normal 2 2")

---------------------------------------
aRand()

A: *

*In the field calculator, show Codeblock.

*In the pre-logic script code box:
import random
def randnum():
    return random.random()

*In the expression box:
randnum()

Result in a new float field:


text:
Q: ThreeJS switch video texture Performance
Hi,
I'm mapping a video texture onto a sphere in ThreeJs. I dynamically changing the source of the video on click to display different videos.
The Code runs and switches the source, but it takes different times on different devices to update. It's kind of a lag. The source is switched and then it takes X-Milliseconds to update to the new video. During that time, the old video keeps playing. So I guess it might be some kind of video memory thing?

The lags are like this:

*

*Desktop PC Chrome - instant exchange

*Macbook Pro 13 Chrome - 0.2 seconds lag

*Nexus 5 Chrome - 0.5 seconds lag

*Iphone 7 Safari - 1 second lag

I'm preloading all videos with preloadJS, but this still didn't change anything. Using smaller videos on mobile (implemented in the example) also didn't help.
Basically I'm doing this:
this.video = document.createElement('video');
this.video.setAttribute('playsinline', '');
this.video.muted = true;
this.video.loop = true;
this.video.src = 'img/Room1Mobile.mp4';
this.video.crossOrigin = '';
this.video.play();

this.videoTexture = new THREE.Texture(this.video);
this.videoTexture.minFilter = THREE.LinearFilter;
this.videoTexture.magFilter = THREE.LinearFilter;
this.videoTexture.format = THREE.RGBFormat;

this.sphereMat.side = THREE.BackSide;
this.sphereMat.transparent = true;
this.sphereMat.opacity = 1;

this.cube = new THREE.Mesh(this.cubeGeometry, this.sphereMat);
this.cube.name = "videoGlobe";
this.scene.add(this.cube)

Later I then switch the source like this:
this.video.src = "img/Room2.mp4";
this.video.load();
this.video.play();

I understand, the problem is quite difficult to debug, but still hope someone could give me a tip :)
Here's a full demo.


text:
Q: Is there a less clumsy way to perform automatic numbering with infinite sequences? While the code I have does what I need, I feel I am missing some coding technique to implement this kind of stuff in a more concise way.
The goal is to compose items and give them an Id value along the way.
Here the code which I feel can be simplified and improved in many ways. If only I knew, how...
type Foo = | A of int | B of int | C of int
let ids startvalue = Seq.initInfinite (fun i -> i + startvalue)
let makeA ids =
    A(Seq.head ids), Seq.skip 1 ids
let makeB ids =
    B(Seq.head ids), Seq.skip 1 ids
let makeC ids =
    C(Seq.head ids), Seq.skip 1 ids
let config = [makeA; makeA; makeC; makeB]
let create (ids : seq<int>) (cfg : (seq<int> -> Foo * seq<int>) list) : Foo list * seq<int> =
    let rec cre ids1 acc cl =
        match cl with
        | [] -> (acc,ids1)
        | x::xs ->
            let v,ids2 = x ids1
            cre ids2 (acc @ [v]) xs
    cre ids [] cfg
let result : Foo list * seq<int> = create (ids 0) config

Which results in the very simple:

val result : Foo list * seq = ([A 0; A 1; C 2; B 3], )

Somehow I feel there should be an easier way to accomplish the same.
In fact, I know one way to make it simpler but this would involve mutable state and memoization (and would thusly be probably considered worse):
let idgen startvalue =
    let v = ref startvalue
    fun () ->
        let result = !v
        v := !v + 1
        result

With the thusly received generator function I could get rid of all those tuples, at least and I could also get rid of create function and simply write:
let ids = idgen 0
let result =
    [
        A(ids())
        A(ids())
        C(ids())
        B(ids())
    ]

But there should also exist a "functional" way to get it done more simply.

A: It seems that what you want is to take two sequences, one of functions, the other of arguments, and produce new sequence by applying functions to corresponding arguments, where in your particular case arguments are successive integer numbers and functions are union case constructors. Would that be a correct assessment?
If so, here's what I would do:
let create args funs =
   Seq.zip args funs
   |> Seq.map (fun (arg, fn) -> fn arg)
   |> List.ofSeq

let result = create (ids 0) [A; A; C; B]

A: type Foo = | A of int | B of int | C of int
let ids startvalue = Seq.initInfinite (fun i -> i + startvalue)
let config = [A; A; C; B]
let create ids i cfg =
    let ids' = ids i
    let nextI = i + List.length cfg
    (Seq.map2 id cfg ids'), nextI
let result, nextI = create ids 0 config
let result2, nextI2 = create ids nextI config

There are several considerations here:

*

*A, B, and C are constructors of the type int -> Foo. You may directly use them as functions and eliminate repetitive wrapper functions;

*Seq.map2 is able to process sequences of different length and ignore the remaining elements of the longer one;

*id is a shortcut for fun f number -> f number, please use the longer one if you find id unclear

*You may also refactor ids function into Seq.initInfinite id |> Seq.skip startvalue.

*At the end, you may convert a sequence into a List if you really need.

Updated to receive an keep i and nextI.

A: As Fyodor pointed out in his answer, you really just want to apply your constructors to consecutive integers. You can use the built-in mapi for that, writing your entire program as:
type Foo = | A of int | B of int | C of int
let config = [A; A; B; C]
let create offset = List.mapi (fun i f -> f (offset + i))
create 78 config
// val it : Foo list = [A 78; A 79; B 80; C 81]


text:
Q: Realm for Android: Many to Many Relationship I am trying to learn Realm basics by implementing a simple Android project.
The idea is that user have several items and several item lists and an item can be added to any of these lists and a list can have many items. Therefore, there is a many to many relationship between Item and List objects. Here are my objects.
public class Item extends RealmObject {

    @PrimaryKey
    private String id;
    private String name;
    private boolean isDone;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDone() {
        return isDone;
    }

    public void setDone(boolean done) {
        isCollected = done;
    }
}

public class List extends RealmObject {

    @PrimaryKey
    private String id;
    private String name;
    private RealmList<Item> items;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public RealmList<Item> getItems() {
        return items;
    }

    public void setItems(RealmList<Item> items) {
        this.items = items;
    }
}

My problem is, the field isDone might be different depending on the item's status in a given list. But when I update this field in a list, all the other items added to different lists get updated too. Since they are using the same object it makes sense but that is not to behavior I want. Is there a Realm way to create a pivot table/object with an extra column/field (in that case isDone) ?
Any help would be appreciated.

A: The problem is that the isDone property of Item doesn't truly belong to Item. If you can set the same Item in multiple Lists, then the property that a given task is deemed complete within a given List is the property of the List.
public class Item extends RealmObject {

    @PrimaryKey
    private String id;
    private String name;
    //private boolean isDone;

    @LinkingObjects("completedItems")
    private final RealmResults<List> tasksCompletedIn = null;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //public boolean isDone() {
    //    return isDone;
    //}

    //public void setDone(boolean done) {
    //    isDone = done;
    //}
}

public class List extends RealmObject {

    @PrimaryKey
    private String id;
    private String name;
    private RealmList<Item> items;
    private RealmList<Item> completedItems;

Then you know if it's a completed item if completedItems.contains(item) (where item is a managed object, or overrides equals to check against only id)


text:
Q: Getting a CGContext from a CGImage I have a CGImage which I would like to draw a line onto. I think that I am supposed to create a CGContext, then draw the image onto it, and then draw my line on it. However, I am not sure how to go from a CGImage to a CGContext. I have seen examples of going from a UIImage to a CGContext, but I was wondering if a more direct way is possible (and hopefully more efficient).
My attempt:
let ctx = CGContext(data: nil, width: cgImage.width, height: cgImage.height, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: cgImage.bytesPerRow, space: cgImage.colorSpace!, bitmapInfo: cgImage.bitmapInfo.rawValue)

      ctx!.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))

      ctx!.setFillColor(UIColor.red.cgColor)

      ctx!.fillEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))

      cgImage = (ctx!.makeImage())!

A: It looks inefficient, creating a blank context and drawing the image to it, doesn't it? On the other hand, that type of image drawing is highly optimised. But let's see what else we can do.
Caution: Do not Copy and Paste
Do not use the code block that follows in your program without:

*

*Profiling for memory leaks

*Measuring performance statistics before and after the change

*Understanding what happens when the input image has a format Core Graphics doesn't know how to use.

Sending Data to CGContext
The CGContext constructor takes a data argument. We set this to nil to tell it to create new data, but if we give it some existing bytes, the context will come into existence with its image in place.
But where do we get those bytes from? There may be a better way to do this, but the simplest was I could find to do it was:

*

*Get CGImage.dataProvider and then CGImageDataProvider.data, which copies the original image bytes into an immutable CFData object.

*Allocate an UnsafeMutablePointer<UInt8> and with the length of the CFData. (Remember to deallocate() it later).

*Copy the CFData contents into the UnsafeMutablePointer<UInt8>.

*Construct the CGContext using the UnsafeMutablePointer<UInt8>.

This already looks a suspicious: we might expect to copy all the bytes in the image once, but we're copying them twice.
Putting it Together
func imageByCopyingBytes(cgImageInput : CGImage) -> CGImage? {
    var cgImageOutput : CGImage? = nil

    if let dataProvider = cgImageInput.dataProvider {
        // Here we make a copy of the image bytes.
        // This copy is immutable, so can't be used by CGContext().
        // The CGDataProvider documentation:
        // https://developer.apple.com/documentation/coregraphics/cgdataprovider/1408309-data
        // Says "You are responsible for releasing this object."
        // However, Swift does manage these types:
        // https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/working_with_core_foundation_types
        if let data : CFData = dataProvider.data {
            let length = CFDataGetLength(data)

            // We must manually deallocate this memory by calling bytes.deallocate() once we finish it.
            let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: length)

            // Copy the immutable image data into the mutable bytes.
            CFDataGetBytes(data, CFRange(location: 0, length: length), bytes)

            // Create a context with the mutable bytes as the data.
            // This may fail and return nil if the input image bitmapInfo is not supported on this operating system.
            //
            if let ctx = CGContext(data: bytes, width: cgImageInput.width, height: cgImageInput.height, bitsPerComponent: cgImageInput.bitsPerComponent, bytesPerRow: cgImageInput.bytesPerRow, space: cgImageInput.colorSpace!, bitmapInfo: cgImageInput.bitmapInfo.rawValue) {

                // Do your drawing here.
                ctx.setFillColor(UIColor.red.cgColor)
                ctx.fillEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))

                // Make a CGImage from the context.
                cgImageOutput = (ctx.makeImage())

                if cgImageOutput == nil {
                    print("Failed to make image from CGContext.")
                }
            } else {
                print("Could not create context. Try different image parameters.")
            }

            // We have finished with the bytes, so deallocate them.
            bytes.deallocate()
        } else {
            print("Could not get dataProvider.data")
        }
    } else {
        print ("Could not get cgImage.dataProvider")
    }

    return cgImageOutput
}

Performance: Disappointing
I set up functions to create CGContext and CGImage copies by these means - no drawing, just copying. I counted how many times I could run them in 1 second, on pictures that ranged from tiny icons, through a regular iPhone photo, to a giant panorama.

On small icon images, imageByCopyingBytes was 11% to 36% faster, probably not enough to justify the additional program complexity. On regular-sized photos and panoramas, it was 60% slower!
I can't fully explain this. But it does show that Apple put a lot of work into optimising their drawing functions. Never assume that you need to work around them.
Additional Caution: CGContext Constructor
You may notice that my imageByCopyingBytes function is optional binding, to make sure that a variable is defined before using it. This can lead to the function quietly returning nil with only a log to the console to let you know it happened.
I don't know if this will come through intact, but this is the first picture I tried to test with. It was one of the smaller PNG files I had, so it should be a safe one to test with, right? Wrong?

I tried to run as a Catalyst application on macOS 11.6.1. The step where I tried to construct the CGContext led to this error being logged to the console. Since no CGContext had been created, the next steps resulted in a crash.
CGBitmapContextCreate: unsupported parameter combination: set CGBITMAP_CONTEXT_LOG_ERRORS environmental variable to see the details

The question and answer to How to set CGBITMAP_CONTEXT_LOG_ERRORS environmental variable? helped me see the full error:
CGBitmapContextCreate: unsupported parameter combination:
    8 bits/component; integer;
    32 bits/pixel;
    RGB color space model; kCGImageAlphaLast;
    default byte order;
    720 bytes/row.

It followed this will a list of supported formats, which showed it didn't like kCGImageAlpaLast, and wanted kCGImageAlphaPremultipliedLast or similar.
I specify my macOS version since this worked fine on the iOS 15.2 simulator, although it still couldn't handle grayscale pictures with kCGImageAlphaLast.
What all this means is I would be very wary of creating your CGContext with the same format as your input image. I get the impulse to match it, especially if you're getting files from the user, drawing things on them, and then returning the edited file. I like applications that preserve my image formats. But the Core Graphics libraries have formats they like, and formats they grudgingly tolerate. For most tasks, it is better to specify your the format of any CGContext you create. Obviously you can no longer use the arrays of bytes we just did the work to create above. But copying the picture by drawing it as you did in your question should still work, and leaves Core Graphics to handle the hard work of converting it.
Conclusion
If you've scrolled all the way down to here, this is my final answer to your question: go on copying the image by drawing it, but in the CGContext constructor specify your own bitmapInfo and possibly colorSpace.
Do you also get the results you expect if you load a JPEG with a non-standard orientation?


text:
Q: Mod_sec rule fails with hex CR or LF in POST On a shared hosting platform, running a WordPress site with comments enabled, some comments are causing 500 errors. The server error.log file shows entries similar to this (some obfustication of path and IP address, and line breaks added for visual clarity):
     [Thu Aug 12 13:38:35.782008 2021] [:error] [pid 24207:tid 3383178114816]
[client 24.113.161.xxx:59792] [client xx.xx.xx.x] ModSecurity: Warning.
    Pattern match "(?:get|post|head|options|connect|put|delete|trace|track|patch|propfind|propatch|mkcol|copy|move|lock|unlock)
\\\\s+(?:\\\\/|\\\\w)[^\\\\s]*(?:\\\\s+http\\\\/\\\\d|[\\\\r\\\\n])"
    at REQUEST_BODY. [file "/dh/apache2/template/etc/mod_sec3_CRS/REQUEST-921-PROTOCOL-ATTACK.conf"] [line "52"] [id "921110"]
    [msg "HTTP Request Smuggling Attack"]
    [data "Matched Data: post request.\\x0d found within REQUEST_BODY: comment=@nick - the error logs indicate that there is some hex characters embedded in the text that causes the 500 error. you may not be able to see the hex characters,
    but they are recognized as a code injection attempt, which is why the server blocks them (via the mod_sec3_crs module, which interprets the pattern as being a security risk, and therefore blocks the request, which is returned as a 500 error).
    \\x0d\\x0a\\x0d\\x0athe embedded characters..."]
    [severity "CRITICAL"] [ver "OWASP_CRS/3.3.2"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-protocol"]
    [tag "paranoia- [hostname "www.ttgnet.com"]
    [uri "/journal/wp-comments-post.php"] [unique_id "YRWGy9SRhtRZmIT81gkAvAAAAA8"], referer: https://example.com/journal/

Similar entries in the error log also catch the hex values for CR/LF as rule violations. Not all comment posts cause the 500 error (or entries in the server error log), but all of the errors seem to include the CR/LF hex pattern in the error message.
I am not well-versed in how mod-sec works. Where should I start to diagnose?
Added
Here's a sample complete line from the log file, with folder names anonymized:
Line 49: [Tue Sep 21 14:16:06.979253 2021] [:error] [pid 21757:tid 3479988672256] [client 38.13.110.xxx:60982] [client 38.13.110.xxx] ModSecurity: Warning. detected SQLi using libinjection with fingerprint 'son;n' [file "/dh/apache2/template/etc/mod_sec3_CRS/REQUEST-942-APPLICATION-ATTACK-SQLI.conf"] [line "65"] [id "942100"] [msg "SQL Injection Attack Detected via libinjection"] [data "Matched Data: son;n found within ARGS:comment: \\x22Put the MP3 files in a zip archive, with a password, put the file in Dropbox, email the link in one email, password in a separate email. No postage involved. \\x22\\x0d\\x0a\\x0d\\x0a \\x0d\\x0a\\x0d\\x0aI can do that.\\xc2\\xa0 A password protected folder on my website.\\xc2\\xa0 Great idea Ray!!!\\x0d\\x0a\\x0d\\x0a "] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.2"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-sqli"] [tag "paranoia-level/1"] [tag "OWASP_CRS"] [tag "capec/1000/152/248/66"] [tag "PCI/6.5.2"] [hostname "www.example.com"] [uri "/folder/wp-comments-post.php"] [unique_id "YUpLllhFado5xTTGY0P7wwAAAA8"], referer: https://www.example.com/journal/post-title/

This is a comment to a WordPress post, and from a known commentor. Standard comment entry box.
Why would this be blocked - and causing a 500 error?
ADDED
Here's another error from the server error log. Note that the submitter is not a hacker (I know the person); just a commenter on the site.
[Thu Sep 23 11:43:42.440238 2021] [:error] [pid 8853:tid 3479955101440] [client 75.53.225.xxx:56406] [client 75.53.225.xxx] ModSecurity: Warning. Pattern match "(?:get|post|head|options|connect|put|delete|trace|track|patch|propfind|propatch|mkcol|copy|move|lock|unlock)\\\\s+(?:\\\\/|\\\\w)[^\\\\s]*(?:\\\\s+http\\\\/\\\\d|[\\\\r\\\\n])" at ARGS:comment. [file "/dh/apache2/template/etc/mod_sec3_CRS/REQUEST-921-PROTOCOL-ATTACK.conf"] [line "52"] [id "921110"] [msg "HTTP Request Smuggling Attack"] [data "Matched Data: lock home.\\x0d found within ARGS:comment: it's the people.\\xc2\\xa0 the un isn't forcing them to be dirty.\\xc2\\xa0 the clinton's removed people from the island, which should have helped (yeah, poor taste).\\x0d\\x0a\\x0d\\x0a\\xa0\\x0d\\x0a\\x0d\\x0aif they don't want to live in garbage under a bridge stay the flock home.\\x0d\\x0a\\x0d\\x0a\\xa0\\x0d\\x0a\\x0d\\x0an"] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.2"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-protocol"] [tag "paranoia-level/1"] [tag "OWASP_CRS"] [tag "capec/1000/210/272/220/33"] [hostname "www.example.com"] [uri "/journal/wp-comments-post.php"] [unique_id "YUzK3shjwDZMxbYxHQ83EQAAAA8"], referer: https://www.example.com/journal/2021/09/23/thur-sept-23-2021-tired-but-the-weather-is-great/

[Thu Sep 23 11:43:42.440563 2021] [:error] [pid 8853:tid 3479955101440] [client 75.53.225.xxx:56406] [client 75.53.225.xxx] ModSecurity: Warning. Pattern match "(?:get|post|head|options|connect|put|delete|trace|track|patch|propfind|propatch|mkcol|copy|move|lock|unlock)\\\\s+(?:\\\\/|\\\\w)[^\\\\s]*(?:\\\\s+http\\\\/\\\\d|[\\\\r\\\\n])" at REQUEST_BODY. [file "/dh/apache2/template/etc/mod_sec3_CRS/REQUEST-921-PROTOCOL-ATTACK.conf"] [line "52"] [id "921110"] [msg "HTTP Request Smuggling Attack"] [data "Matched Data: lock home.\\x0d found within REQUEST_BODY: comment=it's the people.\\xc2\\xa0 the un isn't forcing them to be dirty.\\xc2\\xa0 the clinton's removed people from the island, which should have helped (yeah, poor taste).\\x0d\\x0a\\x0d\\x0a\\xa0\\x0d\\x0a\\x0d\\x0aif they don't want to live in garbage under a bridge stay the flock home.\\x0d\\x0a\\x0d\\x0a\\xa0\\x0d\\x0a\\x0d\\x0an&author=nick flandrey&email=flandrey@aol.com&url=https://www.example.com/journal/&wp-comment-cookies-consent=yes&bcsb_hidden=6f29fb34-6a01..."] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.2"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-protocol"] [tag "paranoia- [hostname "www.example.com"] [uri "/journal/wp-comments-post.php"] [unique_id "YUzK3shjwDZMxbYxHQ83EQAAAA8"], referer: https://www.example.com/journal/2021/09/23/thur-sept-23-2021-tired-but-the-weather-is-great/

[Thu Sep 23 11:43:42.458524 2021] [:error] [pid 8853:tid 3479955101440] [client 75.53.225.xxx:56406] [client 75.53.225.xxx] ModSecurity: Access denied with code 418 (phase 2). Operator GE matched 7 at TX:anomaly_score. [file "/dh/apache2/template/etc/mod_sec3_CRS/REQUEST-949-BLOCKING-EVALUATION.conf"] [line "93"] [id "949110"] [msg "Inbound Anomaly Score Exceeded (Total Score: 10)"] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.2"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-generic"] [hostname "www.example.com"] [uri "/journal/wp-comments-post.php"] [unique_id "YUzK3shjwDZMxbYxHQ83EQAAAA8"], referer: https://www.example.com/journal/2021/09/23/thur-sept-23-2021-tired-but-the-weather-is-great/

A: Are you sure these are really not attack attempts?

A: You will probably need to write an exclusion rule, here's an example of very simple one which should work:
SecRule REQUEST_FILENAME "@streq /journal/wp-comments-post.php" \
    "id:9990000,\
    phase:1,\
    pass,\
    t:none,\
    nolog,\
    ctl:ruleRemoveTargetById=921110;ARGS:comment,\
    ctl:ruleRemoveTargetById=921110;REQUEST_BODY"

Put it into file REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf .


text:
Q: SQL ORACLE 12C ERROR: PLS-00103: Encountered the symbol ")" when expecting one of the following I checked on some SQL validation sites and they found that this script works and that it was correct, but when I make a query in database, it returns me some errors that I will show below. What should I do?
My database: Oracle version 12c. I use SqlDbx.
The script:
CREATE OR REPLACE PROCEDURE SPE210EST()
IS
  v_QtdDis LONG;
  v_TraDep LONG;
  v_QtdFat LONG;
  v_QtdDev LONG;
  v_QtdOrd LONG;
  v_QtdEst LONG;
  v_QtdBlo LONG;
  v_QtdRae LONG;
  v_QtdRes LONG;
  v_CodEmp NUMBER;
  v_CodPro VARCHAR(14);
  v_CodDer VARCHAR(7);
  v_CodDep VARCHAR(10);
BEGIN
 SELECT E210EST.CodEmp INTO v_CodEmp, E210EST.CodPro INTO v_CodPro, E210EST.CodDer INTO v_CodDer, E210EST.CodDep INTO v_CodDep, E210EST.QtdEst INTO v_QtdEst, E210EST.QtdBlo INTO v_QtdBlo, E210EST.QtdRae INTO v_QtdRae, E210EST.QtdRes INTO v_QtdRes, E210EST.QtdOrd INTO v_QtdOrd
   FROM E210EST, E075PRO
  WHERE E210EST.CodEmp = E075PRO.CodEmp
    AND E210EST.CodPro = E075PRO.CodPro
    AND E210EST.CodDep IN ('1','3','4','5','9')
    AND (CASE WHEN (E210EST.QtdEst - E210EST.QtdBlo - E210EST.QtdRae - E210EST.QtdRes) < 0 THEN 0 ELSE E210EST.QtdEst - E210EST.QtdBlo - E210EST.QtdRae - E210EST.QtdRes END) <> (CASE WHEN E210EST.CodDep = '1' THEN E075PRO.USU_Dep1 WHEN E210EST.CodDep = '3' THEN E075PRO.USU_Dep3 WHEN E210EST.CodDep = '4' THEN E075PRO.USU_Dep4 WHEN E210EST.CodDep = '5' THEN E075PRO.USU_Dep5 WHEN E210EST.CodDep = '9' THEN E075PRO.USU_Dep9 END);

 v_QtdDis := (:v_QtdEst - :v_QtdBlo - :v_QtdRae - :v_QtdRes);
 v_QtdOrd := :v_QtdOrd;
 v_QtdFat := 0;
 v_TraDep := 0;
 v_QtdDev := 0;

 IF (:v_CodDep = '1' OR  :v_CodDep = '3' OR :v_CodDep = '4' OR :v_CodDep = '5' OR :v_CodDep = '9') THEN
  SELECT CASE WHEN SUM(CASE WHEN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(E000IPC.UNINFC),'Ç','C'),' ',''),'UND','UN'),'PT','UN'),'M','MT'),'RL','UN') <> E075PRO.UNIMED
                            THEN (SELECT CASE WHEN E015TCU.TIPCNV = '*' THEN E000IPC.QTDREC * E015TCU.VLRCNV
                                              WHEN E015TCU.TIPCNV = '/' THEN E000IPC.QTDREC / E015TCU.VLRCNV END
                                    FROM E015TCU
                                   WHERE E015TCU.UNIMED = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(E000IPC.UNINFC),'Ç','C'),' ',''),'UND','UN'),'PT','UN'),'M','MT'),'RL','UN')
                                     AND E015TCU.UNIME2 = E075PRO.UNIMED)
                       ELSE E000IPC.QTDREC END) IS NULL THEN 0
              ELSE SUM(CASE WHEN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(E000IPC.UNINFC),'Ç','C'),' ',''),'UND','UN'),'PT','UN'),'M','MT'),'RL','UN') <> E075PRO.UNIMED
                            THEN (SELECT CASE WHEN E015TCU.TIPCNV = '*' THEN E000IPC.QTDREC * E015TCU.VLRCNV
                                              WHEN E015TCU.TIPCNV = '/' THEN E000IPC.QTDREC / E015TCU.VLRCNV END
                                    FROM E015TCU
                                   WHERE E015TCU.UNIMED = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(UPPER(E000IPC.UNINFC),'Ç','C'),' ',''),'UND','UN'),'PT','UN'),'M','MT'),'RL','UN')
                                     AND E015TCU.UNIME2 = E075PRO.UNIMED)
                       ELSE E000IPC.QTDREC END)
               END INTO v_TraDep
    FROM E000NFC,E000IPC,E070FIL,E095FOR,E403FPR,E075PRO
   WHERE E000NFC.SITNFC = '1'
     AND E000NFC.TIPNFE = 1
     AND E000NFC.STANFV <> 3
     AND E000NFC.INDCAN <> 'S'
     AND E000NFC.CGCFIL = E000IPC.CGCFIL
     AND E000NFC.CGCFOR = E000IPC.CGCFOR
     AND E000NFC.CHVNEL = E000IPC.CHVNEL
     AND E403FPR.CODEMP = E075PRO.CODEMP
     AND E403FPR.CODPRO = E075PRO.CODPRO
     AND E403FPR.CODEMP = :v_CodEmp
     AND E403FPR.CODPRO = :v_CodPro
     AND E403FPR.CODDER = :v_CodDer
     AND E000IPC.CODDEP = :v_CodDep
     AND E000IPC.CODDEP IN ('1','3','4','5','9')
     AND E000IPC.NOPPRO IN ('5101','5102','5401','5402','5403','5405','6101','6102','6401','6402','6403','6404')
     AND E070FIL.NUMCGC = E000NFC.CGCFIL
     AND E095FOR.CGCCPF = E000NFC.CGCFOR
     AND E403FPR.CODEMP = E070FIL.CODEMP
     AND E403FPR.CODFOR = E095FOR.CODFOR
     AND E403FPR.PROFOR = E000IPC.PROFOR;

  SELECT CASE WHEN SUM(E140IPV.QTDFAT) IS NULL THEN 0 ELSE SUM(E140IPV.QTDFAT) END INTO V_QtdFat
    FROM E140NFV, E140IPV, E090REP, E001TNS, E120PED
   WHERE E140NFV.CODEMP = E140IPV.CODEMP
     AND E140NFV.CODFIL = E140IPV.CODFIL
     AND E140NFV.CODSNF = E140IPV.CODSNF
     AND E140NFV.NUMNFV = E140IPV.NUMNFV
     AND E140NFV.CODREP = E090REP.CODREP
     AND E120PED.CODEMP = E140IPV.CODEMP
     AND E120PED.CODFIL = E140IPV.FILPED
     AND E120PED.NUMPED = E140IPV.NUMPED
     AND E120PED.USU_PEDPRJ <> 'P'
     AND E140NFV.CODSNF = 'NFE'
     AND E140NFV.CODFIL IN (1,3,4,5,9)
     AND E140NFV.DATEMI >= (SYSDATE-91)
     AND E140NFV.DATEMI < (SYSDATE)
     AND E140NFV.SITNFV = '2'
     AND E140NFV.TIPNFS IN (1,10)
     AND E140IPV.CODPRO = :v_CodPro
     AND E140IPV.CODDER = :v_CodDer
     AND E140IPV.CODDEP IN ('1','3','4','5','9')
     AND E090REP.USU_GrpRep = TO_NUMBER(:v_CodDep)
     AND E140IPV.CODEMP = E001TNS.CODEMP
     AND E140IPV.TNSPRO = E001TNS.CODTNS
     AND E001TNS.VENFAT = 'S'
     AND E140IPV.CODEMP = :v_CodEmp;

  SELECT CASE WHEN SUM(E440IPC.QTDEST) IS NULL THEN 0 ELSE SUM(E440IPC.QTDEST) END INTO v_QtdDev
    FROM E440NFC,E075PRO,E440IPC,E001TNS,E090REP
   WHERE E440NFC.CODEMP = :v_CodEmp
     AND E440NFC.CODFIL IN (1,3,4,5,9)
     AND E440NFC.DATENT >= (SYSDATE-91)
     AND E440NFC.DATENT < (SYSDATE)
     AND E440IPC.CODEMP = E440NFC.CODEMP
     AND E440IPC.CODFIL = E440NFC.CODFIL
     AND E440IPC.CODFOR = E440NFC.CODFOR
     AND E440IPC.NUMNFC = E440NFC.NUMNFC
     AND E440IPC.CODSNF = E440NFC.CODSNF
     AND E440IPC.CODEMP = E075PRO.CODEMP
     AND E440IPC.CODPRO = E075PRO.CODPRO
     AND E440IPC.CODDEP IN ('1','3','4','5','9')
     AND E075PRO.CODPRO = :v_CodPro
     AND E440IPC.CODDER = :v_CodDer
     AND E090REP.USU_GRPREP = TO_NUMBER(:v_CodDep)
     AND (E440NFC.TIPNFE = 3 OR E440NFC.TIPNFE = 2)
     AND E440NFC.SITNFC = '2'
     AND E440IPC.CODEMP = E001TNS.CODEMP
     AND E440IPC.TNSPRO = E001TNS.CODTNS
     AND E440NFC.USU_CODREP = E090REP.CODREP
     AND E001TNS.CPRTCF = 'D';

  IF (v_QtdDis < 0) THEN
    v_QtdDis := 0;
  END IF;

  IF (:v_CodDep = '1') THEN
   UPDATE E075PRO
      SET USU_DEP1 = v_QtdDis,
          USU_TRADP1 = v_TraDep,
          USU_MINCCO = ((V_QtdFat - v_QtdDev)/90) * 20
    WHERE CODEMP = :v_CodEmp
      AND CODPRO = :v_CodPro;
  END IF;
  IF (:v_CodDep = '3') THEN
   UPDATE E075PRO
      SET USU_DEP3 = v_QtdDis,
          USU_TRADP3 = v_TraDep,
          USU_MINJOI = ((V_QtdFat - v_QtdDev)/90) * 20
    WHERE CODEMP = :v_CodEmp
      AND CODPRO = :v_CodPro;
  END IF;
  IF (:v_CodDep = '4') THEN
   UPDATE E075PRO
      SET USU_DEP4 = v_QtdDis,
          USU_TRADP4 = v_TraDep,
          USU_MINSJ = ((V_QtdFat - v_QtdDev)/90) * 20
    WHERE CODEMP = :v_CodEmp
      AND CODPRO = :v_CodPro;
  END IF;
  IF (:v_CodDep = '5') THEN
   UPDATE E075PRO
      SET USU_DEP5 = v_QtdDis,
          USU_TRADP5 = v_TraDep,
          USU_MINJDS = ((V_QtdFat - v_QtdDev)/90) * 20
    WHERE CODEMP = :v_CodEmp
      AND CODPRO = :v_CodPro;
  END IF;
  IF (:v_CodDep = '9') THEN
   UPDATE E075PRO
      SET USU_DEP9 = v_QtdDis,
          USU_TRADP9 = v_TraDep,
          USU_MINFLN = ((V_QtdFat - v_QtdDev)/90) * 20
    WHERE CODEMP = :v_CodEmp
      AND CODPRO = :v_CodPro;
  END IF;
 END IF;
END SPE210EST

The error it returns:

1   ORA-24344: success with compilation error
1   PLS-00103: Encountered the symbol ")" when expecting one of the following:
1    <an identifier>
1    <an identifier delimited by double quotes> current delete
1    there is prior
1
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % de
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite
17  PLS-00103: Encountered the symbol "INTO" when expecting one of the following:
17
17     . ( , % ; limite

A: The syntax is:
CREATE PROCEDURE procedure_name
IS
  v_a VARCHAR2(20);
  v_b VARCHAR2(20);
  v_c VARCHAR2(20);
BEGIN
  SELECT dummy, dummy, dummy
  INTO   v_a, v_b, v_c
  FROM   DUAL;
END;
/

You do not need the () braces after the procedure name if there are no parameters and it is SELECT <list of columns> INTO <list of variables> FROM ....


text:
Q: How do I perform my own redraw in the Paint event of a VB6 PictureBox? A coworker is encountering an error when he tries to run a VB6 app we're working on.  The error is, "480: Can't create AutoRedraw image".  Microsoft's documentation says this is because "There isn't enough available memory for the AutoRedraw property to be set to True.  Set the AutoRedraw property to False and perform your own redraw in the Paint event procedure or make the PictureBox control or Form object smaller..."
Making the PictureBox smaller isn't an option.  I'd be glad to "...perform my own redraw in the Paint event procedure...", but I'm not sure how to go about it.  Can someone show me the way?

A: Without details this will be a simplistic answer. In general most beginning VB6 programmers use AutoRedraw=True draw in responds to some input. Fill out some data, click draw, and it appears in the picture box.
The click event in the Draw Button is linked do your drawing code. The first step is move the call to the drawing code to the paint event of the picture. The second step is to replace all calls to the drawing code with MyPictureBox.Refresh. Refresh forces the paint event of that picture box to fire.
The main problem you will have to be concerned with is that the paint event is going to be fired everytime the form needs refreshed. Like if a window covering it is moved. This means that any speed issue in your drawing code will be exposed. AutoRedraw=True takes what you drew and puts in a hidden bitmap that the PictureBox uses to display what you drew.
The Paint event will execute each step of your drawing process so you have to make sure you are as fast as possible. Depending on how dynamic your application is the worse slowdown issues will become. If you are displaying a static image then the problem isn't as bad.

A:
Making the PictureBox smaller isn't an option. I'd be glad to "...perform my own redraw in the Paint event procedure...", but I'm not sure how to go about it. Can someone show me the way?

That is easy. You just implement the _Paint()-Event of your Form or PictureBox and draw.
Because you are asking, i think i should clarify what the AutoRedraw-Propeprty does. If it is set to true, you can "just draw your image" any way you want. In multiple steps. Whatever. If it needs to be redrawn, for example, because another windows was on top it, it will be magically done. The down site is, that is slow, for the drawing part.
If AutoRedraw is false, no magic will happen. The Paint()-Event will be fired and you are responsible to draw your image again. This will be much faster, if your window is not "invalidated" (e.g. "covered") often. Or you are doing a lot of drawing.
Or you are running out of memory for the "magic space" ;-)

A: If you don't mind rewriting your graphics code to use the GDI API - this could be a fairly big task - I found this thread from 2006 in the VB6 discussion group, where Mike Sutton said in answer to a similar problem:

VB's back-buffer implementation uses a
  Device Dependant Bitmap (DDB) to store
  the image data, which is quite limited
  in how large it can be made.  On older
  OS' this used to be ~16mb uncompressed
  data size, on later OS this has been
  expanded but is still quite
  restrictive.
A workaround for this is to use a
  Device Independent Bitmap (DIB) and
  manage the GDI resources yourself,
  have a look at the DIB article on my
  site for an example of how to work
  with them.

I haven't tried it myself.

A: There's usually a drop-down box of events for your control in the forms code window.  You need to pick the paint event:
Private Sub object_Paint()

and fill in your your code for drawing on the PictureBox.


text:
Q: Json to store settings in mysql? could someone maybe tell me if its a common practise to use json (arrays) in a database to store settings or preferences. Are there any pitfalls perhaps?

A: Doctrine ORM 2 in PHP also allows storing json in DB:

json_array: Type that maps a SQL CLOB to a PHP array using
  json_encode() and json_decode()

Ref: http://doctrine-orm.readthedocs.org/en/latest/reference/basic-mapping.html
So it's perfectly OK if you need it!

A: You can store JSON in MySQL (or any other database) using a varchar() field for the serialized format.
When you do so, you lose the flexibility of storing data in a table, because the database does not understand the different "columns" in the JSON object.  You can get the preferences for a single user relatively easily by retrieving the record for the user and parsing the JSON (presumably at the application level).  However, it becomes much harder to efficiently ask questions such as "How many users have option a".
Some databases have native support for JSON (such as Postgres since version 9.2).  In MySQL, you can get libraries of functions that have similar functionality (here is an arbitrary example).
If you have just a handful of known preferences that will not change, then create a table with a column for each one.  If you have many preferences and users may only have a subset, then these can be stored with one row per preference.  Such a UserPreferences table would have columns for:

*

*User id

*Preference name

*Preference value

This is a type of entity-attribute-value (EAV) data store.  This has the flexibility of being able to easily add new preferences.  The database can also take advantage of indexes and other techniques for improved performance.  However, this structure is not as flexible as JSON.

A: You can use a JSON based database like MongoDB, then it is

A: The question may be better asked on https://dba.stackexchange.com/
That being said, from my experience it's common to store json in a nosql database.  For a sql database you'd want to declare the column to be varchar with a fixed size.  You can make it very large to accommodate large json (what happens when you have a small json string).  You could alternatively make the field smaller (what happens when you have a large json string).  You can see how this would be bad for storing arbitrary json.  If your json isn't arbitrary then you should create specific fields in your table.
Also think about how you would query against your data if it's a json string.


text:
Q: Fastest C# collection for searching by property I have the following simple class:
public class MyClass{
    public long StartRange { get; set; }
    public long EndRange { get; set; }
    public int Id { get; set; }
}

I need to store many, 10^5 to 10^6, of these in a in-memory cache. There will be a single write to this cache at app start and many reads. This cache will be accessed in an ASP.NET environment, so many threads.
I need to lookup a row in this cache where my value is between StartRange and EndRange inclusive. The ranges do not overlap, but may be sparse. Simplest way I have found to do this is the following:
public MyClass Lookup(long value){
    return _set.FirstOrDefault(d => value >= d.StartRange && value <= d.EndRange);
}

I have tried this with storing the set as IOrderedEnumerable<T> and SortedSet<T>. The SortedSet is an order of magnitude faster. HashSet<T> is slightly faster than the SortedSet somehow. Any suggestions on the most efficient collection class to use or a better lookup would be most appreciated.

A:
The ranges do not overlap, but may be sparse.

If I'm understanding correctly, this means that if you sort them by StartRange, and then  identify the first item with value >= d.StartRange, you can immediately know that you've either found your item (if value <= d.EndRange), or there is no match, right?
So you can cut your time in half just by doing this:
public MyClass Lookup(long value){
    var candidate = _set.FirstOrDefault(d => value >= d.StartRange);
    if(candidate != null && value <= candidate.EndRange)
    {
        return candidate;
    }
    return null;
}

And, since searching in a sorted collection can easily be done in O(log n) time, you should be able to get significant performance gains with just a binary search. Here's some sample code that should get you on the right track.
List<MyClass> _set = new[]{
   new MyClass{StartRange = 18, EndRange = 18},
    new MyClass{StartRange = 10, EndRange = 15},
     new MyClass{StartRange = 20, EndRange = 21}
}.OrderBy(m => m.StartRange).ToList();

public class StartRangeComparer : IComparer<MyClass>
{
    public int Compare(MyClass first, MyClass second)
    {
        return first.StartRange.CompareTo(second.StartRange);
    }
}

StartRangeComparer startRangeComparer = new StartRangeComparer();

public MyClass Lookup(long value){
    var index = _set.BinarySearch(new MyClass{StartRange = value}, startRangeComparer);
    int candidateIndex = index >= 0 ? index : (~index) - 1;
    if(candidateIndex < 0)
    {
        // the given value is before any start-ranges in the list
        return null;
    }
    MyClass candidate = _set[candidateIndex];
    if(candidate.EndRange >= value)
    {
        return candidate;
    }
    else
    {
        return null;
    };
}

A: Can you not just sort by StartRange, use Array.BinarySearch to find the nearest one (that is still smaller) and because your ranges are sparse, know with one check (if Endrange is larger than x) if you found one or missed?
All you have to do for that to work is implement IComparable<T> with StartRange as key, which is easy.

A: Might not be what you really need, but have you looked into NoSQL ?
Some of the implementations act like what you want, and some have a cache that you can run from memory, so should be fast.
If my memory serves me Redis might be the one you'll want to look into. (here's an article about Redis).
K, some digging through my stuff yielded: NoSQL DB comparisson,  you can see there what are the major flavors and which use cases they are good for.
From what I've seen, they are using B-Trees for speed in some of the implementations. You might want to do something similar if you want to recreate the wheel I guess.

A: If your ranges might overlap now or in the future, you might look into using an interval tree.
But if your really sure your ranges have no overlaps, change your class to struct and do something like the following. The reason for changing class to struct is two-fold:

*

*Saves memory with an array. An array of reference types is an array of references to individual objects on the heap.

*Possibly more importantly, it helps preserve locality of reference. You  going to be jumping around in a contiguous block of memory rather than randomly all over the heap. That should help keep down paging.
Here's the code:
class MyClassMap
{
    MyClass[] backingStore ; // ordered by StartRange, then EndRange

    public MyClassMap( IEnumerable<MyClass> source )
    {
        backingStore.OrderBy( x => x.StartRange ).ThenBy( x => x.EndRange ) ;
    }

    public int? GetIdFromValue( long value )
    {
        int  lo = 0 ;
        int  hi = backingStore.Length ;
        int? ix = null ;
        while ( lo <= hi && !ix.HasValue )
        {
            int mid = lo + ((hi-lo)>>1) ;
            MyClass current = backingStore[mid] ;
            if      ( value > current.EndRange   ) { lo = mid+1      ; }
            else if ( value < current.StartRange ) { hi = mid-1      ; }
            else                                   { ix = current.Id ; }
        }

        return ix ;

    }

}


text:
Q: Calling Webjob from Azure Data Factory pipeline throwing HTTP 409 conflict exception error I have a OnDemand triggered webjob that I want to trigger through ADF copy activity using HTTP linked service. Here is the linked service:-
{
    "name": "LS_WebJob",
    "properties": {
        "hubName": "yas-cdp-adf_hub",
        "type": "Http",
        "typeProperties": {
            "url": "https://cust-app.scm.azurewebsites.net/api/triggeredwebjobs/ConsoleApplication1/run",
            "authenticationType": "Basic",
            "username": "$custdata-app",
            "password": "**********"
        }
    }
}

Input Dataset
{
    "name": "ZZ_Inp_Webjob",
    "properties": {
        "published": false,
        "type": "Http",
        "linkedServiceName": "LS_WebJob",
        "typeProperties": {
            "requestMethod": "Post",
            "requestBody": "Hey Buddy"
        },
        "availability": {
            "frequency": "Day",
            "interval": 1,
            "style": "StartOfInterval"
        },
        "external": true,
        "policy": {}
    }
}

Output Dataset
{
    "name": "ZZ_Out_WebJob",
    "properties": {
        "published": false,
        "type": "AzureBlob",
        "linkedServiceName": "LS_ABLB",
        "typeProperties": {
            "fileName": "webjob.json",
            "folderPath": "yc-cdp-container/Dummy/temp",
            "format": {
                "type": "TextFormat"
            }
        },
        "availability": {
            "frequency": "Day",
            "interval": 1,
            "style": "StartOfInterval"
        }
    }
}

Pipeline
{
"name": "ZZ-PL-WebJob",
"properties": {
    "description": "This pipeline copies data from an HTTP Marina WiFi Source URL to Azure blob",
    "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "HttpSource"
                },
                "sink": {
                    "type": "BlobSink",
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                }
            },
            "inputs": [
                {
                    "name": "ZZ_Inp_Webjob"
                }
            ],
            "outputs": [
                {
                    "name": "ZZ_Out_Webjob"
                }
            ],
            "policy": {
                "timeout": "01:00:00",
                "concurrency": 1
            },
            "scheduler": {
                "frequency": "Day",
                "interval": 1,
                "style": "StartOfInterval"
            },
            "name": "WebjobSourceToAzureBlob",
            "description": "Copy from an HTTP source to an Azure blob"
        }
    ],
    "start": "2017-04-10T01:00:00Z",
    "end": "2017-04-10T01:00:00Z",
    "isPaused": false,
    "hubName": "yas-cdp-adf_hub",
    "pipelineMode": "Scheduled"
}
}

My webjob is a simple C# application:-
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("My Team Rocks!");
        }
    }
}

When I am executing the pipeline, the webjob is being successfully triggered. However the pipeline fails with HTTP 409 conflict error.

Copy activity encountered a user error at Source side:
  ErrorCode=UserErrorFailedToReadHttpFile,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Failed
  to read data from http source
  file.,Source=Microsoft.DataTransfer.ClientLibrary,''Type=System.Net.WebException,Message=The
  remote server returned an error: (409) Conflict.,Source=System,'.

A: Try adding in the gateway name to the linked service json. Refer to this link How to integrate a WebJob within an Azure Data Factory Pipeline .


text:
Q: ng-repeat call controller function too many times I have next code (events is array):

        {{prepareAlertValue(event.AlertValue)}}

time-ago - my custom directive. It is executed events.length times.
My controller:
...
window.callPrepareAlertValueCount = 0

$scope.prepareAlertValue = function(value) {
    window.callPrepareAlertValueCount++;
    if(safemineHelper.isFloat(value)) {
        value = (~~(value * 100)) / 100;
    }
    return value;
}
...

After list is shown - I see that callPrepareAlertValueCount grows. Console log:
 > callPrepareAlertValueCount
 < 41890
 > callPrepareAlertValueCount
 < 46150
 > callPrepareAlertValueCount
 < 480315

Please, can someone explain why is prepareAlertValue executed all time.
Do I need to write directives for each formatter function?

A: That is correct what ever you bind on html, it gets called on each digest cycle run by angular js.
Use {{::prepareAlertValue(event.AlertValue)}} bind once directive that will execute that function only once.

Note Bind Once only work for above Angular 1.3+

A: Angular does not know whats going on inside prepareAlertValue() so
it needs to call this function on every digest

A: callPrepareAlertValueCount is a global variable on the window, and is updated whenever prepareAlertValue function is called.
The catch is, it's called whenever a digest cycle takes place. Whenever a change is made, such as a click event is triggered (through Angular with ng-click), or your events array is altered, that triggers a $digest cycle. When a $digest is triggered, the function reevaluates as all angular watchers are being reevaluated, and increments callPrepareAlertValueCount. So it happens many more times than events.length.
Basically, you shouldn't be relying on keeping a counter that way, since you have no control on how many times the $digest cycles are run.
Here's a simple Fiddle that demonstrates this.

A: You may stop calling controller functions inside ng-repeat. or if you want to call the controller function inside a loop(ng-repeat), then use proper conditions(in your controller), if true then call the function if you don't , then it will be calling the controller function every time.


text:
Q: kendo grid command change button How is possible to change button on click in command column?  In my case, there should be "Validate" and "Reset" button that should be displayed as different buttons depending on Status. Function for validating works normally, but there is a problem with applying another class to the button, there is always .valid class. Here is a problem, I don't know where to apply .reset class. Thanks
template:
    '<kendo button class = "k-primary button button-valid"ng-click="OnChangeStateMaterialDefinitionHeaders($event)"> #= Status == ' + STATUS_MDH_VALIDATE + '  ?  " ' + kendo.htmlEncode(txt.TXT_VALIDATE) + '" : "' +  kendo.htmlEncode(txt.TXT_RESET) + '" #</kendo button>  ' +
                    '<button ng-click="OnRemoveMaterialDefinitionHeaders($event)">' + kendo.htmlEncode(txt.TXT_SET_VALIDATED) + ' </button>',

The other button is not important now, but is a part of this command column.


text:
Q: How to list all solutions appearing in range A function h that I've written (it uses Reduce) outputs a list of integer solutions of the form e.g.
(a0 = 1 && a1 = 2 && a2 = 3) || (a0 = 2 && a1 = 3 && a2 = 4) || ... .
Some of the solutions however are of the form e.g. (a2 \[Element] Integers && a0 = 1 && a1 = 2 && -6 <= a2 <= 8). I'd like to seperate the solutions in the latter form into the former form, i.e. I would like to have the latter ones appearing as
(a0 = 1 && a1 = 2 && a2 = -6) || (a0 = 1 && a1 = 2 && a2 = -5) || ... .
The reason I ask is because I am exporting the wholle list of solutions into a .csv file as follows:
solns = Table[h[b, a0, a1, 0, 12], 1]]
Export["solns.csv", solns]
When solutions are of the former form, the .csv output is manageable for me, but with the latter form it is too messy. Does anyone know a way to fix this?
Many thanks.

A: Say the output you are getting looks like:
out = (a0 == 1 && a1 == 2 && a2 == 3) || (a0 == 2 && a1 == 3 && a2 == 4) ||
      (a2 \[Element] Integers && a0 == 1 && a1 == 2 && -6 <= a2 <= 8) || (a1 \[Element] Integers && a0 == 1 && a1 == 2 && -6 <= a2 <= 8)

Then you can remove the extra "Element" terms by:
DeleteCases[out /. Element -> Nothing, Nothing, 2]

(a0 == 1 && a1 == 2 && a2 == 3) || (a0 == 2 && a1 == 3 && a2 == 4) ||
(a0 == 1 && a1 == 2 && -6 <= a2 <= 8) || (a0 == 1 && a1 == 2 && -6 <= a2 <= 8)


text:
Q: Subsetting a matrix, addressing colnames I have this document term matrix  from package R{tm} which i have coerced to as.matrix. MWE here:
> inspect(dtm[1:ncorpus, intersect(colnames(dtm), thai_list)])
<<DocumentTermMatrix (documents: 15, terms: 4)>>
Non-/sparse entries: 17/43
Sparsity           : 72%
Maximal term length: 12
Weighting          : term frequency (tf)

Terms
Docs toyota_suv gmotors_suv ford_suv nissan_suv
1      0       1       0            0
2      0       1       0            0
3      0       1       0            0
4      0       2       0            0
5      0       4       0            0
6      1       1       0            0
7      1       1       0            0
8      0       1       0            0
9      0       1       0            0
10     0       1       0            0

I need to subset this as.matrix(dtm), such that I get only documents (rows) which refer to toyota_suv but no other vehicle. I get a subset for one term (toyota_suv) using  dmat<-as.matrix(dtm[1:ncorpus, intersect(colnames(dtm), "toyota_suv")]) which works well. How do I set up a query: documents where toyota_suv is non-zero but values of non-toyota_suv columns are zero? I could have specified column-wise as ==0 but this matrix is dynamically generated. In some markets, there may be four cars, in some markets there may be ten. I cannot specify colnames beforehand. How do I (dynamically) club all the non-toyota_suv columns to be zero, like all_others==0?
Any help will be much appreciated.

A: You can accomplish this by getting the index position for toyota_suv, and then subsetting dtm to match that for non-zero, and all other columns using negative indexing on the same index variable to ensure they are all zero.
Here I modified your dtm slightly so that the two cases where toyota_sub are non-zero meet the criteria you are looking for (since none in your example met them):
dtm <- read.table(textConnection("
toyota_suv gmotors_suv ford_suv nissan_suv
      0       1       0            0
      0       1       0            0
      0       1       0            0
      0       2       0            0
      0       4       0            0
      1       0       0            0
      1       0       0            0
      0       1       0            0
      0       1       0            0
      0       1       0            0"), header = TRUE)

Then it works:
# get the index of the toyota_suv column
index_toyota_suv <- which(colnames(dtm) == "toyota_suv")

# select only cases where toyota_suv is non-zero and others are zero
dtm[dtm[, "toyota_suv"] > 0 & !rowSums(dtm[, -index_toyota_suv]), ]
##   toyota_suv gmotors_suv ford_suv nissan_suv
## 6          1           0        0          0
## 7          1           0        0          0

Note:  This is not really a text analysis question at all, but rather one for how to subset matrix objects.

A: It would be helpful if you provided the exact code you are running and a sample data set to work with so that we can replicate your work and provide a working example.
Given that, if I understand your question correctly you are looking for a way to label all non-toyota columns to be zero. You could try:
df[colnames(df) != "toyota"] <- 0


text:
Q: UIRefreshControl cancel touch on top of custom cell - Objective-c iOS I have an issue with my UIRefreshControl : after the first time it was triggered, it cancels touch on top of my first custom cell (even if it is hidden), like if it was invisible.
If I remove it from superview, then add it again, the issue is still there.
Actually I have a UITableView that is populated with some data. The user can refresh the table view by pulling it and for that I've added an UIRefreshControl to my table view like this in viewDidLoad()
self.refreshControl = [[UIRefreshControl alloc]init];
self.refreshControl.tintColor = [UIColor colorWithRed:0.35 green:0.78 blue:0.98 alpha:1.0];
[_tableView addSubview:self.refreshControl];

I've not added selector to the refreshControl object because I want the tableView to refresh only when the user stopped touching the screen. So for that I've added this ScrollView's delegate method :
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView {

    if (self.refreshControl.isRefreshing) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            dispatch_sync(dispatch_get_main_queue(), ^{

                [self refreshTable];

            });

        });

    }

}

And here is my refresh method :
- (void)refreshTable {

    //refresh code

    [self.refreshControl endRefreshing];

}

I don't want to put my app online with this issue, even if this does not block user to use it !
Thanks in advance for your help !

A: I've found the solution by going to this post
So effectively in my case I did not have to add a selector, just implement those UIScrollViewDelegate's method :)


text:
Q: Why does Hibernate throw a QuerySyntaxException for this HQL? While building a query using Hibernate, I noticed something rather odd. If I use sequential named parameters for the ORDER BY clause, Hibernate throws a QuerySyntaxException (the colon prefix being an unexpected token):
createQuery("FROM MyEntity ORDER BY :orderProperty :orderDirection");

However, when this is done with a plain SQL query the query is created without a problem:
createSQLQuery("SELECT * FROM my_entity_table ORDER BY :orderProperty :orderDirection");

I know Hibernate is doing more String evaluation for the HQL query, which is probably why the SQL query is created without an error. I am just wondering why Hibernate would care that there are two sequential named parameters.
This isn't a huge issue since it is simple to work around (can just append the asc or desc String value to the HQL instead of using a named paramater for it), but it struck my curiosity why Hibernate is preventing it (perhaps simply because 99% of the time sequential named parameters like this result in invalid SQL/HQL).

A: I've been testing this in my local, and I can't get your desired outcome to work with HQL.
Here is quote from the post I linked:

You can't bind a column name as a parameter. Only a column value. This name has to be known when the execution plan is computed, before binding parameter values and executing the query. If you really want to have such a dynamic query, use the Criteria API, or some other way of dynamically creating a query.

Criteria API looks to be the more useful tool for your purposes.
Here is an example:
    Criteria criteria = session.createCriteria(MyEntity.class);

    if (orderDirection.equals("desc")) {
        criteria.addOrder(Order.desc(orderProperty));
    }
    else {
        criteria.addOrder(Order.asc(orderProperty));
    }

A: According to the answer accepted in this question, you can only define parameters in WHERE and HAVING clauses.
The same answer also gives you some ways to have a workaround for your problem, however I will add one more way to do this:
Use the CASE - WHEN clause in your ORDER BY, this would work by the following way:
SELECT u FROM User u
ORDER BY
CASE WHEN '**someinputhere**' = :orderProperty
AND '**someotherinput**' = :orderDirection
THEN yourColumn asc
ELSE yourColumn desc END

Please, note that in this approach would required you to write all the possible inputs for ordering. Not really beautiful but really useful, especially because you would not need to write multiple queries with different orderings, plus with this approach you can use NamedQueries, which would be possible by writing the query dinamically using string concats.
Hope this can solve your problem, good luck!


text:
Q: Showing rows in a multiple select When using multiple in a select can you choose how many rows it shows like you can in a textarea?
Right now it shows only 4 Locations as the default when using "multiple" and this select just happens to be a short list. Is there a way to show like 6 or 7 or all Locations instead of just the default 4 rows?

<select name="Location" id="loc" multiple="multiple" required>
 <!---<option selected value="">Select location</option>--->
    <option value="OPERATIONS">Operations</option>
    <option value="CCC">Contact Center</option>
    <option value="QA">QA Department</option>
    <option value="DS">DeSoto</option>
    <option value="PS">Palma Sola</option>
    <option value="LWR">Lakewood Ranch</option>
    <option value="NR">North River</option>
    <option value="SDL">SDL</option>
</select>

A: Just use the size attribute:
 <!-- This will show 10 items of the list -->
 <select multiple size="10">

 </select>

A: Then yes - increase the size of the select box.
JSfiddle
e.g.
select {
  height:300px;
}

A: You could just change the height.

#loc {
  height:140px
}
 <select name="Location" id="loc" multiple="multiple" required>
     <!---<option selected value="">Select location</option>--->
        <option value="OPERATIONS">Operations</option>
        <option value="CCC">Contact Center</option>
        <option value="QA">QA Department</option>
        <option value="DS">DeSoto</option>
        <option value="PS">Palma Sola</option>
        <option value="LWR">Lakewood Ranch</option>
        <option value="NR">North River</option>
        <option value="SDL">SDL</option>
    </select>

Edit: Also as gavin said, using just the size=k attribute:

<select size="8" name="Location" id="loc" multiple="multiple" required>
 <!---<option selected value="">Select location</option>--->
    <option value="OPERATIONS">Operations</option>
    <option value="CCC">Contact Center</option>
    <option value="QA">QA Department</option>
    <option value="DS">DeSoto</option>
    <option value="PS">Palma Sola</option>
    <option value="LWR">Lakewood Ranch</option>
    <option value="NR">North River</option>
    <option value="SDL">SDL</option>
</select>


text:
Q: Have a batch file check the value of a registry key, echo if it is set how I want and change it if it is not I want to have a script that will check the following Registry Key for
HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity
Enabled Reg_DWORD 0x0

If the value is set to 0x0, I want the script to echo Hypervisor Enforced Code Integrity is Disabled
If the value is set to anything else, I want to script to echo a statement, and then edit the registry value.
This is what I have so far, my issue is that the for /f command keeps erroring out. Any help would be really appreciated.
Set regkey="HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity"
Set Value=Enabled

for /f "tokens=2* delims=    "
%%A IN (reg query %regkey% /v %Value%) DO SET base=%%B
if %base%=0x0 && goto Disabled else goto Enabled

:Disabled
echo Hypervisor Enforced Code Integrity is Disabled
pause
exit

:Enabled
echo Hypervisor Enforced Code Integrity is Enabled
echo
echo Continuing will Disable Hypervisor Enforced Code Integrity and then your computer will reboot
echo
echo ****Save your work before continuting****
pause
reg add %regkey% /v %value% /t REG_DWORD /d 0x0

shutdown /r /f /t 005 /c "Restarting to Disable Hypervisor Enforced Code Integrity"

A: Your main issue, is a failure to read or understand the basic command usage information. If you open a Command Prompt window, type for /?, and press the ENTER key, you should see that you are using:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]

Instead of:
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

However, there are several things you could do to improve your script, for this, and future tasks, so I have included a rewritten example for you too. It includes sections which are reusable for other registry checks, a user modifiable registry key and value pair to use with those, and parts specific only to the task laid out in the question.
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Rem The next two lines are user editable.
Set "RegKey=HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity"
Set "RegVal=Enabled"

Rem please do not modify the next twenty three lines.
Set "Elv=0"
For %%G In (RegKey RegVal) Do If Not Defined %%G (
    %%G has not been defined.
    Set "Elv="
)
If Not Defined Elv GoTo EndIt

Set "RegData="
For /F Delims^=^ EOL^= %%G In (
    '%SystemRoot%\System32\reg.exe Query "%RegKey%" /V "%RegVal%" 2^>NUL ^| %SystemRoot%\System32\findstr.exe /RIC:"\<%RegVal%\>"'
) Do (
    Set "RegData=%%G"
    SetLocal EnableDelayedExpansion
    For /F "Tokens=1,*" %%H In ("!RegData:*%RegVal%=!") Do (
        EndLocal
        Set "RegData=%%I"
    )
)
If Not Defined RegData (
    Echo The registry information does not exist.
    GoTo EndIt
)

Rem The following five lines are specific to your task.
Set "Enabled=Disabled"
For %%G In (1 0x1 0x00000001) Do If "%RegData%" == "%%G" Set "Enabled=Enabled"
Echo Hypervisor Enforced Code Integrity is %Enabled%

If "%Enabled%" == "Disabled" GoTo EndIt

Rem Please do not modify the next seven lines.
Set "RegRoot=%RegKey:\="&:"%"
(Set RegRoot) 2>NUL | %SystemRoot%\System32\findstr.exe /XLI "HKLM HKEY_LOCAL_MACHINE" 1>NUL && Set "Elv=1"

%SystemRoot%\System32\reg.exe Query HKU\S-1-5-19 1>NUL 2>&1 || (
    Echo To modify the registry, this script must be run elevated.
    GoTo EndIt
)

Rem The following nine lines are specific to your task.
Echo(
Echo Your computer needs to reboot to disable Hypervisor Enforced Code Integrity.
Echo(
Echo ****Please save your work before continuting.****
Pause

%SystemRoot%\System32\reg.exe Add "%RegKey%" /V "%RegVal%" /T REG_DWORD /D 0 /F 1>NUL

%SystemRoot%\System32\shutdown.exe /R /T 5 /C "Restarting to Disable Hypervisor Enforced Code Integrity." /D P:2:4

Rem Please do not modify anything below.

:EndIt
Echo Press any key to exit . . .
Pause 1>NUL
Exit /B


text:
Q: Visual Studio through MSDN: Can they know it is not mine? So, I was arguing with a great friend of mine about Visual Studio 2012 and Microsoft being able to detect which one you used. According to him if you get your hands on a direct MSDN download of Visual Studio 2012 Professional, and you end up creating an app, like a game or something, and then you submit it to the Windows App Store, they will never know which visual studio version you truly used to develop the App, or if you were the owner of it or not.
Is he right? Because I thought Visual Studio some how left a footprint behind on the .exe file letting Microsoft know about licensing information. Or should I go apologize to him for calling him a f...ing liar.
If you guys say it does leave a print, can you show some proof, or a link to read more about it? Thanks guys.

A: Your friend is likely correct. Why would MS bother when they make freely available all the tools you need to compile your program. You can build .Net applications without the Visual Studio IDE. See this related question
Is it possible to install a C# compiler without Visual Studio?


text:
Q: Iterate over two lists with indexes in Ansible i have good knowledge at programming langage, but there's something I can't make with Ansible filters and YAML syntax.
Basically, I want to iterate over array/lists and make a comparison of each elements, like that in C language :
for (i=0;i<a;i++) {
  for (j=0;j<b;j++) {
     if (array1[i]==array2[j]) {
        ....
     }
  }
}

In my case, i'm trying to compare each attributes of two lists one by one.
Is there anyway to do it with Ansible?
Thanks in advance for your answers.

A: For example
- hosts: localhost
  vars:
    array1: [a, b, c]
    array2: [b, d, c, a]
  tasks:
    - debug:
        msg: "{{ item.0 }} == {{ item.1 }} {{ item.0 == item.1 }}"
      loop: "{{ array1|product(array2)|list }}"

gives
  msg: a == b False
  msg: a == d False
  msg: a == c False
  msg: a == a True
  msg: b == b True
  msg: b == d False
  msg: b == c False
  msg: b == a False
  msg: c == b False
  msg: c == d False
  msg: c == c True
  msg: c == a False

If you want to find indices
    - debug:
        msg: "array1[{{ array1.index(item.0) }}] ==
              array2[{{ array2.index(item.1) }}]"
      loop: "{{ array1|product(array2)|list }}"
      when: item.0 == item.1

gives
  msg: array1[0] == array2[3]
  msg: array1[1] == array2[0]
  msg: array1[2] == array2[2]


text:
Q: How does one get the instance of a Ruby class running in the current RB file? (Embedding Ruby in C++) I have embedded Ruby inside my C++ application. I have generated the bindings using SWIG.
Basically, I run the ruby file and then Ruby takes over and calls my C++ class.
Based on my previous question, I would like to get the current instance of the class that is defined in the ruby file back to the C++ class so that I may execute instance methods.
I execute the ruby file as follows:
rb_eval_string_protect(<ruby script string>, &status );

rb_funcall(Qnil, rb_intern("main"), 0);

The global main method in the script creates an instance of the defined class in the file. That's the instance I am after.
If I have to, I will add a parameter or another function to pass the instance back, however, I'm not sure how to define that in C++ so that when SWIG generates the binding, it all works ok.
Any help would be appreciated.
Previous Question: Calling Ruby class methods from C++

A: The C api for ruby does its best to preserve ruby's functional nature, so rb_eval_string_protect() returns the VALUE of the last line of the script given, and rb_funcall() returns the VALUE of the last line of the method invoked.
So the trick is really to think of it as how would you get that instance value in pure ruby?  If it's just the return value of main, like
# I'm a ruby script!
main_retval = main()

Then capturing the return value in C is similar:
// I'm some C (or C++) code
VALUE main_retval;
// ...
rb_eval_string_protect("...", &status);
main_retval = rb_funcall(Qnil, rb_intern("main"), 0);

And would give you a reference to the ruby object returned by main.
You can use this object as normal, calling methods and the like
VALUE main_retval_as_string = rb_funcall(main_retval, rb_intern("to_s"), 0);


text:
Q: Run grep or other commands on files on a web server I have files on another domain. What's the best way to use commands on them like grep?
wget http://path/to/file.txt | grep search

However this doesn't work. I guess I can use curl but is there a more efficient method?

A: For a pipeline to work, the first command needs to write to standard output. wget doesn't normally do that, but there is a way to request it. From the wget(1) man page:

-O file
  --output-document=file
     The documents will not be written to the appropriate files, but all
     will be concatenated together and written to file.  If - is used as
     file, documents will be printed to standard output

So do it like this
wget -O - http://what/ever | grep something

You might find wget's progress-reporting output to be annoyingly verbose in this context, in which case add the -q option to quiet it down.
wget -q -O - http://what/ever | grep something

Then you'll get nothing except the matching lines as output.

A: You can also use curl to do this, in addition to wget.
$ curl -s <url> | grep <pattern>

Example
$ curl -s http://textfiles.com/100/914bbs.txt | grep Colorama
965-7600 /Colorama        / CoCo / 300/1200 /General BBS

Details of switches
   -s, --silent
        Silent  or  quiet  mode.  Don't  show progress meter or error
        messages.  Makes Curl mute. It will still output the data you ask
        for, potentially even to the terminal/stdout unless you redirect it.


text:
Q: Google Earth crashes when opened I recently downloaded the Google Earth .deb file for 64-bit from here. And I installed it with:
sudo dpkg -i google-earth-stable_current_amd64.deb

And I of course also installed all of the other necessary dependencies with:
sudo apt-get install -f

Which Google Earth depends on. But now when I start Google Earth with:
google-earth

It launches, stays open for about 10 seconds, and then exits. From opening it to it closing this is what I see in Terminal:
[0628/171243:ERROR:net_util.cc(2195)] Not implemented reached in bool net::HaveOnlyLoopbackAddresses()
[0628/171244:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171244:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171244:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171244:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/161245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/161245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171245:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171246:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171247:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171247:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171247:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171247:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171247:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171249:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171249:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171249:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171249:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171250:WARNING:backend_impl.cc(1875)] Destroying invalid entry.
[0628/171253:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171253:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171253:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171253:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.
[0628/171254:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler.

Another crash happened while handling crash!

I am not sure of the meaning of these error messages, and what I should do about them to stop it from only lasting 10 seconds. So is there anyway I can fix this? Or is this some sort of bug? If so, where should I report it?

OS Information:
Description:    Ubuntu 15.04
Release:    15.04

Package Information:
google-earth-stable:
  Installed: 7.1.4.1529-r0
  Candidate: 7.1.4.1529-r0
  Version table:
 *** 7.1.4.1529-r0 0
        100 /var/lib/dpkg/status

A: I have the same problem .. the only way to fix it as far as I know and according to the other forums about googe earth crashing on start up is on start - up just try not to move the mouse and wait for it to be stable (like when the earth has been fully loaded) It works for me .. so give it a try

A: The only workaround for me was to disconnect from the Internet before starting the program.
I downloaded the latest version of google-earth-stable_current_amd64.deb and installed it by Ubuntu Software. I am using Ubuntu 16.04.
The better solution to my mind is to install such unstable programs on Virtualbox. But what could I do if the Virtualbox didn't install?

A: The solution is to remove (or rename) the ~/.googleearth directory.

*

*Close Google-Earth

*Rename the directory
mv ~/.googleearth ~/old_googleearth

*Start Google-Earth and be happy.

Well, with Fedora 23 this didn't help. I had to install the 32 bit version of Google-Earth. At least it works now.

A: Here is a screenshot of a utility available on Ubuntu Software Cente:

Steps:
1. Open Ubuntu software center and search for "googleearth" (no spaces found what I was looking for, with a space between google and earth it yielded something else).

*After that's the software center should look like the image I've posted. Then on your console/terminal run make-googleearth-package.

*Then run sudo dpkg -i googleearth_6.0.3.2197+1.1.0-1_amd64.deb  as the console asks you the same after step 1 is done.

*If some dependencies are unmet run sudo apt-get update then run sudo apt-get -f install

*After step 3 run sudo dpkg -i googleearth_6.0.3.2197+1.1.0-1_amd64.deb.
This did the trick, no crashes.
Erik's and 7th's solution worked for a few months till today when no matter how much I tried to not-move the mouse or play around with the globe while it loaded and is flying-to, it crashed.
EDIT: Chrome and Google Earth will not run simultaneously on my system, wonder why?
EDIT: Chrome and GEarth work simultaneously now.

A: I had the same problem, I executed it as sudo. In terminal:
sudo google-earth

It worked for me.