text:
Q: ef core unit test echec I have a method in my repository that I'm trying to test
public User UpdateUserManyToMany(User user, List<Guid> manyToManyds)
{
    var dbContext = _databaseContext as DbContext;

    dbContext?.TryUpdateManyToMany(user.ManyToMany, manyToManyds
        .Select(x => new ManyToMany{
            OtherEntityId = x,
            UserId = user.Id,
        }), x => x.OtherEntityId);

    return user;
}

My ManyToMany Entity :
public class ManyToMany
{
        public Guid OtherEntityId { get; set; }

        public OtherEntity OtherEntityId { get; set; }

        public Guid UserId { get; set; }

        public User User { get; set; }
}

My TryUpdateManyToMany :
public static class ManyToManyExtensions
{
    public static void TryUpdateManyToMany<T, TKey>(this DbContext db, IEnumerable<T> currentItems, IEnumerable<T> newItems, Func<T, TKey> getKey) where T : class
    {
        db.Set<T>().RemoveRange(currentItems.Except(newItems, getKey));
        db.Set<T>().AddRange(newItems.Except(currentItems, getKey));
    }

    public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKeyFunc)
    {
        return items
            .GroupJoin(other, getKeyFunc, getKeyFunc, (item, tempItems) => new { item, tempItems })
            .SelectMany(t => t.tempItems.DefaultIfEmpty(), (t, temp) => new { t, temp })
            .Where(t => ReferenceEquals(null, t.temp) || t.temp.Equals(default(T)))
            .Select(t => t.t.item);
    }
}

Here's my unit test :
using (var context = new InMemoryDataBaseContext())
{
    // Arrange
    var repository = new UserRepository(context);
    await context.Users.AddRangeAsync(GetUser());
    await context.SaveChangesAsync();

    // Act
    var manyIds = new List<Guid>();
    manyIds.Add(Guid.Parse("855d1a64-a707-40d5-ab93-34591a923abf"));
    manyIds.Add(Guid.Parse("855d1a64-a787-40d9-ac93-34591a923abf"));
    manyIds.Add(Guid.Parse("855d1a64-a707-41d9-ab93-39591a923abf"));

    var user = new User();
    var expected = repository.UpdateUserManyToMany(GetUser(), manyIds);

    // Assert
}

But I get the following error in my test :
 Message:
    System.InvalidOperationException : The instance of entity type 'ManyToMany' cannot be tracked because another instance with the same key value for {'UserId', 'OtherEntityId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
  Arborescence des appels de procédure:
    IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
    IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
    IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
    NullableKeyIdentityMap`1.Add(InternalEntityEntry entry)
    StateManager.StartTracking(InternalEntityEntry entry)
    InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
    InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
    EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
    EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
    EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
    DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
    DbContext.RemoveRange(IEnumerable`1 entities)
    InternalDbSet`1.RemoveRange(IEnumerable`1 entities)
    ManyToManyExtensions.TryUpdateManyToMany[T,TKey](DbContext db, IEnumerable`1 currentItems, IEnumerable`1 newItems, Func`2 getKey) ligne 24
    UserRepository.UpdateUserManyToMany(User user, List`1 manyToManyds) ligne 59
    MyRepoUnitTest.MyTestMethod() ligne 102
    --- End of stack trace from previous location where exception was thrown ```

A: The following sample program, that is based on the code you provided, works without issues:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace IssueConsoleTemplate
{
    public class User
    {
        public Guid Id { get; set; }
        public string Name { get; set; }

        public ICollection<ManyToMany> ManyToMany { get; set; } = new HashSet<ManyToMany>();
    }

    public class OtherEntity
    {
        public Guid Id { get; set; }
        public string Name { get; set; }

        public ICollection<ManyToMany> ManyToMany { get; set; } = new HashSet<ManyToMany>();
    }

    public class ManyToMany
    {
        public Guid OtherEntityId { get; set; }
        public Guid UserId { get; set; }

        public OtherEntity OtherEntity { get; set; }
        public User User { get; set; }
    }

    public class Context : DbContext
    {
        public DbSet<OtherEntity> OtherEntities { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<ManyToMany> ManyToMany { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseSqlServer(@"Data Source=.\MSSQL14;Integrated Security=SSPI;Initial Catalog=So63077461")
                .UseLoggerFactory(
                    LoggerFactory.Create(
                        b => b
                            .AddConsole()
                            .AddFilter(level => level >= LogLevel.Information)))
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<OtherEntity>(
                entity =>
                {
                    entity.HasKey(e => e.Id);

                    entity.HasMany(e => e.ManyToMany)
                        .WithOne(e => e.OtherEntity)
                        .HasForeignKey(e => e.OtherEntityId);

                    entity.HasData(
                        new OtherEntity
                        {
                            Id = new Guid("855d1a64-a707-40d5-ab93-34591a923abf"),
                            Name = "Bicycle"
                        },
                        new OtherEntity
                        {
                            Id = new Guid("855d1a64-a787-40d9-ac93-34591a923abf"),
                            Name = "Bus"
                        },
                        new OtherEntity
                        {
                            Id = new Guid("855d1a64-a707-41d9-ab93-39591a923abf"),
                            Name = "Plane"
                        });
                });
            modelBuilder.Entity<User>(
                entity =>
                {
                    entity.HasKey(e => e.Id);

                    entity.HasMany(e => e.ManyToMany)
                        .WithOne(e => e.User)
                        .HasForeignKey(e => e.UserId);
                });
            modelBuilder.Entity<ManyToMany>(
                entity =>
                {
                    entity.HasKey(e => new {e.OtherEntityId, e.UserId});
                });
        }
    }

    public static class ManyToManyExtensions
    {
        public static void TryUpdateManyToMany<T, TKey>(this DbContext db, IEnumerable<T> currentItems, IEnumerable<T> newItems, Func<T, TKey> getKey) where T : class
        {
            db.Set<T>().RemoveRange(currentItems.Except(newItems, getKey));
            db.Set<T>().AddRange(newItems.Except(currentItems, getKey));
        }

        public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKeyFunc)
        {
            return items
                .GroupJoin(other, getKeyFunc, getKeyFunc, (item, tempItems) => new { item, tempItems })
                .SelectMany(t => t.tempItems.DefaultIfEmpty(), (t, temp) => new { t, temp })
                .Where(t => ReferenceEquals(null, t.temp) || t.temp.Equals(default(T)))
                .Select(t => t.t.item);
        }
    }

    internal class UserRepository
    {
        private readonly Context _databaseContext;

        public UserRepository(Context context)
        {
            _databaseContext = context;
        }

        public User UpdateUserManyToMany(User user, List<Guid> manyToManyds)
        {
            var dbContext = _databaseContext as DbContext;

            dbContext?.TryUpdateManyToMany(user.ManyToMany, manyToManyds
                .Select(x => new ManyToMany{
                    OtherEntityId = x,
                    UserId = user.Id,
                }), x => x.OtherEntityId);

            return user;
        }
    }

    internal static class Program
    {
        private static async Task Main()
        {
            //
            // Operations with referential integrity intact:
            //

            using var context = new Context();

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            // Arrange
            var repository = new UserRepository(context);
            await context.Users.AddRangeAsync(GetUser());
            await context.SaveChangesAsync();

            // Act
            var manyIds = new List<Guid>
            {
                new Guid("855d1a64-a707-40d5-ab93-34591a923abf"),
                new Guid("855d1a64-a787-40d9-ac93-34591a923abf"),
                new Guid("855d1a64-a707-41d9-ab93-39591a923abf")
            };

            var expected = repository.UpdateUserManyToMany(GetUser(), manyIds);
        }

        private static User GetUser()
            => User;

        private static readonly User User = new User
        {
            Id = new Guid("30c35d2e-77fd-480b-9974-6ebf037a8f86"),
            Name = "John"
        };
    }
}

System.InvalidOperationException : The instance of entity type 'ManyToMany' cannot be tracked because another instance with the same key value for {'UserId', 'OtherEntityId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

The error message says, that at least one of your ManyToMany entries already exists in the database (there is an entry with the same UserId and OtherEntityId combination).
You can verify this, by running the following code directly after your filled the manyIds variable with the 3 IDs:
var user = GetUser();
var alreadyExistingManyToMany = context.ManyToMany
    .Where(m => m.UserId == user.Id &&
                manyIds.Contains(m.OtherEntityId))
    .ToList();

Debug.Assert(alreadyExistingManyToMany.Count == 0);


text:
Q: I can upload files with jquery ajax and php, some explaination and modification required I have read this.
https://developer.mozilla.org/en/docs/Web/API/FormData
Still can't understand why is formdata(frm) is empty in code. console.log(frm); returns "FormData{}" empty. Why?
file_form.php =>
<title>Upload File</title>

No Image

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

upload_script1.php =>
<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['image1']['name']);
    move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile);

    $image1 = $_FILES['image1']['name'];
    $images["image1"] = $image1;
    echo json_encode($images);
?>

upload_script2.php =>
<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['image2']['name']);
    move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile);
    $image2 = $_FILES['image2']['name'];
    $images["image2"] = $image2;
    echo json_encode($images);
?>

*

*Can anyone rewrite the two $.ajax() code to one $.ajax() code making the code shorter? Re-write the html and php code if necessary.

Any help will be highly appreciated.
Thanks in advance.

A: Your FormData object is probably showing as empty because your browser doesn't support iterators.
Check out the methods compatibility table at MDN. Internally, the console will probably try to use the iterator exposed by the entries method to enumerate the properties.
I get the same result in Chromium 45.

As for simplifying the code, you can merge both functions and PHP scripts by parameterizing them.
function createFormHandler($form, url, $image) {
  $form.on('submit', function(e) {
    var frm = new FormData($form[0]);
    e.preventDefault();

    $.ajax({
      url: url,
      type: "POST",
      data: frm,
      contentType: false,
      cache: false,
      processData: false,
      success: function(response) {
        var JsonObject = JSON.parse(response);
        $("#targetLayer").html(response);
        var src = "uploads/" + JsonObject.image1;
        $image.attr("src", src).height(100).width(100);
      }
    });
  });
}

createFormHandler($('#uploadForm1'), 'upload_script.php?id=1', $('#my_image1'));
createFormHandler($('#uploadForm2'), 'upload_script.php?id=2', $('#my_image2'));

Now the numeric id of each form is represented as a URL parameter, rather than having to be a separate script. You can merge both PHP files and use a single upload_script.php instead.
<?php
  $id = $_GET['id'];
  $uploaddir = '/var/www/html/file-upload/uploads/';
  $uploadfile = $uploaddir . basename($_FILES['image']['name']);
  move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile);

  $image = $_FILES['image']['name'];
  $images["image" . $id] = $image;
  echo json_encode($images);
?>

This lets you normalize the input names too.
<form id="uploadForm1" enctype="multipart/form-data">
  <input name="image" type="file" />
  <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
  <input name="image" type="file" />
  <input type="submit" value="Submit" />
</form>

A: I think it will minimize your code

<title>Upload File</title>

No Image

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

upload_script1.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';

    $uploadfile = $uploaddir . basename($_FILES['image1']['name']);
     $uploadfile2 = $uploaddir . basename($_FILES['image2']['name']);
    move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile);
    move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile2);
    $image1 = $_FILES['image1']['name'];
    $image2 = $_FILES['image2']['name'];
    $images["image1"] = $image1;
     $images["image2"] = $image2;
    echo json_encode($images);
?>

A: I have modifid only the javascript part.
My example is...
<title>Upload File</title>

No Image

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: My scanner methods aren't working and the while-loop won't break I'm a beginner and don't know what is wrong with my program.
What I would like the program to do is to allow the user to enter an Integer that is under MAX (1 000 000 000) but above 0. I also have put an exception block using the try and catch methods so that the user cannot enter a String.
The exception block works but it also prints the statements inside the if block, which I don't want.
This is what the console prints:
Number of marbles to divide:
*three*
Please enter a number not a word
Try again:
Please enter a number under 1 000 000 000 and above 0
Try again:

I only want it to print... Please enter a number not a word Try again: after the user enters a String. What I mean is that I want the method's while-loop to break if the user has entered a string.
Another problem that I can't seem to solve is that if the user enters an Integer that's value is over MAX (1 000 000 000), the program continues. This is what the console prints.
Number of marbles to divide:
1000000001
Number of people:

As you can see the program continues even though the user has entered an Integer over MAX (1 000 000 000)
This is my code:
import java.util.*;

public class MarblesApp
{
    final static int MAX = 1000000000;
    static int  numberOfMarbles;
    static int numberOfPeople, marblesPerPerson, marblesLeftOver;
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.println("Welcome to the marble divvy-upper.");
        System.out.println("This program will tell you how many marbles to give to each person.\n"
    + "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n");

        System.out.println("Number of marbles to divide: ");
          numberOfMarbles = GetMarbles();

        System.out.println("Number of people: ");
          numberOfPeople = GetPeople();

        marblesPerPerson = (int)numberOfMarbles / numberOfPeople;
        marblesLeftOver = (int)numberOfMarbles % numberOfPeople;

        System.out.println("Give each child " + marblesPerPerson + " marbles.");
        System.out.println("You will have " + marblesLeftOver + " marbles left over.");
    }
private static int GetPeople()
{
    while (true)
    {
        try
        {
            return input.nextInt();
        }
        catch(InputMismatchException f)
        {
            input.next();
            System.out.println("Please enter a number not a word\nTry again: ");
        }

        if(numberOfPeople > MAX || numberOfPeople == 0);
        {
            System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
        }
    }
}
public static int GetMarbles()
{
    while (true)
    {
        try
        {
            return input.nextInt();
        }
        catch (InputMismatchException e)
        {
            input.next();
            System.out.println("Please enter a number not a word\nTry again: ");
        }

        if(numberOfMarbles > MAX || numberOfMarbles == 0);
        {
            System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
        }

        }
    }
}

A: I know how difficult Java can be if you're absolutely new to it. And as I'm not one of those who expect your questions to be perfectly written and brought to the point, I assembled a solution to your problem.
I had to reorganize and squeeze your code a little bit. And I have to make some remarks referring to cleaner code:

*

*method-names in Java always start with a lower-case letter, _ or $

*avoid global variables if you don't need them

*avoid duplicate methodes that only differ in their names

I hope this code gives you a good start into JAVA. Have fun!
import java.util.*;

public class MarblesApp
{
    private final static int MAX = 1000000000;

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        int numberOfMarbles, numberOfPeople, marblesPerPerson, marblesLeftOver;

        System.out.println("Welcome to the marble divvy-upper.");
        System.out.println("This program will tell you how many marbles to give to each person.\n"
    + "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n");

        System.out.println("Number of marbles to divide: ");
          numberOfMarbles = getNumberFromConsole();

        System.out.println("Number of people: ");
          numberOfPeople = getNumberFromConsole();

        marblesPerPerson = (int)numberOfMarbles / numberOfPeople;
        marblesLeftOver = (int)numberOfMarbles % numberOfPeople;

        System.out.println("Give each child " + marblesPerPerson + " marbles.");
        System.out.println("You will have " + marblesLeftOver + " marbles left over.");
    }

    public static int getNumberFromConsole()
    {
        int number;

        while (true)
        {
            try
            {
                // get the number from console
                number = input.nextInt();

                // validate whether it's greater zero and lower MAX
                if(validateNumber(number) == true)
                {
                    // if true, return the number
                    return number;
                }
                else
                {
                    // if not, input again
                    input.next();
                }
            }
            catch (InputMismatchException e)
            {
                System.out.println("Please enter a number not a word\nTry again: ");
                input.next();
            }
        }
    }

    private static boolean validateNumber(int number) {

        if(number > MAX || number == 0)
        {
            System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
            return false;
        }

        return true;
    }
}


text:
Q: CORS headers issue express Angular In dev this works fine, i recently update the code in my vps and I'm getting an error in console: Acces to XMLHttpRequest at 'https://www.example.con/api/register' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tryed with :

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

and: app.use(cors()); but i'm still having the same message in console.

  noAuthHeader = { headers: new HttpHeaders({ 'NoAuth': 'True' }) };

    postUser(user: User){
    return this.http.post(this.url + '/register', user, this.noAuthHeader);
  }

    register: (req, res, next) => {
        let user = new User();
        user.email = req.body.email;
        user.password = req.body.password;
        user.domain = req.body.domain;

        user.save((err, doc) => {
            if (!err)
                res.send(doc);
            else {
                if (err.code == 11000) {
                    if(err.keyValue.hasOwnProperty('domain')){
                        res.status(422).send(['Name repeated']);
                    }
                    if(err.keyValue.hasOwnProperty('email')){
                        res.status(422).send(['Email repeated']);
                    }
                } else {
                    return next(err);
                }
            }
        });
    },

The modifications i've been made in code is the verification in register() api. I'm using mongo DB and checking error code 11000 for repeated unique model data in DB (email & domain fields). Console throws CORS error when i try to register a duplicate email or domain.
EDITED:
I'm getting this error in console:
/home/myapp_full/myapp_v0.2/node_modules/mongoose/lib/helpers/promiseOrCallback.js:19
throw error;
^
TypeError: Cannot read property 'hasOwnProperty' of undefined.

A: I don't think you should need CORS unless you actually intend to have two separate websites: www.example.com and example.com.
If, instead, your server is set up to accept requests from both, and doesn't redirect, I'd recommend that you handle redirects in your code wherever possible, so that you select one canonical URL: Either example.com or www.example.com. Barring that, as long as the script exists on both servers, just load the script without the URL (aka "/register", not this.url + "/register")

A: One time i had the same issue with Angular and i resolved it deleting the CORS headers in the back-end. I hope that works for you.

A: Solved: It seems that Linux and windows throws different error messages, i modified this piece of code and it's working fine, anyways the response is just 'email or name repeated' and i would like to handle each unique data, i'm still waiting for an upgrade, thanks for your time.

 user.save((err, doc) => {
            if (!err)
                res.send(doc);
            else {
                if (err.code == 11000) {
                        res.status(422).send(['Email or name repeated']);

                } else {
                    return next(err);
                }
            }
        });


text:
Q: Calling a Method From Within an onClick Listener I am trying to call "getVenueZipcode" from within onClick which is within setOnclickListener. I expect that "getVenueZipcode" would be called and "zipcode[0] = " + zipcode[0]" would be printed before "ZIPCODE = " + zipcode. However, that is not the case. ZIPCODE = null is printed and then zipcode[0] = 12345 is printed.
Is this how onClick Listener works or am I missing something?
    mAdd_gigEvent_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gigEvent = new GigEvent();

            mBand_name_editText = findViewById(R.id.add_band_name_editText);
            mVenue_name_editText = findViewById(R.id.add_venue_name_editText);
            mDate_editText = findViewById(R.id.add_date_editText);
            mTime_editText = findViewById(R.id.add_time_editText);

            String venue_name = mVenue_name_editText.getText().toString();
            String zipcode = getVenueZipcode(venue_name);

            System.out.println("ZIPCODE = " + zipcode);

            gigEvent.setGigAuth(userID);
            gigEvent.setBand(mBand_name_editText.getText().toString());
            gigEvent.setVenue(mVenue_name_editText.getText().toString());
            gigEvent.setDate(mDate_editText.getText().toString());
            gigEvent.setTime(mTime_editText.getText().toString());
            gigEvent.setZipcode(zipcode);

            mDatabase.child(userID).setValue(gigEvent);

            Toast.makeText(AddGigEvent.this, "Gig/Event added!",
                    Toast.LENGTH_LONG).show();

            startActivity(new Intent(AddGigEvent.this, Search.class));
        }
    });
}

public String getVenueZipcode(String name) {
    final Query venue_query;
    final String v_name = name;
    final String[] zipcode = new String[1];

    DatabaseReference mDatabase =
            FirebaseDatabase.getInstance().getReference().child("venues");
    venue_query = mDatabase.orderByChild("uid");
    venue_query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if(snapshot.child("name").getValue().toString().equals(v_name)) {
                    zipcode[0] = snapshot.child("venue_zipcode").getValue().toString();

                    System.out.println("zipcode[0] = " + zipcode[0]);

                    return;
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });

    return zipcode[0];
}

A: You'll have to implement an Interface which will give you callback once you get zipcode on FirebaseDatabase.
You can do like this:
interface ReceiveZipCodeListener {
    public void onZipCodeReceived(String zipCode);
}

mAdd_gigEvent_btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        gigEvent = new GigEvent();

        mBand_name_editText = findViewById(R.id.add_band_name_editText);
        mVenue_name_editText = findViewById(R.id.add_venue_name_editText);
        mDate_editText = findViewById(R.id.add_date_editText);
        mTime_editText = findViewById(R.id.add_time_editText);

        String venue_name = mVenue_name_editText.getText().toString();
        getVenueZipcode(venue_name, new ReceiveZipCodeListener({
            @Override
            public void onZipCodeReceived(String zipCode) {
                System.out.println("ZIPCODE = " + zipcode);

                gigEvent.setGigAuth(userID);
                gigEvent.setBand(mBand_name_editText.getText().toString());
                gigEvent.setVenue(mVenue_name_editText.getText().toString());
                gigEvent.setDate(mDate_editText.getText().toString());
                gigEvent.setTime(mTime_editText.getText().toString());
                gigEvent.setZipcode(zipcode);

                mDatabase.child(userID).setValue(gigEvent);

                Toast.makeText(AddGigEvent.this, "Gig/Event added!",
                        Toast.LENGTH_LONG).show();

                startActivity(new Intent(AddGigEvent.this, Search.class));
            }
        }));
    }
});

public void getVenueZipcode(String name, ReceiveZipCodeListener listener) {
    final Query venue_query;
    final String v_name = name;

    DatabaseReference mDatabase =
        FirebaseDatabase.getInstance().getReference().child("venues");
    venue_query = mDatabase.orderByChild("uid");
    venue_query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if(snapshot.child("name").getValue().toString().equals(v_name)) {
                    String zipCode = snapshot.child("venue_zipcode").getValue().toString();

                    System.out.println("zipcode = " + zipCode);

                    listener.onZipCodeReceived(zipCode);
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}

A: This is the solution that worked for me:
FirebaseUser fBUser = mAuth.getCurrentUser();
final String userID = fBUser.getUid();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_gig_event);

    actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF0367BE")));

    mAdd_gigEvent_btn = findViewById(R.id.add_gigEvent_btn);
    mAdd_gigEvent_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            beenClicked();
        }
    });
}

public void beenClicked() {
    mDatabase = FirebaseDatabase.getInstance().getReference().child("gigevents");

    gigEvent = new GigEvent();

    mBand_name_editText = findViewById(R.id.add_band_name_editText);
    mVenue_name_editText = findViewById(R.id.add_venue_name_editText);
    mDate_editText = findViewById(R.id.add_date_editText);
    mTime_editText = findViewById(R.id.add_time_editText);

    String venue_name = mVenue_name_editText.getText().toString();
    getVenueZipcode(venue_name);

    Toast.makeText(AddGigEvent.this, "Gig/Event added!",
            Toast.LENGTH_LONG).show();

    startActivity(new Intent(AddGigEvent.this, Search.class));
}

public void getVenueZipcode(String name) {
    final Query venue_query;
    final String v_name = name;
    final String[] zipcode = new String[1];

    final DatabaseReference mVenueDatabase =
            FirebaseDatabase.getInstance().getReference().child("venues");
    venue_query = mVenueDatabase.orderByChild("uid");
    venue_query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if(snapshot.child("name").getValue().toString().equals(v_name)) {
                    zipcode[0] = snapshot.child("venue_zipcode").getValue().toString();

                    System.out.println("zipcode[0] = " + zipcode[0]);

                    gigEvent.setGigAuth(userID);
                    gigEvent.setBand(mBand_name_editText.getText().toString());
                    gigEvent.setVenue(mVenue_name_editText.getText().toString());
                    gigEvent.setDate(mDate_editText.getText().toString());
                    gigEvent.setTime(mTime_editText.getText().toString());
                    gigEvent.setZipcode(zipcode[0]);

                    mDatabase.child(userID).setValue(gigEvent);

                    return;
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}


text:
Q: multicolor text on chart Greetings,
I need to display multicolor text on my chart for example
early <- 30
ontime <- 70
late <- 25

txt <- paste(early, ontime, late, sep='/')
plot(1:2, type='n')
text(1.5, 1.5, txt)

I need values for early, ontime, late in txt, be blue,green, and red respectively.
I found following post on multicolor text in title, however I wasn't able to adapt it to my problem
http://blog.revolutionanalytics.com/2009/01/multicolor-text-in-r.html
Thank you for your help

A: How about this code written by Jim Lemon?
concat.text<-function(x,y,txt,col) {
    thisx<-x
    for(txtstr in 1:length(txt)) {
        text(thisx,y,txt[txtstr],col=col[txtstr],adj=0)
        thisx<-thisx+strwidth(txt[txtstr])
    }
}
plot(0,xlim=c(0,1),ylim=c(0,1),type="n")
ctext<-c("Roses are ","red, ","violets are ","purple")
concat.text(0,0.5,ctext,col=c("black","red","black","purple"))

A: Following the exampe you mentioned would give something like:
early <- 30
ontime <- 70
late <- 25

txt <- paste(early, ontime, late, sep='/')
plot(1:2, type='n')
vars <- list(early=early,ontime=ontime,late=late)
cols <- c('red', 'green', 'blue')
for (i in 1:3) {
    tmpvars <- vars
    tmpvars[-i] <- paste("phantom(",tmpvars[-i],")",sep="")
    expr <- paste(tmpvars, collapse="*")
    text(1.5, 1.5,
        parse(text=expr),
        col=cols[i])
}


text:
Q: ¿Como editar archivos en PowerShell? Expertos en PowerShell necesito de su apoyo.
Tengo en un archivo la siguiente información:
nombre_comando           valor
--------------           -----
systemctl                enable crond
systemctl                disable avahi-daemon
systemctl                disable dhcpd

Lo que quiero es editar el archivo anterior para escribirla en otro archivo de la siguiente manera:
systemctl = enable crond
systemctl =  disable avahi-daemon
systemctl = disable dhcpd

¿se puede? toda la ayuda sera valorada  y agradecida saludos les dejo mi intento aquí abajo pero no me funciona:
$argumento= "="
foreach($line in Get-Content .\procesos.txt) {
  $array = $line.split(" ")
  foreach ($char in $array) {
    $char+$argumento >> archivo.txt
  }
}

A: Puedes probar con lo siguiente:
$argumento= "="
$arrayRaw = Get-Content .\procesos.txt
$array = $arrayRaw[2..$arrayRaw.Count] -replace '\s\s+', ','
foreach($line in $array) {
    $element = $line.split(",")
    $element[0] $argumento $element[1] >> archivo.txt
}


text:
Q: MongoDb - $lookup with where clause given something like this:
posts:
post: {
 subject: 'test',
 category: 123,
 author: 1
}

users:
{
 id: 1,
 name: 'foo'
}

category:
{
 id: 123,
 name: 'bar'
}

How can I do the equivalent query to the sql:
SELECT *
FROM posts
JOIN users on posts.author = user.id
JOIN category on posts.category = category.id
WHERE users.name = 'foo' and category.name = 'bar' //this is the problem

I have been experimenting with project / lookups, but I have no idea how to add the 'where' in the lookup itself (or if that is even the proper way to query this.
db.posts.aggregate(
[
    {
        $project: { 'subject': '$subject' },
    },
    {
        $lookup: {
            from: 'users',
            localField: 'author',
            foreignField: 'id',
            as: 'test'
        }
    },
])

A: You have to use two $lookup
[
  {
    "$lookup": {
      "from": "users",
      "localField": "post.author",
      "foreignField": "id",
      "as": "userJoin"
    }
  },
  {
    "$lookup": {
      "from": "category",
      "localField": "post.category",
      "foreignField": "id",
      "as": "categoryJoin"
    }
  },
  {
    $match: {
      "categoryJoin.name": "bar",
      "userJoin.name": "foo"
    }
  }
]

Working Mongo playground


text:
Q: How to I force lock escalation (to flush out deadlock issues) during testing? Posting the question and one answer here. Maybe somebody has better answer...
It's possible to write code that triggers a deadlock even for a single user if the developer accidentally opens up a second connection to the database instead of reusing the an existing one (which might already have an open transaction). Certain O/RM and LINQ frameworks make this mistake easy.
Here is the scenario in pure SQL terms:
--Setup:
CREATE TABLE Vendors(VendorID int NOT NULL, VendorName nvarchar(100) NOT NULL, ExtraColumn int not null, CONSTRAINT PK_Vendors PRIMARY KEY CLUSTERED(VendorID))
GO
INSERT INTO Vendors(VendorID,VendorName,ExtraColumn) VALUES (1, 'Microsoft', 12345)
INSERT INTO Vendors(VendorID,VendorName,ExtraColumn) VALUES (2, 'Oracle', 12345)

--Connection 1:
BEGIN TRANSACTION
UPDATE Vendors SET ExtraColumn = 222 WHERE VendorID = 2

--Connection 2:
BEGIN TRANSACTION
SELECT VendorName FROM Vendors WHERE VendorID = 1

This code (and the c#/java/ORM/LINQ/whatever that generated it) might run happily in development/testing when the data is small, but suddenly deadlock when the data/memory profile changes in production and the lock escalates from row to page to table.
So how can I force lock escalation up to table level in my test environment so I can flush out any bugs like this (where the code opens up the 2nd connection)?
Lock escalation is completely controlled by the SQL Server database engine and it's not possible to predict when it will escalate from row lock to table lock. I won't rehash all the details which you can find here, but one in particular to note: "Lock escalation is triggered when...The number of locks in an instance of the Database Engine exceeds memory or configuration thresholds." This means that it could be completely unrelated to my carefully-crafted code and perfectly-selected indices.

A: One approach is to:

*

*In the test environment, run a script like the following to disable row and page locking on all indexes (making it go directly to table lock)

*Run the tests

*Run the script again setting it back to normal locking

--
-- Script to disable/enable row & page locking on dev/test environment to flush out deadlock issues
-- executes statement like this for each table in the database:
-- ALTER INDEX indexname ON tablename SET ( ALLOW_ROW_LOCKS  = OFF, ALLOW_PAGE_LOCKS  = OFF )
--
-- DO NOT RUN ON A PRODUCTION DATABASE!!!!
--
set nocount on
declare @newoption varchar(3)
--------------------------------------------------------------------
-- Change variable below to 'ON' or 'OFF' --------------------------
--   'OFF' means row & page locking is disabled and everything
--      triggers a table lock
--   'ON' means row & page locking is enabled and the server chooses
--     how to escalate the locks (this is the default setting)
set @newoption = 'OFF'
--------------------------------------------------------------------

DECLARE    @TableName varchar(300)
DECLARE    @IndexName varchar(300)
DECLARE @sql varchar(max)

DECLARE inds CURSOR FAST_FORWARD FOR
SELECT tablename, indname
FROM (
    select top 100 percent
    so.name as tablename
         , si.indid
         , si.name as indname
         , INDEXPROPERTY( si.id, si.name, 'IsPageLockDisallowed') as IsPageLockDisallowed
         , INDEXPROPERTY( si.id, si.name, 'IsRowLockDisallowed') as IsRowLockDisallowed
    from   sysindexes si
    join sysobjects so on si.id = so.id
    where  si.status & 64 = 0
      and  objectproperty(so.id, 'IsMSShipped') = 0
      and si.name is not null
      and so.name not like 'aspnet%'
      and so.name not like 'auditLog%'
    order by so.name, si.indid
) t

OPEN inds
FETCH NEXT FROM inds INTO @TableName, @IndexName

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @sql = 'ALTER INDEX [' + @IndexName + '] ON [dbo].[' + @TableName + '] SET ( ALLOW_ROW_LOCKS  = ' + @newoption + ', ALLOW_PAGE_LOCKS  = ' + @newoption +' )'
    PRINT @sql
    EXEC(@sql)

    FETCH NEXT FROM inds INTO @TableName, @IndexName
END

CLOSE inds
DEALLOCATE inds

PRINT 'Done'

Other notes:

*

*I got the core of the above script from somebody else's article, but I've long-since forgotten where. Apologies for the lack of attribution.

*Note that the above script will overwrite any existing custom lock escalation settings on your tables. You can check for these by first running the inner select ("SELECT TOP 100 PERCENT so.name...") to see the existing settings.


text:
Q: How do I use manifest.mf to contain correct location of the main class? Can anyone help me with this? I have not been able to find anything that answers this for exactly what I need. All the answers I find have to do with adding additional libraries to manifest files and what not.
Here's the situation:
I have written a game using NetBeans 6.9. The game is in Java. There are about 80 classes. All classes are contained in the default package. The game executes correctly. I've been working on this project for about 18 months and I always maintain executable code as I have developed the game.
What I did:
I needed to import something from a static class I'd written, into another class I was working on. In order to do that, I had to move everything out of the default package. I used NetBeans to refactor everything into a custom package.
What happened:
When I do a "clean and build", the project builds successfully.
When I do a "run main project", I get the following error:
java.lang.NoClassDefFoundError: WarMachine
Caused by: java.lang.ClassNotFoundException: WarMachine
...stack trace
Could not find the main class: WarMachine. Program will exit.
I have checked the .jar file and I see that all the compiled .class files are there, including the main class (called WarMachine.class). All the .class files are in a directory called Machine (that was the package name I had NetBeans refactor everything into).
From what I have been able to find on the internet, the problem is that my manifest.mf file does not point to the correct location of the WarMachine.class file.
What does my manifest file need to say? I don't use any other libraries or anything like that. I have 78 classes, all of which are in the "Machine" package. Can anyone help me?
Thanks for your time!

A: You have to tell Netbeans where the main class file is. Right click on your project, select "Properties", then go to the "Run" tree element on the left.
You will now have a "Main Class" textbox on the right. Click "Browse" and select your main class. Netbeans should then fix the manifest file for you.

In case you are curious, your manifest file inside the .jar file of the dist folder should have a line like this:
Main-Class: Machine.WarMachine

As an aside, it is considered standard practice to use lowercase letters for package names. You should call your package machine.


text:
Q: Angular directive check element? I'm hooking up a $modal service for confirmation boxes in my app and made a directive that only works for ng-click. Well I also need it to work for ng-change so I did it like the following:
.directive('ngConfirmClick', ['$modal',
    function($modal) {
        var ModalInstanceCtrl = function($scope, $modalInstance) {
            $scope.ok = function() {
                $modalInstance.close();
            };
            $scope.cancel = function() {
                $modalInstance.dismiss('cancel');
            };
        };

    return {
        restrict: 'A',
        scope:{
            ngConfirmClick:"&",
            item:"="
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
            var message = attrs.ngConfirmMessage || "Are you sure ?";

            if(element == 'select'){
                var modalHtml = '
' + message + '
';
                    modalHtml += '
<button class="btn btn-success" ng-model="" ng-change="ok()">OK</button><button class="btn btn-warning" ng-change="cancel()">Cancel</button>
';
                } else {
                    var modalHtml = '
' + message + '
';
                        modalHtml += '
<button class="btn btn-success" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button>
';
                }

            var modalInstance = $modal.open({
                template: modalHtml,
                controller: ModalInstanceCtrl
            });

            modalInstance.result.then(function() {
                scope.ngConfirmClick({item:scope.item});
            }, function() {
            });
        });
      }
    }
  }
]);

You can see I'm trying to check if the element is a 'select' element but I'm not sure how angular's link method/function reads the element. Can I check it with a string like how I did it? (It doesn't work when I try this btw).
How can I check if the element I'm attaching my directive to is a select?

A: Angular's jqLite is a subset of jQuery and that is the element parameter passed into the link function (unless you load the full jQuery library, then it will be a jQuery object). As described in this post using element.prop('tagName') will return the element type which is a method included in the jqLite library.

A: So I got confused and the if statement should of been at the element.bind not at the var modalHtml...
Here's the updated code for me to get this to work with both ng-change and ng-click. I just added bind on click and bind on change with an if statement to check the element.context.tagName was select or not
directive('ngConfirmClick', ['$modal',
    function($modal) {
        var ModalInstanceCtrl = function($scope, $modalInstance) {
            $scope.ok = function() {
                $modalInstance.close();
            };
            $scope.cancel = function() {
                $modalInstance.dismiss('cancel');
            };
        };

    return {
        restrict: 'A',
        scope:{
            ngConfirmClick:"&",
            item:"="
        },
        link: function(scope, element, attrs) {

            console.log(element.context.tagName);

            if(element.context.tagName == 'SELECT'){
                    element.bind('change', function() {
                    var message = attrs.ngConfirmMessage || "Are you sure ?";

                    var modalHtml =  '

 Please Confirm

' + message + '
';
                        modalHtml += '
<button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button>
';

                    var modalInstance = $modal.open({
                        template: modalHtml,
                        controller: ModalInstanceCtrl
                    });

                    modalInstance.result.then(function() {
                        scope.ngConfirmClick({item:scope.item});
                    }, function() {
                    });
                    });
                } else {
                    element.bind('click', function() {
                    var message = attrs.ngConfirmMessage || "Are you sure ?";

                    var modalHtml =  '

 Please Confirm

' + message + '
';
                        modalHtml += '
<button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button>
';

                    var modalInstance = $modal.open({
                        template: modalHtml,
                        controller: ModalInstanceCtrl
                    });

                    modalInstance.result.then(function() {
                        scope.ngConfirmClick({item:scope.item});
                    }, function() {
                    });
                    });
                }

            }
        }
    }
]);


text:
Q: Transforming Perl Hash to c# keyvaluepair I have a perl script that calls a c# exe. I have the need to pass a datastructure like this
 testA => 123, testB => 111 etc

I need to construct this variable in perl and pass it to my c# exe as a command line parameter.
I chose do store this value as hash in perl and keyvaluepair in c#.
So, in perl code, I am constructing
 %test_id

I am having trouble passing it to the program. I tried few things, but it seems like there is some parsing needed on both sides. Like convert hash to string; and then convert string to kvp on c# side. Is this expected or is there a better way to do this.
Here is one approach I tried.
 for(keys %ids)
{
     my $key = join (":", $_, $ids{$_});
     $name = join (";", $key, $name);
}

I called c# exe with
 UpdateCode.exe -add $name;

which will be like
 UpdateCode.exe -add "testA:123;testB:111"

So, when c# code sees this. I have to do
   string[] splits = args[1].split(new char[] {';'});

  foreach(string split in splits)
  {
     //You get the idea
     //split again and construct KVP
   }

Seems like lot of code. Is there a better way? I tried Dumper in perl module, but even with that I would need parsing on c# side.
Thanks for looking

A: Use JSON.
There are equivalent libraries in C# to decode the serialized data.
use strict;
use warnings;

use JSON;

my %test_id = ( testA => 123, testB => 111 );

print encode_json(\%test_id);

Outputs:
{"testA":123,"testB":111}


text:
Q: External battery pack not working with laptop I have an HP ProBook 4540s that has a very weak battery from years of use and abuse. I bought an external battery pack, a Poweradd 32000mAh with the intention of using it with my laptop. The battery works just fine when I use it to power a Lenovo IdeaCentre Q190. The voltage required by the Lenovo IdeaCentre is 19V, and my HP ProBook requires 19.5V. The battery is capable of outputting both of these (apparently the battery detects if you need slightly more than 19, according to customer support). Why can I not get the battery to work with my laptop? Whenever I plug the battery in to my laptop when it is running, I get the following error message and the "battery charging" light blinks several times:

I have also tried tried turning off my laptop, pulling the on-board battery, and booting directly from this battery. When I try that, the "battery charging" light blinks a few times and then stops, failing to do anything more. I have also tried the same two tests on two other HP laptops in my house, and the only difference is that on the other laptops, the Smart Adapter message does not appear.
Here is the adapter for my laptop's charger:

A: HP is a total stickler when it comes to OEM batteries and external battery packs (ie: chargers). The reason it works on your Lenovo is because it simply works. There's nothing "wrong" with your external battery pack. The issue is with HP's manufactured firmware.
HP often doesn't charge the internal battery if it detects that the AC Power adapter isn't HP OEM. My personal experience (hundreds of HP's) has been that it will, sometimes, still provide power but not before prompting, through P.O.S.T., that the adapter isn't OEM and may not function properly.
I'm confident this is the issue you're running into. HP only wants you buying HP stuff so they program to detect only their devices (battery and chargers) and limit anything else. Clearly the device works if you can get to the screen you posted. Your HP computer also knows you're not using an OEM device, based on their prompt. From there, HP just doesn't let the device do it's thing and claims it's "not functioning properly."
EDIT: The same can be said for Dell and Apple products.


text:
Q: Care to check what is wrong with my C code I yet again face an error message from this compiler in my online class. I have no idea what this syntax error might be since I've gone trough the code several times and it's almost identical with the example code given in the chapter I'm working on. I thought fresh experienced eyes could spot what I'm missing here
 all tough it might be something completely stupid
EDIT: The error message is just syntax error
"
There is a syntax error in the source code
Check, if you have forgotten a semicolon from the end of a line.
Check the source code near {. "
EDIT2: Yeah it was the lacking ")" thanks for the quick help again!
#include <stdio.h>
int main(void)
{
int i ;
FILE *kirj_tied ;
char luettelo[] = "luettelo.txt";

struct henkilo
{
    char etunimi[21];
    char sukunimi[21];
    char numero[21];
};

struct henkilo henkilo_lista[50];

for (i=0 ; i < 50 ; i++)
{
    printf("Anna etunimi:\n");
    scanf("%s",henkilo_lista[i].etunimi);
    printf("Anna sukunimi:\n");
    scanf("%s",henkilo_lista[i].sukunimi);
    printf("Anna puhelinnumero:\n");
    scanf("%s",henkilo_lista[i].numero);
}

if ((kirj_tied = fopen(luettelo,"w") == NULL)
    {
        printf("Virhe tiedoston avaamisessa.");
        return 0 ;
    }
else
    {
        for(i=0 ; i<50 ; i++)
        {
            fprintf(kirj_tied,"%s %s %s\n", henkilo_lista[i].etunimi,henkilo_lista[i].sukunimi,henkilo_lista[i].numero);
        }
    }

    fclose(kirj_tied);
    printf("Tietojen tallennus onnistui.");
    return 0 ;
}

A: The line
if ((kirj_tied = fopen(luettelo,"w") == NULL)

is missing a parenthesis perhaps? Should be:
if ((kirj_tied = fopen(luettelo,"w")) == NULL)

A: You are missing a right paren ()) on the line with the if-statement.
It should read
if ((kirj_tied = fopen(luettelo, "w")) == NULL) {
                                     ^ that one

Running a code indenter over the code would have flagged this.  Most compilers would have given you a more helpful error message.
The Clang compiler, for example, says
prog.c:28:5: error: expected ')'
    {
    ^
prog.c:27:4: note: to match this '('
if ((kirj_tied = fopen(luettelo,"w") == NULL)
   ^


text:
Q: Dapper using ODBC store procedure Input parm always promt @XXX was not supplied I need help from All Dapper master.
I have been learning using Dapper since one month ago, but I have error when executing query using ODBC SP.
The code originally was written by someone(DapperExample) but not using ODBC, thanks to the writer I forgot your name.
My SP:
CREATE PROCEDURE SP_GET_FIND_EMPLOYEES (@EmpID INT)
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * FROM tblEmployee WHERE EmpID = @EmpID
END
GO

My Code
public class EmployeeDashBoard : IEmployeeDashBoard
    {
    private IDbConnection _db;
    string connStr2 = WebConfigurationManager.ConnectionStrings["DapperExample"].ConnectionString;

    public EmployeeDashBoard()
    {

    }

    public Employee Find(int id)
    {

        //type b, by sp
        using (IDbConnection connection = new OdbcConnection(connStr2))
        {

            var p = new DynamicParameters();

                p.Add("@EmpID", id);

            Employee result = this._db.Query<Employee>("dbo.SP_GET_FIND_EMPLOYEES", new { @EmpID = id }, commandType: CommandType.StoredProcedure).Single();
            return result;

        }

    }

}

Error:
ERROR [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Procedure or function 'SP_GET_FIND_EMPLOYEES' expects parameter '@EmpID', which was not supplied.
Thanks in Advance.
Masa Sih

A: I Solved by my self, I'm using Sybase ODBC SP, ( God Job Sam ), now I can avoid entity framework in the feature.
Here the tricks:

Solved: SP_GET_FIND_EMPLOYEES ?

        using (IDbConnection connection = new OdbcConnection(connStr2))
        {

            var p = new DynamicParameters();

            p.Add("?EmpID?", id.ToString());

            Employee result = this._db.Query<Employee>("dbo.SP_GET_FIND_EMPLOYEES ?", p, commandType: CommandType.StoredProcedure).Single();
            return result;
        }

A: Your implementation for ODBC named parameters is incorrect. You encase the named parameter with question marks in your statement and create the named parameter without the question marks. The question marks are used by Dapper to parse the statement to find the names.
p.Add("EmpID", id.ToString());
Employee result = this._db.Query<Employee>("dbo.SP_GET_FIND_EMPLOYEES ?EmpID?", p, commandType: CommandType.StoredProcedure).Single();

See this answer for more information: https://stackoverflow.com/a/26484944/6490042


text:
Q: inheriting ostream and streambuf problem with xsputn and overflow I have been doing research on creating my own ostream and along with that a streambuf to handle the buffer for my ostream.  I actually have most of it working, I can insert (<<) into my stream and get strings no problem.  I do this by implimenting the virtual function xsputn.  However if I input (<<) a float or an int to the stream instead of a string xsputn never gets called.
I have walked through the code and I see that the stream is calling do_put, then f_put which eventually tries to put the float 1 character at a time into the buffer.  I can get it to call my implementation of the virtual function overflow(int c) if I leave my buffer with no space and thereby get the data for the float and the int.
Now here is the problem, I need to know when the float is done being put into the buffer.  Or to put it another way, I need to know when this is the last time overflow will be called for a particular value being streamed in.  The reason xsputn works for me is because I get the whole value up front and its length.  So i can copy it into the buffer then call out to the function waiting for the buffer to be full.
I am admittedly abusing the ostream design in that I need to cache the output then send it all at once for each inputted value (<<).
Anyways to be clear I will restate what I am shooting for in another way.  There is a very good chance I am just going about it the wrong way.
I want to use an inherited ostream and streambuf so I can input values into it and allow it to handle my type conversion for me, then I want to ferry that information off to another object that I am passing a handle down to the streambuf to (for?).  That object has expensive i/o so I dont want to send the data 1 char at a time.
Sorry in advance if this is unclear.  And thank you for your time.

A: It's not too clear what you're doing, although it sounds roughly
right.  Just to be sure: all your ostream does is provide
convenience constructors to create and install your streambuf,
a destructor, and possibly an implementation of rdbuf to
handle buffers of the right type.  Supposing that's true:
defining xsputn in your streambuf is purely an optimization.
The key function you have to define is overflow.  The simplest
implementation of overflow just takes a single character, and
outputs it to the sink.  Everything beyond that is optimization:
you can, for example, set up a buffer using setp; if you do
this, then overflow will only be called when the buffer is
full, or a flush was requested.  In this case, you'll have to
output buffer as well (use pbase and pptr to get the
addresses).  (The streambuf base class initializes the
pointers to create a 0 length buffer, so overflow will be
called for every character.)  Other functions which you might
want to override in (very) specific cases:
imbue: If you need the locale for some reason.  (Remember that
the current character encoding is part of the locale.)
setbuf: To allow client code to specify a buffer.  (IMHO, it's
usually not worth the bother, but you may have special
requirements.)
seekoff: Support for seeking.  I've never used this in any of
my streambufs, so I can't give any information beyond what
you could read in the standard.
sync:  Called on flush, should output any characters in the
buffer to the sink.  If you never call setp (so there's no
buffer), you're always in sync, and this can be a no-op.
overflow or uflow can call this one, or both can call some
separate function.  (About the only difference between sync
and uflow is that uflow will only be called if there is
a buffer, and it will never be called if the buffer is empty.
sync will be called if the client code flushes the stream.)
When writing my own streams, unless performance dictates
otherwise, I'll keep it simple, and only override overflow.
If performance dictates a buffer, I'll usually put the code to
flush the buffer into a separate write(address, length)
function, and implement overflow and sync along the lines
of:
int MyStreambuf::overflow( int ch )
{
    if ( pbase() == NULL ) {
        // save one char for next overflow:
        setp( buffer, buffer + bufferSize - 1 );
        if ( ch != EOF ) {
            ch = sputc( ch );
        } else {
            ch = 0;
        }
    } else {
        char* end = pptr();
        if ( ch != EOF ) {
            *end ++ = ch;
        }
        if ( write( pbase(), end - pbase() ) == failed ) {
            ch = EOF;
        } else if ( ch == EOF ) {
            ch = 0;
        }
        setp( buffer, buffer + bufferSize - 1 );
    }
    return ch;
}

int sync()
{
    return (pptr() == pbase()
            || write( pbase(), pptr() - pbase() ) != failed)
        ? 0
        : -1;
}

Generally, I'll not bother with xsputn, but if your client
code is outputting a lot of long strings, it could be useful.
Something like this should do the trick:
streamsize xsputn(char const* p, streamsize n)
{
    streamsize results = 0;
    if ( pptr() == pbase()
            || write( pbase(), pptr() - pbase() ) != failed ) {
        if ( write(p, n) != failed ) {
            results = n;
        }
    }
    setp( buffer, buffer + bufferSize - 1 );
    return results;
}


text:
Q: How can you insert a div into another created in javascript So I'm trying to insert one div into another both created with Javascript
I have the following code,
// Assign tool attributes to Javascript Variables
    var tool_name = String(tool['tool_name']);
    tool_name = tool_name.replace(/'/g, '');
    var tool_inventory_number = String(tool['tool_inventory_number']);
    tool_inventory_number = tool_inventory_number.replace(/'/g, '');
    var tool_recnum = String(tool['tool_recnum']);
    tool_recnum = tool_recnum.replace(/'/g, '');

// Create the divs for the search results
    var toolDiv = document.createElement("div");
    var toolDivPicture = document.createElement("div");
    //todo: Insert picture into this toolDivPicture div
    var toolDivDescription = document.createElement("div");
    toolDivDescription = toolDivDescription.innerHTML + "
" + tool_name + "
" + "
" + "Inventory Number: " + tool_inventory_number;

// Assign class to search result toolDiv and add content to it.
    toolDiv.className = "toolDiv";
    toolDiv.appendChild(toolDivDescription);

I keep getting the following error,
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
Could this be because I have to refrence the child div by id? I really just want to have javascript create a div that contains two other divs and then insert it into the page. Any help/suggestions are appreciated!

A: Since you marked the question with the jQuery tag, I assume that you have the jQuery library loaded:
// Create the divs for the search results
var toolDiv = $("
");
var toolDivPicture = $("
");
var toolDivDescription = $("
");
toolDivDescription.html("
" + tool_name + "
" + "
" + "Inventory Number: " + tool_inventory_number);

// Assign class to search result toolDiv and add content to it.
toolDiv.addClass("toolDiv");
toolDiv.append(toolDivDescription);

Note that you start a h2 but end a h3.
jsFiddle

A: Try this:
Wrap up your JavaScript in an onload function. So first add:

Then put your javascript in the load function, so:
function loadJS() {
    // Assign tool attributes to Javascript Variables
    var tool_name = String(tool['tool_name']);
    tool_name = tool_name.replace(/'/g, '');
    var tool_inventory_number = String(tool['tool_inventory_number']);
    tool_inventory_number = tool_inventory_number.replace(/'/g, '');
    var tool_recnum = String(tool['tool_recnum']);
    tool_recnum = tool_recnum.replace(/'/g, '');

// Create the divs for the search results
    var toolDiv = document.createElement("div");
    var toolDivPicture = document.createElement("div");
    //todo: Insert picture into this toolDivPicture div
    var toolDivDescription = document.createElement("div");
    toolDivDescription = toolDivDescription.innerHTML + "
" + tool_name + "
" + "
" + "Inventory Number: " + tool_inventory_number;

// Assign class to search result toolDiv and add content to it.
    toolDiv.className = "toolDiv";
    toolDiv.appendChild(toolDivDescription);
}


text:
Q: How to check an object for a value Hey I created my first app in react native and i run into some trouble, i simple would like to know how i can check an object for an specific value from a local storage. This is what i have so far, i know its not that much.
handleClick = (item)=>{
store.get('myobject').then((res) =>
console.log(res)
)

this is my res object:
[
{ id: '456', p: 'hey' },
{ id: '464', p: 'ho' },
{ id: '467', p: 'lets' },
{ id: '263', p: 'go' }
]

and as example i would like to know, if id 467 is in the object.

A: You could make use of the some method of Array:

var res = [
    { id: '456', p: 'hey' },
    { id: '464', p: 'ho' },
    { id: '467', p: 'lets' },
    { id: '263', p: 'go' }
];

var found = res.some(item => item.id === '467');

console.log(found);

Essentially, as it is stated here

The some() method tests whether at-least one element in the array
  passes the test implemented by the provided function.

A: You could do a forEach loop and check for your desired value:

var res = [
{ id: '456', p: 'hey' },
{ id: '464', p: 'ho' },
{ id: '467', p: 'lets' },
{ id: '263', p: 'go' }
]

function containsCheck(array) {

  var found = false;

  array.forEach(function(element) {
    if (element.id === '467') {
      found = true;
    }
  });

 return found;

};

console.log(containsCheck(res));

A: As an alternative you can check Lodash This lib is a nice thing to have in a project when working with collections or objects.


text:
Q: Proper way to sanitize user input to insert in a Python SQLite table? I am developing a Python application that accepts three arguments then stores them into a database. The first two ("userID", "username") are grabbed automatically, although malicious SQL injection may be present in a username. The last, "location", is a zip code or city provided by the user, but I am treating this as a potential attack vector as well.
This is bad code, for some reason it is not replacing characters, but I will attempt to research and rewrite.
Example, let's set a variable as an SQL injection attack:
username = "'; select true; --" # or "location"
insert_data(userID, username, location)

def insert_data(userID, username, location):
    # Sanitize SQL input. The database is small, but this is good security practice

    # userID - must be 18 characters and only numbers
    if not str(userID).isdecimal() and len(userID) is not 18:
        raise Exception

    # username -
    # Should probably limit the length of the username here to avoid SQL errors
    # Will eventually convert this replace process to a function and repeat for "location"
    sqlBadChars = [";", "'", "=", "\\\\"] # and probably more
    slist = list(username) # make a list of the orig username
    for badChar in sqlBadChars: # for each bad char in the array...
        for i,c in enumerate(slist, start=0): # for each char letter,char in the list...
                if str(slist[i]) == str(badChar): # check if the character indexed is in blacklist
                        slist[i] = ' ' # replace with a space

    usernameNew = ''.join(slist) # finally, join the processed list

I've read many articles here on StackOverflow, Google, OWASP even, but I'm not exactly sure what are the best practices.
I'm also not understanding how these examples work:
Both safe examples return sqlite3.OperationalError: near "%": syntax error
# SAFE EXAMPLES. DO THIS!
cursor.execute("SELECT admin FROM users WHERE username = %s'", (username, ));
cursor.execute("SELECT admin FROM users WHERE username = %(username)s", {'username': username});

# BAD EXAMPLES. DON'T DO THIS!
cursor.execute("SELECT admin FROM users WHERE username = '" + username + "'");
cursor.execute("SELECT admin FROM users WHERE username = '%s'" % username);
cursor.execute("SELECT admin FROM users WHERE username = '{}'".format(username));
cursor.execute(f"SELECT admin FROM users WHERE username = '{username}'");

As far as I know, they do almost the same thing, I'm just not aware of the differences?


text:
Q: Wordpress - wp-admin showing blank Every part of my web site is working fine after I moved it from one hosting to another. The problem I have now is that I can't access wp-admin.
I now get the following error:
Warning: Cannot modify header information - headers already sent by (output started at /home/everd1/public_html/precision/wp-content/themes/Avada/Avada/admin/functions/functions.options.php:1) in /home/everd1/public_html/precision/wp-includes/pluggable.php on line 1121

So far I've tried:

*

*Removing trailing white space before and after functions.php and pluggable.php

*Increasing the allowed memory size on the .htaccess file

*Creating a php.ini within the wp-admin folder with the following memory_limit = 64M ;

*Renamed the plugins folder to plugins-removed

Still no joy, anything I can do to fix this?

A: The warning that you have posted shows the exact error and the place that it is happening.
It looks like something within the Avada theme has broken when you were transfering it and it has since messed up the headers being sent through.
Only 1 set of headers can be sent to the client otherwise it cannot be handled and therefore throws an error.
I would recommend going to the theme creators (click here) and putting in a support ticket. One of their support team should be able to fix the problem that you are having.

A: You can check if some file of your Wordpress copy contains UTF-8 with BOM files and convert it to UTF-8 without BOM.
You can try this php script to make it faster : https://github.com/emrahgunduz/BomCleaner
Be sure to make a backup before running it.


text:
Q: C чего начать изучение JS? Всем привет! Я новенький, но действительно хочу заняться этим делом. Я выбрал язык JS потому что для него очень легко найти применение и также легко связать с веб дизайном. Недавно скачал книгу с носорожком на обложке по JS, также немного помогал друг. Но сейчас друг не может этого делать и поэтому у меня вопрос: есть ли какие-нибудь достаточно легкие и простые в освоении уроки? Желательно, чтоб они были с примерами и детальными описаниями всего. Я действительно готов заняться изучением по-полной, поэтому кидайте всё (ну только хорошее, конечно же), что у вас есть. Другие языки не предлагать. Носорожек написан на слишком научном языке и с какой-то стремной систематизацией. В общем, это всё. Спасибо заранее. Жду ответов!
A: Друг мой, все элементарно, качай сразу книг 20 ( как я и сделал) . Плюс прикупил еще 3 за нормальные деньги. Если че-то не соображал в одной книге - переходил на другую. С течением времени - блин!- все удалось! Но для этого нужны не протухший мозг и желание программировать. А то, что тебе говорят про php - чушь. Веб-программист должен знать как минимум яваскрипт и пхп. Потому что js - язык сценариев, а пхп - серверный язык и исполняется только на стороне сервера )) Вперед!
A: Я тоже недавно начал изучать JavaScript по "Носорогу". Книга то что надо, также использую оригинал на английском языке. Также есть очень хороший учебник на сайте Mozilla:  https://developer.mozilla.org/en/javascript/guide. Если английский вызывает трудности, то лучше сменить профессию, т.к. для программиста он должен быть вторым родным, ИМХО.
С практикой немного сложнее, но дорогу осилит идущий
A: Книга с носорогом - крутая книга. И хорошая в изучении. Хочется не по научному,- не та профессия. Лучшее изучение - практика. Когда что-то надо и не знаешь, лезешь в книгу. Через некоторое время, после самостоятельного решения некоторого количества задач, будете шире мыслить и осваивать более отдаленные высоты. И вообще, быстрее всего научитесь, когда возьмете реальный проект за деньги, и начнете стараться выполнить его в срок, как угодно. В общем, попу рвать. Тогда много нового узнаете. И из книги, и из форумов и вообще, откуда угодно. Может вы очень усидчивы, тогда самоучитель. После изучения которого, принявшись за реальную практику, вы поймете, что почти ничего не знаете. Но зато что-то есть. А если вы уже знаете, как открывать браузер и выводить сообщение, то уже можно выполнять реальные проекты. Небольшие только.
A: Для меня лучшая книга:

Beginning JavaScript Paul Wilton
Jeremy McPeak Third Edition

От издательства Wrox
, у меня перевод этой книги

Пол Вилтон Джереми МакПик Java Script
Руководство программиста

от издательства Питер.
У меня эта книга. Я вам её очень советую и (особенно для дизайна) это самый лучший учебник imho
A: Можно и отсюда - http://www.codecademy.com/ru/courses/javascript-beginner-jMOGH-ru
Правда тут уж все ну совсем просто, но если вы только начинаете - самое то.
A: Как можно отговаривать от изучения JavaScript? Мол C++ или PHP лучше учи! На стороне клиента в браузере всегда исполняется JS, а не С и не ПХП. Хочешь, не хочешь, но учи JS! Браузер IE поддерживает еще бейсик-скрипт. При установленном ActivePerl в windows и perl браузером поддерживается, но JS везде, даже в PDF!


text:
Q: Is there a way to return job status explicity through Livy? I need to return back "DEAD"/"FAIL" to the job "status" if the pyspark job matches a certain condiftion.
Example:
from pyspark.sql import SparkSession
spark = SparkSession.builder\
    .master("yarn")\
    .appName("IDL") \
        .getOrCreate()
for i in range(0,10):
    if i ==5:
         print("Bye " + str(i))
         #Exit the program and return status code

The return has to be explicity done through the pyspark program. Depending on the status, the next pyspark job would run.
Job Submit:
curl -X POST --data '{"file": "/user/root/jsmith/test1.py"}' -H "Content-Type: application/json" localhost:8998/batches

Fetch Job status:
curl localhost:8998/sessions/7

Output of above command should have "state":"DEAD".

A: You can use something like below to get status explicitly from livy:
import requests
def get_status(self, job_id):
        status_url = 'https://{hdi_host}/livy/batches/{batch_id}'.format(hdi_host=self.hdi_host, batch_id=job_id)
        try:
            r = requests.get(status_url, verify=False, auth=self.auth)
            r.raise_for_status()
            return r.json()
        except Exception as e:
            print("Error in getting livy job status {}, error {}".format(status_url, e))
            return e

But if you want to build a pipeline around it, then you will have to use something like airflow or azkaban.


text:
Q: git-tfs: checkin command throw error policy I have a TFS repository on Azure DevOps Server Version 17.143.28621.4
I installed git-tfs V 0.30 downloaded from github.
I cloned the repository, and I am able to fetch, pull, commit and create shelveset.
I have trouble during the checkin operation:

On my pc I have installed both visual studio 2017 and 2019. I am currently able to checkin to TFS with visual studio.
What I tried:
I have read this troubleshooting page, but I can't understand what to do.
This is the result of git tfs info:

I have tried to execute the enable_checkin_policies_support.bat. The execution doesn't give error but the checkin command shows the same error.
I also checked, as the troubleshooting says, the registry keys but I didn't find what is shown in the troubleshooting page:

What am I missing?

A:
Currently able to checkin to TFS with visual studio.

According to this troubleshooting page, you should known that based on this, this issue caused can be narrow down to git-tfs could not find the check-in policy successfully.

According to your git tfs info, your TFS client library is 14 which is Visual Studio 2015.
In your PC, you said that the newest version of VS in your machine is 16.0 (Visual studio 2019). So, here the Git-tfs does not picking the same version of Visual Studio, because:

To tell the Git-tfs to use the specified client library, just go Control Panel, add a environment variable GIT_TFS_CLIENT, and assign its value as the visual studio 2015(in your scenario):


text:
Q: How to get rid of cursor highlight? I held down some key for too long while I was thinking and the Mac bleeped at me to intimate that some mode had been triggered, analogous to StickyKeys or FilterKeys on Windows.
Now, whenever I click, a yellow circle appears around my cursor - some sort of accessibility feature to show where my cursor is on the screen, I assume.
I've looked all over through the accessibility and trackpad settings but can't find how to toggle it off again.
How can I disable this feature?

A: It turned out this is from the Loom app. Quitting the app disabled it.


text:
Q: LDAP: how to search for user with windows id I need to authenticate a user using the windows ID which is not the same as the "user name".  For example: windows ID is jSmith but the user name is "Joe Smith".  I need to find Joe Smith based on the windows ID and then check if he is a member of a certain group.
I'm assuming or hoping that the windows ID is an attribute of the user but I'm new to the LDAP and don't know how to search for a specific attribute in all users.

A: I am assuming when you say Windows ID for authentication your LDAP is actually Active Directory.
If you just want to find the user by LanId in the Active Directory:

*

*connecting to the Active using an Admin/service account username and password.

*search for user with following filter:
"(&(objectClass=user)(sAMAccountName=" + searchUsername + "))"
If you want to authenticate the user:
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");// can make it variable, not needed so far
environment.put(Context.SECURITY_AUTHENTICATION, "simple"); // can make it variable, not needed so far
environment.put(Context.PROVIDER_URL, url);
environment.put(Context.SECURITY_PRINCIPAL, username + "@" + domain); // This is specific to AD
environment.put(Context.SECURITY_CREDENTIALS, password);

return new InitialLdapContext(environment, null);

If the above code is executed successfully without exception, that means user provided correct username/password


text:
Q: How to get url without query string like stackoverflow in jsp I have a jsp page, which url is:

http://localhost:8084/WebApplication1/newjsp.jsp

There is an anchor tag in it:

a href="MobileArticles?name=abcde"

web.xml specification:
<servlet-mapping>
    <servlet-name>MobileArticlesLinkerServlet</servlet-name>
    <url-pattern>/MobileArticles</url-pattern>
</servlet-mapping>

Here is the code for doGet in the servlet:
String respuesta = "Article_template.jsp";
    RequestDispatcher rd = request.getRequestDispatcher(respuesta);
    rd.forward(request, response);
It is getting redirected to a jsp page "Article_template.jsp".
The process is fine. But I need a different URL pattern for this page:
Current URL pattern: "http://localhost:8084/WebApplication1/MobileArticles?name=abcde"
And I want it like:
"http://localhost:8084/WebApplication1/MobileArticles/abcde"
Please help me how I can achieve this?

A: I found out one solution for it.
It may not be the correct way but it works for me.
The trick is:

*

*Servlet is not involved at all

*Set a url-pattern for your jsp page in web.xml
<servlet>
    <servlet-name>ArticleTemplate</servlet-name>
    <jsp-file>/Article_template.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>ArticleTemplate</servlet-name>
    <url-pattern>/ArticleTemplate/*</url-pattern>
</servlet-mapping>

*We have to call the JSP page directly from the anchor tag
Article Link

*Finally at the JSP page, we have to use scriptlets to access the java classes and fetch the data from the database.
<%
----- Your code -----
%>


text:
Q: Why can't object inside a Kotlin companion object be accessed "statically" when other members can? Given a Kotlin companion object
class A {
    companion object {
        val a = 0
        fun b() = 1
        object C {
            val d = 0
        }
    }
}

fun main(args: Array<String>) {
    println(A.a)
    println(A.b())
    println(A.C.d) // doesn't compile
    println(A.Companion.C.d)
}

Why is Companion required to access A.C when it isn't for a and b()?

A: This serves the purpose of disambiguating an object declared in a companion object from one declared directly in the class.
Note that the properties and functions defined in a class are not ambiguous with those from the companion object, because the former ones can only be called on an instance of the class. But a nested object can be referenced with the class name:
class A {
    object C {
        val d = 0
    }
}

println(A.C.d)


text:
Q: Remove items from collection in VBA I want to remove collA(1)(9, 0), collA(1)(9, 1), collA(1)(9, 2), collA(1)(9, 3), collA(1)(9, 4), collA(1)(9, 5) and collA(1)(9, 6).
The remove statement in the Sub Test() below doesn't work.
How can this problem be solved?
Sub Test()

    Dim A() As Integer
    Redim A(0 To 367907, 0 To  6) As Integer

    Dim i As Long
    Dim j As Integer

    For i = 0 To 367907
    For j = 0 To 6
        A(i, j) = Worksheets("Sheet1").Cells(i + 1, j + 1)
    Next j
    Next i

    Dim collA As VBA.Collection

    Set collA = New Collection
    collA.Add A

    Erase A

    collA(1).Remove 10     '<--- This doesn't work

End Sub

A: You don't really need the array, you can add the values directly to the collection object. That's what its for :)
If you want then remove cell D2 from the collection you have to know it's index
So set up your sheet like this

then notice
your collection starts with number 1 and the first item added is cell A1, then second cell B1
therefore your index 10 is cell D2
use the below code to remove D2 from the collection
Sub Test()

    Dim c As Collection
    Set c = New Collection

    Dim i As Long, j As Long

    For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
        For j = 1 To 6
            c.Add Cells(i, j)
        Next j
    Next i

    For i = 1 To c.Count
        Debug.Print c.Item(i), "count: " & i, "total items: " & c.Count
    Next i

    c.Remove 10
    Debug.Print vbCrLf

    For i = 1 To c.Count
        Debug.Print c.Item(i), "count: " & i, "total items: " & c.Count
    Next i

End Sub

results in Immediate Window CTRL+G


text:
Q: attempted relative import beyond top-level package with boost/Python I've tried multiple ways to import a module in a post here, but I decided to post a new question since that post was about boost not being able to find the module. Here's the structure of the folder:
project
   |__ utilities
   |      |__ foo.py
   |
   |__ boost_extensions
   |      |__ myclass.cpp
   |      |__ myclass.so
   |
   |__ someotherstuff
   |      |__ bar.py
   |
   |__ mylib.py
   |
   |__ __main__.py

in foo.py, I have some code that imports from mylib.py:
from ..mylib import MyLib
class Foo:
    # code

in myclass.cpp, I could not find a way to import Foo using a relative path, so I used an absolute path (inspired from an answer to the post here):
boost::python::object mod;
void set_global(){
    boost::python::object importlib_util = import("importlib.util");

    boost::python::object spec = \
        importlib_util.attr("spec_from_file_location")("module.name",\
            "/home/username/projectfiles/project/utilities/foo.py");

    boost::python::object foo = importlib_util.attr("module_from_spec")(spec);
    mod = spec.attr("loader").attr("exec_module")(foo);
}

And this gave me an error:
    from ..mylib import MyLib
ValueError: attempted relative import beyond top-level package

How can I fix this?
Thanks
edit : not sure if this is relevant or not but if I print the variable __name__ it's always module.name, regardless of what I put in the code
# with ..utilities.foo instead of module.name in the function
# importlib_util.attr("spec_from_file_location")("module.name",\
#            "home/username/projectfiles/project/utilities/foo.py");
print(__name__)
from ..mylib import MyLib
#output : module.name

A: Your path on Linux should be "/home/username/projectfiles/project/utilities/foo.py". You are missing the first /.

A: I posted a similar question and the solution for that works here too (it was about trying to import a python module in C++ by using a relative path, I made a different post about it because it gave a completely different error). Basically I loaded the module in python and passed it as an argument to C++.


text:
Q: CSS Tooltip Overlap Issue I'm working with a simple CSS and HTML tooltip. The general gist of the layout is there are a number of images in a row, with several rows of these images. Each image has some text and a tooltip. When the mouse rolls over the image a tooltip appears. The problem is when the tooltip list appears the mouse-over does not extend to the bottom of the tooltip list. If the current open list overlaps the image in the next row below, the current tooltip will disappear as you roll your mouse down through it.
Here's a JSFiddle of what I'm talking about: https://jsfiddle.net/kxskzrsr/
If you roll over the first image a tooltip list will appear. If you try to scroll to the bottom of the tooltip list it will cut out and open the tooltip for the image below instead of staying open in the current tooltip.

.centre-profiles {
    margin: 0 auto;
    max-width: 1000px;
}

.team-pic {
    position:relative;
    background-color:#99C;
}

.team-name {
    line-height:40px;
    font-size:60%;
    padding-top:90px;
}

.bg-image-sm {
    display:inline-block;
    max-width:210px;
    max-height:150px;
    padding-right:15px;
}

.transparent-maroon  {
    position:absolute;
    color:#fff;
    background: rgba(119, 0, 0, 0.8);
    width:210px;
    text-align:center;
    height:40px;
    z-index:20;
    top:110px;
}

/* Tooltip text */

.bg-image-sm .tooltiptext-sm {
    visibility: hidden;
    width: 210px;
    background: rgba(255, 255, 255, 0.9);
    color: #000;
    font-size:50%;
    line-height:20px;
    text-align: center;
    padding: 5px 0;
    opacity: 0;

/* Position the tooltip text - see examples below! */
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -105px;
    opacity: 0;
    transition: opacity 1s;
    z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */

.bg-image-sm:hover .tooltiptext-sm {
    visibility: visible;
    opacity: 1;
}

        Name

        Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text Last

Tooltip text

        Name

        Tooltip text

Tooltip text

        Name

        Tooltip text

Tooltip text

        Name

        Tooltip text

Tooltip text

        Name

        Tooltip text

Tooltip text

        Name

        Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text Last
Tooltip text

A: This should work now, remove all z-indexing from your css, with the exception of .bg-image-sm .tooltiptext-sm
https://jsfiddle.net/kxskzrsr/3/

@charset "utf-8";
/* CSS Document */

.team-row {

}

.team-member {
 display:inline-block;
 max-width:210px;
 max-height:150px;

}

.team-pic {
 position:relative;
 background-color:#99C;

}

.transparent-red  {
 position:absolute;
 color:#fff;
 background: rgba(142, 0, 0, 0.8);
 width:210px;
 text-align:center;
 height:40px;
 /* z-index:20; */
 top:110px;
}

.team-name {
 line-height:40px;
 font-size:60%;
 padding-top:90px;

}

.team-title {
 line-height: 1px;
 font-size:40%;

}

/* Tooltip text */
.team-member .tooltiptext {
    visibility: hidden;
    width: 210px;
    background: rgba(255, 255, 255, 0.9);
    color: #000;
 font-size:50%;
 line-height:20px;
    text-align: center;
    padding: 5px 0;

    /* Position the tooltip text - see examples below! */
    position: absolute;
    /* z-index: 1; */
 top: 100%;
    left: 50%;
    margin-left: -105px;

 opacity: 0;
    transition: opacity 1s;

}

/* Show the tooltip text when you mouse over the tooltip container */
.team-member:hover .tooltiptext {
    visibility: visible;
 opacity: 1;
}

.centre-profiles {

 margin: 0 auto;
    max-width: 1000px;

}

/********  Code for smaller image with red overlay 210 x 150 ********/

.bg-image-sm {
 display:inline-block;
 max-width:210px;
 max-height:150px;
 padding-right:15px;
}

.transparent-maroon  {
 position:absolute;
 color:#fff;
 background: rgba(119, 0, 0, 0.8);
 width:210px;
 text-align:center;
 height:40px;
 /* z-index:20; */
 top:110px;
}

/* Tooltip text */
.bg-image-sm .tooltiptext-sm {
    visibility: hidden;
    width: 210px;
    background: rgba(255, 255, 255, 0.9);
    color: #000;
 font-size:50%;
 line-height:20px;
    text-align: center;
    padding: 5px 0;

 opacity: 0;

/* Position the tooltip text - see examples below! */
    position: absolute;
 top: 100%;
    left: 50%;
    margin-left: -105px;
 opacity: 0;
    transition: opacity 1s;
 z-index: 100 !important;

}

/* Show the tooltip text when you mouse over the tooltip container */
.bg-image-sm:hover .tooltiptext-sm {
    visibility: visible;
 opacity: 1;
}

Name

Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text Last

Tooltip text

Name

Tooltip text

Tooltip text

Name

Tooltip text

Tooltip text

Name

Tooltip text

Tooltip text

Name

Tooltip text

Tooltip text

Name

Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text Last
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text

Tooltip text
Tooltip text Last


text:
Q: Getting "Invalid server address" error while trying to fetch from Windows Server 2012 r2 I want to fetch user details from Active Directory of Windows Server 2012 r2 from Python Scripting... This code is showing Invalid server address. Any ideas?
import sys

from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES,
AUTO_BIND_NO_TLS, SUBTREE

from ldap3.core.exceptions import LDAPCursorError

server_name = 'MyServerName'

domain_name = 'MyDomainName'

user_name = 'MyName'

password = 'MyPassword'

format_string = '{:25} {:>6} {:19} {:19} {}'
print(format_string.format('Users', 'Logins', 'Last Login', 'Expires', 'Description'))

server = Server(server_name, get_info=ALL)
conn = Connection(server, user='{}\\{}'.format(domain_name, user_name), password=password, authentication=NTLM,auto_bind=True)
print(conn.result)

conn.search('dc={},dc=com'.format(domain_name), '(objectclass=User)',attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])

for e in conn.entries:
    try:
        desc = e.description
    except LDAPCursorError:
        desc = ""

print(format_string.format(str(e.name), str(e.logonCount), str(e.lastLogon)[:19], str(e.accountExpires)[:19], desc))


text:
Q: Python. How to create a local datetime with datetime.today() The server sends a string that I striptime and keep in a variable called here time_from_frontend and then add a tzinfo like this:
import pytz

my_timezone = pytz.timezone("America/Guayaquil")

A = time_from_frontend.replace(tzinfo=my_timezone)
print A
print A.tzinfo

B = (datetime.datetime.today()).replace(tzinfo=my_timezone)
print B
print B.tzinfo

print B - A

Why do I get a huge difference between A and B? Here is what the terminal prints:
2016-02-11 20:00:00-05:19
America/Guayaquil
2016-02-12 01:08:35.478507-05:19
America/Guayaquil
5:08:35.478507

The frontend is sending me the actual time, when I do datetime.today() and then specify the timezone, I thought I was gonna get a tiny difference between the A time and the B time (i.e microseconds), but I get 5 hours. which is the timezone difference ("America/Guayaquil" is GMT-5).
I kind of understand the error. But how can I solve it? is there a way to create a datetime.today() object that corresponds to the local time?

A: I'm guessing that the datetime from your frontend is in UTC.  Doing a replace doesn't actually convert the datetime.  It uses the data/hour/etc. and just uses a new timezone.
When you call datetime.today(), you create a naive datetime without any timezone info.  When you do a replace on that, it's not actually doing a conversion either, it's just assuming the date you gave it is already in the timezone you provided, the same as the replace you did on the server time.
To actually convert datetimes to another timezone, you need to use astimezone.  If the datetime from the server is also naive and doesn't specify a timezone, astimezone will error.  To fix that. add a timezone of UTC first.
time_from_frontend = time_from_frontend.replace(tzinfo=pytz.timezone('UTC'))
converted_server_time = time_from_frontend.astimezone(my_timezone)

A: datetime.today() already returns the local datetime (the result is almost the same as datetime.now()). Both return the local time as naive datetime objects (avoid them unless you want to display them immediately).
The correct way to get the current time in a given timezone is to use datetime.now(tz):
#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal

local_time = datetime.now(tzlocal.get_localzone())

It works even during DST transitions when the local time may be ambiguous (using a naive datetime.today() may fail in this case).
tzlocal returns a pytz tzinfo object and therefore it handles timezones that might have had a different UTC offset in the past (non-pytz code may fail in this case).

There are several issues in your code:

*

*don't use naive_dt.replace(tzinfo=tz) where tz has a non-fixed utc offset. Use tz.localize(naive_dt, is_dst=None) instead

*the time difference in your question indicates that time_from_frontend might be in UTC (not your local timezone) as @Brendan Abel suggested. To compare it with the current time, you could use datetime.utcnow() if time_from_frontend is a naive datetime object that represents UTC time:
time_diff = datetime.utcnow() - time_from_frontend

To get timezone-aware datetime, you can use .replace() with UTC timezone (the utc offset is fixed -- it is always zero), :
frontend_time = time_from_frontend.replace(tzinfo=pytz.utc)

If both datetime objects are timezone-aware then the subtraction works too:
time_diff = local_time - frontend_time

See also:

*

*How to get current time in Python

*Python: How to get a value of datetime.today() that is "timezone aware"?


text:
Q: Grayed form while loading i have written the following code in c#. but it didn't the way i want it...
my current code opens the "LoadingForm", but when it shows on screen i can see it as "gray screen with squares" - instead of the Loading_Gif which i have added to that form, hope you help me (By the way, i tried to run the first part of code throw a Thread, it worked normal but i was unable to close that LoadingForm since i can't close it from a different thread than the one i opened it in, and if i try to open and close it in the same Thread that happens at the same time!)
here is my code,
Note: when movies.usingApi finishes, my form comes back to work in normal way
private void RefreshButton_Click(object sender, EventArgs e)
{
    LoadingForm l1 = new LoadingForm();//a form that shows loading gif while
    working in the background
    L1.Show();
    Movies.UsingApi();//calling a function to add all available movies to DB
    L1.Close();
}

and here is my code using Threads,
private void LoadMTV()
{
    Movies.UsingApi();}
    private void ShowLoading()
    {
           L1.ShowDialog();
    }

    private void RefreshButton_Click(object sender, EventArgs e)
    {
        System.Threading.Thread myThread;
        myThread = new System.Threading.Thread(new
        System.Threading.[enter image description here][1]ThreadStart(LoadMTV));
        System.Threading.Thread myThread1;
        myThread1 = new System.Threading.Thread(new
        System.Threading.ThreadStart(ShowLoading));
        myThread1.Start();
        myThread.Start();
    }
}

A:
It is unsafe to call a control from a thread other than the one that
  created the control without using the Invoke method. To make a thread-safe
  call to a Windows Forms control Query the control's InvokeRequired
  property.
If InvokeRequired returns true, call Invoke with a delegate that makes
  the actual call to the control.
If InvokeRequired returns false, call the control directly.

https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls


text:
Q: How to use dlookup in access 2007 with multiple criteria, one of them being in date format? I have a Advance/Miscellaneous Exp table where there are 4 fields as follows,
Employer Name, Advance Expense, Miscellaneous Expense, Adv_Miscl_Date.
I have a form something like this
Employee Name:
Last_date:
Advance:
Miscellaneous:
When the last_date field gets focus, it displays the latest date from advance/miscellaneous exp table with respect to the employee name.
Now in the next field i.e the Advance field, I want the latest advance to be displayed. I tried the following with dlookup but kept getting syntax error or mismatch error.
Private Sub Adv()
[Adv]=Dlookup("Advance","Adv_Miscl_Exp","[Emp_Name]=Forms![Calculate Salary]![Emp_Name]" AND "    [Adv_M_Date]=Forms![Calculate Salary]![Last_date]")
End Sub

What is the right syntax? How do i use dlookup with one criteria as employee name and the other criteria as the advance/miscellaneous date
Any help is highly appreciated.
Thank You

A: It would be something like this:
Private Sub Adv()
    [Adv] = Dlookup("Advance", "Adv_Miscl_Exp", "[Emp_Name] = '" & Forms![Calculate Salary].Emp_Name & "' AND [Adv_M_Date] = #" & Forms![Calculate Salary].Last_date & "#")
End Sub

For the correct syntax on DLookups, I tend to use the following page;
http://access.mvps.org/access/general/gen0018.htm