Q: Consuming an XML API in CakePHP I have a web application that involves calling a number of different XML/API webservices.  The application has already been implemented in old school procedural code (by my predecessor) and I have managed to convince the IT director that it needs to be coded into a more robust framework.  I've settled on CakePHP because it's the framework I am most familiar with.
I have Googled extensively for advice on how to consume an XML/API.  One blog post did it in the controller, but I feel it belongs more in the model.  Perhaps I could create a behaviour that handles the transfers and then code methods in the Model that will strip out the information I need from the returned XML?
Does anybody have some advice on this or a pointer?

A: I imagine you are using it to get database like data or config data, this is normally done in the model, though there is not restriction in where you do it. You could do the extracting and preparing of the data in the model and the logic in the controller. Something like loading the config parameters and putting them in variables and then using this variables in the controller.
Also you may use cakephp XML library to do all this. Since is a library you MAY do it either in controller or model.
Hope this helps you :)


Q: Convert Apple Emoji (String) to UIImage I need all Apple Emojis. I can get all the emojis and put them into a String by copying them from the site getemoji but in my app i need the emojis in the right order as images.
Is there a nice way to convert the emojis I copy into a String to a UIImage?
Or a better solution to get all the Apple emojis in the right order?

A: Updated @Luca Angeletti answer for Swift 3.0.1
extension String {

    func image() -> UIImage? {
        let size = CGSize(width: 30, height: 35)
        UIGraphicsBeginImageContextWithOptions(size, false, 0);
        UIColor.white.set()
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(CGRect(origin: CGPoint(), size: size))
        (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}

A: Swift 4.2
I really liked @Luca Angeletti solution. I hade the same question as @jonauz about transparent background. So with this small modification you get the same thing but with clear background color.
I didn't have the rep to answer in a comment.
import UIKit

extension String {
    func emojiToImage() -> UIImage? {
        let size = CGSize(width: 30, height: 35)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.clear.set()
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(CGRect(origin: CGPoint(), size: size))
        (self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 30)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

A: Swift 5: ( with optional fontSize, imageSize and bgColor)
use it like this:
let image      = "".image()
let imageLarge = "".image(fontSize:100)
let imageBlack = "".image(fontSize:100, bgColor:.black)
let imageLong  = "".image(fontSize:100, imageSize:CGSize(width:500,height:100))

import UIKit

extension String
{
    func image(fontSize:CGFloat = 40, bgColor:UIColor = UIColor.clear, imageSize:CGSize? = nil) -> UIImage?
    {
        let font = UIFont.systemFont(ofSize: fontSize)
        let attributes = [NSAttributedString.Key.font: font]
        let imageSize = imageSize ?? self.size(withAttributes: attributes)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        bgColor.set()
        let rect = CGRect(origin: .zero, size: imageSize)
        UIRectFill(rect)
        self.draw(in: rect, withAttributes: [.font: font])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

A: Updated version of @Luca Angeletti's answer using UIGraphicsImageRenderer:
extension String {
    func image() -> UIImage? {
        let size = CGSize(width: 100, height: 100)
        let rect = CGRect(origin: CGPoint(), size: size)
        return UIGraphicsImageRenderer(size: size).image { (context) in
            (self as NSString).draw(in: rect, withAttributes: [.font : UIFont.systemFont(ofSize: 100)])
        }
    }
}

A: Here's an updated answer with the following changes:

*

*Centered: Used draw(at:withAttributes:) instead of draw(in:withAttributes:) for centering the text within the resulting UIImage

*Correct Size: Used size(withAttributes:) for having a resulting UIImage of size that correlates to the actual size of the font.

*Comments: Added comments for better understanding

Swift 5
import UIKit
extension String {
    func textToImage() -> UIImage? {
        let nsString = (self as NSString)
        let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
        let stringAttributes = [NSAttributedString.Key.font: font]
        let imageSize = nsString.size(withAttributes: stringAttributes)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) //  begin image context
        UIColor.clear.set() // clear background
        UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
        nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
        let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
        UIGraphicsEndImageContext() //  end image context

        return image ?? UIImage()
    }
}

Swift 3.2
import UIKit
extension String {
    func textToImage() -> UIImage? {
        let nsString = (self as NSString)
        let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
        let stringAttributes = [NSFontAttributeName: font]
        let imageSize = nsString.size(attributes: stringAttributes)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) //  begin image context
        UIColor.clear.set() // clear background
        UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
        nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
        let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
        UIGraphicsEndImageContext() //  end image context

        return image ?? UIImage()
    }
}

A: Same thing for Swift 4:
extension String {
    func emojiToImage() -> UIImage? {
        let size = CGSize(width: 30, height: 35)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.white.set()
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(rect)
        (self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

A: Updated for Swift 4.1
Add this extension to your project
import UIKit

extension String {
    func image() -> UIImage? {
        let size = CGSize(width: 40, height: 40)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.white.set()
        let rect = CGRect(origin: .zero, size: size)
        UIRectFill(CGRect(origin: .zero, size: size))
        (self as AnyObject).draw(in: rect, withAttributes: [.font: UIFont.systemFont(ofSize: 40)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

The code above draws the current String to an Image Context with a white background color and finally transform it into a UIImage.
Now you can write

Example
Given a list of ranges indicating the unicode values of the emoji symbols
let ranges = [0x1F601...0x1F64F, 0x2702...0x27B0]

you can transform it into a list of images
let images = ranges
    .flatMap { $0 }
    .compactMap { Unicode.Scalar($0) }
    .map(Character.init)
    .compactMap { String($0).image() }

Result:

I cannot guarantee the list of ranges is complete, you'll need to search for it by yourself

A: This variation is based on @Luca's accepted answer, but allows you to optionally customize the point size of the font, should result in a centered image, and doesn't make the background color white.
extension String {
    func image(pointSize: CGFloat = UIFont.systemFontSize) -> UIImage? {
        let nsString = self as NSString
        let font = UIFont.systemFont(ofSize: pointSize)

        let size = nsString.size(withAttributes: [.font: font])
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let rect = CGRect(origin: .zero, size: size)
        nsString.draw(in: rect, withAttributes: [.font: font])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}


Q: How do you choose where to put information based on an index into a pandas DataFrame? In MATLAB, the loop I create looks like:
header_names = {'InvoiceNo','Customer',...}

for i = 1:length(x)
    entry(index+i,:) = [InvoiceNo, Customer,...]
end
% Create a table from the data.
fin_table = cell2table(entry,'VariableNames',header_names);

% Write to the finish file.
writetable(fin_table,finish);

With the table values and headers, I will end up getting something that looks like:

InvoiceNo
Customer

1000
Jimmy

1001
Bob

1002
Max

1003
April

1004
Tom

...
...

...
...

...
...

...
...

I would like to know how to accomplish this in Python. My main question is how do I create the entry? How do I put a table in a for loop and ask it to print information on the next row for each iteration?
In Python, I currently have the following:
        for i in range(len(item)):
            entry = pd.DataFrame(
                [InvoiceNo, Customer, invoice, due, terms, Location, memo, item[i], item[i], quan[i], rate[i], taxable,
                 tax_rate, invoice, email, Class],
                columns=['InvoiceNo', 'Customer', 'InvoiceDate', 'DueDate', 'Terms', 'Location', 'Memo', 'Item',
                         'ItemDescription', 'ItemQuantity', 'ItemRate', 'ItemAmount', 'Taxable', 'TaxRate',
                         'ServiceDate', 'Email', 'Class'])
        # Increment the index for entry values to be correct.
        index += len(item)

Any help would be awesome!

A: Although I do not get your question completely, I will try to give you some tools that might be useful:
To get input value you can use (and put this inside of a 'for' loop depending on the number of rows you want to create)
new_InvoiceNo= input("Enter InvoiceNo:\n")
new_Customer= input("Enter Customer:\n")
new_invoice = input("Enter invoice:\n")
...

then you can either append these values as list into the main DF :
to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
new_values = pd.Series(to_append, index = df.columns)
df = df.append(new_values , ignore_index=True)

or , you can use '.loc' method:
to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
df_length = len(df)
df.loc[df_length] = to_append

Try to implement this in your code and report it back here.


Q: MultiThreading with searchbox I have a listbox with list of persons (first name ,last name , addresses...) and a searchbox (TextBox with TextChaned event
the thing is i'm running a search throw database and it take a long time and the UI freeze for seconds ...so,how can I make it responsive ?

A: Assuming that you are working with DataTables, here is what you can do:
private async void btnSearch_Click(object sender, EventArgs e) // async is important
{
    DataTable dt = await Task.Run(() => // await is important (avoids the UI freeze)
    {
        return GetData(); // Fetch your data from DB
    });
    // Fill your listbox with the data in dt
}


Q: How to enable and disable button accordingly if i select the dropdown options in Angular js If I click on the dropdown which is marked inside the blue border, I want the buttons below to be enabled/disabled according to the condition.
If I select first dropdown value. I want the 3rd and 4th button to disabled and 1st and 2nd should be active.
I was looking some angular js code (ng-disabled or ng-class)

A: The selector must be binded to some ng-model, which keep track of the current value. Supposing you have something like this:
<select ng-model="FooBar">
    Some options... (with their respectives value)
</select>

you can enable or desable multiple buttons using this var "FooBar":
<input ng-disabled="FooBar !== desiredEnableValue">


Q: Is it worth mitigating against the effects of garbage collection? I have an application where the memory profile looks something like this:

(source: kupio.com)
The slow upwards crawl of memory usage is caused by the allocation of lots and lots of small, simple, transient objects. In low-memory situations (This is a mobile app) the GC overhead is noticeable when compared to less restrictive memory amounts.
Since we know, due to the nature of the app, that these spikes will just keep on coming, I was considering some sort of pool of multitudinous transient objects (Awesome name). These objects would live for the lifetime of the app and be re-used wherever possible (Where the lifetime of the object is short and highly predictable).
Hopefully this would mitigate against the effects of GC by reducing the number of objects collected and improve performance.
Obviously this would also have its own performance limits since "allocation" would be more expensive and there would be an overhead in maintaining the cache itself.
Since this would be a rather large and intrusive change into a large amount of code, I was wondering if anyone had tried something similar and if it was a benefit, or if there were any other known ways of mitigating against GC in this sort of situation. Ideas for efficient ways to manage a cache of re-usable objects are also welcome.

A: This is similar to the flyweight pattern detailed in the GoF patterns book (see edit below). Object pools have gone out of favour in a "normal" virtual machine due to the advances made in reducing the object creation, synchronization and GC overhead. However, these have certainly been around for a long time and it's certainly fine to try them to see if they help!
Certainly Object Pools are still in use for objects which have a very expensive creation overhead  when compared with the pooling overheads mentioned above (database connections being one obvious example).
Only a test will tell you whether the pooling approach works for you on your target platforms!
EDIT - I took the OP "re-used wherever possible" to mean that the objects were immutable. Of course this might not be the case and the flyweight pattern is really about immutable objects being shared (Enums being one example of a flyweight). A mutable (read: unshareable) object is not a candidate for the flyweight pattern but is (of course) for an object pool.

A: Normally, I'd say this was a job for tuning the GC parameters of the VM, the reduce the spiky-ness, but for mobile apps that isn't really an option. So if the JVms you are using cannot have their GC behavioure modified, then old-fashioned object pooling may be the best solution.
The Apache Commons Pool library is good for that, although if this is a mobile app, then you may not want the library dependency overhead.

A: Actually, that graph looks pretty healthy to me.  The GC is reclaiming lots of objects and the memory is then returning to the same base level.  Empirically, this means that the GC is working efficiently.
The problem with object pooling is that it makes your app slower, more complicated and potentially more buggy.  What is more, it can actually make each GC run take longer.  (All of the "idle" objects in the pool are non-garbage and need to be marked, etc by the GC.)

A: Does J2ME have a generational garbage collector? If so it does many small, fast, collections and thus the pauses are reduced. You could try reducing the eden memory space (the small memory space) to increase the frequency and reduce the latency for collections and thus reduce the pauses.
Although, come to think of it, my guess is that you can't adjust gc behaviour because everything probably runs in the same VM (just a guess here).

A: You could check out this link describing enhancements to the Concurrent Mark Sweep collector, although I'm not sure it's available for J2ME.  In particular note:
"The concurrent mark sweep collector, also known as the concurrent collector or CMS, is targeted at applications that are sensitive to garbage collection pauses."
... "In JDK 6, the CMS collector can optionally perform these collections concurrently, to avoid a lengthy pause in response to a System.gc() or Runtime.getRuntime().gc() call. To enable this feature, add the option"
-XX:+ExplicitGCInvokesConcurrent

A: Check out this link. In particular:

Just to list a few of the problems
  object pools create: first, an unused
  object takes up memory space for no
  reason; the GC must process the unused
  objects as well, detaining it on
  useless objects for no reason; and in
  order to fetch an object from the
  object pool a synchronization is
  usually required which is much slower
  than the asynchronous allocation
  available natively.

A: You're talking about a pool of reusable object instances.
class MyObjectPool {
    List<MyObject> free= new LinkedList<MyObject>();
    List<MyObject> inuse= new LinkedList<MyObject>();
    public MyObjectPool(int poolsize) {
        for( int i= 0; i != poolsize; ++i ) {
           MyObject obj= new MyObject();
           free.add( obj );
        }
    }
    pubic makeNewObject( ) {
        if( free.size() == 0 ) {
            MyObject obj= new MyObject();
            free.add( obj );
        }
        MyObject next= free.remove(0);
        inuse.add( next );
        return next;
   }
   public freeObject( MyObject obj ) {
       inuse.remove( obj );
       free.add( obj );
   }
}
        return in

A: Given that this answer suggests that there is not much scope for tweaking garbage collection itself in J2ME then if GC is an issue the only other option is to look at how you can change your application to improve performance/memory usage. Maybe some of the suggestions in the answer referenced would apply to your application.
As oxbow_lakes says, what you suggest is a standard design pattern. However, as with any optimisation the only way to really know how much it will improve your particular application is by implementing and profiling.


Q: HTML: Accept-Charset attribute and Accept attribute I'm using angularJS, and when i try to set there Accept-Charset attribute i get: Refused to set unsafe header "Accept-Charset", but when i set manually something like:
    headers: {
      'Content-Type': 'text/csv',
      'Accept': 'application/json, text/plain; charset=WIN-1251'
    }

all is ok
so... question)
Is there any difference between this two attributes?
or server will recognize my accept with charset, and i do not need Accept-Charset anymore?


Q: Menu flow is wrong in android mobile phones I have one word-press site ,the menu flow of the site is working fine in desktop and i-phone , but flow is wrong in all android phones .
the problem is :
i have a main menu "courses" and sub menu under courses is "school programs".
when ever i click "courses" then the page "school programs" will load aromatically instead of "courses" page .
and i am clear that this problem is with android mobiles only .
code is :

  Courses

School Programs

Women’s self defence

Security Programs

Business Workshops

Krav Maga Instructor Course

site URL : http://www.kravmagaoz.com.au/
any help .

A: Actually there is some overlapping of your div of
 tag so you need to check the css and add updated code in @media query.
Thanks


Q: Javacard form factors I'm totally new in the Smartcard world, and would really appreciate some clarifications regarding Javacard form factors and interfaces, as I've found it very hard to research the different options.
Ideally I would like to find a contactless Javacard 2 (or 3) chip + antenna that is not encased in plastic, because I want to put it inside another product. I want it to be as small as possible, and therefore just contactless, not dual interface.
However all the Javacards I've found that's sold by manufacturers, seem to only have the "business card" form factor. Does anyone know if this is available at all or if not, or at least theoretically possible to produce? Does the Javacard version make any difference in feasibility of this form factor (My applet only requires Javacard 2+)?
If anyone knows what a reasonable bulk price per chip with such a form factor would be, that would also be very interesting to hear.
Thank you!

A: The reason that you find these chips only in smart cards is that that is the best method of developing on them without hassle. There are also form factors for use in e.g. key fobs, which is probably what you're after. That means smaller antenna space and less chance of a good response. These chips and antenna's are tricky to get right so that all distances and orientations work well.
Paper smart cards are commonly not smart cards but throw away memory cards like MiFare or MiFare ultra-light. Usually smart cards come in credit card form, like -uh- those in credit cards. And then they are in plastic (PVC) or polycarbonate for the higher end cards. Demo cards are usually plastic though. Manufacturers aren't shy of not putting any chips or antenna's in there at all when it comes to demo cards (they might be showing off their printing capabilities instead).
The classic Java cards can be in any form factor. However, the more memory the larger the die may be. That can be an issue with some packaging, the small container that the IC is put in and to which the antenna's are connected. Although Java Card 3 is somewhat of a jump in functionality, most cards capable of version 2 would also be OK to run version 3 of Java Card.
The failed web-based "connected" Java Card requires a lot of memory and if you can find it, it will probably be limited to specific form factors. Java Card 3.1 seems to be another jump in functionality for the common "classic" platform and I would expect for high end smart cards to lead the way.

Generally we don't talk prices here. If you are interested in bulk pricing for specific form factors then you need to contact the resellers, not us. But I would first try and read into it. There are some great general purpose books out there on smart cards. That way you'd at least know a bit what you're talking about when contacting such vendor, and in that case you're more likely to be taken seriously.


Q: How to nest transactions in EF Core 6? I am already using transactions inside my repository functions in some cases because I sometimes need to insert data into two tables at once and I want the whole operation to fail if one of the inserts fails.
Now I ran into a situation where I had to wrap calls to multiple repositories / functions in another transaction, but when one of those functions already uses a transaction internally I will get the error The connection is already in a transaction and cannot participate in another transaction.
I do not want to remove the transaction from the repository function because this would mean that I have to know for which repository functions a transaction is required which I would then have to implement in the service layer. On the other hand, it seems like I cannot use repository functions in a transaction when they already use a transaction internally. Here is an example for where I am facing this problem:
// Reverse engineered classes
public partial class TblProject
{
    public TblProject()
    {
        TblProjectStepSequences = new HashSet<TblProjectStepSequence>();
    }

    public int ProjectId { get; set; }

    public virtual ICollection<TblProjectStepSequence> TblProjectStepSequences { get; set; }
}

public partial class TblProjectTranslation
{
    public int ProjectId { get; set; }
    public string Language { get; set; }
    public string ProjectName { get; set; }

    public virtual TblProject Project { get; set; }
}

public partial class TblProjectStepSequence
{
    public int SequenceId { get; set; }
    public int ProjectId { get; set; }
    public int StepId { get; set; }
    public int SequencePosition { get; set; }

    public virtual TblStep Step { get; set; }
    public virtual TblProject Project { get; set; }
}

// Creating a project in the ProjectRepository
public async Task<int> CreateProjectAsync(TblProject project, ...)
{
    using (var transaction = this.Context.Database.BeginTransaction())
    {
        await this.Context.TblProjects.AddAsync(project);
        await this.Context.SaveChangesAsync();
        // Insert translations... (project Id is required for this)
        await this.Context.SaveChangesAsync();
        transaction.Commit();

        return entity.ProjectId;
    }
}

// Creating the steps for a project in the StepRepository
public async Task<IEnumerable<int>> CreateProjectStepsAsync(int projectId, IEnumerable<TblProjectStepSequence> steps)
{
    await this.Context.TblProjectStepSequences.AddRangeAsync(steps);
    await this.Context.SaveChangesAsync();

    return steps.Select(step =>
    {
        return step.SequenceId;
    }
    );
}

// Creating a project with its steps in the service layer
public async Task<int> CreateProjectWithStepsAsync(TblProject project, IEnumerable<TblProjectStepSequence> steps)
{
    // This is basically a wrapper around Database.BeginTransaction() and IDbContextTransaction
    using (Transaction transaction = await transactionService.BeginTransactionAsync())
    {
        int projectId = await projectRepository.CreateProjectAsync(project);
        await stepRepository.CreateProjectStepsAsync(projectId, steps);

        return projectId;
    }
}

Is there a way how I can nest multiple transactions inside each other without already knowing in the inner transactions that there could be an outer transaction?
I know that it might not be possible to actually nest those transactions from a technical perspective but I still need a solution which either uses the internal transaction of the repository or the outer one (if one exists) so there is no way how I could accidentally forget to use a transaction for repository functions which require one.

A: You could check the CurrentTransaction property and do something like this:
var transaction = Database.CurrentTransaction ?? Database.BeginTransaction()

If there is already a transaction use that, otherwise start a new one...
Edit: Removed the Using block, see comments. More logic is needed for Committing/Rollback the transcaction though...

A: I am answering the question you asked "How to nest transactions in EF Core 6?"
Please note that this is just a direct answer, but not an evaluation what is best practice and what not. There was a lot of discussion going around best practices, which is valid to question what fits best for your use case but not an answer to the question (keep in mind that Stack overflow is just a Q+A site where people want to have direct answers).
Having said that, let's continue with the topic:
Try to use this helper function for creating a new transaction:
public CommittableTransaction CreateTransaction()
    => new System.Transactions.CommittableTransaction(new TransactionOptions()
    {
        IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
    });

Using the Northwind database as example database, you can use it like:
public async Task<int?> CreateCategoryAsync(Categories category)
{
    if (category?.CategoryName == null) return null;
    using(var trans = CreateTransaction())
    {
        await this.Context.Categories.AddAsync(category);
        await this.Context.SaveChangesAsync();

        trans.Commit();

        return category?.CategoryID;
    }
}

And then you can call it from another function like:
/// <summary>Create or use existing category with associated products</summary>
/// <returns>Returns null if transaction was rolled back, else CategoryID</returns>
public async Task<int?> CreateProjectWithStepsAsync(Categories category)
{
    using var trans = CreateTransaction();

    int? catId = GetCategoryId(category.CategoryName)
                ?? await CreateCategoryAsync(category);

    if (!catId.HasValue || string.IsNullOrWhiteSpace(category.CategoryName))
    {
        trans.Rollback(); return null;
    }

    var product1 = new Products()
    {
        ProductName = "Product A1", CategoryID = catId
    };
    await this.Context.Products.AddAsync(product1);

    var product2 = new Products()
    {
        ProductName = "Product A2", CategoryID = catId
    };
    await this.Context.Products.AddAsync(product2);

    await this.Context.SaveChangesAsync();

    trans.Commit();

    return catId;
}

To run this with LinqPad you need an entry point (and of course, add the NUGET package EntityFramework 6.x via F4, then create an EntityFramework Core connection):
// Main method required for LinqPad
UserQuery Context;

async Task Main()
{
    Context = this;
    var category = new Categories()
    {
        CategoryName = "Category A1"
        // CategoryName = ""
    };
    var catId = await CreateProjectWithStepsAsync(category);
    Console.WriteLine((catId == null)
           ? "Transaction was aborted."
           : "Transaction successful.");
}

This is just a simple example - it does not check if there are any product(s) with the same name existing, it will just create a new one. You can implement that easily, I have shown it in the function CreateProjectWithStepsAsync for the categories:
int? catId = GetCategoryId(category.CategoryName)
            ?? await CreateCategoryAsync(category);

First it queries the categories by name (via GetCategoryId(...)), and if the result is null it will create a new category (via CreateCategoryAsync(...)).
Also, you need to consider the isolation level: Check out System.Transactions.IsolationLevel to see if the one used here (ReadCommitted) is the right one for you (it is the default setting).
What it does is creating a transaction explicitly, and notice that here we have a transaction within a transaction.

Note:

*

*I have used both ways of using - the old one and the new one. Pick the one you like more.

A: Just don't call SaveChanges multiple times.
The problem is caused by calling SaveChanges multiple times to commit changes made to the DbContext instead of calling it just once at the end. It's simply not needed. A DbContext is a multi-entity Unit-of-Work. It doesn't even keep an open connection to the database. This allows 100-1000 times better throughput for the entire application by eliminating cross-connection blocking.
A DbContext tracks all modifications made to the objects it tracks and persists/commits them when SaveChanges is called using an internal transaction. To discard the changes, simply dispose the DbContext. That's why all examples show using a DbContext in a using block - that's actually the scope of the Unit-of-Work "transaction".
There's no need to "save" parent objects first. EF Core will take care of this itself inside SaveChanges.
Using the Blog/Posts example in the EF Core documentation tutorial :

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer($"Data Source=.;Initial Catalog=tests;Trusted_Connection=True; Trust Server Certificate=Yes");
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

The following Program.cs will add a Blog with 5 posts but only call SaveChanges once at the end :

using (var db = new BloggingContext())
{
    Blog blog = new Blog { Url = "http://blogs.msdn.com/adonet" };
    IEnumerable<Post> posts = Enumerable.Range(0, 5)
                                       .Select(i => new Post {
                                            Title = $"Hello World {i}",
                                            Content = "I wrote an app using EF Core!"
                                         });
    blog.Posts.AddRange(posts);

    db.Blogs.Add(blog);

    await db.SaveChangesAsync();
}

The code never specifies or retrieves the IDs. Add is an in-memory operation so there's no reason to use AddAsync. Add starts tracking both the blog and the related Posts in the Inserted state.
The contents of the tables after this are :
select * from blogs

select * from posts;
-----------------------

BlogId  Url
1   http://blogs.msdn.com/adonet

PostId  Title   Content BlogId
1   Hello World 0   I wrote an app using EF Core!   1
2   Hello World 1   I wrote an app using EF Core!   1
3   Hello World 2   I wrote an app using EF Core!   1
4   Hello World 3   I wrote an app using EF Core!   1
5   Hello World 4   I wrote an app using EF Core!   1

Executing the code twice will add another blog with another 5 posts.
PostId  Title   Content BlogId
1   Hello World 0   I wrote an app using EF Core!   1
2   Hello World 1   I wrote an app using EF Core!   1
3   Hello World 2   I wrote an app using EF Core!   1
4   Hello World 3   I wrote an app using EF Core!   1
5   Hello World 4   I wrote an app using EF Core!   1
6   Hello World 0   I wrote an app using EF Core!   2
7   Hello World 1   I wrote an app using EF Core!   2
8   Hello World 2   I wrote an app using EF Core!   2
9   Hello World 3   I wrote an app using EF Core!   2
10  Hello World 4   I wrote an app using EF Core!   2

Using SQL Server XEvents Profiler shows that these SQL calls are made:
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Blogs] ([Url])
VALUES (@p0);
SELECT [BlogId]
FROM [Blogs]
WHERE @@ROWCOUNT = 1 AND [BlogId] = scope_identity();
',N'@p0 nvarchar(4000)',@p0=N'http://blogs.msdn.com/adonet'

exec sp_executesql N'SET NOCOUNT ON;
DECLARE @inserted0 TABLE ([PostId] int, [_Position] [int]);
MERGE [Posts] USING (
VALUES (@p1, @p2, @p3, 0),
(@p4, @p5, @p6, 1),
(@p7, @p8, @p9, 2),
(@p10, @p11, @p12, 3),
(@p13, @p14, @p15, 4)) AS i ([BlogId], [Content], [Title], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([BlogId], [Content], [Title])
VALUES (i.[BlogId], i.[Content], i.[Title])
OUTPUT INSERTED.[PostId], i._Position
INTO @inserted0;
SELECT [i].[PostId] FROM @inserted0 i
ORDER BY [i].[_Position];
',N'@p1 int,@p2 nvarchar(4000),@p3 nvarchar(4000),@p4 int,@p5 nvarchar(4000),@p6 nvarchar(4000),@p7 int,@p8 nvarchar(4000),@p9 nvarchar(4000),@p10 int,@p11 nvarchar(4000),@p12 nvarchar(4000),@p13 int,@p14 nvarchar(4000),@p15 nvarchar(4000)',@p1=3,@p2=N'I wrote an app using EF Core!',@p3=N'Hello World 0',@p4=3,@p5=N'I wrote an app using EF Core!',@p6=N'Hello World 1',@p7=3,@p8=N'I wrote an app using EF Core!',@p9=N'Hello World 2',@p10=3,@p11=N'I wrote an app using EF Core!',@p12=N'Hello World 3',@p13=3,@p14=N'I wrote an app using EF Core!',@p15=N'Hello World 4'

The unusual SELECT and MERGE are used to ensure IDENTITY values are returned in the order the objects were inserted, so EF Core can assign them to the object properties. After calling SaveChanges all Blog and Post objects will have the correct database-generated IDs


Q: How to convert byte[] to float[] and back in Java? I'm reading data from .wav files through InputStream, and read() returns bytes. A sound processing library I use, only accepts float[] to process. After it it done it gives me a float[] back. Now I need to write to the Android's AudioTrack in byte format again.
How do I convert these bytes to floats[], and back to byte[]? I've searched a bit, but everything seemed to be kinda a different situation to mine, and all problems seemed to be solved in different ways... so i'm kinda lost right now.
If something like this conversion is already offered in some kind of library, i'd be glad to hear about that too!
Thanks!

A: You can use of java.nio.ByteBuffer. It has a lot of useful methods for pulling different types out of a byte array and should also handle most of your issues.
        byte[] data = new byte[36];
        ByteBuffer buffer = ByteBuffer.wrap(data);
        float second = buffer.getFloat(); //This helps to
        float x = 0;
        buffer.putFloat(x);

A: You just need to copy the bits.
Try using BlockCopy.
 float[] fArray = new float[] { 1.0f, ..... };
 byte[] bArray= new byte[fArray.Length*4];
 Buffer.BlockCopy(fArray,0,bArray,0,bArray.Length);

The *4 is since each float is 4 bytes.


Q: ASP.NET MVC3 - Redirect to a different directory We have a bunch of published URLs that reference a directory called "events"
http://www.mysite.com/anniversary/events/
http://www.mysite.com/anniversary/events/[...]

They now want to rename "events" to "events1" so I need to redirect all URLs that look like this:
http://www.mysite.com/anniversary/events/[...]

To:
http://www.mysite.com/anniversary/events1
http://www.mysite.com/anniversary/events1/[...]

I've done these in Apache - Not sure if I am on the right track?
<rule name="events1" stopProcessing="true">
        <match url="^/anniversary/events(/.+)?$" />
        <action type="Redirect" url="http://www.mysite.com/aniverssary/events1{C:1}" redirectType="Found" />
</rule>

What should this look like?
Thanks

A: Well, it turns out that IIS has a really nice rewrite rule pattern tester. I found this tutorial extremely helpful. If you use the IIS URL Rewrite GUI, you can create a test redirect and then the URL Rewrite will write the redirect into web.config. You can then look in there and check your syntax.


Q: Finding argmax indices along a dimension and negate the corresponding values if the index is 1 Given a tensor in size DxCx2xHxW I try to find the argmax indices for the third dimension (between two values) and if the index is 0 I'll keep it or if it is 1 I'll negate the value and reduce the tensor to size DxCxHxW with the modified values and ignoring the non argmax indices.
Could you suggest a way to do this correctly? Thanks in advance for any further comment...
Here also my first stupid attempt that might give some insights about what am I trying to do.
max_val = self.pool_function(input_reshaped, axis=self.axis + 1) //input_rehshaed in size DxCx2xHxW
max_arg = T.argmax(input_reshaped, axis= self.axis+1)            //find argmax indices for the third dimension
return ifelse(T.lt(max_arg, 1), max_val, -max_val)               //negate argmax indices > 0 and return modified matrix ignoring the nonargmax indices

A: For the potential benefit of other people, this question was answered on the theano-users mailing list: https://groups.google.com/forum/#!topic/theano-users/6P5KxLph2I8
The recommended solution, by Pierre Luc Carrier, was:
mask = input_reshaped.argmax(axis=3).astype("float32") * -2 + 1
return input_reshaped.max(axis=3) * mask


Q: Github Action trigger on release not working on tag I've created a "publish" workflow in new repository that publish my project on new release with this trigger
on:
  release:
    types:
    - created

In my local machine I created a tag and pushed it:
git tag v0.0.1 main
git push origin v0.0.1

Now I see that my repo contains 1 tag and 1 release, but the workflow did not run.
Why the release trigger did not fire when new release created with the tag?

A: This is confusing in the GitHub Actions documentation on the "Events that Trigger Workflows." https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#release
It states that Activity Types are "published," "unpublished," and "prerelease" but it doesn't tell you how to invoke these activities.  You need to create a GitHub "Release" Event by either using the web portal or the gh CLI.  Follow this documentation: https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository
If that link changes look for the Release button in the GitHub web portal.  Just creating a git tag is not enough.
From the gh CLI the command is like: gh release create v1.3.2 --title "v1.3.2 (beta)" --notes "this is a beta release" --prerelease
In short git tag is not the event that triggers a GitHub Release event.


Q: Is the map mask register used to do plane switching in VGA? I've got an understanding problem when it comes to the memory mapping of VGA. So I think I've got a wrong assumption somewhere.
From what I've understood, I think that a VGA adapter has 256 KB of memory but usually only exposes 64 KB to the host at any given time. So if you like to have a resolution of 640x480 pixels with 16 colors then you would need 153 600 bytes of the memory. But since the host can only access 64 KB it needs to swap the planes/banks behind the 64 KB window to access different parts of the 256 KB of video memory.
So when I set a mode I write the value 0001|b to the map mask register to select plane #0. When the OS asks my miniport driver for the bank switching code then I return some code that changes the value in the map mask register to 0010|b for example to switch to plane #1.
Now my problem is, that I seem to be the only person who does this. For example, when I looked at how Microsoft sets a mode, I noticed that they write 1111|b in the map mask register and when it comes to providing the code for the bank switching they simply provide a return-instruction with the comment that this function should never be called anyway. When a miniport driver sets a mode they even overwrite the map mask register right afterwards to make sure it contains 1111|b. When I looked at ReactOS I noticed that they haven't even implemented the function that provides the bank switching code.
But how is this possible?


Q: Is Spring Cache clusterable? I've got an application that uses Spring Cache (Ehcache), but now we need to add a 2nd node (same application). Can the cache be shared between the nodes or each with their own instance but synched?
Or do I need to look at a different solution?
Thanks.

A: That depends on your cache implementation - not on Spring, which only provides an abstract caching API. You are using EhCache as your caching implementation, which comes with a Terracotta server for basic clustering support and is open source. See http://www.ehcache.org/documentation/3.1/clustered-cache.html#clustering-concepts for more details


Q: Is there an API that will return how many results there are based your query search? Is there an api that returns how many results/logs there are based off your query search? or like a built in feature with NEST that will tell you how many results there is like i.e. count? Because I have a NEST query search that will do the following:
var response = await _elasticClient.SearchAsync<EsSource>(s => s
                  .Size(3000) // must see about this
                  .Source(src => src.Includes(i => i
                                    .Fields(f => f.timestamp,
                                            fields => fields.messageTemplate,
                                            fields => fields.message)))
                  .Index("customer-simulation-es-app-logs*")
                  .Query(q => +q
                      .DateRange(dr => dr
                          .Field("@timestamp")
                              .GreaterThanOrEquals("2021-06-07T17:13:54.414-05:00")
                              .LessThanOrEquals(DateTime.Now))));

but I realized that the search api cannot go past 10,000 results because the array is empty when you paginate beyond 10,000 results.  search api
So, if there is an api or a feature that will let you know how much results there is based on your index or if you are doing a monthly query search as I am above; with knowing that number I can then create a forloop to paginate through each of those documents say the first 10,0000 hits I can view then the next iteration for the next 10,000 hits and so on. Hope this makes sense, i'll clarify if needed.

A:
Is there an API that will return how many results there are based your query search?

I'm not aware of any ES API that will return an exact count. At high values, it becomes very approximate.

array is empty when you paginate beyond 10,000 results.

First, returning >10k search results is highly unusual. It sounds like you're trying to use ElasticSearch as a database, which you can do for some things, but don't go depending on ACID or anything like that.
To page over large result sets in ElasticSearch, create a point in time and pass that to the search API with the search_after parameter.


Q: Django or Nodejs or Ruby on Rails? I want to learn web development, I know little bit Python and Nodejs.
I dont have any knowledge on Ruby.
So, In the below 3, which one should I choose for Web Development?

*

*Django

*Nodejs

*Ruby on Rails

Thanks in advance.

A: Of course this question will be opinionated because it's fairly broad. Everyone has their own preferred choice. Though if you are a beginner to web programming and you'd like to use python I'd say start with flask.


Q: Amcharts5 chart add tooltip to circle I`m trying to add a tooltip to my chart but it doesn't work. I've added it both to bullet and to series as well.
There is no enough info in docs about how to add tooltip in this case.
When I add tooltip to series in which graphic is based everything works perfectly
Can you help?
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

am5.ready(function() {

  // Create root element
  // https://www.amcharts.com/docs/v5/getting-started/#Root_element
  var root = am5.Root.new("chartdiv");

  // Set themes
  // https://www.amcharts.com/docs/v5/concepts/themes/
  root.setThemes([
    am5themes_Animated.new(root)
  ]);

  // Create chart
  // https://www.amcharts.com/docs/v5/charts/xy-chart/
  var chart = root.container.children.push(am5xy.XYChart.new(root, {
    panX: true,
    panY: true,
    wheelY: "zoomXY",
    pinchZoomX: true,
    pinchZoomY: true
  }));

  chart.get("colors").set("step", 2);

  // Create axes
  // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
  var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
    renderer: am5xy.AxisRendererX.new(root, {}),
    maxDeviation: 0.3,
  }));

  var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
    renderer: am5xy.AxisRendererY.new(root, {}),
    maxDeviation: 0.3,
  }));

  var tooltip = am5.Tooltip.new(root, {
    labelText: "MCaPos: {valueY}\nRN: ${valueY}",
    getFillFromSprite: false,
    getStrokeFromSprite: false,
    autoTextColor: false,
    getLabelFillFromSprite: false,
  });

  tooltip.get('background').setAll({
    fill: am5.color('#ffffff'),
    strokeWidth: 0,
  })

  tooltip.label.setAll({
    fill: am5.color('#000000')
  });

  console.log(tooltip)

  // Create series
  // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
  var series0 = chart.series.push(am5xy.LineSeries.new(root, {
    calculateAggregates: true,
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: "y",
    valueXField: "x",
    valueField: "value",
    tooltip: am5.Tooltip.new(root, {
      labelText: "{valueY}"
    })
  }));

  // Create series
  // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
  var series = chart.series.push(am5xy.LineSeries.new(root, {
    name: "Series 1",
    xAxis,
    yAxis,
    valueYField: "y",
    valueXField: "x",
    tooltip: am5.Tooltip.new(root, {
      labelText: "{valueY}"
    })
  }));
  series.strokes.template.setAll({
    strokeWidth: 2,
    strokeDasharray: [3, 3]
  });

  series.data.setAll([{
    "x": 0.01,
    "y": 1409090.91
  }, {
    "x": 0.06,
    "y": 1589743.59
  }, {
    "x": 0.11,
    "y": 1823529.41
  }, {
    "x": 0.16,
    "y": 2137931.03
  }, {
    "x": 0.21,
    "y": 2583333.33
  }, {
    "x": 0.26,
    "y": 3263157.89
  }, {
    "x": 0.31,
    "y": 4428571.43
  }, {
    "x": 0.36,
    "y": 6888888.89
  }, {
    "x": 0.41,
    "y": 15500000
  }]);

  var circleTemplate = am5.Template.new({});

  series0.bullets.push(function() {
    var graphics = am5.Circle.new(root, {
      fill: am5.color('#31DB42'),
    }, circleTemplate);
    return am5.Bullet.new(root, {
      sprite: graphics,
      radius: 1
    });
  });

  // Add heat rule
  // https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/
  series0.set("heatRules", [{
    target: circleTemplate,
    min: 3,
    max: 35,
    dataField: "value",
    key: "radius"
  }]);

  // Add bullet
  // https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
  var starTemplate = am5.Template.new({});

  series0.strokes.template.set("strokeOpacity", 0);
  series0.set('tooltip', tooltip);

  // Add cursor
  // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
  chart.set("cursor", am5xy.XYCursor.new(root, {
    xAxis,
    yAxis,
    snapToSeries: [series0, series]
  }));
  series0.data.setAll([{
    "x": 0.09271021903999942,
    "y": 2712290
  }]);
  series0.appear(1000);

  // Make stuff animate on load
  // https://www.amcharts.com/docs/v5/concepts/animations/
  series.appear(1000);
  chart.appear(1000, 100);

}); // end am5.ready()


Q: Firebase query hex codes contained within randomly generated keys I would like to query a particular child from the array of color hex codes.
Here's a snapshot of my database structure:

How do I query a particular hex code and obtain the entire array of its parent object?

A: You cannot query whether a specific value exists in a list. This is one of the many reasons why the Firebase documentation recommends against using arrays in the database.
But in this case (and most cases that I encounter), you may likely don't really need an array. Say that you just care about what colors your user picked. In that case, you can more efficiently store the colors as a set:
palettes
    -KSmJZ....A5I
        "0x474A39": true
        "0xbA9A7C": true
        "0xDEDEDF": true
        "0x141414": true
        "0x323E35": true

A: I did it in a different way,
made a function that does this:
let databaseRef = FIRDatabase.database().reference()
        let HEX1 = hex1.text! as String
        let HEX2 = hex2.text! as String
        let HEX3 = hex3.text! as String
        let HEX4 = hex4.text! as String
        let HEX5 = hex5.text! as String
        let URL = url.text! as String

        // First set
        let colorArray1 = [HEX2, HEX3, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX1).setValue(colorArray1)

        // second set
        let colorArray2 = [HEX1, HEX3, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX2).setValue(colorArray2)

        // third set
        let colorArray3 = [HEX1, HEX2, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX3).setValue(colorArray3)

        // fourth set
        let colorArray4 = [HEX1, HEX2, HEX3, HEX5, URL]
        databaseRef.child("palette").child(HEX4).setValue(colorArray4)

        // fifth set
        let colorArray5 = [HEX1, HEX2, HEX3, HEX4, URL]
        databaseRef.child("palette").child(HEX5).setValue(colorArray5)

so that when I target any of the 5 hexes, it will bring me back the whole array together with it.


Q: SQL query for counting combinations and including entries that don't exist This is a simplified version of the table I am dealing with which is Orders
+-------------------+------------------+---------------+
| Order_Base_Number | Order_Lot_Number | Other Cols... |
+-------------------+------------------+---------------+
|                 1 |                3 |               |
|                 1 |                3 |               |
|                 1 |                4 |               |
|                 1 |                4 |               |
|                 1 |                4 |               |
|                 1 |                5 |               |
|                 2 |                3 |               |
|                 2 |                5 |               |
|                 2 |                9 |               |
|                 2 |               10 |               |
+-------------------+------------------+---------------+

What I want to do is to get a count for the unique entries base on Base and Lot numbers. I have two set of numbers, one is a set of Base numbers and the other is a set of Lot numbers.
for example, lets say the two sets are Base In (1,2,3) and Lot is in (3,4,20).
I am looking for an SQL query that can return all the possible combination of (Base,Lot) from the two sets with a count that shows how many times the combination was found in the table. My problem is that I want to include all the possible combinations and if a combination is not in the Orders table, I want the count to show zero. So, the output I am looking for is something like this.
+------+-----+-----------+
| Base | Lot | Frequency |
+------+-----+-----------+
|    1 |   3 |    2      |
|    1 |   4 |    3      |
|    1 |  20 |    0      |
|    2 |   3 |    1      |
|    2 |   4 |    0      |
|    2 |  20 |    0      |
|    3 |   3 |    0      |
|    3 |   4 |    0      |
|    3 |  20 |    0      |
+------+-----+-----------+

I tried a lot of queries but never got close to this and not even sure if it can be done. Right now I am figuring out the combinations on the client side and hence I am performing too many queries to get the frequencies.

A: Perhaps the clearest way is to start with the lists as CTEs:
with bases as (
    select 1 as base from dual union all
    select 2 as base from dual union all
    select 3 as base from dual
   ),
     lots as (
    select 3 as lot from dual union all
    select 4 as lot from dual union all
    select 20 as lot from dual
   )
select b.base, l.lot, count(Order_Base_Number) as Frequency
from bases b cross join lots l left outer join
     Orders o
     on o.base = b.base and o.lot = l.lot
group by b.base, l.lot

Note that this makes the cross join explicit, purposely not using the , for a Cartesian product.
The first part of this query could also be written as something like the following (assuming that each base and lot has at least one record in the table):
with bases as (
     select distinct base
     from Orders  -- or some other table, perhaps Orders ?
     where base in (1, 2, 3)
    ),
     select distinct lot
     from Orders  -- or some other table, perhaps Lots ?
     where lot in (3, 4, 20)
    )
. . .

This is more succinct, but might result in a less efficient query.

A: What you need in the innermost subquery is called CROSS JOIN, which gets cartesian products (all possible combinations) of records. That's what you get when you have neither JOIN..ON condition nor WHERE:
SELECT Base.Id as baseid, Lot.Id as lotid FROM Bases, Lots

Now put it into subquery and LEFT JOIN to the rest of your stuff:
SELECT ... FROM
   (SELECT Base.Id as baseid, Lot.Id as lotid
           FROM Bases, Lots) baseslots
   LEFT JOIN Orders ON Order_Base_Number = baseid,
             Order_Lot_Number = lotid ....

With this LEFT JOIN, you'll get NULL for nonexistent combinations. Use COALESCE (or something like this) to turn them into 0.

A: I don't have Oracle to test it but this is what I would do:
CREATE TABLE pairs AS
(
SELECT DISTINCT Base.Order_Base_Number, Lot.Order_Lot_Number
FROM ORDERS Base
CROSS JOIN ORDERS Lot
);

CREATE TABLE counts AS
(
SELECT Order_Base_Number, Order_Lot_Number, Count(*) AS C
FROM ORDERS
GROUP BY Order_Base_Number, Order_Lot_Number
);

SELECT P.Order_Base_Number, P.Order_Lot_Number, COALESCE(C.C,0) AS [Count]
FROM Pairs P
LEFT JOIN counts C ON P.Order_Base_Number = C.Order_Base_Number
             AND P.Order_Lot_Number = C.Order_Lot_Number


Q: Java wait for Serial Input I linked a caliper to my computer with a RS232C-USB cable and I managed to get the data and print them in console. The caliper sends data everytime I press a pedal.
The problem is I can only acquire data once at the beginning, I'm searching for a function that would freeze the program, waiting for an input from the caliper before printing. The only one I have in mind is read(), but it doesn't seem to make the program wait for input.
Thanks in advance


Q: Lxml not finding all tables on page? I'm trying to get some data and when I'm using lxml it's find 2 tables and not the 3rd which I want.  I suspect this has to do with the xpath or the way that specific table is being generated.
I'm trying to get the price history from: http://web.tmxmoney.com/pricehistory.php?qm_symbol=WDO.DB.A
Here are the different attempts I've made and the results.
import requests
from lxml import html

def financialPriceData():
        priceData = requests.get('http://web.tmxmoney.com/pricehistory.php?qm_symbol=WDO.DB.A')
        PriceScraperTree = html.fromstring(priceData.content)
        #PriceTreeTickers = PriceScraperTree.xpath('//*[@id="innerContent"]/div[4]/div[1]/div[1]/div[1]/table/tbody/tr[1]/td/table/tbody/tr[5]/td/table/tbody/tr/td/table/tbody/tr[2]/td[1]/text()') # no luck. From Chrome.
        # PriceTreeTickers = PriceScraperTree.xpath('//table[@id="qm_history_historyContent"]') # no luck, can't find the table
        PriceTreeTickers = PriceScraperTree.xpath('//table')  # no luck, finds only 2 tables top of the page and bottom of the page data. When I look at text result the daily price is missing.
        print(PriceTreeTickers)

financialPriceData()


Q: validate and match the zip code with bill/ship country in magento checkout I want to validate the zip code as per bill/ship country in magento checkout process.
entered bill/ship country should matches the entered zipcode.
If the entered zipcode and country did not match - customer should not be able to save the address and appropriate error message should be displayed.
Example:- customer entered zip code 12345 and selected country as US.
          Then it should display the message "Zip code do not match with selected country."
can anyone suggest me , how can i validate the zip as per country ?
Can i use the google API to validate the zip code ?
What portion of magento file i need to customize ?

A: If you want to achieve this functionality, first you need to map the zipcodes with countries or use any plugin for it. Then, define a model or table for it. Then, during checkout make an ajax call from zipcode field to your controller, call your model there and then check the pincode. Based on your comparison, return the result and display what you want to.


Q: Python Produce empty list if condition not satisafied I am creating a if condition-based list. I want to create an empty list if the condition is not satisfied.
My code:
ip_list = []
op_list= [ip_list[0] if len(ip_list)>0 else '']

Present output:
op_list = ['']

Expected output:
op_list = []

A: This can be accomplished more succinctly via slicing:
op_list = ip_list[:1]

If ip_list has at least one element, op_list will be a singleton list with the first element of ip_list. Otherwise, op_list will be an empty list.
>>> a = [1, 2, 3]
>>> b = []
>>> a[:1]
[1]
>>> b[:1]
[]

A: op_list = [] if ip_list else [ip_list[0]]

A: You only need the first element if ip_list has any.
Here is one of the easiest solution for that:
[ip_list[0]] if ip_list else []


Q: Ng2-smart-table: is possible to pass data rows without keys? I want to pass to my data table some values as rows, like the following:
["ab", "b", "c"]. So, my json is just an array that doesn't have any keys, just a value. I know that we need to have a keys for each element that is the same of the column, but is there any solution? thanks

A: According to the documentation, the type of table row data can only be object. You can convert raw data, for example, like this:
// We should know the columns order
var columns = ['id', 'name', 'username', 'email'];

var data = rawData.map(function(item) {
  return item.reduce(
    function(result, item, columnIndex) {
      result[columns[columnIndex]] = item;
      return result;
    },
    {}
  );
});

https://jsfiddle.net/jLwmhbwv/


Q: Saving file properties results in Value does not fall in range exception I have the following code that is supposed to retrieve a canvas, save an image, and then write File properties to it. Sadly, it crashes when trying to save the properties. They are in string form, and the Property requires a string too, so I don't see what might be wrong:
try
{
    using (Windows.Storage.Streams.IRandomAccessStream stream =
            await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        stream.Size = 0;
        await MyInkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
    }

    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();
    string title = CanvasGrid.Width + " x " + CanvasGrid.Height;
    imageProperties.Title = title;
    await imageProperties.SavePropertiesAsync();

    //MainPage.NotifyUser("File has been saved!", NotifyType.StatusMessage);
}
catch (Exception ex)
{
    //MainPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}

Value does not fall within the expected range.


Q: Renaming coat colors in R goes wrong with str_detect I have a dataset with horses and want to group them based on coat colors. In my dataset more than 140 colors are used, I would like to go back to only a few coat colors and assign the rest to Other. But for some horses the coat color has not been registered, i.e. those are unknown. Below is what the new colors should be. (To illustrate the problem I have an old coat color and a new one. But I want to simply change the coat colors, not create a new column with colors)

Horse ID
Coatcolor(old)
Coatcolor

1
black
Black

2
bayspotted
Spotted

3
chestnut
Chestnut

4
grey
Grey

5
cream dun
Other

6

Unknown

7
blue roan
Other

8
chestnutgrey
Grey

9
blackspotted
Spotted

10

Unknown

Instead, I get the data below(second table), where unknown and other are switched.

Horse ID
Coatcolor

1
Black

2
Spotted

3
Chestnut

4
Grey

5
Unknown

6
Other

7
Unknown

8
Grey

9
Spotted

10
Other

I used the following code
mydata <- data %>%
  mutate(Coatcolor = case_when(
     str_detect(Coatcolor, "spotted") ~ "Spotted",
     str_detect(Coatcolor, "grey") ~ "Grey",
     str_detect(Coatcolor, "chestnut") ~ "Chestnut",
     str_detect(Coatcolor, "black") ~ "Black",
     str_detect(Coatcolor, "") ~ "Unknown",
     TRUE ~ Coatcolor
  ))
mydata$Coatcolor[!mydata$Coatcolor %in% c("Spotted", "Grey", "Chestnut", "Black", "Unknown")] <- "Other"

So what am I doing wrong/missing? Thanks in advance.

A: You can use the recode function of thedplyr package. Assuming the missing spots are NA' s, you can then subsequently set all NA's to "Other" with replace_na of the tidyr package. It depends on the format of your missing data spots.
mydata <- tibble(
  id = 1:10,
  coatcol = letters[1:10]
)

mydata$coatcol[5] <- NA
mydata$coatcol[4] <- ""

mydata <- mydata %>%
  mutate_all(list(~na_if(.,""))) %>% # convert empty string to NA
  mutate(Coatcolor_old = replace_na(coatcol, "Unknown")) %>% #set all NA to Unknown
  mutate(Coatcolor_new = recode(
    Coatcolor_old,
    'spotted'= 'Spotted',
    'bayspotted' = 'Spotted',
    'old_name' = 'new_name',
    'a' = 'A', #etc.
  ))
mydata


Q: PostgreSQL - "Include Error Detail" connection string parameter - how sensitive is the information returned? https://www.npgsql.org/doc/connection-string-parameters.html

Include Error Detail -
When enabled, PostgreSQL error and notice details are included on PostgresException.Detail and PostgresNotice.Detail. These can contain sensitive data.

If I provide the "Include Error Detail=True" in the connection stringg to PostgreSQL, what sensitive data do I need to be concerned about? If the query itself is returned in an exception or error message, that is fine by me, but if say the connection password were returned in plaintext obviously that would be bad. What sensitive data is conditionally included in errors based on this parameter?

A: These messages include no sensitive data that the database user should not see. So I wouldn't worry, unless perhaps you show the information to the application user rather than logging them. Your database user may have access to information that the application user shouldn't see.


Q: Reading from a pre-populated database file for android I followed this tutorial at this page. I followed it thoroughly but I still can't get the prepopulated database file to work. I keep getting an error saying .getReadableDatabase or .getWritableDatabase is called recursively. Also tried the solution of the answer for this page and also it doesn't work. Is there a simpler way to copy a prepopulated database to a local database which enables me to update and create data?

A: Try this :
public class DatabaseManager {
private DatabaseHelper dataHelper;
private SQLiteDatabase mDb;
private Context ctx;
private String DATABASE_PATH = "/data/data/Your_Package_Name/databases/";
private static String DATABASE_NAME = "Your_Database";
private static String TABLE_NAME = "Your_Table";
private static final int DATABASE_VERSION = 1;
String Class_Tag = "DatabaseManager";

public DatabaseManager(Context ctx) {
    this.ctx = ctx;
    dataHelper = new DatabaseHelper(ctx);
}

private static class DatabaseHelper extends SQLiteOpenHelper {
    @SuppressWarnings("unused")
    Context myContext = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("DBHelper", "Upgrading database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data");
        onCreate(db);
    }
}

public boolean checkDataBase() {

    File f = null;
    try {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        f = new File(myPath);
    } catch (Exception e) {
        Log.e(Class_Tag, "checkDataBase()", e);
    }
    return f.exists();
}

public void createDataBase() {

    try {
        openDB();
        InputStream myInput = ctx.getAssets().open(DATABASE_NAME + ".db");
        OutputStream myOutput = new FileOutputStream(DATABASE_PATH
                + DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        if (mDb.isOpen())
            mDb.close();
        myOutput.flush();
        myOutput.close();
        myInput.close();

    } catch (Exception e) {
        Log.e(Class_Tag, "createDataBase()", e);
    }
}

public DatabaseManager openDB() throws SQLException {

    mDb = dataHelper.getWritableDatabase();
    return this;
}
public void closeDB() {
    try {
        if (mDb != null) {
            mDb.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

and in MainActivity
DatabaseManager dbMgr=new DatabaseManager(this);
try {
    if (!dbMgr.checkDataBase()) {
                dbMgr.createDataBase();
            }
        } catch (Exception e) {
            Log.e(Class_Tag, "onCreate()", e);
        } finally {
            dbMgr.closeDB();
        }

Hope it helps...


Q: Localized dates inconsistency I am localizing my date strings, but having issues.
I expect UK locales to have dayOfTheMonth then Month while US ones to have Month then DayOfTheMonth.
It seems to be the case for getMediumDateFormat but not for getDateFormat.
If I use:
android.text.format.DateFormat.getMediumDateFormat

then I get:
UK: 25 Nov 2015
US: Nov 25, 2015
Which is what I expect (day and month are in reverse order)
However, if I use:
android.text.format.DateFormat.getDateFormat

Then I get:
UK and US: 25/11/2015
In both cases the format is: dd/MM/yyyy
Did I miss something here?
Is there a better way to get a localized short date format?


Q: Yeoman/Grunt clean:dist task property undefined I'm new to grunt and having trouble with the clean:dist task for grunt-contrib-clean. This is my code for the task.
clean: {
    dist: {
        files: [{
            dot: true,
            src: [
                '.tmp',
                '<%= yeoman.dist %>/*',
                '!<%= yeoman.dist %>/.git*',
                '!<%= yeoman.dist %>/Procfile',
                '!<%= yeoman.dist %>/package.json',
                '!<%= yeoman.dist %>/web.js',
                '!<%= yeoman.dist %>/node_modules'
           ]
        }]
    },
    server: '.tmp'
},

When I run grunt build I get the following warning "An error occurred while processing a template (Cannot read property 'dist' of undefined). Use --force to continue." I'm thinking it must be a syntax error or something wrong with a plugin, but I don't know enough to keep figure it out.

A: For some reason, changing from <%= yeoman.dist %> to <%= config.dist %> solves the problem from me. Not sure when using yeoman.dist syntax is appropriate, but in any case I solved my own problem. So the solutions is...
clean: {
  dist: {
    files: [{
      dot: true,
      src: [
        '.tmp',
        '<%= config.dist %>/*',
        '!<%= config.dist %>/.git*',
        '!<%= config.dist %>/Procfile',
        '!<%= config.dist %>/package.json',
        '!<%= config.dist %>/web.js',
        '!<%= config.dist %>/node_modules'
      ]
    }]
  },
  server: '.tmp'
},


Q: Windows Phone Emulator error, Hyper-V components not running, Windows 8.1 hosted in Windows Azure Environment:
Windows 8.1 Enterprise 64-bit hosted in Windows Azure
Visual Studio Ultimate 2013 (Update 2)

I get the following error when trying to run a very simple phone app. I know MS says a VM-within-a-VM environment isn't supported, but I know it can work. Has anyone had success with this? Any help is greatly appreciated.
Windows Phone Emulator

The Windows Phone Emulator wasn't able to ensure the virtual machine was running:

Something happened while starting a virtual machine: 'Emulator WVGA 512 MB.' failed to start.
(Virtual machine ID CADD6546-129A-4683-9A2D-52EAE777E888)

The Virtual Machine Management Service failed to start the virtual machine 'Emulator WVGA 512 MB.'
because one of the Hyper-V components is not running
(Virtual machine ID CADD6546-129A-4683-9A2D-52EAE777E888).

Prior to seeing the error, the emulator emits the on-screen messages:
Loading ...

The Windows Phone OS is starting ...

And then the error. Of all the Hyper-V services available, the Hyper-V Virtual Machine Management service is the only one which is running.
Thanks,
Chris

A: I had the same issue with Visual Studio running on windows 8.1 in vmware player
What I had to do to solve the problem was this :
Tick the box "Virtualize Intel VT-x/EPT or AMD-V/RVI" in the processor settings of your VM
Add the line "hypervisor.cpuid.v0 = FALSE" in the file "Windows 8 x64.vmx" (add it between line 5 and 6. Not sure this matters, but at this line I'm sure it works)
Should be working fine

A: "You cannot host it in Azure.  It needs to be a physical machine." -- Jeff Sanders (MSFT)

A: Florian.C's answer got me on the right track to get the emulator working correctly in VMware Fusion on my MacBook Pro.  In Fusion, the settings are under the "Processors & Memory" section.  You have to open the "Advanced" section at the bottom and check the "Enable hypervisor applications for this virtual machine".  Once that was done, I had to also open the .vmx file and add the "hypervisor.cpuid.v0 = "FALSE"" line.  Originally I copied and pasted from SO and the VM threw an error when I booted it.  It turns out the " I added around FALSE were not normal quotes.  Once I fixed that, the VM booted and the emulator ran just fine under Fusion.  Thanks for the great info!


Q: Class with multiple interfaces i have 2 interfaces inter1 and inter2 and class that implements both of them:
public interface Interface1 {
    method1();
}
public interface Interface2 {
    method2();
}
public class Implementer implements Interface1, Interface2 {
    method1() {
         // something
    }
    method2() {
         // something
    }
}
public class Test {
    public static void main(String[] args) {
        Interface1 obj = quest();
        obj.method1();
        if(obj instanceof Interface2) {
            obj.method2(); //exception
        }
    }

    public static Interface1 quest() {
        return new cl();
    }
}

How to cast obj to Interface2 and call method2() or it is possible to call method2() without casting ?

A: If you write inter1 obj = ... then you will not be able to write obj.method2) unless you cast to inter2 or to a type that implements inter2.
For example
inter1 obj = quest();
if (obj instanceof class1)
    ((class1) obj).method2();

or
inter1 obj = quest();
if (obj instanceof inter2)
    ((inter2) obj).method2();

As an aside, when you write in Java you normally give classes and interfaces names that begin the a capital letter, otherwise you confuse people reading your code.

A: Using genecics it is possible to declare generic reference implementing more than one type. You can invoke method from each interface it implements without casting. Example below:
public class TestTwoTypes{

    public static void main(String[] args) {
        testTwoTypes();
    }

    static <T extends Type1 & Type2> void testTwoTypes(){
        T twoTypes = createTwoTypesImplementation();
        twoTypes.method1();
        twoTypes.method2();
    }

    static <T extends Type1 & Type2> T createTwoTypesImplementation(){
        return (T) new Type1AndType2Implementation();
    }
}

interface Type1{

    void method1();
}

interface Type2{
    void method2();
}

class Type1AndType2Implementation implements Type1, Type2{

    @Override
    public void method1() {
        System.out.println("method1");
    }

    @Override
    public void method2() {
        System.out.println("method2");
    }
}

The output is:
method1
method2

A: If you want to do this in spring, the general idea would be:
// Test.java
public class Test {
    private final Interface1 i1;
    private final Interface2 i2;
    public Test(Interface1 i1, Interface2 i2) {
        this.i1 = i1;
        this.i2 = i2;
    }
}

<!-- application-context.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="implementer" class="org.mypackage.Implementer" />
    <bean id="test" class="org.mypackage.Test">
        <constructor-arg ref="implementer"/>
        <constructor-arg ref="implementer"/>
    </bean>
</beans>

// Main.java
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Test t = (Test) context.getBean("test");
}


Q: How to set Image as pdf page background I'm having problems to use an image as background in table column. I need the image to be the background of each page in pdf.
The image is being displayed but it seems to be zoomed in. It sizes are width : 2487px, heigth : 3516px (width : 21.06cm, height : 29.77cm).
This is my code:
<xsl:template name="template-body">
        <fo:block backgorund-color="yellow">
            <fo:table>
                <fo:table-column background-image="image.jpg"/>
                <fo:table-body>
                    <fo:table-row height="29.7cm">
                        <fo:table-cell>
                            <fo:block color="white">
                                SOME TEXT INSIDE THE IMAGE
                            </fo:block>
                        </fo:table-cell>
                    </fo:table-row>
                </fo:table-body>
            </fo:table>
        </fo:block>

    </xsl:template>

This code generates this:

But i need this:

I also tried  to put the image as background of <fo:region-body> but i had the same problem. I think i need some way to specify the image width and height.
Any help? Thanks in advance.

A: Since you are using FOP, I believe there is no provision to scale a background-image to fit. This would be an extension to the XSL FO Specification.
RenderX XEP supports this (http://www.renderx.com/reference.html#Background_Image).
It is unclear if you actually want the image behind the table (and you have other content) or you actually want the image behind the whole page.
You could put the image in an absolute positioned block-container and use content-width and content-height to scale, but this is not going to repeat for only the table. This would work for the page. If it is only the table, you are likely going to have to resize the actual image to fit correctly.


Q: Magento manipulate weight on checkout I have simple products in Magento 1.9 that I can combine ship and would like to change the total shipping weight at checkout (and in shopping cart view for shipping estimate calculation etc) based on sku. For example, if one or two widgets with the correct sku are purchased, their weight is 1 lbs combined. If three to five widgets with the correct sku are purchased, their weight is 2 lbs combined etc. Tablerates could handle this if all items were included. However, I must limit it to certain items determined by sku.
So currently in Magento, each item has a weight of 1 lbs and total weight is number of items * 1 lbs. I have found answers to display total weight, or update the item's weight in the database, but nothing that fulfills these requirements. I'm very new to Magento and am struggling to achieve this. If you reply back with suggested code changes, could you please be specific as to the file's location that should be edited?
Edit
Following Mladen Ilić's suggestions, I have come up with the follow code that calculates the total weight on the event sales_quote_collect_totals_after event. How do I send the new adjusted weight to Magneto to use it through checkout?
/app/etc/modules/Weight_Extension.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Weight_Extension>
            <codePool>local</codePool>
            <active>true</active>
        </Weight_Extension>
    </modules>
</config>

/app/code/locale/Weight/Extension/etc/config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Weight_Extension>
            <version>0.0.1</version>
        </Weight_Extension>
    </modules>
    <global>
        <models>
            <weight_extension>
                <class>Weight_Extension_Model</class>
            </weight_extension>
        </models>
        <events>
            <sales_quote_collect_totals_after>
                <observers>
                    <weight_extension>
                        <class>weight_extension/observer</class>
                        <method>adjustTotalWeight</method>
                    </weight_extension>
                </observers>
            </sales_quote_collect_totals_after>
        </events>
    </global>
</config>

/app/code/locale/Weight/Extension/Model
<?php
class Weight_Extension_Model_Observer
{
    public function adjustTotalWeight($observer)
    {
        $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();

        $combinedItems = 0;
        foreach($items as $item)
        {
            if($item->getSku() == 1 || $item->getSku() == 2)
            {
                 $combinedItems++;
            }
        }

        if($combinedItems > 0 && $combinedItems < 3)
            $weight = 1;
        if($combinedItems >= 3 && $combinedItems < 6)
            $weight = 2;

        //send new $weight to Magento and persist through checkout?
    }
}

How do I send the new adjusted weight to Magneto to use it through checkout?

A: Magento calculates weight used for getting shipping rates in Mage_Sales_Model_Quote_Address_Total_Shipping::collect.
When collecting shipping address totals, items are looped and their weight accumulated and then set to address object.
That being said, you have to be careful how are you going to change this behavior. On a first look, it seems that using sales_quote_collect_totals_after event could be the right way.
When event is triggered get all shipping address items, loop through them and use custom logic for calculating weight.
Best of luck.

A: You writted event in adminhtml context, you have to change it to frontend.


Q: sound for notification I want to play an mp3 sound when my Notification is triggered. For this, I have put an mp3 file in my "res/raw" folder and used the following instruction:
notification.sound=Uri.parse("android.resource://"+getPackageName()+"/" + R.raw.mySound);.
But I am getting no sound when the Notifications appears!
Any idea?

A: I found an example here -

*

*How to play an android notification sound
This is the code that is used
try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
        ring.play();
    } catch (Exception e) {}

On the other hand, if you want to customize the sound (as I ausume you do), you should use this code taken from here
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE

;

A: Simply put this below code inside the block which will be triggered when notification occurs..
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.mySound);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);  // Set false if you don't want it to loop
mMediaPlayer.start();


Q: XAML GridView to GridView Drag and Drop Mouse vs Touch Here's XAML code where you can drag and drop GridView elements between different GridViews, however, this approach only works with mouse input and just partially with touch input.
With touch input the elements "unlock" from the GridView only on vertical drag. On horizontal drag the UI tries to scroll the screen instead of just moving the GridView element.
So mouse works perfectly and touch works only on inital vertical drag, after the inital vertical drag you can move the element around just as you could with mouse. This is a Windows 8 app.
<Page.Resources>
        <DataTemplate x:Key="ItemTemplate1">
            <Border Background="#25BDC0">
                <Grid Width="230" Height="230" Margin="10">
                    <TextBlock Text="{Binding Title}" Style="{StaticResource HeaderTextStyle}"
                               HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Grid>
            </Border>
        </DataTemplate>
    </Page.Resources>

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Width="Auto" Height="Auto">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <GridView Grid.Column="0" ItemTemplate="{StaticResource ItemTemplate1}"
            ItemsSource="{Binding FirstCollection}"
            AllowDrop="True" CanDragItems="True"
            DragItemsStarting="GridViewDragItemsStarting"
            Drop="GridViewDrop" Margin="10">
        </GridView>
        <GridView Grid.Column="1" ItemTemplate="{StaticResource ItemTemplate1}"
            ItemsSource="{Binding SecondCollection}"
            AllowDrop="True" CanDragItems="True"
            DragItemsStarting="GridViewDragItemsStarting"
            Drop="GridViewDrop" Margin="10">
        </GridView>
    </Grid>

A: I've stumbled upon the same issue and found the answer here :
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/7fcf8bb8-16e5-4be8-afd3-a21e565657d8/drag-and-drop-gridview-items-and-disabled-scrollbar
It appears that with a GridView you can't initiate the drag horizontally, you have to do it vertically and it's the exact opposite with the ListView.
So if you want to drag 'n drop items horizontally you have to use a ListView. (as recommended in the MS guidelines http://msdn.microsoft.com/en-us/library/windows/apps/hh465299.aspx )
Regards


Q: How to get the connected SSID in Xamarin.Forms? I need to get the SSID of the current network that I am connected to.
Here is the code I used to find the SSID in Xamarin.Android:
WifiManager wifiManager = (WifiManager)(Application.Context.GetSystemService(WifiService));

if (wifiManager != null)
{
    var ssid =  wifiManager.ConnectionInfo.SSID;
}
else
{
    var str =  "WiFiManager is NULL";
}

But I need to implement this in Xamarin.Forms.
How can I do this ?

A: You can use DependencyService.

The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code.

1º
Create a public interface (for organization sake, maybe under Mobile > Services > IGetSSID)
public interface IGetSSID
{
    string GetSSID();
}

2º Create the Android Implementation
[assembly: Dependency(typeof(GetSSIDAndroid))]
namespace yournamespace
{
    public class GetSSIDAndroid : IGetSSID
    {
        public string GetSSID()
        {
            WifiManager wifiManager = (WifiManager)(Android.App.Application.Context.GetSystemService(Context.WifiService));

            if (wifiManager != null && !string.IsNullOrEmpty(wifiManager.ConnectionInfo.SSID))
            {
                return wifiManager.ConnectionInfo.SSID;
            }
            else
            {
                return "WiFiManager is NULL";
            }
        }
    }
}

3º
Then in your forms you get the SSID like this:
var ssid = DependencyService.Get<IGetSSID>().GetSSID();

Note: Don't forget to add this permission on your Android Manifest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

A: Get SSID and BSSID API31 Xamarin C# Example
Required permissions: CHANGE_NETWORK_STATE, ACCESS_FINE_LOCATION
If API<31 TransportInfo will return Null
using Android.Content;
using Android.Net;
using Android.Net.Wifi;

protected override void OnStart()
    {
        base.OnStart();

        NetworkRequest request = new NetworkRequest.Builder().AddTransportType(transportType: TransportType.Wifi).Build();
        ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;

        NetworkCallbackFlags flagIncludeLocationInfo = NetworkCallbackFlags.IncludeLocationInfo;
        NetworkCallback networkCallback = new NetworkCallback((int)flagIncludeLocationInfo);
        connectivityManager.RequestNetwork(request, networkCallback);
    }

    private class NetworkCallback : ConnectivityManager.NetworkCallback
    {
        public NetworkCallback(int flags) : base(flags)
        {
        }

        public override void OnCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities)
        {
            base.OnCapabilitiesChanged(network, networkCapabilities);
            WifiInfo wifiInfo = (WifiInfo)networkCapabilities.TransportInfo;

            if (wifiInfo != null)
            {
                string ssid = wifiInfo.SSID.Trim(new char[] {'"', '\"' });
                string bssid = wifiInfo.BSSID;
            }
        }
    }

Click Android API reference.ConnectivityManager.NetworkCallback(int)!


Q: Formula to reference data from a PivotTable I am having some difficulty writing a specific Excel formula. I have a summary sheet that pulls data from various other sheets extracted from a database. One of these is a PivotTable whereby using the Item Number in the first column and the dates along the top row as a reference I can pinpoint the data I need. eg:

To address the highlighted cell I would normally manually write:
=GETPIVOTDATA(HighPiv,"SPN010977-204 11333")

HighPiv is the name I gave to the pivot table as I am referring to it from my summary sheet.
This works, however the Week numbers along the top will continuously be changing in the pivot every month and therefore this formula will not pick up the values accurately once the pivot is updated. I have been looking into a way to make the referencing more dynamic. This is the summary where the data is required:

Rather than within the quotation marks of the formula (adding the specific Item number and Week number word for word), I was hoping to refer to the cell references of the summary sheet. (So if I wanted Item number, say A55, and Week number, say H50). The dates in the summary sheet change according to the pivot so referring to the dates on the summaries to get the data would be a better way for it to be kept up-to-date.
The problem here is I don't know how to go about it. I have tired to refer to the cells in question but it doesn't seem to work giving me #REF! or #VALUE! errors.

A: I think what you would like is:

=GETPIVOTDATA("Qty",HighPiv,"Item",A55,"Week",H50)

I find the easiest way to write such a formula is to start by ensuring that Pivot Table Tools > Options > PivotTable – Options, Generate GetPivotData is checked then in the desired cell enter = and select the required entry from the PT (here63). That would show (for example) “SPN010977-204” and 11333 or ”11333” but these can be changed to A55 and H50.


Q: How Would I replace a string if its input in a certain order? var xboxConverter = {
  "1" : "Up",
  "2" : "Down",
  "3" : "Down Foward",
  "4" : "Backward",
  "5" : "Standing",
  "6" : "Forward",
  "7" : "Up Backward",
  "8" : "Up",
  "9" : "Up Foward",
  "236S": "Quarter Circle Special",
  ",": "  ",
  "H" : "B",
  "M": "Y",
  "L": "X",
  "S": "A",
  "2" : "Down",
  "RB" : "RB",
  "236" : "Quarter Circle Forward",
  "214" : "Quarter Circle Backwards",
  "214S" : "Quarter Circle Backwards Special",

};

document.querySelector("textarea").addEventListener("keyup", (e) => {
  const input = e.target.value.toUpperCase();
  const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, "");
  const arrOfIns = inputValidated.split(" ");
  const arrOfOuts = arrOfIns.map((e) =>
    xboxConverter[e] ? xboxConverter[e] : ""
  );
if (parseInt.innerText == 236 & 214)
return
  const out = arrOfOuts.join(" , ");
  document.getElementById("output").innerText = out;

});

To better describe what I mean if someone inputs 236 together it should say "Quarter Circle Forward" or if they input 236RT it should say "Quarter Circle Forward Right Trigger".

A: From your comments, I can understand that you are looking for a value matching the key that the user inputs. You can simply check for it without any splits and for loops like:

var xboxConverter = {
  "1": "Up",
  "2": "Down",
  "3": "Down Foward",
  "4": "Backward",
  "5": "Standing",
  "6": "Forward",
  "7": "Up Backward",
  "8": "Up",
  "9": "Up Foward",
  "236S": "Quarter Circle Special",
  ",": "  ",
  "H": "B",
  "M": "Y",
  "L": "X",
  "S": "A",
  "2": "Down",
  "RB": "RB",
  "236": "Quarter Circle Forward",
  "214": "Quarter Circle Backwards",
  "214S": "Quarter Circle Backwards Special",

};

document.querySelector("textarea").addEventListener("keyup", (e) => {
  const input = e.target.value.toUpperCase();
  const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, "");
  document.getElementById("output").innerText = xboxConverter[inputValidated] ? xboxConverter[inputValidated] : "No data";
});
<textarea></textarea>

Is this what you're looking for?


Q: How to bring BigDecimal to fractional power? BigDecimal was the choice to store numbers that have up to 5 digits after decimal point. I need to raise the BigDecimal to fractional power (up to 2 digits after decimal point).
For example I have to bring 9.09671 to power of 1.51. Do I need some conversions from/to BigDecimal? How to do it?
EDIT:
I cannot use 3rd party libraries as described in Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it?
Is there more elegant, succint way for this case than described in How to do a fractional power on BigDecimal in Java?


Q: multi-part identifier could not be bound on insert from another database on another server I am trying to insert information from one database on one server into a table on another with out inserting a duplicate and i get the title error. here is the code
INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description)
SELECT job_no, description
FROM OPENDATASOURCE('SQLNCLI',
'Data Source=server\server;Integrated Security=SSPI')
.cas_tekworks.dbo.jobs WHERE Job_Status ='A' and data_job_t.JobCode  not in (select Jobcode from [Datamaxx].[dbo].[data_job_t])

A: Did you tried this....
job_no not in instead of data_job_t.JobCode
INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description)
SELECT job_no, description
FROM OPENDATASOURCE('SQLNCLI',
'Data Source=server\server;Integrated Security=SSPI')
.cas_tekworks.dbo.jobs WHERE Job_Status ='A' and job_no not in (select Jobcode from [Datamaxx].[dbo].[data_job_t])


Q: image auto rotate counterclockwise when width is less than height My all images auto rotate counterclockwise when width is less than height.
Example: this example
Help me please! Thanks!


Q: Javascript, find object in list of objects by id I have a list of objects in where I need to find one specifically by an ID. So very simply like so:
{
 {
   "id": "1"
 },{
   "id": "2"
 }
}

I have a function where I want to find the object by it's id, that does not work like so
 function findOb (id) {

   return _.find(myList, function(obj) { return obj.id === id } );

 }

it is not returning the correct object (this is using lodash) uncertain what I am doing incorrect and could use some help. Thanks!
edit - I don't know if this helps but I am building and trying to search an object in this format - https://github.com/pqx/react-ui-tree/blob/gh-pages/example/tree.js . So there are just objects with module and leaf sometimes, and I want to be able to search and find by the 'module' key. Thanks for the feedback everyone!

A: Your code should have worked, but it can be simplified.
If you provide a property name for the predicate argument to _.find, it will search that property for the thisArg value.
function findOb(id) {
    return _.find(myList, 'id', id);
}

The only problem I can see with your code is that you use === in your comparisons. If you pass 1 as the ID argument instead of "1", it won't match because === performs strict type checking.


Q: Does Azure TableQuery handle continuation tokens internally? I'm trying to find a definitive answer to the question of continuation tokens and the Azure Storage Library 2.0, as there seems to be significant differences between pre-2.0 versions (StorageClient) and the current version (Storage).
Aside from the MSDN documentation, which doesn't clarify the above question for me, its very hard to find information on continuation tokens which specifically relates to version 2.0 and above of the library, because earlier versions are named so similarly (CloudTableQuery vs TableQuery) search results get polluted with information about the earlier versions.
So, are continuation tokens handled internally on the Microsoft.WindowsAzure.Storage client (version 2.0 of the storage library)?  Can I trust that the result sets I get back are the full result sets?
Thanks!

A: There're two methods in question when it comes to executing queries against a table: CloudTable.ExecuteQuery and CloudTable.ExecuteQuerySegmented. The first one (ExecuteQuery) will handle the continuation token internally while the second one (ExecuteQuerySegmented) will return you the continuation token as a part of result set which you can use to fetch next set of data.


Q: pulling out list from wordpress post I want to pull out the list (ul) element from my wordpress post(s) so I can put it in a different location.
My current css pulls out the images and blockqute and puts just the text
html
<?php
  $content = preg_replace('/
(.*?)<\/blockquote>/', '', get_the_content());
  $content = preg_replace('/(]*>)/', '', $content);
  $content = wpautop($content); // Add paragraph-tags
  $content = str_replace('

', '', $content); // remove empty paragraphs
    echo $content;
?>

A: Just a friendly reminder is that it is generally not recommended to parse html with regex.
If you would like to do that anyway you could try like this:
$pattern = '~
(.*?)
~s';

So in your code it would look like this:
preg_match_all('/(~
(.*?)
~s)/', $content, $ulElements);

And then for removing it from the original string:
preg_replace('/(~
(.*?)
~s)/', '', $content);


Q: Android java.lang.OutOfMemoryError: GC overhead limit exceeded I got an error as of title. I know there are many answers but it didn't works.
What I did already,
First.
add code on build.gradle(Module:app)
"multiDexEnabled true" at defaultConfig  &
"compile 'com.android.support:multidex:1.0.1'" at dependencies
add code on AndroidMenifest
android:name="android.support.multidex.MultiDexApplication" at application
Second.
add code on build.gradle(Project:~~)(I also tried on build.gradle(Module:app)
"dexOptions{
             javaMaxHeapSize "2g" (I also tried for "4g"
}"
First one was not works which means show same error.(Out of memory)
Second one was show another error(could not find method~~) which means I use higher targetSDKVersion to use it.(My app is 23 for targetSDKVersion.)
So there were no answer until I tried google it....
How could I solve it....?
is there anybody who can help me?
I'm waiting for you such a kind person.... Thank you in advance.....