text:
Q: How to synchronize two methods in a singleton pattern I have created a database object according to the singleton pattern. The database object contains 2 methods: connect() and update().
The update should run multithreaded, meaning that I cannot put synchronized in the update method signature (I want users to access it simultaneously not one at a time).
My problem is that I want to make sure that 2 scenarios according to this flows:

*

*A thread 1 (user1) is the first to create an instance of the DB and thread 2 (user2) is calling the connect() and update() method to this DB - should not give NullPointerException even if by the time that user2 is doing the update() the connect from user1 is not done.

*update() should not include synchronized (because of the reason I mentioned above).
Thanks for all the helpers!
SingeltonDB
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

    public class SingeltonDB {
        private static DBconnImpl db = null;
        private static SingeltonDB singalDb = null;
          Lock dbLock;

        private SingeltonDB(String username, String password) {
            db = new DBconnImpl();
        }

        public static boolean isOpen() {
            return (db != null);
        }

        public synchronized static SingeltonDB getInstance(String username,
                String password) throws Exception {

            if (db != null) {
                throw (new Exception("The database is  open"));
            } else {
                System.out.println("The database is now open");
                singalDb = new SingeltonDB(username, password);
            }
            db.connect(username, password);
            System.out.println("The database was connected");

            return singalDb;
        }

        public synchronized static SingeltonDB getInstance() throws Exception {
            if (db == null) {
                throw (new Exception("The database is not open"));
            }

            return singalDb;
        }

        public void create(String tableName) throws Exception {
            dbLock = new ReentrantLock();
            dbLock.lock();
            db.create(tableName);
            dbLock.unlock();
        }

        public  User query(String tableName, int rowID) throws Exception {
            if (db == null) {
                System.out.println("Error: the database is not open");
                return null;
            }
            return (db.query(tableName, rowID));
        }

        public  void update(String tableName, User user) throws Exception {
            if (db == null) {
                System.out.println("Error: the database is not open");
                return;
            }
            db.update(tableName, user);
        }

    }

Main
public class Main {
    public static void main(String[] args) throws Exception {

        Creator cr= new Creator(new UserContorller());
        Thread t1 = new Thread(cr);
        t1.start();
        Producer pr = new Producer(new UserContorller());
        Thread t2 = new Thread(pr);
        t2.start();

        /*
         * Consumer cn = new Consumer(new UserContorller()); Thread t2 = new
         * Thread(cn); t2.start();
         */
    }
}

class Creator implements Runnable {
    UserContorller uc;

    public Creator(UserContorller uc) {
        this.uc = uc;
    }

    @Override
    public void run() {
        try {
            uc = new UserContorller("MyAccount", "123");
            uc.createTable("table1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Producer implements Runnable {
    UserContorller uc;

    public Producer(UserContorller uc) {
        this.uc = uc;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                uc.saveUser("table1", i, "User", i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable {
    UserContorller uc;

    public Consumer(UserContorller uc) {
        this.uc = uc;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                System.out.println(uc.getUser("table1", i));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

A: Connect once, when creating the singleton (in the constructor, perhaps).
Have a synchronized static method (getInstance or something), that checks if an instance exists, creates and connects as necessary, and returns the instance. By following this protocol, you ensure that threads always get a connected Db object ready to be used.
The users will call that method to get the singleton instance, and call update or whatever they want on it, it does not need to be synchronized.

A: Note: The post below was written in the perspective of both users using the same credentials (hidden from them) to connect to the database. If users employ different credentials, the idea of a singleton db object is purposeless, each user should have their own connection object, and of course then connection details are passed on from the user to the Db via whatever represents the user in the program (here the thread instances apparently).
The main issue in the implementation you provided is that the getinstance method requires its caller to know the connection details, or assume that the connection has already been done. But neither threads could nor should know in advance if the Db has been opened already -- and design wise it's a mistake to hand them the responsibility of explicitely opening it. These threads are work threads, they shouldn't be concerned about Db configuration details.
The only sane way to handle this situation is to have these configuration parameters held by the Db object directly, or better yet another object in charge of providing it (it's the factory pattern).
However, if you want first your code to work with minimal changes, get rid of the parameter less getinstance method, have any thread requiring the Db object to use the remaining variant of that method, passing along the correct parameters, and change it to return the instance if it exists, or create it otherwise, without raising an exception. I believe that it's what @Dima has been trying to explain in his answer.


text:
Q: Combine Views in asp.net core MVC I am new to this, so sorry for my maybe stupid question
I created two tables Movie and Owner. My plan was that it should be possible to add a owner to a movie, so when the view is show up, i get a dropdown that load the content from the owner table
I can Create the standard create, delete etc pages, but if i wish to combine the create page with this new field i am lost
The view
  @model MvcMovie.Models.Movie

@{
    ViewData["Title"] = "Create";
}

Create

Movie

        <form asp-action="Create">

                <input asp-for="Title" class="form-control" />

                <input asp-for="ReleaseDate" class="form-control" />

                <input asp-for="Genre" class="form-control" />

                <input asp-for="Price" class="form-control" />

                <input asp-for="Owners" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

The models
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string? Title { get; set; }

        [Display(Name = "Release Dates")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string? Genre { get; set; }

        [Column(TypeName = "decimal(18, 2)")]
        public decimal Price { get; set; }

        public virtual ICollection<Owner> Owners { get; set; }

    }

}
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Owner
    {

            public int Id { get; set; }
            public string Name { get; set; }
            public string LastName { get; set; }
            public string Adress { get; set; }

        }
}

Controller:
namespace MvcMovie.Controllers
{
    public class MoviesController : Controller
    {
        private readonly MvcMovieContext _context;

        public MoviesController(MvcMovieContext context)
        {
            _context = context;
        }

        // GET: Movies
        public async Task<IActionResult> Index()
        {
              return View(await _context.Movie.ToListAsync());
        }

        // GET: Movies/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Movie == null)
            {
                return NotFound();
            }

            var movie = await _context.Movie
                .FirstOrDefaultAsync(m => m.Id == id);
            if (movie == null)
            {
                return NotFound();
            }

            return View(movie);
        }

        // GET: Movies/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Movies/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                _context.Add(movie);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(movie);
        }

        // GET: Movies/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Movie == null)
            {
                return NotFound();
            }

            var movie = await _context.Movie.FindAsync(id);
            if (movie == null)
            {
                return NotFound();
            }
            return View(movie);
        }

        // POST: Movies/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
        {
            if (id != movie.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(movie);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MovieExists(movie.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(movie);
        }

        // GET: Movies/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Movie == null)
            {
                return NotFound();
            }

            var movie = await _context.Movie
                .FirstOrDefaultAsync(m => m.Id == id);
            if (movie == null)
            {
                return NotFound();
            }

            return View(movie);
        }

        // POST: Movies/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Movie == null)
            {
                return Problem("Entity set 'MvcMovieContext.Movie'  is null.");
            }
            var movie = await _context.Movie.FindAsync(id);
            if (movie != null)
            {
                _context.Movie.Remove(movie);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool MovieExists(int id)
        {
          return _context.Movie.Any(e => e.Id == id);
        }
    }
}

A:
My plan was that it should be possible to add a owner to a movie

If so, your model design should be one-to-one instead of one-to-many relationship. Your current model design will be possible to add multiple owners to a movie.
Then, if you use .NET 6, it is better for you to remove <Nullable>enable</Nullable> in your project file, otherwise it will make required validation although you do not add the [Required] attribute.
Here is a whole working demo:
Model
public class Movie
{
    public int Id { get; set; }
    public string? Title { get; set; }

    [Display(Name = "Release Dates")]
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }
    public string? Genre { get; set; }

    [Column(TypeName = "decimal(18, 2)")]
    public decimal Price { get; set; }

    public Owner Owner { get; set; }

    //public virtual ICollection<Owner> Owners { get; set; }
}
public class Owner
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Adress { get; set; }
}

View
@model Movie

@{
    ViewData["Title"] = "Create";
}

Create

Movie

        <form asp-action="Create">

                <input asp-for="Title" class="form-control" />

                <input asp-for="ReleaseDate" class="form-control" />

                <input asp-for="Genre" class="form-control" />

                <input asp-for="Price" class="form-control" />

                <select asp-for="Owner.Id" asp-items="@ViewBag.Owners" class="form-control" >
                    <option>Select the Owner</option>
                </select>

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller
// GET: Movies/Create
public IActionResult Create()
{
    ViewBag.Owners = new SelectList(_context.Owner.ToList(), "Id", "Name");
    return View();
}

[HttpPost]
public async Task<IActionResult> Create (Movie movie)
{
    if (ModelState.IsValid)
    {
        var owner = _context.Owner.Find(movie.Owner.Id);
        movie.Owner = owner;
        _context.Add(movie);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    ViewBag.Owners = new SelectList(_context.Owner.ToList(), "Id", "Name");
    return View(movie);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extract a list of changed files between two mercurial revisions I need to extract a list of changed files from Mercurial from the last "revision" tag to the current working version instead of the head. The process is part of a batch script, so the current revision bit needs to be automated.
I know that I can get the current revision using:
hg id -n

or
hg parent --template "{rev}\n"

I also know that I can get a list of changed files from a tagged version ("from") like this:
hg st --rev from > file_list.txt

I also know that I can get a list of changed files from a tagged version ("from") to another tagged version ("to") like this:
hg st --rev from --rev to > file_list.txt

However, is there a tag or a way that one can specify the "to" version to be the current working version automatically? I need to be able to exclude the "tip" or "default" files.
This process happens in a DOS batch file, if that helps, and the results are all output to text files.

A: Sorry - I got confused about which files actually had changed... The answer is as simple as:
hg st --rev from > file_list.txt

That will list all files that have changed from the named revision to the current working version and NOT the head revision (tip or default).


text:
Q: Trying to make a each row in a table that is embedded in a form clickable to make a project work as designed (no submit button) I have fixed the problem of the table working within a form. I just added an extra  field and created a hidden input field within it that will POST a separate tipID for each tip in the table. The entire table is also wrapped with the form tag to get the tipID to POST to the next page.
Now I need to know how make each individual table row send the data from the form kind of like each one being a button or making a hidden button click onclick of one of these table rows.
<form method="post" action="tips.php">

           <?php if(!empty($tips))
             while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
             echo "
 "; echo $recd['tip_desc']; echo "	 ";
             echo "".date('H:i', strtotime($recd['datetime'])).""; echo "
";
             echo date('m-d-y', strtotime($recd['datetime'])); echo"	<input type=";
             echo '"hidden" '; echo 'name='; echo '"tip_id" '; echo 'value="';
             echo ($recd['tip_id']); echo'">
';
                }
           ?>

</form>

My next page will use the query below and echo the full tip_desc since a tip can be several hundred characters.  It will also have a text area in which an admin can send a message back to the original user.
My PHP and query should look like this on the next page:
<?php
$tipID = $_POST['tipID'];
mysql_query="SELECT * FROM tips WHERE tipID = $tipID";
?>

A: Just surround your table into a form, place a hidden input field into it.
<form action="tips.php">
    <input name="tipID" type="hidden" value="id" />

                <?php
                    if(!empty($tips)) {
                        while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
                            echo "
 "; echo $recd['tipDescription'];
                            echo "	 ";
                            echo "".date('H:i', strtotime($recd['dateTime']))."";
                            echo "
"; echo date('m-d-y', strtotime($recd['dateTime']));
                            echo"
";
                        }
                    }
                ?>

</form>

Have a look at this to make your rows clickable. Working demo
function addRowHandlers() {
    var table = document.getElementById("tableId");
    var rows = table.getElementsByTagName("tr");
    for (i = 0; i < rows.length; i++) {
        var currentRow = table.rows[i];
        var createClickHandler =
            function(row)
            {
                return function() {
                    var cell = row.getElementsByTagName("td")[0];
                    var id = cell.innerHTML;
                    alert("id:" + id);
                };
            };
        currentRow.onclick = createClickHandler(currentRow);
    }
}

Credit: SolutionYogi
Ref: Adding an onclick event to a table row


text:
Q: Multiple Monitors, shared desktop Say I have two monitors, one an LCD on my laptop and the other a HD 21". I've disabled display mirroring as I want to use the extra space to view another window, however I want the items on the desktop of both screens to be the same.
Is it possible to mirror the desktop to both screens in this way?

A: No, as the second monitor is an extension of your desktop. An empty extension.

The mirroring would obviously give you the same desktop items on both monitors, but without the extra screen estate that you wish for. By desktop items, I assume you mean the dock and the file icons on the actual desktop.
You seem to want a hybrid of both modes, and unfortunately you can not do this. Also, it would lead to a rather confusing situation as you you would end up having duplicates of the same files on, what is effectively, the same desktop space.
I must admit though, the first time I connected a second monitor to a mac, I had expected two docks, one on each screen. But it just doesn't work like this.
I hope that this helps to explain it.

A: Unfortunately the only way you would be able to "mirror" the items on the desktop over both displays (without actually Mirroring the displays) is to create aliases for those items and place them on the second display manually.


text:
Q: Drawing a surface over a nonrectangular domain in asymptote I use asymptote because of its amazing 3D capabilities. However, when I tried to plot a surface over a nonrectangular domain, I could not do it without getting jagged edges. As far as I know, other software such as Mathematica, Maple, or JavaView allow this kind of plots.
So the question is: is it possible to draw a generic surface in asymptote over a nonrectangular domain in such a way that its edges are smooth?

A: I found a solution that consists of mapping the domain onto a rectangle. If a domain D in R^2 can be represented as
D={(a(u,v), b(u,v)); u1<=u<=u2, v1<=v<=v2}

then, to plot a function f(x,y) over D, we could define the following function in asymptote:
triple g(pair p){
    real x=a(p.x,p.y), y=b(p.x,p.y);
    return (x,y,f(x,y));
}

Finally, the surface is plotted as follows
draw(surface(g,(u1,v1),(u2,v2),...),...);


text:
Q: SwiftUI ForEach not updating following changes to the ObservableObject class array Background
In my app I have an array of friends that can be added to from another view. I've stored this array of friends in a class which is an ObservableObject. Within my main view, FriendListView, I am using a ForEach to display a custom view for each friend that a user has added.
I have not been able to add to the array and have the list display the new item. I have tried two different attempts based upon what I was able to understand and put together. Any help that someone is able to provide would be greatly appreciated. I currently have the method to display the 2nd view where I will be adding a new friend commented out and a method to automatically save a new one exists as a navigation bar item.
Attempts
Attempt #1
I was successful in displaying the list of friends if they were appended to the array during the class initializer. Calling the class method to add to the array from another view seems to work based upon me being able to print the contents of the array but the UI does not update.
This was completed by using a ForEach(0..<Array.count) approach but I received the following console error after adding a new item.
Error
ForEach<Range<Int>, Int, HStack<TupleView<(Spacer, FriendView, Spacer)>>> count (4) != its initial count (3).
`ForEach(_:content:)` should only be used for *constant* data.
Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!

Model Code
struct Pet: Identifiable {
    var id = UUID().uuidString
    var name: String
    var breed: String
}

class FriendModel: ObservableObject {

    @Published var petList = [Pet]()

    func addFriend(name: String, breed: String) {
        petList.append(Pet(name: name, breed: breed))
    }

    init() {
        petList.append(Pet(name: "Woofer", breed: "Dawg"))
        petList.append(Pet(name: "Floofer", breed: "Dawg"))
        petList.append(Pet(name: "Super", breed: "Dawg"))
//        petList.append(Pet(name: "Dooper", breed: "Dawg"))
//        petList.append(Pet(name: "Booper", breed: "Dawg"))
    }
}

UI Code
struct FriendListView: View {

    @EnvironmentObject var dataModel: FriendModel

    @State private var displayAddFriendSheet = false

    var body: some View {
        GeometryReader { geo in
            NavigationView {
                ScrollView {
                    ForEach(0..<self.dataModel.petList.count) { pet in
                        HStack {
                            Spacer()
                            FriendView(
                                name: self.dataModel.petList[pet].name,
                                breed: self.dataModel.petList[pet].breed,
                                screenWidth: geo.size.width,
                                randomPic: Int.random(in: 1...2)
                            )
//                            FriendView(
//                                name: self.dataModel.petList[pet].name,
//                                breed: self.dataModel.petList[pet].breed,
//                                screenWidth: geo.size.width)
                            Spacer()
                        }
                    }
                }// End of ScrollView
                .navigationBarTitle(Text("Furiends"))
                    .navigationBarItems(trailing: Button(action: self.showAddFriend) {
                    Image(systemName: "plus")
                }

                )
                .sheet(isPresented: self.$displayAddFriendSheet) {
                        AddFriendView()
                }

            }// End of NavigationView
        }// End of GeometryReader geo1
    }// End of body

    func showAddFriend() {
//        self.displayAddFriendSheet.toggle()
        self.dataModel.addFriend(name: "Jax", breed: "Doodle")
        print(dataModel.petList)

    }// Enf of showAddFriend

}// End of FriendListView

Attempt #2
After seeing the error from the first attempt, I read how I could skip the range and provide just the array as a part of the ForEach since I am adhering to the Identifiable protocol with my UUID in the Pet struct. With the model code remaining the same as my first attempt, my updated UI code is below. Note the only change was to the ForEach but I received the following error:
Error
Cannot convert value of type '[Pet]' to expected argument type 'Range<Int>'
UI Code
struct FriendListView: View {

    @EnvironmentObject var dataModel: FriendModel

    @State private var displayAddFriendSheet = false

    var body: some View {
        GeometryReader { geo in
            NavigationView {
                ScrollView {
                    ForEach(self.dataModel.petList) { pet in  // <--- Changed to directly reference the array
                        HStack {
                            Spacer()
                            FriendView(
                                name: self.dataModel.petList[pet].name,
                                breed: self.dataModel.petList[pet].breed,
                                screenWidth: geo.size.width,
                                randomPic: Int.random(in: 1...2)
                            )
//                            FriendView(
//                                name: self.dataModel.petList[pet].name,
//                                breed: self.dataModel.petList[pet].breed,
//                                screenWidth: geo.size.width)
                            Spacer()
                        }
                    }
                }// End of ScrollView
                .navigationBarTitle(Text("Furiends"))
                    .navigationBarItems(trailing: Button(action: self.showAddFriend) {
                    Image(systemName: "plus")
                }

                )
                .sheet(isPresented: self.$displayAddFriendSheet) {
                        AddFriendView()
                }

            }// End of NavigationView
        }// End of GeometryReader geo1
    }// End of body

    func showAddFriend() {
//        self.displayAddFriendSheet.toggle()
        self.dataModel.addFriend(name: "Jax", breed: "Doodle")
        print(dataModel.petList)

    }// Enf of showAddFriend

}// End of FriendListView

A: I assume the remaining try to access by subscription confuses compiler, so as far as Pet is Identifiable the following should work
ForEach(self.dataModel.petList) { pet in
    HStack {
        Spacer()
        FriendView(
            name: pet.name,        // << pet is not index
            breed: pet.breed,      // << so access by property
            screenWidth: geo.size.width,
            randomPic: Int.random(in: 1...2)
        )
 // .. other code


text:
Q: IMPORTRANGE and SUM funcions I am working with this function =SUM(IMPORTRANGE("Link", "Sheet!A2:A15")) and it works fine, but now I have issue with cases, where the SUM is not a range but seperate cells, for example:
=SUM(IMPORTRANGE("Link", "Sheet!A2,A8,A15"). How can I fix this?

A: its either:
=SUM(IMPORTRANGE("Link", "Sheet!A2"),
     IMPORTRANGE("Link", "Sheet!A8"),
     IMPORTRANGE("Link", "Sheet!A15"))

or:
=SUM(QUERY(TRANSPOSE(IMPORTRANGE("Link", "Sheet!A1:A15")),
 "select Col2,Col8,Col15"))


text:
Q: Why can't volatile FILE* be assigned to FILE*? I have a Visual C++ program that opens a file in one thread with FILE* fp = fopen(...). I want that thread to block on an event object while another thread reads the file, then signals the blocked thread when it is done, which will then close the file. Because fp is shared between threads, I have declared it as volatile FILE* fp. However, fread() won't accept a volatile as its FILE* argument. I tried using a local pointer, with FILE* fpLocal = fp; in the thread that will call fread(), but that got me this:
 Error: a value of type "volatile FILE*" cannot be assigned to an entity of type "FILE*"

Naturally, this has me worried that maybe I'm making a mistake by trying to open a file in one thread and read it in another to begin with, though I don't see why (yet).
Can someone help me with this? Why can't I assign a volatile FILE* to a FILE*?

A: Why can't I assign a volatile FILE* to a FILE*?
Because C++ has strict type checking and you cannot assign types that do not match to each other.
One needs to use casting operators if that be the case, however it is important to note that using them incorrectly might lead to Undefined Behaviors as well.
This behavior is same as for the const qualifier.
As a side note as already mentioned in comments, volatile is not the way to go here.


text:
Q: MiKTeX Update directly after Installation makes it not usable as the title says, the update that MiKTeX want to do directly after installation makes it unusable.

*

*I want to install MiKTeX on my Windows 10 that is in a DOM of my company.

*Link for installation: https://miktex.org/download

*The installation is just on the local user.

*Installation works fine.

*If I force MiKTeX not to do the Updates, I can compile a standard .tex-Document without problems. But only one package for each compilation process is installed. So I had to start the compiling about 5 times to have the basic-packages.

*If I do the 102 Updates that MiKTeX recommends directly after installation (or later after trying step 5), I get an error message. The installation seems to run completely through, but nevertheless the error is appearing:

*If I click on yes I get this message: The executed procress did not succeed. and fileName="C:\Users\xxxxxx\AppData\Local\Programs\MiKTeX\miktex\bin\x64\miktex-fc-cache.exe", exitCode="1"

*The Copy Info gives me the follwing text:

GENERAL MIKTEX INFORMATION
ReportDate: 2021-03-29 14:04:13
CurrentVersion: 21.2
SetupDate: 2021-03-29 14:02:00
SetupVersion: 21.2
Configuration: Regular
GitInfo: 7a7e645 / 2021-02-20 10:38:14
OS: Windows 10 Education, 64-bit, build 18363
SharedSetup: no
LinkTargetDirectory: C:\Users\xxxxxx\AppData\Local\Programs\MiKTeX\miktex\bin\x64
PathOkay: no
LastUpdateCheck: 2021-03-29 14:02:53
LastUpdate: 2021-03-29 14:03:35
LastUpdateDb: 2021-03-29 14:02:51
SystemAdmin: no
RootPrivileges: no
AdminMode: no
Root0: C:\Users\xxxxxx\AppData\Roaming\MiKTeX
Root1: C:\Users\xxxxxx\AppData\Local\MiKTeX
Root2: C:\Users\xxxxxx\AppData\Local\Programs\MiKTeX
Root3: C:\ProgramData\MiKTeX
Root4: C:\Program Files\MiKTeX
UserInstall: C:\Users\xxxxxx\AppData\Local\Programs\MiKTeX
UserConfig: C:\Users\xxxxxx\AppData\Roaming\MiKTeX
UserData: C:\Users\xxxxxx\AppData\Local\MiKTeX
CommonInstall: C:\Program Files\MiKTeX
CommonConfig: C:\ProgramData\MiKTeX
CommonData: C:\ProgramData\MiKTeX
Invokers: non-existing/cmd

ERROR DETAILS
Program: miktex-fc-cache.exe
Error: The executed process did not succeed.
Details:
  fileName: C:\Users\xxxxxx\AppData\Local\Programs\MiKTeX\miktex\bin\x64\miktex-fc-cache.exe
  exitCode: 1

*After this failed update, MiKTeX will no longer show any updates or so. It just says: "No new Updates availabe".

*But if I now try to compile any LaTeX-document (e.g. in TeXMaker or TeXworks), I get this error message: Die Ausführung des Codes kann nicht fortgesetzt werden, da MiKTeX210200-png.dll nicht gefunden wurde. Durch eine Neuinstallation des Programms kann das Problem möglicherweise behoben werden. or The execution of the code cannot continue because MiKTeX210200-png.dll was not found. Reinstalling the program may fix the problem. (translated to English)

*I could get a kind of log-file out of this problem with "TeXworks". Is says the following:

2021-03-29 15:04:02,156+0200 INFO  texify - this process (18644) started by 'miktex-texworks' with command line: C:\Users\xxxxxx\AppData\Local\Programs\MiKTeX\miktex\bin\x64\texify.exe --pdf --synctex=1 --clean Beispiel.tex
2021-03-29 15:04:02,204+0200 INFO  texify.core - start process: pdflatex --synctex=1 C:/Users/xxxxxx/Downloads\Beispiel.tex
2021-03-29 15:04:02,248+0200 ERROR texify.core - Das System kann die angegebene Datei nicht finden.

2021-03-29 15:04:02,248+0200 ERROR texify.core - Function: CopyFileW
2021-03-29 15:04:02,248+0200 ERROR texify.core - Result: 2
2021-03-29 15:04:02,248+0200 ERROR texify.core - Data: existing="Beispiel.log", path="C:/Users/xxxxxx/Downloads\Beispiel.log"
2021-03-29 15:04:02,248+0200 ERROR texify.core - Source: Libraries\MiKTeX\Core\File\win\winFile.cpp:390
2021-03-29 15:04:02,248+0200 FATAL texify.core - TeX engine failed for some reason.
2021-03-29 15:04:02,248+0200 FATAL texify.core - Data:
2021-03-29 15:04:02,248+0200 FATAL texify.core - Source: Programs\MiKTeX\texify\mcd.cpp:1529
2021-03-29 15:04:02,248+0200 FATAL texify - TeX engine failed for some reason.
2021-03-29 15:04:02,248+0200 FATAL texify - Info:
2021-03-29 15:04:02,248+0200 FATAL texify - Source: Programs\MiKTeX\texify\mcd.cpp
2021-03-29 15:04:02,248+0200 FATAL texify - Line: 1529

*I reinstalled the MiKTeX several times. And tired also:

*

*Installing as local admin

*Installing with the option, that new packages will install without asking

So. Has somebody an idea? After 4 h I could not solve the problem, and am now a bit desperate. I also could not find the solution in the www so far.
Thank you very much in advance!


text:
Q: In-App Purchase For Google Pay With Flutter So am trying to use google pay in my flutter application and below is my code. When I run the application is shows google pay dialog with my google pay email and card details and an error "Unrecognised app. Please make sure that you trust this app before proceeding. When I press the "Continue" button I get "Request failed" "Unexpected developer error, please try again later" Please what am I doing wrong?
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:google_pay/google_pay.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _googlePayToken = 'Unknown';

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await GooglePay.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    await GooglePay.initializeGooglePay("my google play base64EncodedPublicKey");

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
              children: <Widget>[
                Text('Running on: $_platformVersion\n'),
                Text('Google pay token: $_googlePayToken\n'),
                FlatButton(
                  child: Text("Google Pay Button"),
                  onPressed: onButtonPressed,
                )
              ]
          ),
        ),
      ),
    );
  }

  void onButtonPressed() async{
    setState((){_googlePayToken = "Fetching";});
    try {
      await GooglePay.openGooglePaySetup(
          price: "10.0",
          onGooglePaySuccess: onSuccess,
          onGooglePayFailure: onFailure,
          onGooglePayCanceled: onCancelled);
      setState((){_googlePayToken = "Done Fetching";});
    } on PlatformException catch (ex) {
      setState((){_googlePayToken = "Failed Fetching";});
    }

  }

  void onSuccess(String token){
    setState((){_googlePayToken = token;});
  }

  void onFailure(){
    setState((){_googlePayToken = "Failure";});
  }

  void onCancelled(){
    setState((){_googlePayToken = "Cancelled";});
  }
} ```

When I run the application is shows google pay dialog with my google pay email and card details and an error "Unrecognised app. Please make sure that you trust this app before proceeding. When I press the "Continue" button I get "Request failed" "Unexpected developer error, please try again later" Please what am I doing wrong?


text:
Q: Вывод прогресса асинхронной операции во вторичное окно Есть метод, загружающий данные из файла. О своём прогрессе он сообщает через вызов события OnFileLoad
    public Task UploadDataAsync()
    {
        return Task.Run(() =>
        {
            ...
            if (string.IsNullOrEmpty(FilePath))
            {
                OnFileLoading?.Invoke($"Error while loading: Path is empty");
                ...
                throw new Exception("Path is emprty");
            }

            if (!File.Exists(FilePath))
            {
                OnFileLoading?.Invoke($"Error while loading: File not found");
                ...
                throw new Exception("File not found");
            }

            OnFileLoading?.Invoke($"Start loading from '{FilePath}'");
            ...
            OnFileLoading?.Invoke("Loaded first line");
            OnFileLoading?.Invoke("Loaded second line");
            ...
            OnFileLoading?.Invoke("Loaded n line");
            ...
            OnFileLoading?.Invoke("Loading completed");
        });
    }

В классе главного окна есть обработчик события нажатия на кнопку "Открыть". В нём создаётся новое окно, в котором показывается прогресс загрузки данных из файла.
    public async void OpenFileClick(object sender, RoutedEventArgs e)
    {
        try
        {
            var dataProvider = IocContainer.GetService<IDataProvider>();
            LoadingDataStatusWindow loadingDataStatusWindow = new LoadingDataStatusWindow();
            dataProvider.OnFileLoad = loadingDataStatusWindow.UpdateLoadingStatus;
            loadingDataStatusWindow.Show();
            dataProvider.FilePath = AppGlobalSettings.DataFilePath;
            await dataProvider.UploadDataAsync();
            items = dataProvider.CircuitItems;
            CircuitItemDataGrid.ItemsSource = dataProvider.CircuitItems;
        }
        catch(Exception ex)
        {
            LogUtility.LogError(ex);
        }
    }

Метод отображения прогресса окна LoadingDataStatusWindow:
    public void UpdateLoadingStatus(string currentRow)
    {
        StatusTextBox.Text += currentRow + Environment.NewLine;
    }

При попытке загрузить данные возникает ошибка, говорящая о том, что поток пытается обратиться к объекту, владельцем которого является другой поток.
Я пробовал починить это, сделав добавление текста в StatusTextBox через Dispatcher. Но это не помогло.
Как в данном случае можно организовать вывод прогресса во второе окно с асинхронной загрузкой данных, чтобы она не подвешивала GUI?

A: Как совершенно верно заметил @aepot в комментариях, для сообщения о прогрессе операции используйте Progress<T>, он именно для этого и предназначен, и сам маршаллирует в нужный контекст.
Попробуйте как-то так:
public async void OpenFileClick(object sender, RoutedEventArgs e)
{
    // ...
    Progress<string> p = new(s => StatusTextBox.Text += s + Environment.NewLine);
    await UploadDataAsync(p);
    // ...
}

и соответственно
public async Task UploadDataAsync(IProgress<string> progress)
{
    // ...
    progress.Report($"Start loading from '{filePath}'");
    // ...
    progress.Report("Loaded first line");
    // ...
    progress.Report("Loaded second line");
    // ...
    progress.Report("Loaded n line");
    // ...
    progress.Report("Loading completed");
    // ...
}


text:
Q: Non-parametrized partial match query I'm an access beginner.
I'm trying to write a query that finds all partial matches between a field in one table and a field in another.
I'll give a simplified example of what I'm looking for as a final result and maybe you can help me write the SQL for it.
Table 1: Strings
pre
ing
up

Table 2: Words
present
door
cup
making
kingdom

Desired Result Table:
pre     present
up      cup
ing     kingdom
ing     making

Here's what I have - it can give me a prompt where I type in what I'm looking for. (e.g. if I type in 'up', then I get cup from the word list). What I want is a way to automate the whole process for all of the strings in the first list.
SELECT *
FROM word
WHERE (((word) LIKE "*" & string & "*"));

Thanks,

A: I don't have Access in front of me, but I think you can do something similar to this (this is for SQL Server):
select stringname, wordname
from strings
  join words on wordname like '%' + stringname + '%'

SQL Fiddle Demo
If I had to guess at the Access syntax, replace % with * and possibly change the + to &, but hopefully this will get you going in the right direction.


text:
Q: Shift key disabled using Windows 8 running in Virtualbox, with multiple monitors I have windows 8 installed in VirtualBox - running on linux.
I also have multiple monitors.
When I extend my display over both monitors, my shift key stops working.  I can still access capital letters using caps-lock, but cannot access certain symbols such as @, which require the shift key.
If I only use a single monitor, the shift key works fine.
Problem persists after a complete wipe and reinstall.
Any idea what could be causing this?  It would be really handy to be able to use both my monitors in Windows.


text:
Q: ElasticSearch ERROR StatusLogger Log4j2 could not find a logging implementation when I'm using Logback I am using logback for logging in my application
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

And in my class i use this
Logger logger = Logger.getLogger(ElasticSearchRepository.class.getName());

In dependency analyzer, I found that elasticsearch uses log4j-api 2.11.1
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.7.0</version>
</dependency>

I have this error:

ERROR StatusLogger Log4j2 could not find a logging implementation.
  Please add log4j-core to the classpath.
  Using SimpleLogger to log to the console...

I resolved it by excluding log4j-api from elasticsearch dependency, but on the other hand, I have got this error:

Cause: java.lang.ClassNotFoundException: org.apache.logging.log4j.Logger

I have got the Log4j dependency back by removing the exclusion but I had the first error also back, and I have no intention of adding log4j jars since I am already using logback

A: Adding this dependency seems to resolve it.
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.11.1</version>
</dependency>

This did not generate conflicts with logback which is good enough, the only sad thing is that I added a dependency to just resolve an error and not for feature purposes.


text: Q: Internet access after the user logs in I am building a web application for cyber cafe users, they need to register to it before using internet. I need to implement a functionality which makes the internet inaccessible to the user before login. (The users log in from computers in a LAN with a single gateway to internet-cafe owner's computer). Help!


text:
Q: No route matches [GET] "/users/sign_up" - When I uncomment :registerable and :recoverable I also receive this error in the browser;
/Users/DylanRichards/Sites/Sites/dylanrichards/app/models/user.rb:4: syntax error, unexpected ',' devise :database_authenticatable, registerable:, :recoverable, ^

How can I fix this? This site is my personal blog. I've opted to use Devise for authentication.
user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, registerable:, :recoverable,
          :rememberable, :trackable, :validatable
end

routes.rb
Dylanrichards::Application.routes.draw do

  resources :quotes

  resources :photos

  devise_for :users do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end
end

end

A: Add : before registerable: and omit from end


text:
Q: ssh public-key sharing using only git bash I wan't to make a script that retrieve the public keys from two remote servers and share them each others.
Problem is that i'm not allowed to install any tools but git bash hence i do not have access to things like sshpass...
here is my script
#!/bin/bash

clear

#Server 1 id
read -p "Usr name srv 1 (root if empty): " usrname1;
usrname1=${usrname1:-root}
read -p "Ip srv1 : " ip1;

#Server 2 id
read -p "Usr name srv 2 (root if empty)" usrname2;
usrname2=${usrname2:-root}
read -p "Ip srv2 : " ip2;

echo ""

read -p "(Re)generate key ? (y/n)" choice;

case $choice in
   y)
       ssh $usrname1@$ip1 'ssh-keygen -f ~/.ssh/id_rsa'
       ssh $usrname2@$ip2 'ssh-keygen -f ~/.ssh/id_rsa'
       ;;

   *)
       scp $usrname2@$ip2:~/.ssh/id_rsa.pub ~/
       ssh $usrname1@$ip1 'cat >>.ssh/authorized_keys' < ~/id_rsa.pub

       scp $usrname1@$ip1:~/.ssh/id_rsa.pub ~/
       ssh $usrname2@$ip2 'cat >>.ssh/authorized_keys' < ~/id_rsa.pub

esac

So this script is working but I litteraly have to write password 3 times per servers which might seems way too much. I'm fairly new in shell and I can't find a way which do not ask for password during keygen, retrieve the key and adding it to the authorized_keys file from each server. Any ideas ?


text:
Q: How to send stream closure with XMPPFramework I am developing a chat App using XMPPFramework and I ran into trouble when trying to close the stream.
I have stream management enabled on my Ejabberd server and I would like to use APNS to send notification while the client monitor is switched off or App is in the background. I call the below function every time while the app is going to background.
func disconnect() {
    goOffline() // send unavailable presence
    self.stream.disconnect()
}

Unfortunately, the connection is not immediately terminated as stream management is enabled. And all messages were lost during the time the stream is still active.
According to XEP-0198 documentation, a </stream:stream> must be sent to close the stream, how may I do that? or should I use another approach to handle this situation?
Thank you.


text:
Q: Test fails with recyclerview item I don't know how to fix this exception I want to test if recyclerview item layout textview matches with the provided text or not?
What is wrong ?
and for RecyclerView matcher I am using  https://gist.github.com/baconpat/8405a88d04bd1942eb5e430d33e4faa2
Here is layout.xml
<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            app:imageUrl="@{imageUrl}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.05"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/title_herobanner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin_small"
            android:ellipsize="end"
            android:text="@{title}"
            android:textSize="@dimen/text_large"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:text_color="@{theme.primaryTextColor}" />
    </androidx.constraintlayout.widget.ConstraintLayout>

and here is my test

@RunWith(AndroidJUnit4::class)
class HomeFragmentTest {

  @get:Rule
  val activityRule = ActivityTestRule(SingleFragmentActivity::class.java, true, true)

  @get:Rule
  val dataBindingIdlingResourceRule = DataBindingIdlingResourceRule(activityRule)

  private lateinit var viewModel: HomeViewModel
  private val contentRow = MutableLiveData<List<ContentRow>>()
  private val errorMessage = MutableLiveData<String>()
  private val homeFragment = TestHomeFragment()

  @Before
  fun init() {
    viewModel = Mockito.mock(HomeViewModel::class.java)
    Mockito.`when`(viewModel.contentRows).thenReturn(contentRow)
    Mockito.`when`(viewModel.errorMessageData).thenReturn(errorMessage)
    homeFragment.viewModelFactory = ViewModelUtil.createFor(viewModel)
    activityRule.activity.setFragment(homeFragment)
  }

  @Test
  fun loadResults() {
    contentRow.postValue(TestUtil.createContentRows())
    Espresso.onView(listMatcher().atPositionOnView(0, R.id.title_herobanner))
        .check(ViewAssertions.matches(ViewMatchers.withText("WE BRING")))
  }

  private fun listMatcher(): RecyclerViewMatcher {
    return RecyclerViewMatcher(R.id.list_herobanner)
  }

  class TestHomeFragment : HomeFragment() {
    override fun onAttach(context: Context) {
      super.onAttach(context)
    }

    override fun injectMembers() {
    }
  }
}

and here is RecyclerViewMatcher.java
class RecyclerViewMatcher(private val recyclerViewId: Int) {

    fun atPosition(position: Int): Matcher<View> {
        return atPositionOnView(position, -1)
    }

    fun atPositionOnView(position: Int, targetViewId: Int): Matcher<View> {
        return object : TypeSafeMatcher<View>() {
            var resources: Resources? = null
            var childView: View? = null

            override fun describeTo(description: Description) {
                var idDescription = recyclerViewId.toString()
                if (this.resources != null) {
                    idDescription = try {
                        this.resources!!.getResourceName(recyclerViewId)
                    } catch (var4: Resources.NotFoundException) {
                        "$recyclerViewId (resource name not found)"
                    }
                }

                description.appendText("RecyclerView with id: $idDescription at position: $position")
            }

            public override fun matchesSafely(view: View): Boolean {

                this.resources = view.resources

                if (childView == null) {
                    val recyclerView = view.rootView.findViewById<RecyclerView>(recyclerViewId)
                    if (recyclerView?.id == recyclerViewId) {
                        val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
                        childView = viewHolder?.itemView
                    } else {
                        return false
                    }
                }

                return if (targetViewId == -1) {
                    view === childView
                } else {
                    val targetView = childView?.findViewById<View>(targetViewId)
                    view === targetView
                }
            }

        }
    }
}```

and the exception is here:

E/TestRunner: androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: is "WE BRING"' doesn't match the selected view.
    Expected: with text: is "WE BRING"
         Got: "AppCompatTextView{id=2131231023, res-name=title, visibility=VISIBLE,...}"

A: Converting my comment to an answer:
Try hardcoding the text inside the XML layout at first with WE BRING instead of relying on Databinding and see if that makes a difference.
There might be an issue with Databinding if you're not running executePendingBindings() after setting your datamodel on the XML layout.


text:
Q: Python Problem: "OverflowError: Python int too large to convert to C long" import sympy as sy
x = sy.symbols('x')
def f2(x,t,l):
    return 5*sy.log(x)+14388/((273+t)*x)-sy.log((1.1910*10**8)/l+1)
print(sy.solve(f2(x,35,80),x))

Result is:

OverflowError: Python int too large to convert to C long

How to solve this problem?

A: Please check your equation. There does not appear to be a solution:
>>> eq=f2(x,35,80);eq
5*log(x) - 14.2134480713559 + 327/(7*x)

There is a minimum in the function and it is convex up at that point and positive:
>>> solve(eq.diff(x))
[327/35]
>>> eq.subs(x,_[0]).n()
1.95961247568333
>>> eq.diff(x,2).subs(x,Rational(327,35))
6125/106929

So if the constant were a little more negative, everything would work:
>>> eq.subs(eq.atoms(Float).pop(),-20)
5*log(x) - 20 + 327/(7*x)
>>> ans=solve(_)
>>> [i.n(2) for i in ans]
[44., 3.3]


text:
Q: What's wrong with register(_:forCellWithReuseIdentifier:) on UICollectionView? I'm working with an UICollectionView. As dequeueReusableCell(withReuseIdentifier:for:) expects You must register a class or nib file using the register(_:forCellWithReuseIdentifier:) method before calling this method, I added a line in my viewDidLoad func as
self.collectionView!.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

Now when I'm using the cell for dequeuing and configuring, I'm getting error and app crashes.

fatal error: unexpectedly found nil while unwrapping an Optional value

This is my DataSource method:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                  for: indexPath) as! PhotoCollectionViewCell

    let aPhoto = photoForIndexPath(indexPath: indexPath)
    cell.backgroundColor = UIColor.white

    cell.imageView.image = aPhoto.thumbnail //this is the line causing error

    return cell
}

And this is my PhotoCollectionViewCell class
class PhotoCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView! //I double checked this IBOutlet whether it connects with Storyboard or not
}

Original question
Now comes the interesting part.
I'm using a prototype cell in the UICollectionView and I set a reusable identifier from attributes inspector. Also I changed the custom class from identity inspector to my PhotoCollectionViewCell.
I searched for the same issue and found out that when using prototype cell, deleting
self.collectionView!.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

from code will work. I gave it a try and it works.

But I'm curious to know the reason behind this issue. I couldn't reproduce the same issue with UITableView but with UICollectionView.

Not a possible duplicate:
This UICollectionView's cell registerClass in Swift is about how to register class in UICollectionView. But my question doesn't expect how to register. My question is about an issue that isn't true with UITableView class but with UICollectionView only. I'm expecting the actual difference between this conflicting issue.

A: There are 3 ways to register a cell (either for UITableView or UICollectionView).

*

*You can register a class. That means the cell has no nib or storyboard. No UI will be loaded and no outlets connected, only the class initializer is called automatically.

*You can register a UINib (that is, a xib file). In that case the cell UI is loaded from the xib and outlets are connected.

*You can create a prototype cell in the storyboard. In that case the cell is registered automatically for that specific UITableViewController or UICollectionViewController. The cell is not accessible in any other controller.
The options cannot be combined. If you have a cell prototype in the storyboard, you don't have to register again and if you do, you will break the storyboard connection.

A: You can assign Nib to Collection view cell with an identifier as follows :
self.collectionView.register(UINib(nibName: "nibName", bundle: nil), forCellWithReuseIdentifier: "cell")

Hope it helps.


text:
Q: How to check if the mouse control is inside VM console c#? Suppose i have opened a vm console(EXSI or vcloud) in a browser.
I have a requirement to check whether the mouse pointer is inside the vm console or in the physical machine.
Is there a way in which i can find out where the mouse control is ?
what would be the difference in the properties of a mouse control when it is captured inside a vm console and in physical machine ?
Thanks


text:
Q: Trying to locate Codeigniter function executed in the view file I'm trying to find where below query is coming from. Below is executed in view file which is resource_update.php but I cannot find add_resource function from resource controller...
Is there a reason why?
$this->resources->add_resource($desc_arr, $desc_limit, $new_clients);

A: Check if "resources" is actually a library or a model. I don't think we ever need to call another controller from a view (which is again loaded by a controller).
i.e., How is resources loaded?
$this->load->library('resources');

or
$this->load->model('resources');

Other than lack of sleep, I see no reason why you should not find the function that way. :)
If its really bothering you - try Changing your IDE to PhpDesigner, Netbeans etc. They have a cool way of finding the function definition and code hinting.
Cheers!


text:
Q: WP Query and multiple pages Can anyone tell me why this isn't working? Assuming two things here - 1. WP Query handles multiple page requests, and 2. doesn't need a reset because I'm creating a new WP Query.
What happens is I only get the last page to be shown (389). Above this code on the same page there is another WP Query that only fetches one page. Could this be the reason, or is it the way I request the pages? I've tried applying all the reset handlers but they gave no effect.
The code -
<?php $promo = new WP_Query( array( 'post_type' => 'page', 'post__in' => array(62,18,389) ) ); while ($promo->have_posts()) : $promo->the_post(); ?>
<?php the_permalink() ?>
<?php the_post_thumbnail() ?>
<?php the_title() ?>
<?php the_excerpt() ?>
<?php endwhile; ?>

A: Because your posts are only saved whithin the $promo var and not in the $wp_query global var. I recommend you to use get_posts() http://codex.wordpress.org/Template_Tags/get_posts

A: You need to do paging in the WP Query to make it work right (using paged parameter)


text:
Q: Derivative of function $f(x) = \sqrt{2x}+ \sqrt{2/x}$ The derivative of function
$$f(x) = \sqrt{2x}+ \sqrt{2/x}$$
Here's what I did,
$$f(x) = \sqrt{2x}+ \sqrt{2/x}
\\ = (2x)^{1\over2} + ({2\over x})^{1 \over 2}\\\\$$
$$f'(x)={1\over 2}(2x)^{-{1\over 2}}(2) + {1\over 2}({2 \over x})^{-{1 \over 2}}({2\over x^2})
\\=2x^{-{ 1\over 2}}+({1\over x})^{-{1\over 2}} ({2\over x^2})$$
I don't know what is going on!
Please help what I did wrong and what I should do
Thank you.
Or Can I see the steps how it's solved?

A: You have
\begin{align}
f(x) &= \sqrt{2x} + \sqrt{\frac{2}{x}} \\
&= (2x)^{\frac{1}{2}} + (2x^{-1})^{\frac{1}{2}} \\
&= \frac{1}{2}\cdot 2 \cdot (2x)^{\frac{-1}{2}} + \frac{1}{2} \cdot -2x^{-2} \cdot (2x^{-1})^{\frac{-1}{2}} \\
&= \frac{1}{\sqrt{2x}} - \frac{1}{\sqrt{2} x^{\frac{3}{2}}}
\end{align}


text:
Q: Mongodb : Clone all documents in a collection I have a mongoDB Collection and I want to clone all the documents in the same collection but all the new documents should have a unique "_id" field.
Document within my Collection 'event'
{
"_id" : ObjectId("fsfd324324324wer"),
"active" : false,
"channels" : [
    "1",
    "2"
],
"created" : ISODate("2013-06-16T00:25:57.781Z"),
"curationId" : ObjectId("51bd0612b0bf4e7035bfea00"),
"deleted" : true,
"lower_name" : "garden",
"name" : "Garden",
"user" : "abc"

}
The query which I tried is as below :
    db.event.find().forEach(function (x) {
    delete x._id;
    db.event.insert(x);
});

A: I am assuming collection name as myCollection.
db.myCollection.find().forEach(function (x) {
    delete x._id;
    db.myCollection.insert(x);
});


text:
Q: Pager app - When app is killed - Listen to firebase changes and send notification As part of my learning of Google's Firebase and Android (Kotlin), I have come up with a simple app idea that I wanted to pursue and actually publish on Google store.
The idea is that you create a group, join people, and send short pre-defined messages as push notifications to everyone in the group. Kind-of like a pager or chat app.

*

*Creating users and groups is done using Firebase Cloud Firestore --> that part works perfectly fine

*For the notification part, within the group, I insert a notification object under the Group collection and have a database listener on my app side that creates the notification, simple implemention like this:

val docRef = DatabaseController.db.collection(NaggerGlobalNotifications.TABLE_NAME)
        docRef.addSnapshotListener { snapshot, e ->
            if (e != null) {
                Log.w(TAG, "Listen failed.", e)
                return@addSnapshotListener
            }

            for (dc in snapshot!!.documentChanges) {
                when (dc.type) {
                    DocumentChange.Type.ADDED -> {
                        val newNotification = dc.document.toObject<MyNotification>()
                        NotificationsController.createNotification(
                            this,
                            newNotification.title,
                            newNotification.message
                        )
                    }
                }
            }
        }

The "NotificationsController.createNotification" creates the notification using standard NotificationCompat.Builder which works perfectly fine.
Now comes the part with which I am struggling
My initial plan was to have a Service that has this listener running in the background. As soon as some notification is added to my Firebase Cloud Firestore node, the listener catches it and makes the notification on the group members' phones.
This works perfectly fine when the app is alive. When the app is killed, the notifications cease to work.
I tried a solution described here: https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android but I ended up here: Listen to firebase database changes when app is closed . In general, the proposed fix worked except...
It seems it is not possible to listen for Firebase database changes in the background
I could implement this is as a kind of a timer task, to call Firebase DB every 30 seconds or use the FCM messages instead of the database, but that begs the question:

*

*In case of timer call - if I would have a million users and every 30 seconds there would be a million calls to firebase for updates, would I have to be a millionaire to buy that kind of bandwidth with Google Firebase?

*In case of FCM - triggering FCM messages is possible only using Firebase console or with the need of a setting up a dedicated server (I think?) --> nice for big companies, but not for a single developer like me :(

In general, what I seek here is a bit of a guidance.
The app is kind of like a chat app with predefined short messages (like 100 characters max) and I guess I am trying to implement this with the least possible hardware expenses. Perhaps I'm being foolish here to believe this is possible without huge servers.
Thank you for any tips!
Keran

A: You can use Cloud Functions for Firebase

The developer writes code for a new function, selecting an event
  provider (such as Realtime Database), and defining the conditions
  under which the function should execute.

I have a chat app. I am using Functions and Realtime Database. When it is written a new message to database, I'm sending a notification to user. In this way, I do not need to take any action. Firebase makes the listening process for me and sends a notification.
Free mode:

Invocations => 125K/month


text:
Q: How to create loop for opposite or reverse classes in Sass? Have two different classes and they have values that are opposite to one another. Is there a way to write them in Sass through an optimized way?
For example:
.left-column{
    float: left;
    margin: 20px;
    padding-right: 20px;
    transform: rotateY(30deg);
}
.right-column{
    float: right;
    margin: 20px;
    padding-left: 20px;
    transform: rotateY(-30deg);
}

These two classes are quite similar, except for some of the values being either reversed (right/left) and one negative while the other positive. I wish to be able to change their values more easily through one medium and have it change relatively for both when generating for the CSS (say I change the rotation to 45, from 30, and it would change to 45 and -45 respectively).
Currently I have this setup:
@each $direction, $distinctions in (
left: (left, right, 30),
right: (right, left, 30)
) {
    $_float: nth($distinctions, 1);
    $_padding: nth($distinctions, 2);
    $_transformation: nth($distinctions, 3);

    .#{$direction}-column {
        float: #{$_float};
        margin: 20px;
        padding-#{$_padding}: 20px;
        transform: rotateY(30deg * #{$_transformation});

        border-color: darken($primary-color, $min-difference-amount) $_border-color-right darken($primary-color, $min-difference-amount) $_border-color-left;
        #{$_ribbon-position}: -30px;
    }
}

I don't even mind creating a new mixin or function seeing as this scenario will probably repeat itself a lot.

A: If we consider only 2 "directions", the solution could be easier.
@mixin mirror($side1) {
  $side2: right;
  $k1: 1;
  @if $side1 == right {
    $side2: left;
    $k1: -1;
  }
  $k2: $k1 * -1;

  float: $side1;
  margin: 20px * $k1;
  padding-#{$side2}: 20px;
  transform: rotateY(30deg * $k2);
}

.left-column {
  @include mirror(left);
}
.right-column {
  @include mirror(right);
}

Here we have 2 opposite coefficients and 2 opposite "sides". The SCSS above is compiled to:
.left-column {
  float: left;
  margin: 20px;
  padding-right: 20px;
  transform: rotateY(-30deg);
}

.right-column {
  float: right;
  margin: -20px;
  padding-left: 20px;
  transform: rotateY(30deg);
}


text:
Q: Run ipython notebook with django-extensions I installed django-extensions and ipython with pip install. Both of them work separately.
However, when I run:
python manage.py shell_plus --notebook

I got:
[C 15:35:20.267 NotebookApp] Bad config encountered during initialization:
[C 15:35:20.267 NotebookApp] Unrecognized flag: '--ext'

I used everything by default, nothing changed at all. Did I do something wrong?
BTW: my django project is installed in virtualenv.

A: Problem solved.
The django-extensions doesn't work with ipython 3.0, changed it to 2.4 solve the problem.


text:
Q: Retrieve response body from ClientResource I try to issue a POST request with ClientResource, I'm able to retrieve the response STATUS, I also want to get the response body when I get an exception.
Here is my code:
public static Pair<Status, JSONObject> post(String url, JSONObject body) {
    ClientResource clientResource = new ClientResource(url);
    try {
        Representation response = clientResource.post(new JsonRepresentation(body), MediaType.APPLICATION_JSON);

        String responseBody = response.getText();
        Status responseStatus = clientResource.getStatus();

        return new ImmutablePair<>(responseStatus, new JSONObject(responseBody));
    } catch (ResourceException e) {
        logger.error("failed to issue a POST request. responseStatus=" + clientResource.getStatus().toString(), e);
        //TODO - how do I get here the body of the response???
    } catch (IOException |JSONException e) {
        throw e;
    } finally {
        clientResource.release();
    }
}

Here is the code that my server resource returns in case of failure
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
        put("result", "failed to execute") );
return response;

I try to catch the "result" with no success

A: In fact, the getResponseEntity method returns the content of the response. It corresponds to a representation. You can wrap it by a JsonRepresentation class if you expect some JSON content:
try {
    (...)
} catch(ResourceException ex) {
    Representation responseRepresentation
           = clientResource.getResponseEntity();
    JsonRepresentation jsonRepr
           = new JsonRepresentation(responseRepresentation);
    JSONObject errors = jsonRepr.getJsonObject();
}

You can notice that Restlet also supports annotated exceptions.
Otherwise I wrote a blog post about this subject: http://restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/. I think that it could help you.
Thierry


text:
Q: JProfiler, connecting to a machine behind a firewall I am trying to use JProfiler on my MAC to connect to a machine remotely that is behind a firewall and only accessible via a Linux machine.
I have set up a direct SSH tunnel as follows:
ssh -L 8849:remote:8849 forwardingmachine

And start Jprofiler with
java -agentpath:/path/jprofiler8/bin/linux-x64/libjprofilerti.so=port=8849 ..."

I systematically get the error:

Connection error
Either an old version of the native library is used or another
  application is listening on port 8849. Please check your
  DYLD_LIBRARY_PATH environment variable and your port configuration

Online there are solutions for using a 2 hop SSH tunnel, but I can't do that due to the second machine only being accessible to forwardingmachine.
Any ideas of how to get around this?
(The remote machine uses Java 1.7, whereas my Mac uses Java 1.8). Both machines are using jprofiler8

A: A direct tunnel to remote is set up with the command
ssh -t user@remote -L [localPort]:localhost:[remotePort] -N


text:
Q: How do I fix my selection sort? only returns "0" Hello I'm fairly new to c++ coding as a first-year comp sci major and I am working on a lab in which I have to fill an array and do multiple types of sorting and searching, and I'm stuck on selection sort as my code will only return 0. any help is appreciated! <3 ^_^
HOW TO USE

*

*FIRST DO OPTION "1" TO FILL IN ARRAY

*ENTER 10 NUMBERS (PREFERABLY IN MESSED UP ORDER

*CODE WILL RETURN TO MAIN MENU

*DO OPTION "4"

CODE
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;

//Fill In Array
void fillData(int array[])
{

    cout << "Enter 10 numbers to fill in the array ";
    for (int i = 0; i < 10; i++)
    {
        cin >> array[i];
    }
}
//Linear search
int lSearch(int array[], int size, int target, int option)
{
    if (option == 2)
    {
        cout << "What number are you looking for?";
        cin >> target;

        for (int index = 0; index < size; index++)
            if (target == array[index])
                return index;
    }
    else
        return -1;
}
//Binary Search
int bSearch(const int array[], int size, int value)
{
    cout << "What number are you looking for?";
    cin >> value;

    int first = 0,
        last = size - 1,
        middle,
        position = -1;
    bool found = false;
    while (!found && first <= last)
    {
        middle = (first + last) / 2;
        if (array[middle] == value)
        {
            found = true;
            position = middle;
        }
        else if (array[middle] > value)
            last = middle - 1;
        else
            first = middle + 1;
    }
    return position;
}
//Selection Sort
int selectionSort(int array[], int size )
{
    int i{};
    for (int i = 0; i < size; i++)
    {
        int smallest = array[i];
        int smallestIndex = i;

        for (int m = i; m < 10; m++)
        {
            if(array[m] < smallest)
                {
                    smallest = array[m];
                    smallestIndex = m;
                }
        }
        swap(array[i], array[smallestIndex]);
    }
    return array[i];

}

//everything together
int main()
{
    int option{};
    int array[10];
    int result;
    int target{};
    //display menu
    do
    {
        cout << setw(20) << setfill('-') << "" << "MENU" << setw(20) << setfill('-') << "" << endl;
        cout << "1. Fill Data" << endl;
        cout << "2. Linear Search" << endl;
        cout << "3. Binary Search" << endl;
        cout << "4. Selection Sort" << endl;
        cout << "5. Bubble Sort" << endl;
        cout << "6. Display Data" << endl;
        cout << endl;
        cout << "Which Option Would you like to do? ";
        cin >> option;
        cout << endl;

        switch (option)
        {
        case 1:
            fillData(array);
            break;

        case 2:
            //Linear search
            result = lSearch(array, 10, target, option);
            cout << " That number is inside of index # " << result << endl;
            cout << endl;
            break;

        case 3:
            //Binary search
            result = bSearch(array, 10, option);
            cout << " That number is inside of index # " <<  result << endl;

        case 4:
            //Selection Sort
            result = selectionSort(array, 10);
            cout << "selection sort is " << result << endl;

        }

    } while (option != -1);
    system("pause");
    return 0;

}

A: Ask yourself what the result of sorting an array should be. I hope you can see that it should be another array. If you sort the array {4, 8, 1, 3} (for instance) into ascending order the result is the sorted array {1, 3, 4, 8}.
But your code assumes that the result of a sorting an array is an integer.
result = selectionSort(array, 10);

This is fine for your other operations like linear search or binary search where the result is an array index, but for sorting it just makes no sense at all.
The selectionSort function you've written looks OK (although I haven't tested it). It's what's known as a in-place sort, which means that instead of creating and returning a new array it modifies the array it has been given so that array itself is sorted.
What this means for your program is that your sorting routine doesn't have to return anything at all. Instead it sorts the array it has been given. So change your selectionSort function to return nothing
void selectionSort(int array[], int size )

and change the code after you've called selectionSort to print the array that was passed to selectionSort, which should now be sorted. Something like this
selectionSort(array, 10);
cout << "selection sort is";
for (int i = 0; i < 10; i++)
    cout << ' ' << array[i];
cout << '\n';


text:
Q: Creating a 360 degree product preview slider in angular js I want to create a 360 degree product preview showing lots of images by controlling that rotation with touch events. I created this by jquery plugin but i need this by angular js. Please suggest any approach to create this in angular js.My Jquery code snippet

var ab=[
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0001.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0001.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0002.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0003.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0004.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0005.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0006.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0007.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0008.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0009.png",
" https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0010.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0010.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0011.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0012.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0013.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0014.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0015.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0016.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0017.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0018.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0019.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0020.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0021.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0022.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0023.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0024.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0025.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0026.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0027.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0028.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0029.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0030.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0031.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0032.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0033.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0034.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0035.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0036.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0037.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0038.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0039.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0040.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0041.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0042.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0043.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0044.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0045.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0046.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0047.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0048.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0049.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0050.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0051.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0052.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0053.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0054.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0055.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0056.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0057.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0058.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0059.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0060.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0061.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0062.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0063.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0064.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0065.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0066.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0067.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0068.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0069.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0070.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0071.png","https://s.tmocache.com/content/dam/tmo/en-p/cell-phones/lg-g5/silver/spin/lg-g5-silver.spin.0072.png"];
$("#mySpriteSpin").spritespin({
  // path to the source images.
  source: ab,
  width   : 500,  // width in pixels of the window/frame
  height  : 500,  // height in pixels of the window/frame
  sense: -1,
  frame: 1,
  animate: false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://spritespin.ginie.eu/spritespin.js"></script>
<div id='mySpriteSpin'/>

A: You can follow this github link for angularjs 360 product view plugin


text:
Q: AddressSanitizer:DEADLYSIGNAL error for linked list in C I'm trying to make a linked list in C where it reads from an input file and either adds or deletes nodes. I'm getting an AddressSanitizer:DEADLYSIGNAL error (pictured) which I think is from dereferencing a null pointer in my insert node function, but I cannot find where I do that. If I am wrong on what this error means, or you see where I am going wrong that would be a ton of help. Thanks so much!!
'''
#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
  int data;
  struct Node *next;
} Node;

void printList(Node *head){
  Node *temp = head->next;
  int count;
  while(temp != NULL){
    temp = temp->next;
    count++;
  }
  printf("%d\n", count);
  temp = head->next;
  while(temp != NULL){
    printf("%d\t", temp->data);
    temp = temp->next;
  }
}

Node *makeNode(int value){
  Node *newNode = malloc(sizeof(Node));
  newNode->data = value;
  newNode->next = NULL;
  return newNode;
}

void insertNode(Node *head, Node *newNode){
  Node *temp ,*prev;
  temp = head;
  while(temp != NULL && temp->data <= newNode->data) {
    prev = temp;
    temp = temp->next;
  }
  newNode->next = temp;
  prev->next = newNode;
}

void deleteNode(Node *head, int deleteNum){
  if(head->next != NULL){
    if(head->next->data == deleteNum){
      head->next = head->next->next;
      free(head->next);
    }
    else{
      //printf("hello");
      Node *temp ,*prev;
      temp = head;
      while(temp != NULL && temp->data != deleteNum) {
        prev = temp;
        temp = temp->next;
      }
      if(temp != NULL){
        prev->next = temp->next;
        //free(temp);
      }
    }
  }
}

int main(int argc, char* argv[])
{
  Node* head = malloc(sizeof(Node));
  Node *temp;
  char* filename = argv[1];
  if(fopen(filename, "r") == NULL){
    printf("error");
  }
  else{
  FILE* fp = fopen(filename, "r");
  char mode;
  int tempData;

  while (fscanf(fp, "%c\t%d\n", &mode, &tempData ) == 2) {
    //printf("%c\n", mode);
    if(mode == 'i'){
      //printf("%c\n", 'i');
      Node *insert = makeNode(tempData);
      insertNode(head, insert);
    }
    else if(mode == 'd'){
      //printf("%c\n", 'd');
      //printList(head);
      deleteNode(head, tempData);
      //printList(head);
    }
  }
  printList(head);
}
}

'''

A: You never initialize the node that head points to in main, so when you pass it to insertNode, the value of head->next may be garbage; in particular it may not be NULL.  In that case the while loop will run at least two iterations, setting temp to the garbage pointer head->next, and the access of temp->data in the condition of the while will dereference that garbage pointer.  Hence the crash.
You probably want head->next = NULL; somewhere in main, after the malloc but before the insertNode.   Or better still, use your existing makeNode function to allocate head.
There is another bug in that you also never initialize head->data, which is compared against newNode->data.  If the garbage in head->data is greater than newNode->data, insertNode will attempt to insert it in the list prior to head, which won't work and will simply result in the node being lost.  Moreover prev will be used uninitialized, which will probably also crash.  You could work around by initializing head->data to INT_MIN, but it would be better to fix the logic of insertNode so that it never compares against head->data in the first place.  deleteNode has a similar issue.
One more bonus bug: count is uninitialized in printList.
You could have found the latter bugs by compiling with -Wall -O; gcc will then detect and warn about uninitialized variables.  valgrind also detected the printList bug for me.


text:
Q: Why am I getting LazyInitializationException when using OpenEntityManagerInViewFilter? (using Spring Roo) I've generated my project using Spring Roo and has not touched the xml files.
All I'm trying to do is to get a collection through a ITD method of an entity.
I get the following error:
    SEVERE: Servlet.service() for servlet MyProject threw exception
org.hibernate.LazyInitializationException: failed to lazily initialize a collect
ion of role: com.myproject.main.domain.Juser.securityRoles, no session or session
was closed

Please guide me. I'm stuck badly.

A: Lazy init in hibernate is where it loads relationships on demand instead of at query time.
This is often more efficient as it means the main query is simpler.
Sometimes you need to force the loading of the lazy relp's before the session is closed.
In this case, you just need to call a method on the relp objects just after the query to load them completes.


text:
Q: Install a Service as x64 I have developed a service on a 64 bit system using Visual Studio 2010. The service is just a skeleton that accesses the Start and Stop methods in a secondary library. The library accesses a 64 bit COM object, and must be built as x64. The COM object is a dll that was built separately as x64 and tested in a 64-bit environment. I have an installer that sets up the project and installs the service through a custom action.
I debug the code with a test app that bypasses the service, and so I can confirm that the library the service is accessing is working correctly.
The problem I am having is a BadImageFormatException when installing. I am using an installer with a target platform of x64. If I build everything as x64, I get the following message:
Error 1001. Exception occured while initializing the installation: System.BadImageFormatException. Could not load file or assembly... or one of its dependencies. An attempt was made to load a program with an incorrect format.

If I set the service to build as Any CPU, the installation works, and the service can access the library, but the COM object cannot be found. The installation will also work if I remove the custom action that installs the service. If I then try to install the service manually using installutil, I get the same error message as above.
Below is a list of the libraries I am using in the service.
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using MAPIMail;
using MAPIMail.Logging;

Note that the MAPIMail project is being built as x64.
Does anyone have an idea about why I cannot install the service specifically as x64 when it installs fine as Any CPU on an x64 system. I appreciate any and all suggestions.

A: I tried both Alex's and Jacob Seleznev's solutions, and they both worked. I found that the second answer, by Greg Sansom, from Jacob's link provided the best solution. To assist others, I have copied his answer below:

This can happen if your installer is installing 64-bit dlls. The
  following is copied from MSDN:
If you add a 64-bit managed custom action to a Setup project, the
  Visual Studio build process embeds a 32-bit version of
  InstallUtilLib.dll into the MSI as InstallUtil. In turn, the 32-bit
  .NET Framework is loaded to run the 64-bit managed custom action and
  causes a BadImageFormatException exception.
For the workaround, replace the 32-bit InstallUtilLib.dll with the
  64-bit version.
1. Open the resulting .msi in Orca from the Windows Installer SDK.
2. Select the Binary table.
3. Double click the cell [Binary Data] for the record InstallUtil.
4. Make sure "Read binary from filename" is selected and click the Browse button.
5. Browse to %WINDIR%\Microsoft.NET\Framework64\v2.0.50727.
6. The Framework64 directory is only installed on 64-bit platforms and corresponds to the 64-bit processor type.
7. Select InstallUtilLib.dll.
8. Click the Open button.
9. Click the OK button.

share|edit|flag    answered Jul 23 '11 at 3:09 Greg Sansom 6,5781335

A: My guess is that you are using the 32bit InstallUtil which can only install as 32 bit, you need to use the 64 bit Installutil as described here


text:
Q: Spring Security Filter and Posted Data I wrote a custom Spring Security filter that needs to user XML data that was posted to it.  How would the filter get the posted data?

A: It's not a really Spring Security-specific problem, since you are likely just implementing the javax.servlet.Filter interface. In this case, you are implementing the method:
public void doFilter ( ServletRequest request, ServletResponse response,
   FilterChain chain ) throws IOException, ServletException;

You can then cast the ServletRequest to a HttpServletRequest if you need HTTP-specific data (which is usually required):
import javax.servlet.http.HttpServletRequest;
// ...
HttpServletRequest httpRequest = (HttpServletRequest) request;
String xml = httpRequest.getParameter("xml");

If you are extending one of the standard Spring Security filters, make sure you look at the source for the filter you're extending! Many of them already override doFilter and expect that you will override another method to augment their behavior.

A: Read through the documentation for AbstractAuthenticationProcessingFilter (based on your earlier question, I guess this is the class that your custom filter extends), the abstract method to implement is attemptAuthentication, which receives HttpServletRequest and HttpServletResponse as parameters:
Parameters:
    request - from which to extract parameters and perform the authentication
    response - the response, which may be needed if the implementation has to do a redirect as part of a multi-stage authentication process (such as OpenID).