text:
Q: C# Properties - Set question I'm working in C# and I'm starting to play with properties. One thing I don't know is what is the best way/where to put the logic for the set accessors of class properties and how to handle the errors.
For instance, say I have this (basic) class:
class Person
{
    private int _Age = 18;

    public Person()
    {

    }

    public int Age
    {
        get
        {
            return _Age;
        }
        set
        {
            _Age = value;
        }
    }
}

Now say I have a requirement on the Age property, 0 < Age < 100. Where do I put the logic for this?
Should I put it in the property?
public int Age
    {
        get
        {
            return _Age;
        }
        set
        {
           if (value < 0 || value > 99)
               // handle error
           else
               _Age = Convert.ToInt32(value);
        }
    }

or through class that is creating a Person object?
static void Main(string[] args)
{
   Person him = new Person();
   int NewAge = -10;

   if (NewAge < 0 || NewAge > 100)
      // handle error
   else
      him.Age = NewAge;
}

Now what if there is a problem with the NewAge (it doesn't meet my constraint)? Should I create a custom exception and throw that? Should I just print a message saying supply a valid age?
I've done some Googling and I cannot find anything that fully answers my questions. I need a book :-/

A: You will want to put the logic in the setter and throw an exception if it doesn't meet the requirement. However, you will also want to create an IsValidAge static method or something so that classes creating a Person can check the age value instead of just seeing if it throws an exception. Alternatively you could have MinAge and MaxAge properties so calling code could check if the age they're about to set is between it.
Don't create a custom exception type though, use ArgumentOutOfRangeException or something like that.

A: Put it in the property. That's one of the main purposes of properties!
Consider that you'll be placing the responsibility in the lowest level possible. The example you gave doesn't require anything other than the value parameter in order to make its decision. It doesn't even depend on other members of the same class. There's no reason for the rest of the class to know how validity works for the Age property, and certainly no reason for any other piece of code to know it.

A: You may want to look into the IDataErrorInfo interface.
By implementing this interface in your class, you'll open the class to other mechanisms that can benefit from the additional error information.

A: Use the property setter, it is there for that reason (adding functionality to a field).
If out of range value is passed in, you can throw ArgumentOutOfRangeException or just set it to minimum (or maximum) value, but this depends on your process requirement.

A: I'd implement it like this:
public int Age
{
    get
    {
        return _Age;
    }
    set
    {
       if (IsValidAge(value))
           _Age = value;
       else
           throw new ArgumentOutOfRangeException("value", string.Format("value should be between {0} and {1} inclusive.", MinAge, MaxAge));
    }
}

private bool IsValidAge(int age)
{
    return (age >= MinAge && age <= MaxAge);
}

A few things to note:

*

*Don't change their value instead of throwing an exception, this is unexpected behaviour.

*The .NET framework throws Argument* exceptions in setters, so I'd say it's a good idea to follow this practice. In this case ArgumentOutOfRangeException is perfect, IMO.

*When referring to the argument in exception messages and xml docs, the standard is to call the argument "value", not the name of your property.

*I'd recommend MinAge and MaxAge as private consts in your class, don't fall into the trap of hardcoding error messages with range boundaries in them, there's nothing worse than being told "5 in invalid, please enter a number between 1 and 10" when someone changes the spec later on but forgets to update a string.

A: I'm going to play devil's advocate and give an answer why you WOULD NOT want to put it in the setter.  There are plenty of cases when you want to be able to set the value of your Age property, and at a later time ask if that object is valid in a holistic sense.
For instance, keep your property simple:
public int Age { get; set; }

Then when an invalid value is passed in you can have some IsValid function which indicates if the object in question is ok.  This can be extremely useful because you can do more complicated validation other than a simple Age restriction.
bool IsValid()
{
   if (Age < 0 || Age > 99)
     return false;
}

For something simple like this there isn't a lot of benefit, but consider also that you can use this in your persistence layer so you can ensure that any object that is NOT valid will never be persisted.  In those cases you don't necessarily want to throw an exception.
Also consider this:
DateTime StartDate { get; set; }
DateTime EndDate { get; set;}

bool IsValid()
{
   return StartDate > EndDate
}

This is only pseudocode, but you get my point.  This is something you can't do inside a setter, or at least, not in a way that is maintainable.

A: Use the setter, and use ArgumentOutOfRangeException, as others have already said.
Sometimes you will call another method, usually something like OnAgeChanged(int age), where you could perform the validation (which may be a call to yet another method so you can use it anywhere) and invoke an event handler, which if hooked up, may have other logic to apply depending on how you are using your object.  That may not be necessary in your scenario, but it's pretty common to do that for properties.  Especially if you are going to update a form - the form would hook into the AgeChanged event to update itself.

A: If you are doing factored design (ie. it is important that the state of the object be valid at all points during the life of the object), then you might want to set and check this in the constructor.  In a component design, you'd want to check this in the method that uses the property, e.g.
class Person
{
  public int calculateTimeToExpiration()
  {
  if (Age < 0 || Age > 100)
     //throw
  }
}

Static void main is client code and not a good place for business logic.

A: Thanks for the answers! In case you were curious here is what I change my little example (although it is more detailed now) to (based from the comments).
class Person
{
    private string _FirstName = "Joe";
    private string _LastName = "Smith";
    private int _Age = 18;

    private const int MinAge = 1;
    private const int MaxAge = 99;

    public Person()
    {

    }

    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }

    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
        }
    }

    public string LastName
    {
        get
        {
            return _LastName;
        }
        set
        {
            _LastName = value;
        }
    }

    public int Age
    {
        get
        {
            return _Age;
        }
        set
        {
            if (IsValidAge(value))
                throw new ArgumentOutOfRangeException("value","Please enter a positive age less than 100.");
            else
                _Age = value;
        }
    }

    private bool IsValidAge(int age)
    {
        return (age < MinAge || age > MaxAge);
    }

    public override string ToString()
    {
        if (Age == 1)
            return "My name is " + FirstName + " " + LastName + " and I am " + Age + " year old.";
        else
            return "My name is " + FirstName + " " + LastName + " and I am " + Age + " years old.";
    }
}

static void Main(string[] args)
    {
        Person him, her;

        try
        {
            him = new Person("Joe Bob", "McGruff", 1);
            Console.WriteLine(him);
        }
        catch (ArgumentOutOfRangeException range)
        {
            Console.WriteLine(range.Message);
        }

        try
        {
            her = new Person();
            her.Age = -5;
            Console.WriteLine(her);
        }
        catch (ArgumentOutOfRangeException range)
        {
            Console.Write(range.Message);
        }

        Console.ReadKey();
    }

A: Your updated answer is good but you should clean up one little piece in your setter/validation
 public int Age
    {
        get
        {
            return _Age;
        }
        set
        {
            if (!IsValidAge(value))
                throw new ArgumentOutOfRangeException("Age","Please enter a positive age less than 100.");

             _Age = value;
        }
    }

    private bool IsValidAge(int age)
    {
        return (age > MinAge && age < MaxAge);
    }


text:
Q: How to release memory allocated by a slice? package main

import (
    "fmt"
    "time"
)

func main() {
    storage := []string{}

    for i := 0; i < 50000000; i++ {
        storage = append(storage, "string string string string string string string string string string string string")
    }

    fmt.Println("done allocating, emptying")

    storage = storage[:0]
    storage = nil

    for {
        time.Sleep(1 * time.Second)
    }
}

The code above will allocate about ~30mb of memory, and then won't release it. Why is that? How can I force go to release memory used by this slice? I sliced that slice and then nilled it.
The program I'm debugging is a simple HTTP input buffer: it appends all requests into large chunks, and sends these chunks over a channel to goroutine for processing. But problem is illustrated above - I can't get storage to release the memory and then eventually run out of memory.
Edit: as some people pointed out to similar question, no, it first doesn't work, second isn't what I'm asking for. The slice gets emptied, the memory does not.

A: In the program you wrote, it makes no sense to release memory because no part of code is requesting it any more.
To make a valid case, you have to request a new memory and release it inside the loop. Then you will observe that the memory consumption will stabilize at some point.

A: There are several things going on here.
The first one which is needed to be absorbed is that Go is
a garbage-collected language; the actual algorithm of its GC
is mostly irrelevant but one aspect of it is crucial to understand:
it does not use reference counting, and hence there's no way to
somehow make the GC immediately reclaim the memory of any given
value whose storage is allocated on the heap.
To recap it in more simple words, it's futile to do
s := make([]string, 10*100*100)
s = nil

as the second statement will indeed remove the sole reference
to the slice's underlying memory but won't make the GC go
and "mark" that memory as available for reuse.
This means two things:

*

*You should know how the GC works.
This explains how it works
since v1.5 and up until now (v1.10 these days).

*You should structure those of your algorythms which are
memory-intensive in a way that reduces memory pressure.

The latter can be done in several ways:

*

*Preallocate, when you have a sensible idea about how much to.
In your example, you start with a slice of length 0,
and then append to it a lot. Now, almost all library code which deals
with growing memory buffers—the Go runtime included—deals with these
allocations by 1) allocating twice the memory requested—hoping to
prevent several future allocations, and 2) copies the "old" contents
over, when it had to reallocate. This one is important: when reallocation
happens, it means there's two memory regions now: the old one and the new
one.
If you can estimate that you may need to hold N elements on
average, preallocate for them using make([]T, 0, N)—
more info here
and here.
If you'll need to hold less than N elements, the tail of that buffer
will be unused, and if you'll need to hold more than N, you'll need
to reallocate, but on average, you won't need any reallocations.

*Re-use your slice(s). Say, in your case, you could "reset" the slice
by reslicing it to the zero length and then use it again for the next
request. This is called "pooling", and in the case of mass-parallel access
to such a pool, you could use sync.Pool to hold your buffers.

*Limit the load on your system to make the GC be able to cope with
the sustained load. A good overview of the two approaches to such
limiting is this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Incorrect Conversion of Date as a Factor to a Date I am having trouble calculating a date that is imported in from a .csv file.   What I want to do is take that date in the factor DateClosed and generate a date in a date field (a).   Example if a=203 I want the date to be the equivalent of DateClosed-203.   However, I am having trouble with the code listed below.
DateClose is a factor.
> head(DateClosed)
[1] 7/30/2007  12/12/2007 5/8/2009   6/24/2009  6/24/2009  2/29/2008
165 Levels: 1/12/2010 1/15/2011 1/15/2013 1/17/2009 1/18/2008 1/19/2012 1/2/2013 1/21/2013 1/22/2010 1/24/2013 1/26/2014 ... 9/7/2010
> head(as.Date(DateClosed,format="%m/%d/%y"))
[1] "2020-07-30" "2020-12-12" "2020-05-08" "2020-06-24" "2020-06-24" "2020-02-29"

 head(as.Date(DateClosed,format="%m/%d/%y"))-203
[1] "2020-01-09" "2020-05-23" "2019-10-18" "2019-12-04" "2019-12-04" "2019-08-10"

It subtracts 203 days correctly but for some reason reads the date wrong.

A: DateClosed <- factor(c("7/30/2007","12/12/2007", "5/8/2009"))
as.Date(DateClosed, format="%m/%d/%Y")

Produces:
[1] "2007-07-30" "2007-12-12" "2009-05-08"

Notice the capital "Y" in the format param. The lower case "y" is for 2 digit years, so as.Date reads the first two digits of the year token ("20"), and then assumes that refers to just the last two digits of the year, and adds the current date's century (also "20"), so you end up with dates in 2020.

A: Manipulating dates becomes really easy using lubridate package.
mdy(factor(c("7/30/2007","12/12/2007", "5/8/2009")))

"2007-07-30 UTC" "2007-12-12 UTC" "2009-05-08 UTC"

Or using parse_date_time with the same package:
parse_date_time(factor(c("7/30/2007","12/12/2007", "5/8/2009")),c('mdY'))
[1] "2007-07-30 UTC" "2007-12-12 UTC" "2009-05-08 UTC"


text:
Q: Ordering when using scipys Jenson Shannon distance I am currently the scipy implementation of the Jenson-Dhannon distance to compare 2 vectors sampled from 2 distributions.
I'd expect the distance to be zero if I get the same samples - regardless of the order of my samples; this does however not apply:
a = np.array([0.1,0.2,0.7])

b = np.array([0.1,0.2,0.7])

c = np.array([0.2,0.7,0.1])

print(scipy.spatial.distance.jensenshannon(a,b))
# 0.0
print(scipy.spatial.distance.jensenshannon(a,c))
# 0.4567211416577999

The original application would be the quality measurement of synthetic data.
My use case is as follows:

I have an original data vector and a synthesized data vector and want
to compare them to asses whether my synthetic vector is close to the
original distribution of my original vector. As I randomly sample each
entry from the distributions, the two vectors will not align.

Am I missing something here or is this metric simply not suited for my use case? Or would it make sense to sort my samples beforehand? I have yet to find any application note that matches my use case.


text:
Q: Multiples features inside a feature I have defined a Store with Angular and NgRx 13. I have a SharedModule where I define component such as selectors, etc. Each selector content is loaded in the store, so that I can avoid the repeat of an API call.

This is defined in this way:
shared.module.ts
/**...*/
 StoreModule.forFeature(clientsFeature),
 StoreModule.forFeature(prioritiesFeature),
/**...*/

clients.feature.ts
import { createFeature, createSelector, createReducer, on } from '@ngrx/store';
import { ClientDTO } from '@shared/model/client.models';

import * as ClientsActions from './clients.actions';

export const initialState: ClientDTO[] = [];

export const clientsFeature = createFeature({
  name: 'clients',
  reducer: createReducer(
    initialState,
    on(ClientsActions.getClientListSuccess, (state, { clients }): ClientDTO[] => clients)
  ),
});

export const selectClientList = createSelector(clientsFeature.selectClientsState, clients => clients);

Priorities feature is similar.
What I'm trying to do is avoiding to declare each feature and use a 'shared' feature that contains all the subfeatures. To do this, I create:
index.ts
import { ActionReducerMap } from '@ngrx/store';
import { ClientDTO } from '@shared/model/client.models';
import { Priority } from '@shared/model/priorities.models';
import { clientsFeature } from './clients/clients.reducer';
import { prioritiesFeature } from './priorities/priorities.reducer';

export const sharedFeatureKey = 'shared';

export interface SharedState {
  clients: ClientDTO[] | null;
  priorities: Priority[] | null;
}

export const reducers: ActionReducerMap<SharedState> = {
  clients: clientsFeature.reducer,
  priorities: prioritiesFeature.reducer,
};

And my shared.module :
    StoreModule.forFeature(fromShared.sharedFeatureKey, fromShared.reducers),

All ok.
PROBLEM
Doing this I cannot access to the content of the list. I'm sure I'm missing something, but I don't know what. I get this warning:

ngrx-store.mjs:724 @ngrx/store: The feature name "clients" does not exist in the state, therefore createFeatureSelector cannot access it.  Be sure it is imported in a loaded module using StoreModule.forRoot('clients', ...) or StoreModule.forFeature('clients', ...).  If the default state is intended to be undefined, as is the case with router state, this development-only warning message can be ignored.

And another similar with priorities. I'm pretty sure that the problem are in the selectors, but after trying for hours, I cannot found a solution.
The undefineds are the log of the content of the selector:
    this.store
      .select(selectPrioritiesList)
      .pipe(take(1))
      .subscribe(priorities => {
        console.log('priorities -->', priorities);
      });

What I am doing wrong? Thanks in advance

A: The problem is with the selectors.
Because you added an extra "shared" layer, the selectors need to be updated.
Currently, the createFeature isn't configurable and uses the top level state to select sub-states. This means you can't use the provided selectors from createFeature, but you'll have to write the selectors manually.


text:
Q: Live-action sci-fi movie or TV show episode. 70s or 80s The protagonist(s) is followed by a cyborg/android through a desert.
The cyborg/android is ambushed by a giant spider-like creature, which lies on its back under the sand and grabs the cyborg/android like a fist.
The cyborg/android is damaged and components are hanging from its ear/temple.

A: Sounds a lot like an episode I watched on DVD a few months ago.
Buck Rogers in the 25th Century -- Season 1, Episode 9, "Unchained Woman." (Original air date: November 1, 1979.)
Buck is sent to break a woman out of a prison facility on Zeta Minor. They get out of the prison, but they still have to cross a desert to get to the nearest city. They are being pursued by an android prison guard (called "Hugo"), and at one point it catches up with Buck and the lady (played by Jamie Lee Curtis) and it seems to have the advantage in hand-to-hand combat (being stronger and feeling no pain probably helps) -- until, as you said, a large predator lurking under the surface of the sand manages to grab hold of the android when it steps on the wrong spot.
We later learn that the android survives and escapes the trap, after Buck and the lady have gotten a good head start -- probably because pulling an android down under a ton of sand does not cause it to quickly suffocate for lack of air, the way you or I might. Buck has to fight Hugo the android all over again, later.
Here's a picture of that android, looking somewhat the worse for wear after getting battered by various experiences. (But at the end of the episode, it was still "alive," just barely, and thus available for a comeback in some later episode, if the writers wanted to do it that way.)


text:
Q: stringBuilder killed my brain I am new to java and I am trying to work with the stringBuilder at the moment. my current project will allow the user to input a "colors.txt" file. I want to verify that the entered string is valid. The information that is entered is:
Had to parenthesize the # but it need to be taken out and reentered on the valid output.
(#)F3C- valid, ouput(#FF33CCFF)
(#)aa4256- valid, output(AA4256FF)
(#)ag0933 - is invalid because 'g' is not hexadecimal
(#)60CC- valid, output(6600CCFF)
095- valid, output(009955FF)
Be0F- valid, output(BBEE00FF)
(#)AABB05C- invalid, to many characters (7)
So the output to another file called "-norm" appended to the name of the file before the dot ".". I want to verify if the entered line is a true hexadecimal color. Also the out put has to have the validated line equal 8 by doubling the characters, if the double does not equal 8 then "FF" has to be appended to it.
I was able to input the file however without verification. It will read each line and go through 2 methods(Just learning as well) for verification. I am having a lot of issues with my code. I can visualize and know what I want to do, I am having an issue translating that into code.
Thank you for all your help!
 import java.util.*;  // for Scanner
import java.io.*;  // for File, etc.
import java.lang.*;
//import java.awt.* //to use the color class

public class RGBAColor
{
      //Scanner file = new Scanner(new File("colors.txt"));

      public static void main(String[] args) //throws IOException
          throws FileNotFoundException
      {
         Scanner console = new Scanner(System.in);
         System.out.println("Please make sure you enter the colors.txt ");

         //assigning the colors file
         String fileName = console.nextLine();
         Scanner inputFile = new Scanner(new File(fileName));

         //outputing to colors-norm file
         int dotLocation;

         StringBuilder dot = new StringBuilder(fileName);
         dotLocation = dot.indexOf(".");

         //PrintWriter FileName =
         //new PrintWriter("colors-norm.txt");

           while (inputFile.hasNextLine())
               {
                  String currLine = inputFile.nextLine();
                  int lineLenght = currLine.length();
                  //System.out.printf("line length is %s \n", currLine);
                  verification(currLine);

               }

               inputFile.close();
      }

          //this will verify the color
          public static void verification(String line)
          {
               StringBuilder newString = new StringBuilder(line);

               //will be used to compare the length

               int stringLength;

               //will remove the # if in string
               if (newString.charAt(0) == '#')
               {
                   newString = newString.deleteCharAt(0);

               }

                    //assigns the length
               stringLength = newString.length();

                  //checks the length of the string
                  //prompt will show if the number of digits is invalid
                  if (!(stringLength == 3 || stringLength == 4 || stringLength == 6 || stringLength == 8))
                  {
                        System.out.println("invalid number # of digits " + stringLength + " in "
                                            + newString);
                  }
                  StringBuilder errorLessString = new StringBuilder("");

                   //checks number and letter for valid entries for hexadecimal digit
                  for (int i = 0; i < newString.length(); i++ )
                  {
                        char valid = newString.toString().toUpperCase().charAt(i);
                        if (!(valid >= '0' && valid <= '9' || valid >= 'A' && valid <= 'F'))
                        {
                              System.out.println("invalid color '" + newString.charAt(i) +
                                             "' in " + newString );
                        }

                       errorLessString.append(valid);
                  }

              System.out.println("this is the length of  " + errorLessString + "  " + errorLessString.length());

                   String resultingString = " ";

           // validating length only allowing the correct lengths of 3,4,6,and 8
               switch (errorLessString.length())
               {
                  case 3:  System.out.println("begin case 3");
                            dbleAppend(newString.toString());
                            addFF(newString.toString());
                            System.out.println("end case 3");
                        break;

                  case 4:   dbleAppend(newString.toString());
                        break;

                  case 6:  addFF(newString.toString());
                        break;

                  case 8:

               }
          }

          //method to have two characters together
          public static String dbleAppend(String appd)
          {
                  StringBuilder charDouble = new StringBuilder("");

                  //pass in append string to double the characters
                  for (int i = 0; i < appd.length(); i++)
                  {
                        charDouble.append(appd.charAt(i));
                        charDouble.append(appd.charAt(i));
                  }
                  return appd;
          }

         //method will append ff to string
         public static String addFF(String putFF)
         {
               StringBuilder plusFF = new StringBuilder("FF");

                     plusFF.append(putFF.toString());

               System.out.println(plusFF);

               return putFF;
         }
}

A:
1) someone suggested finding the index of the "." and appending the "-norm" so the output file will be whatever file name the user enters with "-norm" attached but before the ".".

So you are unsure whats the best way to get from colors.txt to colors-norm.txt or from foo.txt to foo-norm.txt?
One option is to find the index of the (last) dot in the file name and to split the filename at this point and use the parts to construct the new filename:
String filename = "colors.txt"

int indexOfDot = filename.lastIndexOf(".");
String firstPart = filename.substring(0, indexOfDot); // Will be "colors"
String lastPart = filename.substring(indexOfDot); // Will be ".txt"
return firstPart + "-norm" + lastPart;

A more elegant option is to use a regular expression:
String filename = "colors.txt"

Matcher filenameMatcher = Pattern.compile("(.*)\\.txt").matcher(filename);
if (matcher.matches()) {
    String firstPart = matcher.group(1) // Will be "colors"
    return firstPart + "-norm.txt"
} else {
    //Invalid input, throw an Exeption and/or show an error message
}

If other file extensions than .txt are allowed you'd have to capture the extension too.

2) I want to validate the text file to make sure they are entering a valid file. Do I have to validate each separate part? or the whole string?

The easiest way is to first separate the different color values an then validate each color value. You might want to develop a grammar first, so writing the actual code will be easier.
Since there is only one value per line you could use something like this:
List<String> outputColors = Files.lines(new File(fileName).toPath())
    .filter(line -> isValidColor(line))
    .map(validColor -> convertToOutputFormat(validColor))
    .collect(Collectors.toList());

Files.write(new File(outputFileName).toPath(), outputColors);

3) also writing to a file is a huge issue, I was able to read in the file.

Google is you friend:

*

*http://www.baeldung.com/java-write-to-file

*How do I create a file and write to it in Java?

*https://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/

4) the output file can only hold the valid inputs.

After you solved 2) properly, this shouldn't be a big problem


text:
Q: write data in binary format in Files in Android hi all:
making a sample application in which we can store data on File and then could Read it.,
m using the following code.:
Code to Write:
OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(openFileOutput("finear.fin", 0));
        out.write(data); //data is String variable
        out.close();
        Toast.makeText(getApplicationContext(), "Data has been Saved! ", Toast.LENGTH_LONG).show();
    }

Code to Read:
instream = openFileInput("finear.fin");
if(instream!=null)
{
InputStreamReader inputReader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputReader);
String dataRead = buffreader.readLine();
}

Now problem is: The Data is stored in simple Text Form but i want that no one could read my data from that file and it should store the data in some binary form or some symbols type format so that when one opens the file in windows it should not display my text stored in the file or should display some other data.. BUT also that data could be readable in String form when i read. PLease Help

A: You can use Android's internal storage, which is private to your application:

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

Here you can find the docs: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

A: Encrypt the String before saving it to the stream and the other way to read it. If you want your file's contents to be unreadable, encryption would be a win.


text:
Q: Zoom HTML/CSS/Jquery I want to try out the zoom effect on click of an element as similar to this link https://codepen.io/soniajain/full/QBejVL/
what I have tried is this https://codepen.io/soniajain/pen/dqXZxg but unable to do the correct calculation.
It would be great if anyone could help me with this.
    <script type="text/javascript">
    $(document).ready(function() {
       $('.zoomTarget').click(function () {

            centerSelected();

       });
    });

function centerSelected() {

    var ele = $('.zoomTarget');
    var offset = ele.offset();
    var offsetLeft = offset.left;
    var offsetTop = offset.top;
    var vw = $(window).width();
    var vh = $(window).height();
    var scale = 2;

    $('.wrapper').css({});

}

    </script>

A: Here is my solution and  the working example is as follows:
https://codebrace.com/editor/b1169cb27
In this solution I have added transition for the animation (to achieve smooth zooming) and transform to achieve zooming in the css. Now To get the "zoom target" into focus I have written following jquery:
$(document).ready(function() {
    var wrapper = $(".wrapper");
        position = wrapper.offset();
   $('.zoomTarget').click(function (e) {
            wrapper.toggleClass("wrapperzoom");
        var lx = e.currentTarget.offsetLeft,
        ly = e.currentTarget.offsetTop;
        if(wrapper.hasClass("wrapperzoom")){
            //where 3 represent the amount of scaling value used in css
            wrapper.offset({ top: (position.top - ly)*3, left: (position.left - lx)*3});
        }else{
            wrapper.css({ top: "auto", left: "auto"});
        }

   });
});

A: Just use the following code on onclick for zoom in :

$("#imgID").css({
      'width' : $("#img01").width()  * 1.1
    , 'height': $("#img01").height() * 1.1
  });

Use the following code on onclick zoom out:

 $("#imgID").css({
      'width' : $("#img01").width()  * 0.9
    , 'height': $("#img01").height() * 0.9
  });


text:
Q: How to store a n*n matrix consisting of integers into a bitmask value? I have a n*n matrix, let us consider n as 3.
So there will be a total 9 elements. My Matrix can store Integers. When I change these integer values of the 9 elements, I will get some unique combinations of matrices.
Now i want to put these grids as key in a Hash Map.
An easy way to do this is to convert my matrix in some format(may be bits). So there will be encoding of this matrix, and then when i retrieve i must decode.
I read bit masks work well here. But I am unable to figure out how to create a bit mask out of a grid in java.
I am looking for a solution which tells me how to do it through an example, and the logic flow for encoding or decoding the grid to bit mask.


text:
Q: How to close modal on bootstrap after function runs vue3 composition api I am running a vue3 web app and I have bootstrap 5 running perfectly after I installed it using npm install bootstrap.
I am running a function that works fine but I'd like the modal to be closed once the function is run. Below is my code:
    <template>

                    Upload new property

Add property to the list

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                <form @submit.prevent="saveToDatabase">
                   Property Name
                  <input
                    type="text"
                    v-model="name"
                    required
                    placeholder="e.g. my house"
                  />
                  Area
                  <select v-model="area" required>
                    <option value="" selected disabled="">Select an option</option>
                    <option value="Island">Lagos Island</option>
                    <option value="Mainland">Lagos Mainland</option>
                  </select>
                  Number of Beds
                  <input type="number" v-model="beds" required placeholder="e.g. 4" />
                  Price Per Night (NGN)
                  <input
                    type="text"
                    v-model="price"
                    required
                    placeholder="e.g. 120,000"
                  />

                    <button class="ui button fluid blue" @click="saveToDatabase">
                      Save
                    </button>

                </form>

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

    </template>

Below is my main.js :
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { projectAuth } from './firebase/config'
import "bootstrap/dist/css/bootstrap.css";
import 'semantic-ui-css/semantic.min.css'
import './assets/main.css'
let app

projectAuth.onAuthStateChanged(()=>{
    if(!app){
        app =   createApp(App).use(router).mount('#app')
    }
})
import "bootstrap/dist/js/bootstrap.js"

Is there a way to programmatically close the modal once the saveToDatabase function is run?

A: *

*Get modal instance from DOM: Modal.getInstance().

*Use template refs to interact with DOM in Vue.

Generic example:

<template>

...

    ...

</template>


text:
Q: JSON keep Getting the old data My JSON parser keep getting my member data which I accessed earlier even when I was supposed to get another data EX:Job data. Here is my JSONParser.java Code:
package travenz.tacos;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
       try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        url += "?";
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        json = EntityUtils.toString(httpResponse.getEntity());
        Log.d("JSON", json);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

       // try parse the string to a JSON object
       try {
           jObj = new JSONObject(json);
       } catch (JSONException e) {
           Log.e("JSON Parser", "Error parsing data " + e.toString());
       }

       // return JSON String
       return jObj;

}
public JSONObject setJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 20);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.d("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
public JSONObject getJSONFromUrlWithParams(String url, List<NameValuePair> params) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?"+paramString;
        HttpGet httpGet = new HttpGet(url);
        Log.d("url", url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 20);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.d("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

    }
}

and this is my code to get job data:
private static final String JOB_URL = "http://192.168.1.6/DatabaseCon/selectalltugas.php";
class LoadJobList extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(JobSchedule.this);
        pDialog.setMessage("Loading Jobs ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Job JSON
     * */
    protected String doInBackground(String... args) {

        // getting JSON string from URL
        JSONObject json = jsonParser.getJSONFromUrl(JOB_URL);

        // Check your log cat for JSON reponse
        Log.d("Job JSON: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                job = json.getJSONArray(TAG_JOBS);
                // looping through All messages
                for (int i = 0; i < job.length(); i++) {
                    JSONObject c = job.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String date = c.getString(TAG_DATE);
                    String time = c.getString(TAG_TIME);
                    String place = c.getString(TAG_PLACE);
                    String detail = c.getString(TAG_DETAIL);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_DATE, date);
                    map.put(TAG_TIME, time);
                    map.put(TAG_PLACE, place);
                    map.put(TAG_DETAIL, detail);

                    // adding HashList to ArrayList
                    JobList.add(map);
                }
            } else {
                // no products found
                nodata = true;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
       protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                    ListAdapter adapter = new SimpleAdapter(
                            JobSchedule.this, JobList,
                            R.layout.job_list_item, new String[] { TAG_ID, TAG_NAME, TAG_DATE, TAG_TIME, TAG_PLACE },
                            new int[] {R.id.jid, R.id.name, R.id.date, R.id.time, R.id.place });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
    }

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

}

from the URL I posted above, It should be the correct php and I already checked the php file to. It definitely typed: select * from jobs instead of members but I'm still getting my previously accessed member data even if I restarted my emulator and didn't enter the member page first

A: You have jObj as a class level variable, you should probably have it as a method level variable (declare it inside the getJsonFromUrl() method) and assign it a default value or null.
I would guess that you are catching a JSONException or one of the other connection Exceptions and the previous value for it is not getting set to the new input and then you are returning the old version or worse, a version from another method's last run.
In this case, even though errors occur either fetching or parsing the JSON you return the jObj regardless. This means that if an error has occurred then jObj will still be set to its last value and that gets returned instead.
The same also holds true for the other class level variables (InputStream is and String json). I would actually suggest that you remove all class level variables and make all the class' methods static. That way you can be sure no stale data is ever returned.
Here is your class changed:
public class JSONParser
{
    public static JSONObject getJSONFromUrl(String url)
    {
        String json = null;
        JSONObject jObj = null;

        // Making HTTP request
        try
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            url += "?";
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            json = EntityUtils.toString(httpResponse.getEntity());
            Log.d("JSON", json);
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        // try parse the string to a JSON object
        try
        {
            jObj = new JSONObject(json);
        }
        catch (NullPointerException e)
        {
            Log.e("JSON Parser", "json String was null");
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }

    public static JSONObject setJSONFromUrl(String url, List<NameValuePair> params)
    {
        InputStream is = null;
        String json = null;
        JSONObject jObj = null;
        // Making HTTP request
        try
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 20);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            json = sb.toString();
            Log.d("JSON", json);
        }
        catch (Exception e)
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        finally
        {
            // you should always close any open handles in a finally clause
            if (is != null)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {}
            }
        }
        // try parse the string to a JSON object
        try
        {
            jObj = new JSONObject(json);
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        catch (NullPointerException e)
        {
            Log.e("JSON Parser", "json String was null");
        }
        // return JSON String
        return jObj;
    }

    public static JSONObject getJSONFromUrlWithParams(String url, List<NameValuePair> params)
    {
        InputStream is = null;
        String json = null;
        JSONObject jObj = null;

        // Making HTTP request
        try
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            Log.d("url", url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 20);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            json = sb.toString();
            Log.d("JSON", json);
        }
        catch (Exception e)
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        finally
        {
            if (is != null)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        // try parse the string to a JSON object
        try
        {
            jObj = new JSONObject(json);
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

Note that this is just a possible implementation that developed slowly as the OP supplied more code. The answer by JayR is an probably the better fix. The choice to make the JSONParser have static methods is an optional design decision. However, the changes made to closing the InputStream safely probably should still be applied.

A: This is because you only use a single instance of JSONParser when you are calling a web service call.
Try to create a new instance for every call so that they have different response.
you can do such.
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(JOB_URL);

'json' has now the value of response you want.
Hope it helps. Cheers!


text:
Q: Vuejs 2 + laravel elixir + lodash Uncaught ReferenceError: _ is not defined I'm using the tools specified in the title. I import lodash in my bootstrap.js
window._ = require('lodash');

However, when I try to use something like this (similar example to here), I get the error discribed in the title
created() {
   this.test();
},

methods: {
   test: _.debounce(function () {
      console.log('calculating', true);
      setTimeout(function () {
         console.log('calculating', false);
      }.bind(this), 1000)
   }, 500),
}

However, if I remove the window._ = require('lodash'); and insert lodash manually in the page it works fine, like
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>

What I'm missing?
Also, What is the advantage of importing the libraries by require instead of using Gulp to merge and uglyfy everything?

A: I am not sure why you are getting that error related to _.
On your other question, I can think following advantage of using require over gulp or any other build tool:

*

*All build tools comes with their own set of dependencies and other accessories, which bloats your overall code size.

*You may start to rely on their plugins and time can come, when you need to use grunt for one task, while for other tasks you are using grunt, quting from gulp-grunt

What if your favorite grunt plugin isn't available for gulp yet? Don't fret, there is nothing to worry about! Why don't you just hook in your grunt configuration?

*

*You will have to manage updating of different plugins of gulp and make sure all are working with new updated versions.

These are some of the things I have experienced or read about, but these tools do remove the pain of building, hot-reloading, compressing or obfuscating your code, but definetely there can be other raw way to do these, as what these are doing is providing you an abstraction.


text:
Q: invalid 'in' operand profile in worklight.js I have two Worklight apps an one SQL-adapter in one project. the first app is the client app and works perfectly well. the second one is the the managment app which is using the same SQL-Adapter. they also call the same procedure, which makes a SQL-statement and returns the results. But when initializing the procedure from the controller app I am getting an error:
TypeError: invalid 'in' operand profile worklight.js:4039

Adapter-Procedure:
var selectStatement = WL.Server.createSQLStatement("select TITLE, BODY, DATE from MESSAGES where DATE>?");

function getMessages(param1) {
   return WL.Server.invokeSQLStatement({
     preparedStatement : selectStatement,
     parameters : [param1]
   });
}

Call from the Controller:
function getMessages(){
    console.log("lala");
    var invocationData = {
            adapter : 'ClientAdapter',
            procedure : 'getMessages',
            parameters: ['2014-07-21 00:00:00.000000']
    };

    WL.Client.invokeProcedure(invocationData, {
        onSuccess : success,
        onFailure : failure
    });

    function success(result){
        console.log("Successfully gathered Messages");
    }
    function failure(ErrorObject){
        console.log("ERROR: could not get Messages/n" + ErrorObject);
    }
}

I don't get how there can be an error there because i never touch that file (to be honest: I don't even know where it's located in my Project)  and in the web inspector it looks the same in both apps.
The only difference is that I'm using Bootstrap in the contorller app instead of jquery mobile.
Any ideas how to fix it or work around?
Sincerely
Max
EDIT: Added code


text:
Q: How can I automatically identify certain boxes in the \tracingoutput log? I have a program that is automatically generating a tex file describing a document. I want to be able to record the position and page number where a few boxes were ultimately laid out.
Is there any simple way to match up parts of the document with the matching part of the log file created by \tracingoutput? For example, is it possible to name boxes somehow and have those names show up in the log?

A: Are you sure you want \tracingall, You can be more specific in what you put out, eg
\documentclass{article}
\loggingoutput\scrollmode
\begin{document}

\sbox0{\parbox{2cm}{on two three four five six\[a=2\]seven}}

\typeout{my first box looks like this:}
\showbox0 \usebox0

\sbox0{\parbox{4cm}{on two three four five six\[a=2\]seven}}

\typeout{my second box looks like this:}
\showbox0 \usebox0

\end{document}

which produces
my first box looks like this:
> \box0=
\hbox(33.97223+28.97221)x56.9055
.\mathon
.\vbox(33.97223+28.97221)x56.9055
..\hbox(6.94444+0.0)x56.9055, glue set 0.5633
...\hbox(0.0+0.0)x0.0
...\OT1/cmr/m/n/10 o
...\OT1/cmr/m/n/10 n
...\glue 3.33333 plus 1.66666 minus 1.11111
...\OT1/cmr/m/n/10 t

and
my second box looks like this:
> \box0=
\hbox(27.97223+22.97221)x113.81102
.\mathon
.\vbox(27.97223+22.97221)x113.81102
..\hbox(6.94444+0.0)x113.81102, glue set 4.2553fil
...\hbox(0.0+0.0)x0.0
...\OT1/cmr/m/n/10 o
...\OT1/cmr/m/n/10 n
...\glue 3.33333 plus 1.66666 minus 1.11111
...\OT1/cmr/m/n/10 t


text:
Q: jQuery load not working I've only recently started using jQuery and am having no problems with most of it.  I've just started to look at using Ajax calls and have immediately hit a stumbling block.  To illustrate my problem I have written a small piece of demo code...

As you can see, the page loads and then it's supposed to load the contents of a URL (google in this case) into the only div on the page, but it doesn't work.
Using the developer tools in Chrome I can see the request being sent, but it's marked as "canceled" (yes, with 1 l!)
I'd really appreciate someone helping me with what must be a really simple issue.  As I said, this is literally my 1st attempt at doing this.  It normally takes me a lot longer to get stuck!
Thanks in advance for any suggestions :)

A: I'd guess it's a security issue. You can't load pages from another server into your document. See http://api.jquery.com/load/ for more info.

A: its because of SAME ORIGIN POLICY
alternate approach
make a server side proxy, have it request the page and send the response to your client side via json or your preferred format of choice
OR
Using YQL as a proxy for cross-domain Ajax

A: To load external link in ".load()"
create page say external.php
In external.php put following code:
<?php $url = 'http://ur/url/here'; echo $var = get_file_contents($url);?>

now load this page in jquery n it will load external link
$('div').load('external.php');


text:
Q: Image is not updating in UI in ionic 2.How can I show the change image in dynamically? I am taking pic from camera and uploading to server , then returning the url of picture from server.But previous picture is still there.Image is not updating.

A: You have to create a variable in TYPESCRIPT something like :
path:String = "";

then the function to take a photo
    takePicture(){
        Camera.getPicture({
            destinationType: Camera.DestinationType.DATA_URL,
            targetWidth: xxx,
            targetHeight: yyy
        }).then((imageData) => {
          // imageData is a base64 encoded string,
            this.path = "data:image/jpeg;base64," + imageData;
//create a function here to send the photo and the return will be the link
            this.path = getServerLink();
        }, (err) => {
            console.log(err);
        });
      }

then in HTML
      <img src="{{path}}"/>
<!--or -->
    <img [src]="path" *ngIf="path" />


text:
Q: Remove binary search I'm working on a Path method that returns the path from the given node to the node with the key of a given value. My code returns the correct numbers, but they are inside a bracket. How do I remove the bracket?
 private boolean pathhelp(Node n, int val, ArrayList<Integer> lst){
    if(n == null){
        return false;
    }else if(val < n.key){
        lst.add(n.key);
        return pathhelp(n.left, val, lst);
    }else if(val > n.key ){
        lst.add(n.key);
        return pathhelp(n.right, val, lst);
    }else{
        lst.add(n.key);
        return true;
    }
  }
   public String path(Node node, int value) {
    ArrayList<Integer> path = new ArrayList<Integer>();

    if(pathhelp(root,value,path) == true ){
        System.out.println(path);
        String p = "";
        //build p from path list

        return p;
    }else{
        return "";
    }
 }
  }

The actual output is:
[6, 5, 1, 4]

But it is supposed to be:
6, 5, 1, 4

A: Something like that for example (using Java 8 Streams):
import java.util.*;
import java.util.stream.Collectors;

class Scratch {

    public static void main(String[] args) {
        ArrayList<Integer> path = new ArrayList<Integer>();
        path.add(1);
        path.add(2);

        String asString = path.stream()
                                    .map(Object::toString)
                                    .collect(Collectors.joining(", "));

        System.out.println(asString);
    }
}

You may also use Guava's Joiner


text:
Q: SQLplus row limiting Is there a setting like SET ROW LIMIT 100 That I can use to limit the output of sqlplus? This is the command I've written already and I'm hoping I can keep my html more manageable.
sqlplus -S -L user@host <<EOF
SET MARKUP HTML ON
SPOOL output.html
START script.sql
EXIT
EOF
Edit: This is going in a script, to get a preview of a sql command's output

A: EDIT: If this is fine with you, try to restrict the output in query itself, following worked when I tested it in sqlplus
select * from (SELECT column1, column2 FROM dm_singh_test_table) WHERE ROWNUM <= 10

Could you please try following in sqlplus and let me know if this helps.
SQL> set pause on
SQL> set pages 10 pause 'press enter in case you want to continue'
SQL> select field_name from your_table;


text:
Q: Empty default option on select Angular 4 What I'm trying to do is Angular to get the value from an variable and put it on the first option, while the others below will be static. Angular is getting the data but the first option is always blank.
HTML
<select [(ngModel)]="sub_planning">
<option value="data[0].value" >{{data[0].name}}</option>
<option *ngFor="let c of subdimension" [ngValue]="c.value">{{c.name}}</option>
</select>

TS
sub_planning = '0';
subdimension = [{'name': 'oneabc','value': 1 },
  {'name': 'twoabc','value': 2}];

I found some answers on the internet but it's on Angular 2 and it does't seems to work for Angular 4

A: Because of invalid datatypes,
sub_planning = 1

Note: Type of number.
LIVE DEMO


text:
Q: How do "collisions" occur on Firebase data updates? In my application, I'm storing the data of my users in Firebase's real-time database. It can happen that I modify one of its data via setValue and that there is directly afterwards another modification of this same data (for example on the user spamming this action button), and thus I think that there can be two writings in the same place at the same time.
Already I wanted to know if what I said true or if anyway with the time lag between the two clicks, the changes can't occur simultaneously.
For the moment I have managed this problem by hiding the button until the modification finished, but it turns out that the problem is already managed by Firebase and I don't know it.
If anyone can help me out, that would be great :)

A: In the Firebase realtime database the last change will be saved. If you don't want to overried other fields on a path use update instead of set. You can read more about it here.


text:
Q: Need help on debugging calloc related error, minimal code attached I want to allocate an array dynamically in one function, load the obtained memory with data, and then free it in the calling function. Is there a glaring mistake in the following code?
Thanks for your time.
#include <stdio.h>
#include <stdlib.h>

void tf(int** ptr);

int main(int argc, char* argv[])
{
    int *arr;
    tf(&arr);
    free(arr);
}

void tf(int** ptr)
{
    *ptr = (int *) calloc(2, sizeof(int));
    if(*ptr!=NULL)
    {
        *ptr[0]=10;
        *ptr[1]=20;
    }
}

A: The glaring mistake is the assignment of 20 beyond the end of ptr. (on x86_64) The reason has to do with operator precedence in C. When you pass the address of arr to tf for allocation and to initialize values, you cannot simply assign
    *ptr[0]=10;
    *ptr[1]=20;

(well, you can assign *ptr[0]=10; but only because the index of 0 no possibility or pointer / type mismatch. However, *ptr[1]=20; is beyond the end of your allocated memory, again on x86_64)
Why? Answer: operator precedence. If you look at the operator precedence table, you will see that [] has higher precedence than the * (dereference) operator:
                C Operator Precedence

Priority   Operators                                Associativity

(high)      () [] . ->  (postfix)++  (postfix)--       l -> r

  ^         ++(prefix)  --(prefix)                     r -> l
  |         !  ~ sizeof(type) +(unary)
  |         -(unary)  &(address)
  |         *(dereference)
<snip>
(low)

What occurs with *ptr[1] according to precedence is the ptr[1] index is applied (moving the address to the second element of ptr (by sizeof *ptr bytes), which since you only allocated 8-bytes (two ints on x86/x86_64) ptr is will be an address outside of your allocation on x86_64) Then the dereference operator is applied in attempt to change the value at that address.
Why is ptr[1] outside of the allocation? (here is the insidious nature of the issue -- it depends...) Consider an x86_64 machine. On x86_64 an int is 4-bytes and a pointer is 8-bytes. You allocate for 2 int or 8-bytes. What is ptr? It is a pointer to pointer to int. How many bytes does ptr[1] advance? 8-bytes (by sizeof *ptr). So on x86_64, you are attempting to assign 4-bytes of 20 to an address 1-byte beyond the end of ptr (which has bytes 0-7 allocated). Now on x86, both a pointer and int are 4-bytes (so you are safe by accident, even if wrong -- only by virtue of a pointer and int being the same size).
How do you fix it? By surrounding the dereference of ptr in parenthesis, e.g. (*ptr) so now by rules of precedence the, look at the table above again, () applies before [], meaning the dereference for (*ptr) occurs before [1] giving you the proper pointer address (which is a pointer to int -- which advances by 4-bytes instead of 8 on x86_64.)
So bottom line, if working with the address of an array, you must dereference within parenthesis before applying the index to avoid the pointer / type mismatch which will occur otherwise.
Think through this and let me know if you have any questions. As for your approach to dynamic allocation (other than the operator precedence issue), it is up to you whether you pass the address of or whether you declare ptr within tf and return a pointer for assignment in the calling function.
Your tf could be written as follows:
/* allocate memory for 'ptr' using address of 'ptr' */
void tf (int **ptr)
{
    *ptr = calloc (2, sizeof **ptr);
    if (!*ptr) {
        fprintf (stderr, "tf() error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }

    (*ptr)[0] = 10;
    (*ptr)[1] = 20;
}

Or as discussed in the previous answer now deleted, you could simply declare ptr within tf (we'll call it tf2) and return the value for assignment, e.g.
/* allocate memory for 'ptr' and return for assignment */
int *tf2 ()
{
    int *ptr = calloc (2, sizeof *ptr);

    if (ptr) {
        ptr[0] = 30;
        ptr[1] = 40;
    }

    return ptr;
}

Then in main
arr = tf2();

(you will validate arr in main following the call to tf2 and assignment of the return in this case)
There are other ways to do that as well. In fact you can combine both methods above and have the convenience of either passing the address or assigning the return available. Again, let me know if you have any questions.

A: Many thanks for your time in detailing the explanation. I appreciate that a lot. Although the fine details that you have pointed out are very relevant and did not occur to me, operator precedence did. I found that with a pointer to a pointer to an array, one can assign values in (at least) the following three ways:
void tf(int** ptr)
{
    *ptr =  (int*) calloc(3, sizeof(int));
    if(*ptr!=NULL)
    {
        (*ptr)[0]=10; (*ptr)[1]=20; (*ptr)[2]=30;
        *(*ptr)=10; *(*ptr+1)=20; *(*ptr+2)=30;
        ptr[0][0]=10; ptr[0][1]=20; ptr[0][2]=30;
    }
}

Actually, I will generally do what you have indicated for a single pointer if thats the only entity to compute and report, however, here I only posted a minimal snippet that was causing the problem. The context is that I am reading a sparse matrix's CSR arrays from disk, whereby the read function that I wrote is supposed to first calloc space, then write the various arrays at the addresses passed as input arguments.
Once more, thanks a lot for your help and the time taken to elaborate.


text:
Q: Themes for python e-commerce solutions There are two good open source python e-commerce solutions exist: Satchmo and LFS. But I can't find any theme for them. Does at least one open source theme for them exist? There are thousands themes for Magento, osCommerce, OpenCart, but zero themes for Satchmo.
Thanks.

A: well, if that is the case, I think the only reason I can think up of is that this Satchmo is not that popular so that nobody is willing to port or design a theme for it.
I would suggest randomly grab a theme, port it here accordingly


text:
Q: Android - Glide resizing image via "override" and "fitCenter" deforms Bitmap I'm using Glide to load images from gallery into GLSurfaceView. However, when I tried to resize the image using override(width, height), it does not do so. Thus, I added fitCenter(), which seems to be the key to get the desired size.
My problem is when the Bitmap is resized the result is quite weird! Everything is good except for images that have small width values. The attached pictures illustrate the difference between using and not using fitCenter().
Here's the code I used for loading via Glide
Glide.with(this)
    .load(imageUri)
    .asBitmap()
    .override(newWidth, newHeight)
    .fitCenter()
    .atMost()
    .into(new SimpleTarget<Bitmap>(newWidth, newHeight) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
            Log.e(TAG, "Loaded Bitmap Size :" + resource.getWidth() + "x" + resource.getHeight());
            /*
            .
            . Initialize GLSurfaceView with Bitmap resource
            .
            */
        }
    }) ;

I thought for a second that it may be a GLSurfaceView problem, something related to very small width I guessed. But it looks that it renders perfectly until the image is resized.
Is there anything wrong with my code? I would really appreciate any suggestion.

A: It looks like the problem occurs when using fitCenter() with GLSurfaceView with a Bitmap that has either width or height as an odd number. I solved the issue by adding the following custom transformation to Glide call.
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int maxWidth, int maxHeight) {
    if (maxHeight > 0 && maxWidth > 0) {
        int width = toTransform.getWidth();
        int height = toTransform.getHeight();

        float ratioBitmap = (float) width / (float) height;
        float ratioMax = (float) maxWidth / (float) maxHeight;

        int finalWidth = maxWidth;
        int finalHeight = maxHeight;
        if (ratioMax > ratioBitmap) {
            finalWidth = (int) ((float) maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float)maxWidth / ratioBitmap);
        }

        return Bitmap.createScaledBitmap(toTransform, previousEvenNumber(finalWidth), previousEvenNumber(finalHeight), true);
    }
    else {
        return toTransform;
    }
}

private int previousEvenNumber(int x){
    if ( (x & 1) == 0 )
        return x;
    else
        return x - 1;
}

And editing Glide call to the following:
Glide.with(this)
    .load(imageUri)
    .asBitmap()
    .override(newWidth, newHeight)
    .transform(new CustomFitCenter(this))
    .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
            Log.e(TAG, "Loaded Bitmap Size :" + resource.getWidth() + "x" + resource.getHeight());
            /*
            .
            . Initialize GLSurfaceView with Bitmap resource
            .
            */
        }
    }) ;

I'm not sure if it's the best way to do it, but it worked.

This answer was posted as an edit to the question Android - Glide resizing image via "override" and "fitCenter" deforms Bitmap by the OP Zac Jokface under CC BY-SA 3.0.


text:
Q: VLC media player - is there a way to keep one song playing while exploring others (in Media Library view)? This is a feature that I'm sure VLC media player must support, but I can't find it.
Assume I am not using a playlist in VLC media player, but just scrolling through my folders (in the "Media Library" view) and picking tracks to play.  I double click on an audio file and it starts playing.  Fantastic!
However, each time I click on a new folder to cue up another track, the current song stops playing, even though I haven't yet drilled down far enough to get to the audio files in the folder to select one.
I've searched through all the preferences/settings, including "show all" options, and also search this forum and others.
In Windows Media Player (apologies) the behaviour I want is the default.  What am I doing wrong in VLC media player?
Many thanks.


text:
Q: How to only accept inputs that are 3 digit numbers? UserNumber = 0

UserNumber = int(raw_input("Enter a 3 digit number: "))

if UserNumber >= 100 and UserNumber <= 999:

    print "My name is: xxxxx xxxxx"
    print "My UBIT name is: xxxxxxx"
    print "The number you entered was", UserNumber, "."

How can I make the program only run when a 3 digit number is entered (i.e a number > 99 and number < 1000? I know it has to be some sort of while loop but I don't know how to implement it.

A: The input is a string, therefore, you can len(input) before the cast to an integer.
The check that every character is a digit can be done with and input.isdigit.
UserNumber = 0

input = raw_input("Enter a 3 digit number: ")

if len(input) == 3 and input.isdigit():
    UserNumber = int(input)
    print "My name is: xxxxx xxxxx"
    print "My UBIT name is: xxxxxxx"
    print "The number you entered was", UserNumber, "."

But think, 007 is also a valid 3 digit number. So if you want that it is bigger than 99, you need that check too.

To your "update", that you want a "fail-save" such that somebody is forced to do a 3 digits input:
UserNumber = 0

input = ""
while not (len(input) == 3 and input.isdigit()):
    input = raw_input("Enter a 3 digit number: ")

UserNumber = int(input)
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was %03d." % UserNumber

As long as somebody does not input 3 digits, the question for that input will appear.

A: You could use regex to check if the number is 3 digits and just ask the user again if it is not matching the regex
import re

UserNumber = int(raw_input("Enter a 3 digit number: "))

while not(re.search("^\d{3}$", str(UserNumber))):
    UserNumber = int(raw_input("that  was not a 3 digit number, Enter a 3 digit number: "))

if UserNumber >= 100 and UserNumber <= 999:

    print "My name is: xxxxx xxxxx"
    print "My UBIT name is: xxxxxxx"
    print "The number you entered was", UserNumber, "."


text:
Q: Saving state of UIButton (checkbox) - Swift I'm a new developer and I'm making a to-do list app in Swift. I was able to figure out how to change the state of the UIButton (checkbox) on clicking. At the moment I'm trying to figure out how to save that state for when I exit the app or switch views and return. I was able to successfully save the text (to-do list tasks) by using NSUserDefaults and have also experimented with it on my buttons but cannot figure out how to get it to work.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var myButton: Qbutton!

override func viewDidLoad() {
    super.viewDidLoad()

    var isChecked = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
    myButton.isChecked = isChecked
    self.view.addSubview(myButton)

I have the UIButton in a subclass of QButton.
class Qbutton: UIButton {

    var isSelected: Bool = defaults.boolForKey("isButtonChecked")

    // Images
    let selectedImage = UIImage(named: "Selected")
    let unselectedImage = UIImage(named: "Unselected")

    //Bool Property
    var isChecked:Bool = false{
        didSet{
            if isChecked == true{
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }else{
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }
            defaults.setObject(isChecked, forKey: "isButtonChecked")
        }
    }

    override init(frame: CGRect){
    super.init(frame:frame)
    self.layer.masksToBounds = true
    self.setImage(unselectedImage, forState: UIControlState.Normal)

    self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    self.isChecked = false
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

func buttonClicked(sender: UIButton) {
    if(sender == self){
        if isChecked == true{
            isChecked = false
        }else{
            isChecked = true
        }
    }
}
}

A: well i think you can save the state of the UIButton with the NSUserDefaults just when the variable isChecked is changed. Something like this:
var isChecked:Bool = false{
    didSet{
        if isChecked {
            self.setImage(selectedImage, forState: UIControlState.Normal)
        }else{
            self.setImage(unselectedImage, forState: UIControlState.Normal)
        }
        NSUserDefaults.standardUserDefaults().setObject(isChecked, forKey: "isBtnChecked")
        // this method is automatically invoked at periodic intervals, but
        //if you cannot wait for the automatic synchronization you can invoke it
        NSUserDefaults.standardUserDefaults().synchronize()
    }

}

Now when your app is launched you can check the last state of the UIButton with this:
var isSelected: Bool = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked")

UPDATE
I made an example using your Qbutton class. I hope this can help you:
import Foundation
import UIKit

class Qbutton: UIButton {

    // Images
    let selectedImage = UIImage(named: "Selected")
    let unselectedImage = UIImage(named: "Unselected")

    //Bool Property
    var isChecked:Bool = false{
        didSet{
            if isChecked {
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }else{
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }
            NSUserDefaults.standardUserDefaults().setObject(isChecked, forKey: "isBtnChecked")
            // this method is automatically invoked at periodic intervals, but
            //if you cannot wait for the automatic synchronization you can invoke it
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override init(frame: CGRect){
        super.init(frame:frame)
        self.layer.masksToBounds = true
        self.setImage(unselectedImage, forState: UIControlState.Normal)

        self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
        self.isChecked = false
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func buttonClicked(sender: UIButton) {
        if(sender == self){
            if isChecked == true{
                isChecked = false
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }else{
                isChecked = true
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }
        }
    }
}

Now in the UIViewController i create a Qbutton and before i add it to the UIViewController view i read the last state of the variable "isBtnChecked".
From the official docs:

If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned.

import UIKit
class ViewController: UIViewController {
    var myButton: Qbutton!

    override func viewDidLoad() {
        super.viewDidLoad()

        myButton = Qbutton(frame: CGRectMake(100,100,50 ,50));
        var isChecked = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
        myButton.isChecked = isChecked // we set the value
        self.view.addSubview(myButton)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

UPDATE 2
Here is an example using the selected property of UIButton
import Foundation
import UIKit

class Qbutton: UIButton {

    // Images
    let selectedImage = UIImage(named: "Selected")
    let unselectedImage = UIImage(named: "Unselected")

    //Bool Property
    override var selected: Bool{
        didSet{
            if selected {
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }else{
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }
            NSUserDefaults.standardUserDefaults().setObject(selected, forKey: "isBtnChecked")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override init(frame: CGRect){
        super.init(frame:frame)
        self.layer.masksToBounds = true
        self.setImage(unselectedImage, forState: UIControlState.Normal)

        self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
   }

    func buttonClicked(sender: UIButton) {
        self.selected = !self.selected
    }
}

And the UIViewController :
import UIKit
class ViewController: UIViewController {
    var myButton: Qbutton!

    override func viewDidLoad() {
        super.viewDidLoad()

        myButton = Qbutton(frame: CGRectMake(100,100,50 ,50));
        myButton.selected = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
        self.view.addSubview(myButton)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

I hope this really can help you!

A: I think you are completely over-thinking it and making it complicated. Since it's just a simple button the easiest way to do it is set a bool through an IBAction. Let me know if I'm missing something from your question though.
In Objective-C it would be something like this..
{
    BOOL _isStateEnabled;
}

-(IBAction)clickedButton: (id)sender {
    _isStateEnabled = !_isStateEnabled;
}

In Swift I'm not fluent but, something like this..
{
    let _isStateEnabled as boolean;
}

func buttonClicked(sender: UIButton) {
    _isStateEnabled = !_isStateEnabled;
}


text:
Q: How safe is the thread local in Rails? In our multi tenant Rails 4.2 app, we would like to define a thread local current_token for User model and intend to use it through out the whole app. Here is the how the current_token is defined:
class User < ActiveRecord::Base
  def self.current_token=(token)
    Thread.current['current_token'] = token
  end

  def self.current_token
    Thread.current['current_token']
  end
end

The token is retrieved with User.current_token. It is vital to keep User.current_token thread safe and alive throughout the lifespan of a user session. It is pointed out that the thread local may be cleared up by some web server such as puma. We would like to get feedback from the community about how sound is the thread local in real production. What kind of problem we should be aware of (and possible solution if there is one).

A: Thread.current per se is secure. The risk of Thread.current is that you have to use it correctly, because it doesn't reset automatically at the end of a request. Some examples:

*

*Imagine you set a token in Thread.current in one request and do not set to an other token in the next (perhaps because there was no token in the next request), then the old token will still be available.

*Or you plan to nullify Thread.current at the end of each request to ensure each request starts with a blank Thread.current. Will happen if a request fails with an exception, does it still get nullified?
It is just error-prone to work with Thread.current directly and there is the risk of exposing data from one request (one user) to a later request (user) on the same server.
You might want to check the RequestStore gem that internally uses Thread.current, but warps it with some layers of security.

A: I've never heard of an issue with puma and thread locals. You might want to use the sentient_user gem since its behavior is very close to what you're describing. The only difference is that instead of keeping around a token, you keep around the whole user.
I will note that this pattern is basically a global variable, so it acts like an unstated parameter to any method that uses it. But it can be nice for auditing, so that it is always available no matter where you need it.


text:
Q: Creating multiple keys inside javascript object with Array.map What I am trying to accomplish is from an array, I want to map all of those values into one object. For example, if I have the following data below
const myKeys = ["prop_1", "prop_2", "prop_3"];

When I map over this array I would like to return an object with 3 properties from the array listed above. Something like this.
const myKeysObj = myKeys.map( key => {
// expected outcome {"prop_1" : "some_value", "prop_2": "some_value", "prop_3": "some_value"}
// actual outcome {key: "some_value"}
return {[key]: "some_value"}
})

What can I do to have all three of my props in my array to be properties for a each object returned?

A: It looks like you want to reduce the keys into an object, in which case reduce is more appropriate than .map:

const myKeys = ["prop_1", "prop_2", "prop_3"];
const output = myKeys.reduce((a, key) => {
  a[key] = 'some_value';
  return a;
}, {});
console.log(output);


text:
Q: AV When using a Procedure from one Component called by another Im not sure if i have explaned this the best i can but, here we go...
I have 2 Custom components on a form, Which are link together at design time through the IDE. Whenever i call a procedure from on of the Component i get the  Access violation,

Access violation at address 0049A614
  in module 'Project2.exe'. Read of
  address 00000034.

This is a small section of my code
TMyClient = class(TClientSocket)
{...}
end;

and...
TPresence = class(TComponent)
 private
  ftheClient: TMyClient
 public
  procedure SetStatus(status: string);

 published
  property UserName : string read fUserName write fUserName;
  property theClient: TMyClient read ftheClient write ftheClient;
 end;

procedure TPresence.SetStatus(status: string);
begin
 try
*****   if theClient = nil then
     Exception.Create('theClient  is Nil');
 except
   on e:Exception do
   MessageDlg(e.classname+', '+e.message, mtWarning, [mbOK], 0);
 end;
  {...}
end;

0049A614 is at the *****, and the IDE stops here.
I Have also tried to do the assign at run time with
Presence1.theClient := MyClient1;

with no luck
using procedures from Presence1 or MyClient1 that do not rely on each other work fine.
Delphi 7
Follow Up:
from mghie comments, i rethought about it.
I removed the TPresence Component from the form (which caused some strange IDE errors, that might have had something to do with it) and created it design time, assigning everything that was needed.  Now it works, but putting the TPresence Component back on the from brings the error back.
Thankyou for your help guys, i should be able to work this one out now, if i can't ill reopen another question :)

A: You seem to be thinking that the exception is raised because the client field of Presence1 is not set - if you do however get the exception "Read of address 00000034" it means that the Self pointer in the SetStatus() call is nil. That would indicate that you call SetStatus() on an unassigned TPresence reference. It is not really possible to tell the reason for that from the snippet you posted, but it should get you started debugging.
I would still advise you to write a proper setter method for all component references in your own custom components - first because you have a better hook when debugging such problems (you can set a breakpoint there), and second because you should always call TComponent.FreeNotification() on such linked components to be able to track their destruction and set the internal reference to nil.

A: We probably need more of your code.  It is possible you are not correctly creating an instance of TPresence which would give you the error you are experiencing.  Try to give us a simple as possible code snippet that causes your error.


text:
Q: Formatting json object into spreadsheet like array in JS i'm trying to reformat data in Json object, ive wrote simple function, strange thing is that all the rows of new array have the same values.
 var array_json = [{"date_hour":{"value":"2018-04-12T12:12:00"},"avg_ech1":0,"avg_ech2":20,"avg_ech3":30,"avg_ech4":40,"avg_pm2_5":21,"avg_pm10":22,"data_points":1},{"date_hour":{"value":"2018-04-12T12:13:00"},"avg_ech1":10,"avg_ech2":20,"avg_ech3":30,"avg_ech4":40,"avg_pm2_5":21,"avg_pm10":22,"data_points":2},{"date_hour":{"value":"2018-04-12T12:14:00"},"avg_ech1":10,"avg_ech2":20,"avg_ech3":30,"avg_ech4":40,"avg_pm2_5":20,"avg_pm10":21,"data_points":2},{"date_hour":{"value":"2018-04-12T12:15:00"},"avg_ech1":10,"avg_ech2":20,"avg_ech3":30,"avg_ech4":40,"avg_pm2_5":19.5,"avg_pm10":20.5,"data_points":2}];

function json2array(json_array){
  var array_full = [["Date","ECH1","ECH2","ECH3","ECH4","PM2_5","PM10"]];
  //header in first line
  var array_line = [];

  for (var i=0; i<json_array.length;i++){
    array_line[0]=json_array[i].date_hour.value;
    array_line[1]=json_array[i].avg_ech1;
    array_line[2]=json_array[i].avg_ech2;
    array_line[3]=json_array[i].avg_ech3;
    array_line[4]=json_array[i].avg_ech4;
    array_line[5]=json_array[i].avg_pm2_5;
    array_line[6]=json_array[i].avg_pm10;
    console.log('line',array_line);
    array_full[i+1]=array_line;
    console.log('full line',array_full[i+1]);
    }
    return array_full;
}

console.log('test',json2array(array_json));

Console output:
you can see at output that each row looks good but when checking whole array all rows have same values. Am i missing something here?
node v9.7.1 linux/amd64

line [ '2018-04-12T12:12:00', 0, 20, 30, 40, 21, 22 ]
full line [ '2018-04-12T12:12:00', 0, 20, 30, 40, 21, 22 ]
line [ '2018-04-12T12:13:00', 10, 20, 30, 40, 21, 22 ]
full line [ '2018-04-12T12:13:00', 10, 20, 30, 40, 21, 22 ]
line [ '2018-04-12T12:14:00', 10, 20, 30, 40, 20, 21 ]
full line [ '2018-04-12T12:14:00', 10, 20, 30, 40, 20, 21 ]
line [ '2018-04-12T12:15:00', 10, 20, 30, 40, 19.5, 20.5 ]
full line [ '2018-04-12T12:15:00', 10, 20, 30, 40, 19.5, 20.5 ]

test [ [ 'Date', 'ECH1', 'ECH2', 'ECH3', 'ECH4', 'PM2_5', 'PM10' ],
  [ '2018-04-12T12:15:00', 10, 20, 30, 40, 19.5, 20.5 ],
  [ '2018-04-12T12:15:00', 10, 20, 30, 40, 19.5, 20.5 ],
  [ '2018-04-12T12:15:00', 10, 20, 30, 40, 19.5, 20.5 ],
  [ '2018-04-12T12:15:00', 10, 20, 30, 40, 19.5, 20.5 ] ]

A: You take the same object reference for each loop. By moving array_line = []; inside of the loop, you create an independent array.
var array_line;                               // declare in advance
for (var i = 0; i < json_array.length; i++) {
    array_line = [];                          // initialize with empty array

    // assignemnts
}

A: Create a new variable inside of for loop. When you create an object  outside of loop and push to an array , all the array contents are referencing the same object and whenever the object changes all the array values are being changed.

function json2array(json_array){
  var array_full = [["Date","ECH1","ECH2","ECH3","ECH4","PM2_5","PM10"]];
  //header in first line

  for (var i=0; i<json_array.length;i++){
       var array_line = [];
    array_line[0]=json_array[i].date_hour.value;
    array_line[1]=json_array[i].avg_ech1;
    array_line[2]=json_array[i].avg_ech2;
    array_line[3]=json_array[i].avg_ech3;
    array_line[4]=json_array[i].avg_ech4;
    array_line[5]=json_array[i].avg_pm2_5;
    array_line[6]=json_array[i].avg_pm10;
    console.log('line',array_line);
    array_full[i+1]=array_line;
    console.log('full line',array_full[i+1]);
    }
    return array_full;
}

var array_json = []; // initialize your data
console.log('test', json2array(array_json));


text:
Q: Why did my reputation just change without activities? More or less one hour ago I had 2475 reputation. Now I find I have 2495, but I have no notifications on reputation tab in my profile.
It's good, but why did it happen? Maybe for recent changes in rep calculation system (now always recalculating from real activities)?


text:
Q: Delphi insert image to database firebird i have table (employee) with many fields.
first name, last name, middle name, image and so on.
i'm using dbExpress (TclientDataset) and have code in the event After Post
 clientdataset1.applyupdates(0)

and it works but i want to insert/update also the image but it doesn't save the image to database(Fire bird)
id search in google but it doesn't fit to what i want, please help thanks

A: Below is the source and DFM of a project I've put together to see if I get the same problem as you.
I don't.  It successfully loads and saves .BMP files to the CDS1Image field.
You didn't say what your column type is, but in my FB db, the Image column is defined as a BLOB.
Btw, I'm not sure what kind of image you're trying to work with, but there is a long-standing problem that TDBImage doesn't handle JPEGs.
procedure TForm2.GetImage;
var
  ImageFN : String;
  MS : TMemoryStream;
begin
  if OpenDialog1.Execute then begin
    ImageFN := OpenDialog1.FileName;
  end;

  MS := TMemoryStream.Create;
  MS.LoadFromFile(ImageFN);
  MS.Seek(0, soBeginning);
  try
    CDS1.Edit;
    CDS1Image.LoadFromStream(MS);
    CDS1.Post;
  finally
   MS.Free;
  end;
end;

procedure TForm2.RefreshCDS;
begin
  CDS1.ApplyUpdates(0);
  CDS1.Close;
  CDS1.Open;
end;

procedure TForm2.CDS1NewRecord(DataSet: TDataSet);
var
  ID : Integer;
begin
  Inc(ID);
  if SqlQuery2.Active then
    SqlQuery2.Close;
  SqlQuery2.Open;
  ID := 1 + SqlQuery2.Fields[0].AsInteger;

  CDS1.FieldByName('ID').AsInteger := ID;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  CDS1.Open;
end;

procedure TForm2.btnGetImageClick(Sender: TObject);
begin
  GetImage;
end;

procedure TForm2.btnRefreshClick(Sender: TObject);
begin
  RefreshCDS;
end;

DFM
object Form2: TForm2
  Left = 256
  Top = 95
  Caption = 'Form2'
  ClientHeight = 303
  ClientWidth = 452
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object DBGrid1: TDBGrid
    Left = 8
    Top = 8
    Width = 320
    Height = 120
    DataSource = DataSource1
    TabOrder = 0
    TitleFont.Charset = DEFAULT_CHARSET
    TitleFont.Color = clWindowText
    TitleFont.Height = -11
    TitleFont.Name = 'Tahoma'
    TitleFont.Style = []
  end
  object DBNavigator1: TDBNavigator
    Left = 24
    Top = 144
    Width = 240
    Height = 25
    DataSource = DataSource1
    TabOrder = 1
  end
  object btnRefresh: TButton
    Left = 350
    Top = 8
    Width = 75
    Height = 25
    Caption = 'Refresh'
    TabOrder = 2
    OnClick = btnRefreshClick
  end
  object DBImage1: TDBImage
    Left = 128
    Top = 175
    Width = 105
    Height = 105
    DataField = 'IMAGE'
    DataSource = DataSource1
    TabOrder = 3
  end
  object btnGetImage: TButton
    Left = 350
    Top = 64
    Width = 75
    Height = 25
    Caption = 'GetImage'
    TabOrder = 4
    OnClick = btnGetImageClick
  end
  object SQLConnection1: TSQLConnection
    DriverName = 'Firebird'
    LoginPrompt = False
    Params.Strings = (
      'DriverUnit=Data.DBXFirebird'

        'DriverPackageLoader=TDBXDynalinkDriverLoader,DbxCommonDriver180.' +
        'bpl'

        'DriverAssemblyLoader=Borland.Data.TDBXDynalinkDriverLoader,Borla' +
        'nd.Data.DbxCommonDriver,Version=18.0.0.0,Culture=neutral,PublicK' +
        'eyToken=91d62ebb5b0d1b1b'

        'MetaDataPackageLoader=TDBXFirebirdMetaDataCommandFactory,DbxFire' +
        'birdDriver180.bpl'

        'MetaDataAssemblyLoader=Borland.Data.TDBXFirebirdMetaDataCommandF' +
        'actory,Borland.Data.DbxFirebirdDriver,Version=18.0.0.0,Culture=n' +
        'eutral,PublicKeyToken=91d62ebb5b0d1b1b'
      'GetDriverFunc=getSQLDriverINTERBASE'
      'LibraryName=dbxfb.dll'
      'LibraryNameOsx=libsqlfb.dylib'
      'VendorLib=fbclient.dll'
      'VendorLibWin64=fbclient.dll'
      'VendorLibOsx=/Library/Frameworks/Firebird.framework/Firebird'
      'Database=d:\delphi\firebird\databases\employee.fdb'
      'User_Name=sysdba'
      'Password=masterkey'
      'Role=RoleName'
      'MaxBlobSize=-1'
      'LocaleCode=0000'
      'IsolationLevel=ReadCommitted'
      'SQLDialect=3'
      'CommitRetain=False'
      'WaitOnLocks=True'
      'TrimChar=False'
      'BlobSize=-1'
      'ErrorResourceFile='
      'RoleName=RoleName'
      'ServerCharSet='
      'Trim Char=False')
    Connected = True
    Left = 40
    Top = 24
  end
  object SQLQuery1: TSQLQuery
    MaxBlobSize = 1
    Params = <>
    SQLConnection = SQLConnection1
    Left = 112
    Top = 24
  end
  object DataSource1: TDataSource
    DataSet = CDS1
    Left = 272
    Top = 88
  end
  object CDS1: TClientDataSet
    Active = True
    Aggregates = <>
    CommandText = 'select * from maimages'
    Params = <>
    ProviderName = 'DataSetProvider1'
    AfterOpen = CDS1AfterOpen
    OnNewRecord = CDS1NewRecord
    Left = 280
    Top = 24
    object CDS1ID: TIntegerField
      FieldName = 'ID'
      Required = True
    end
    object CDS1NAME: TStringField
      FieldName = 'NAME'
      Size = 50
    end
    object CDS1IMAGE: TBlobField
      FieldName = 'IMAGE'
      Size = 1
    end
  end
  object DataSetProvider1: TDataSetProvider
    DataSet = SQLQuery1
    Options = [poAllowCommandText, poUseQuoteChar]
    Left = 184
    Top = 24
  end
  object OpenDialog1: TOpenDialog
    Filter = 'BMPs|*.Bmp'
    Left = 400
    Top = 32
  end
  object SQLQuery2: TSQLQuery
    Active = True
    MaxBlobSize = 1
    Params = <>
    SQL.Strings = (
      'select max(ID) from maimages')
    SQLConnection = SQLConnection1
    Left = 16
    Top = 120
  end
end


text:
Q: Vim (key-bindings) with Visual Studio Code vim extension This is in my .vimrc file:
:nmap p :pu<CR>

I'm looking for the equivalent in vs-code(vim extension), and I tried the following but it didn't work:
 "vim.normalModeKeyBindings": [
    {
        "before": ["p"],
        "after": ["p","u","<CR>"]
    },
]


text:
Q: Autofill/Autocomplete not working, if the form has more than 200 input fields I am working on a HTML5 Form which has more than 200 input fields, among these fields I need to autofill two fields basically which are name and email address, all other fields are marked as autocomplete=off.
It is observed autocomplete works only if total number of input fields in the form is <= 200, this is happening in Google Chrome and Microsoft Edge browsers.
Has anyone come across this issue?

A: Try removing autocomplete="off" from <form> tag and enter autocomplete in input tags of name and email only.