text:
Q: Join 2 Columns with same ID in Linq My problem is how can i join the selected rows with identical ID but different contacts
This is the output of what I'm doing
|     Name     |    Address   |     Cellphone    |     Email      |
|     John     |     NY       |       n/a        |   johndoe@y.c  |
|     John     |     NY       |    123456781     |       n/a      |

and i want my output to be one liner combined
|     Name     |    Address   |     Cellphone    |     Email      |
|     John     |     NY       |     123456781    |   johndoe@y.c  |

this is my Linq
var an = (from a in  db.Info
                     join b in db.Contact
                     on a.ID equals b.InfoID
                     where b.ContactTypeID == 56
                     || b.ContactTypeID == 59
                      select new
                                 {
                                     a.ID,
                                     a.LastName,
                                     a.FirstName,
                                     a.MiddleName,
                                     b.ContactTypeID,
                                     b.Values

                                 }).ToList();

            List<Info> wlist = new List<Info>();
            foreach (var row in an)
            {
                Info ci = new Info

                                           {

                                               ID = row.ID,
                                               Name = row.FirstName + " " + row.MiddleName + " " + row.LastName,
                                               ContactType = GetLookupDisplayValById(row.ContactTypeID),
                                               ContactValue = row.Values

                                           };
                wlist.Add(ci);
            }
            return Json(wlist.ToList(), JsonRequestBehavior.AllowGet);
        }

I hope someone can help me with this
Thanks :)

A: You can do it:
from info in db.Info
join contact in db.Contact
on info.ID == contact.InfoID
select new Contact(info, contact)

And your constructor will merge.
public class Contact
{
public int ID { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public int ContactTypeID { get; set; }

public Contact(Info info, Contact contact)
{
   ID = info.ID;
   LastName = string.IsNullOrEmpty(info.LastName) ? contact.LastName : info.LastName;
}
}

A: try with GroupBy
var resuts = db.Info.GroupBy(i=>i.ID)
 .Select(g=>new Info{
            ID = g.Key,
            Address = g.Fist().Address,
            Cellphone = g.FistOrDefault(x=> x.Cellphone !="n/a"),
            Email = g.FistOrDefault(x=> x.Email !="n/a")
        }).ToList();


text:
Q: Swift: How to check intersection with multiple sets? I have a master set generated by 5 random numbers from 1 to 52; I would like to compare this master set with 13  other sets, each containing 4 numbers between 1 and 52.
Is there a way to check if there are any 2 sets, each containing 2 numbers from the master set?
import UIKit

var firstCard = 0
var secondCard = 0
var thirdCard = 0
var fourthCard = 0
var fifthCard = 0

func generateRandomNumber(_ from:Int, _ to:Int, _ qut:Int?) -> [Int]
{
   var myRandomNumbers = [Int]()
   var numberOfNumbers = qut

let lower = UInt32(from)
let higher = UInt32(to+1)

    if numberOfNumbers == nil || numberOfNumbers! > (to-from) + 1
    {
        numberOfNumbers = (to-from) + 1
    }

    while myRandomNumbers.count != numberOfNumbers
    {
        let myNumber = arc4random_uniform(higher - lower) + lower

        if !myRandomNumbers.contains(Int(myNumber))
        {
            myRandomNumbers.append(Int(myNumber))
        }
    }

    return myRandomNumbers

}

let myArray = generateRandomNumber(1, 53, 5)

firstCard = myArray[0]
secondCard = myArray[1]
thirdCard = myArray[2]
fourthCard = myArray[3]
fifthCard = myArray[4]

let mainSetA = Set([firstCard, secondCard, thirdCard, fourthCard, fifthCard])

let setB: Set = [1, 2, 3, 4]
let setC: Set = [5, 6, 7, 8]
let setD: Set = [9, 10, 11, 12]
let setE: Set = [13, 14, 15, 16]
let setF: Set = [17, 18, 19, 20]
let setG: Set = [21, 22, 23, 24]
let setH: Set = [25, 26, 27, 28]
let setI: Set = [29, 30, 31, 32]
let setJ: Set = [33, 34, 35, 36]
let setK: Set = [37, 38, 39, 40]
let setL: Set = [41, 42, 43, 44]
let setM: Set = [45, 46, 47, 48]
let setN: Set = [49, 50, 51, 52]

no clue what to do next...

A: Something like this might help:
let mainSet = Set([1, 2, 3, 4])

Here I have three sets out of four that contain at least two items in the main set:
let inputs: [Set<Int>] = [
    Set([9, 8, 7, 1]),
    Set([9, 8, 1, 2]),
    Set([9, 1, 2, 3]),
    Set([9, 0, 3, 4])
]

Filter the input sets array, to find any where the intersection between that set and the main set is at least 2:
let matchingSets = inputs.filter {
    $0.intersection(mainSet).count >= 2
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sec-WebSocket-Key returned from server does not match expected response I got some hot stuffs going on this morning.
I was kind of proud to add some websocket features in a swing client to communicate with the server using tyrus-standalone-client version 1.12.
All the tests did run successfully.
Yesterday I released the new version of the swing client. A couple of our customers could start the client anymore due to the following error:
Caused by: org.glassfish.tyrus.core.HandshakeException: Sec-WebSocket-Key returned from server does not match expected response.

            at org.glassfish.tyrus.core.SecKey.validateServerKey(SecKey.java:139)

            at org.glassfish.tyrus.core.Handshake.validateServerResponse(Handshake.java:187)

            at org.glassfish.tyrus.client.TyrusClientEngine.processUpgradeResponse(TyrusClientEngine.java:516)

            at org.glassfish.tyrus.client.TyrusClientEngine.handleSwitchProtocol(TyrusClientEngine.java:340)

            at org.glassfish.tyrus.client.TyrusClientEngine.processResponse(TyrusClientEngine.java:277)

            at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleHandshake(GrizzlyClientFilter.java:346)

            at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleRead(GrizzlyClientFilter.java:315)

            at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)

            at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)

            at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)

            at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)

            at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)

            at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)

            at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)

            at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)

            at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)

            at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)

            at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)

            at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)

            at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)

            at java.lang.Thread.run(Unknown Source)

I have not been able to really figure out what the cause of the issue might be since that same client is running successfully with other customers of mine.
My only clue is the java version. A customer who encouters the problem is using java 1.8.0_71. I have tested on java 1.8.0_73 and 1.8.0_45 without problem.
Thanks


text:
Q: Entity Framework and DataSet.WriteXml() In the past I have some code that works with datasets that are persisted to disk using XML. Is there an EF provider that would allow me to use EF where the "back end" is XML rather than SQLExpress?

A: No there isn't. Linq to xml is very handy but you would have to roll your own models and abstraction to the xml files. I just heard that EF7 will have support for other types of data sources, but I'm not sure if xml is one of them.


text:
Q: Inserting pages into large mmap() files without copying data I'm wondering if there is a way to insert blank pages near the beginning of a large (multi-GB) file that I have open with mmap().  Obviously it would be possible to add a page or two to the end, and move everything forward with memcpy(), but this would dirty every page and require an awful long time when eventually flushed to disk.
I'm guessing that a solution would require some complex coordination between a customized filesystem and manual manipulation of the page tables: add a block to the inode, somehow update the cached pages in the VMM to reflect this, then somehow swizzle the page table to match.  This sounds non-trivial, which makes me wonder if there's a better way.
This is intended as a somewhat deep question about memory and file manipulation on Linux, although I'd be happy to hear about how this can be done in other systems.  I'm not particularly interested in workarounds that involve making the copying more efficient, although a technique that requires remapping but avoids the disk IO would be a good start.

A: Embed a simple FAT in your file.  For instance, the first 4k of the file would be a the FAT page.  Data would be in following pages.  The first FAT page could link to other FAT pages as your file grew.  Each entry in the fat would be a data page index and the index of the next FAT entry.  A FAT entry would be the page of the FAT and the index on that page of the entry itself.  I think you get the idea.  The FAT entries are A linked list.  The FAT pages are a linked list.  The FAT entries link data pages.  This should be enough information to use remap_file_pages() to make your file look contiguous in memory even though its not contiguous on the disk.


text:
Q: Python - empty dirs & subdirs after a shutil.copytree function This is part of a program I'm writing. The goal is to extract all the GPX files, say at G:\ (specified with -e G:\ at the command line). It would create an 'Exports' folder and dump all files with matching extensions there, recursively that is. Works great, a friend helped me write it!! Problem: empty directories and subdirectories for dirs that did not contain GPX files.
import argparse, shutil, os

def ignore_list(path, files): # This ignore list is specified in the function below.
    ret = []
    for fname in files:
         fullFileName = os.path.normpath(path) + os.sep + fname
         if not os.path.isdir(fullFileName) \
            and not fname.endswith('gpx'):
            ret.append(fname)
         elif os.path.isdir(fullFileName) \ # This isn't doing what it's supposed to.
            and len(os.listdir(fullFileName)) == 0:
            ret.append(fname)
    return ret

def gpxextract(src,dest):
    shutil.copytree(src,dest,ignore=ignore_list)

Later in the program we have the call for extractpath():
if args.extractpath:
    path = args.extractpath
    gpxextract(extractpath, 'Exports')

So the above extraction does work. But the len function call above is designed to prevent the creation of empty dirs and does not. I know the best way is to os.rmdir somehow after the export, and while there's no error, the folders remain.
So how can I successfully prune this Exports folder so that only dirs with GPXs will be in there? :)

A: If I understand you correctly, you want to delete empty folders? If that is the case, you can do a bottom up delete folder operation -- which will fail for any any folders that are not empty. Something like:
for root, dirs, files in os.walk('G:/', topdown=true):
    for dn in dirs:
        pth = os.path.join(root, dn)
        try:
            os.rmdir(pth)
        except OSError:
            pass


text:
Q: Google Play Services "Connecting" pop up does not appear I have have implemented the Google Play Services and BaseGameUtils to my app. Everythings works fine, but when sign-in button is clicked there is no pop-up with displaying the sign in progess, after a few seconds sign-in progress ends succesfully and "Welcome -username-" pop up appears.
I didn't change anything but the sign-in progress doesn't appear. In developer.google.com it says "On Android devices, the Google Play Games 'Connecting' pop-up is displayed by default whenever the sign-in flow is invoked.". How can I solve this issue, any ideas?

A: The sign-in pop-up is only displayed on first sign-in, or after you've signed-out and then sign-in again.
Note that sign-out never happens during the normal GameHelper flow, you have to manually call the mHelper.signOut() method to sign out - by default GameHelper only disconnects, which is different from signing-out.


text:
Q: Help with EF Code First, many to many relationship Person and EHR(electronic health record) are one to one related.
Person has EHRId nullable and EHR has PersonId not nullable.
At the same time EHR and Person must be many to many related.
Because a person can have many medics (represented by person entity) and a medic can have many EHRs.
I would like to have extra attributes on the join table.
I dont know how to define this in EF.
Please help.
Here are my classes.
    public class Person
        {
            public int ID { get; set; }
            public string firstName { get; set; }
            public string lastName { get; set; }
            public ICollection<UserSpecialist> patients { get; set; }
            public int ehrID { get; set; }
            public virtual EHR ehr { get; set; }

        }

public class EHR
    {
        public int ID { get; set; }
        public bool asthmatic{ get; set; }
        public ICollection<UserSpecialist> specialists { get; set; }
        public int PersonID { get; set; }
        public virtual Person Person { get; set; }
    }

public class UserSpecialist
    {
        public int ID { get; set; }
        public DateTime creationDate { get; set; }
        public int PersonID { get; set; }
        public int EHRID { get; set; }
        public virtual Person Person { get; set; }
        public virtual EHR EHR { get; set; }
    }

When EF tries to create the database throws this error

Unable to determine the principal end
  of an association between the types
  'Project.Person' and 'Project.EHR'.
  The principal end of this association
  must be explicitly configured using
  either the relationship fluent API or
  data annotations.

Please help

A: Person and EHR are not one-to-one related and they cannot be in EF. What you have defined is bidirectional one-to-many. You have also declared both relations as required because FK's are not nullable.
Real one-to-one can be defined in EF only if EHR's PK (Id) is also FK to Person. Once you define this the part with many-to-many becomes really strange because Person will be related with EHRs of other persons. You domain description is most probably not correct.


text:
Q: Adding drop down menu using d3.js I am trying to add a drop down menu to my d3 visualization. The problem is that the eventlistener does not get invoked on selecting any of the options. Also, how can I access the value of the option selected? Following is a snippet of my code..
d3.text("uniqueTeams.php",function(json){
    var dd=JSON.parse(json);
    var b= d3.select("#s4").select("#shru");
    var u=b.append("select");
    var t=u.selectAll("option").data(dd).enter().append("option")
        .attr("value",function(d){return d.teamShotID;})
        .text(function(d){return d3.select(this).node().__data__.teamShotID;});
    t.on("change",change);
});
function change(value)
{
    console.log("team",value);
}
change();

Thankx

A: You need to add the .on("change") to the select element, not the option elements.
var select  = d3.select("#shru").append("select").on("change", change),
    options = select.selectAll('option').data(dd); // Data join

// Enter selection
options.enter().append("option").text(function(d) { return d.teamShotID; });

The currently selected option index is kept in a property called selectedIndex on the select element. Selections are arrays, so elements can be accessed directly (e.g., selection[0][0]). Each option element will have data bound to it, stored in a property called __data__:
function change() {
    var selectedIndex = select.property('selectedIndex'),
        data          = options[0][selectedIndex].__data__;
}

Edit: For readability and hopefully to help you understand the code above, I'd like to also include this alternative syntax:
function change() {
    var si   = select.property('selectedIndex'),
        s    = options.filter(function (d, i) { return i === si }),
        data = s.datum();
}

A: hope this can guide you...
      var dispatch = d3.dispatch("load", "countrychange");
  d3.csv("data/ERSreputationBlocked.csv",type, function (error, country) {
      if (error) throw error;
      var countryById = d3.map();
      country.forEach(function (d) { countryById.set(d.id, d); });
      dispatch.load(countryById);
      dispatch.countrychange(countryById.get("PH"));
      //console.log(country);
  });
  dispatch.on("load.menu", function(countryById) {
      var select = d3.select("body")
        .append("div")
        .append("select")
        .on("change", function () { dispatch.countrychange(countryById.get(this.value)); });

      select.selectAll("option")
        .data(countryById.values())
        .enter().append("option")
        .attr("value", function (d) { return d.id; })
        .text(function (d) { return d.Country; });

      dispatch.on("countrychange.menu", function (country) {
          select.property("value", country)
          //loading the value based on the selected data
          var svg1 = d3.select("body").append("svg1")
                .attr("width", width)
                .attr("height", height)
          //end of selection

         console.log(country);
      });
  });
  //end of drop down

  function type(d) {
      d.total = d3.sum(d.value, function (k) { return d[k] = +d[k]; });
      return d;
  }


text:
Q: UWP FolderPicker Select Folder button disabled by default? I have a simple code for FolderPicker:
        var diagFolder = new FolderPicker();
        diagFolder.FileTypeFilter.Add("*");

        var outputFolder = await diagFolder.PickSingleFolderAsync();
        if (outputFolder == null) { return; }

It works well on first launch. However, upon second call, the Select Folder button is disabled and user cannot choose the same folder although it is perfectly valid. I have to go back a level and re-enter the folder if I want to pick that same folder.

Anyone is having this problem and know a fix for it?
EDIT: as of my guess, it is not actually UWP code problem, but Windows problem, so I posted a feedback here: https://aka.ms/AA1hloz . I think voting there should help.


text:
Q: Git don't merge specific files (or even lines) when merging branches First of all, I have a feeling that this has been covered somewhere else, however I was unable to find it despite searching both SO and Google. If this is indeed a duplicate please feel free to mark it as so
My git-based website is currently composed to two branches - Development and Production. (I'm currently the only developer on the team, so I didn't bother creating a release branch)
My project is done on top of a MVC Framework (laravel), and I would like to have branch-dependent files (don't update these when I merge development into production).
For example, in the production branch the config file is set to not output debug info when a server error occurs, while in the development branch I want it to output debug info.
As such, is it possible to get git to ignore specific files like the config file? Or even better, get it to ignore that specific line in the config file?
Note, this is a website - not a small project.

A: I'm pretty certain there is not, at least not without considerable effort. This idea is kind of confusing the purpose between version control software like git and build software like make or SCons. Typically you want everything that could be built/deployed in a managed repository, and then you have a build to manage bundling/deploying. It sounds like you are managing a website repository which doesn't seem like a great candidate for make and is the reason I actually use SCons to manage deploys (production and development) for a website and highly recommend it. If you definitely wanted to do it without a proper build software you could manage it by:
1) Making separate release trees/branches where changes to be saved to the master never get performed there, just create the differences in the files you want for development vs. production, develop elsewhere, push the updates into the isolated trees and use those for deploy. If you end up with edits that will cause conflicts in unmerged files, you would have to git stash and possibly edit manually to incorporate them. Obviously this is not great since certain things will never get checked into the master.
2) Do something with post-receive hooks, where you include the relevant different files that are under version control in a different location in the repository than where they would be in production (and would not be accessible to a user), to move the appropriate file into that location. To do this you'd have to have a repo where you want to deploy and where you develop (a bad idea - see below).
Those are really the only two I can think of, and I re-reviewed the git documentation in regards to your questions and could not find much else, but it would be much better just to use a proper build tool. It is the purpose of those types of tools and your comment "Or even better, get it to ignore that specific line in the config file?" just screams to use build-dependent defines to create the line you want based on a flag. You can additionally incorporate things like syntax checkers (JShint), web code minimizers (Google Closure) or static page templating (wpp) as part of your build process - I know nothing about laravel so maybe those would not be helpful, it's just some general ideas - so while some may think it's ok to push web files into production straight from git and building is not necessary for code that does not have to compile, I'd have to say that is a short-sighted idea. When you separate your code base from deployment in this regard, it also helps manage things that may be critical to your website that also don't belong in the web-accessible framework like server configurations, database migrations, cgi scripts, etc.

A: I found a solution for that (at least for the branch dependent files)
1) Create a custom merge driver that will ignore merge conflicts for the respective file. The driver has to be registered for each file in .gitattributes
2) Create merge conflicts at each commit in that file (otherwise, the merge is trivial and the merge driver will not be used). This can be done with a post-commit hook in .git/hooks/post-commit that changes that file in each branch after each commit.
I combined that in some scripts: https://github.com/keepitfree/faithfulgit


text:
Q: ++ Syntax for Content Inside Array? can you do array[i]++?
Is it the same as array[i] = array[i] + 1?
If not, why not? Is it something to do with how primitives vs references are treated?

A: There's a slight difference: postfix vs prefix increment operator

*

*If you use array[i]++, the old value will be used for the calculation and the value of i will be increased by 1 afterwards.

*For array[i] = array[i] + 1, it's the opposite: i will first be incremented and only then the calculation will take place.
For more details, check this out.


text:
Q: Compare User Input with WordPress Meta Key Value I have searched, but could not find it anywhere,
I need a function to compare, user's input with a meta key value, and then process.
For example, user will type 5000 in given box. User will see the result according to if specific user meta key value is greater, lesser or equals to 5000.
Thanks in advance.....

A: Use get_post_meta();
Function ref. get_post_meta()
You can compare dynamically with ajax


text:
Q: How do I access a derived classes data members when creating a pointer of the base class to hold the derived class? I have a class Airplane:
class Airplane {
    private:
        int value;
   public:
        // some public functions that arent relevant
};

and then another class that derives from Airplane
class Model : public Airplane {
    private:
        bool flag;
    public:
       // some functions
};

What I need to do is create a pointer of type airplane that points to the child class, aka model.
Like so: Airplane* A = new Model();
Then I can use A->functions to access the public functions of airplane to modify airplanes private data members.
My problem is I need to modify the private data members of Model. I created public member functions in model to change models private members, but it doesnt let me do A->modelfunctions. Is there a way to modify the Model private members with my system above?
My instructions were to create a dynamic instance of a Model and hold the address in an Airplane pointer. I want to do this while being able to modify private variables from both classes, either directly or through public functions. Right now I can modify "value" from airplane, but not "flag" from model using the Airplane* A = new Model(); system.
Thank you.


text:
Q: htaccess RewriteRule automatically removes queue slashes I have this in .htaccess file,
RewriteRule ^(.+)$ index.php?url=$1

Then if write in browser addres this url site.com/asd////bla and then in index.php if print $_GET['url'],  result is: asd/bla.
question: where is other slashes? why they are not printed ?


text:
Q: How to Error Handle a NullReferenceException My website went down for a few days, therefore I am trying to produce some error handling while the MVC app doesnt have access to certain resources so if something doesnt become unavailable again the WHOLE THING doesnt have to go down.
At the moment a controller is trying to access viewbag.moreNewProducts that isnt available.
public ActionResult Index(string search)
    {
        string[] newProductLines = this.getMoreNewProducts();
        string[] newNews = this.getMoreNews();
        string[] newPromotions = this.getMorePromotions();
        string[] fewerProductLines = this.getLessNewProducts(newProductLines);
        ViewBag.moreNewProducts = newProductLines;
        ViewBag.moreNews = newNews;
        ViewBag.morePromotions = newPromotions;
        ViewBag.lessNewProducts = fewerProductLines;
        bool disableShowMore = false;

This is where I run into an error: " foreach (string line in newProductLines)"
public string[] getLessNewProducts(string[] newProductLines)
    {
        int charCount = 0;
        int arrayCount = 0;
        string[] displayProductLines = new string[6];
        bool continueWriting;

            if (newProductLines == null)
            {

                foreach (string line in newProductLines)
                {
                    continueWriting = false;
                    for (int i = 0; charCount < 250 && i < line.Length && arrayCount < 5; i++)
                    {
                        string index = newProductLines[arrayCount].Substring(i, 1);
                        displayProductLines[arrayCount] += index;
                        charCount++;
                        continueWriting = true;
                    }
                    if (continueWriting == true)
                    {
                        arrayCount++;
                    }
                }
                string[] LessNewProducts = new string[arrayCount];
                for (int d = 0; d < arrayCount; d++)
                {
                    LessNewProducts[d] = displayProductLines[d];
                }
                return LessNewProducts;

            }

            else
            {
                return null;
            }

    }

how do I get around an if else statement so the whole thing doesnt have to crash?

A: if (newProductLines == null)
should be replaced with if (newProductLines != null) so you don't have to handle the code with newProductLines  as null. Basically, with this condition you will always have the NullReferenceException unless you manage your exception with a try catch block.

A: Two things.

*

*Your if (newProductLines == null) statement has the wrong condition on it. I don't believe that you want to enter that if newProductLines is null. You can inverse this condition to get the desired result(if (newProductLines != null)).

*If you run into another situation later where you need to catch an error, you can always use the try-catch block to catch exceptions that you are expecting.

try
{
   //code that could cause the error here
}
catch(NullReferenceException nullRefExcep)
{
   //what you want it to do if the null reference exception occurs
}

A: The real question to ask yourself is:

Why would newProductLines be null?

Presumably getMoreNewProducts() found a situation where it thought it would be appropriate to return a null value.
If this is happening because the system has an error that would make your page meaningless, then you may just want to change getMoreNewProducts() so that it throws an exception when that error state occurs. Typically it's safest and easiest to debug programs that fail as soon as they run into an unexpected situation.
If this is happening because there are no new products, then you should just return an empty collection, rather than null. All your code should work just fine after that, without the need for an if/else statement: it will return an empty array for LessNewProducts, which is probably correct.
However, let's assume that there's a situation that you're anticipating will occur from time to time, which will make it impossible for you to retrieve newProductLines at that time, but which you would like the system to handle gracefully otherwise. You could just use null to indicate that the value isn't there, but it's really hard to know which variables might be null and which never should be. It may be wiser to use an optional type to represent that getMoreNewProducts() might not return anything at all, so you can force any consuming code to recognize this possibility and figure out how to deal with it before the project will even compile:
public ActionResult Index(string search)
{
    Maybe<string[]> newProductLines = this.getMoreNewProducts();
    string[] newNews = this.getMoreNews();
    string[] newPromotions = this.getMorePromotions();
    Maybe<string[]> fewerProductLines = newProductLines.Select(this.getLessNewProducts);

Disclaimer: I am the author of the Maybe<> class referenced above.
Here are some additional improvements I'd suggest:

*

*Don't use ViewBag. Instead, create a strongly-typed ViewModel so that you can catch errors in your code at compile-time more often:
var viewModel = new ReportModel {
    newProductLines = this.getMoreNewProducts(),
    newNews = this.getMoreNews(),
    ...
};
...
return View(viewModel);

*Learn to use LINQ. It will simplify a lot of your very complicated code. For example, instead of:
        string[] LessNewProducts = new string[arrayCount];
        for (int d = 0; d < arrayCount; d++)
        {
            LessNewProducts[d] = displayProductLines[d];
        }
        return LessNewProducts;

... you can say:
        string[] LessNewProducts = displayProductLines.Take(arrayCount).ToArray();

In fact, I think your entire getLessNewProducts() method can be replaced with this:
return newProductLines
    .Where(line => line.Length > 0)
    .Select(line => line.Substring(0, Math.Min(line.Length, 250)))
    .Take(5);


text:
Q: How is possible build apk in terminal with different SIGN credentials I have build.gradle that can have signingConfigs, but I want TO ignore this setting and use other credentials. I don't want to edit or replace values in build.gradle.
Does gradle have same command like gradle assemble -storeFile='PATH' -storePassword='password' -keyAlias='alias' -keyPassword='password'?
If it's no way create signed apk with other signingConfigs, is it possible to create unsigned apk?

A: There is no gradle build command which takes sign configs.
You have two options based on the requirement you mentioned in your question.
1.Edit the build.gradle to create multiple build flavors and provide different signing details for each build flavor.
    android {
    signingConfigs {
        abc {
            keyAlias 'abc'
            keyPassword 'yyy'
            storeFile file('keystore/astro.keystore')
            storePassword 'zzz'
        }
        xyz {
            keyAlias 'xxx'
            keyPassword 'xxx'
            storeFile file('keystore/sample.keystore')
            storePassword 'xxx'
        }
        //add another block for new customer
    }}

*Create multiple copies of keystore properties file with different signing config and when you want to use one particular copy of keystore.properties file, rename it to "keystore.properties".
def keystorePropertiesFile = rootProject.file("keystore.properties")
https://developer.android.com/studio/publish/app-signing#secure-shared-keystore

A: I suggest you using the solution reported by @Ranjan. It is the cleaner and a standard solution.
However if you would like to use the command line command, all properties passed to gradle in the command line via -P parameter are accessible in the project variable in your gradle script.
You can do something like that:
gradle assembleRelease -PmyKeyPassword='xxx' -PmyStorePassword='xxx' -PmyKeyAlias='xxx' -PmyStoreFile='...xxx.keystore'

and then define in your build.gradle.
signingConfigs {
   release {
      storeFile project.mystoreFile
      storePassword project.myStorePassword
      keyAlias project.myKeyAlias
      keyPassword project.myKeyPassword
   }
}

Pay attention because it can cause errors if you don't specify the keys in the gradle command (not so good in my point of view).
You can mitigate the issue doing a check on the parameter (using the project.hasProperty(xxx) method) and defining the default value in the build.gradle.
Something like that:
signingConfigs {
       release {
         storeFile project.hasProperty('myStoreFile') ? project.myStoreFile : 'default'
         //..
       }
}


text:
Q: Share same variable among multiple js scripts - one has .ready function and other doesn't I have 2 js script:
 <script type="text/javascript">

 function capture(){
var canvas = document.getElementById('canvas');
var video = document.getElementById('video');
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
var img = canvas.toDataURL("image/png");
alert(img);
}
</script>
<script type="text/javascript">
 $(document).ready(function() {

 $(".post").click(function() { alert(img);
 var level = document.getElementById('level');
 var language = document.getElementById('language');
 var textac = document.getElementById('textac');
 var decribac = document.getElementById('decribac');
 $.ajax({
 type: "POST",
url: "love.php",

data: {img: img, language: language, level: level, decribac:decribac, textac: textac },
  cache: false,
  success: function(data){

   }});
     window.location.replace("love.php");

   });
   });
   </script>

What they do is first one on click on 'capture' makes a thumbnail of video and puts it in canvas and saves the var img. And other one on click of another button 'post' posts everything via ajax including the image base64 encoded string. My problem is that when I try to click 'post' console loggs out
-  404 Uncaught ReferenceError: img is not defined

And I dont know why as if I alert it in the first script it gets alerted correctelly but second one doesnt know it. And if i put the capture finction under
   $(document).ready(function(){..});

then it doenst work and console says - capture function is undefined. Thats also weird. And if I dont put the second button handler it doesnt do anything on click. So I needed to put them in their own scripts - one with .ready function and one without. Now I cant get the img var to the second script to send it via ajax to the php script. Help.

A: You define that variable inside a function:
function capture(){
    //...
    var img = canvas.toDataURL("image/png");
    //...
}

So it exists only within the scope of that function.  If it needs to be global, define it globally:
var img;

function capture(){
    //...
    img = canvas.toDataURL("image/png");
    //...
}

That would attach it to the window object where it can be accessed by by other code within the overall window scope.


text:
Q: Determine state of viewcontroller in storyboard I'd like to know how to manage this:
I have 4 viewcontrollers in a storyboard, each one has the same class but i would like to know how to determine when they change their state from fullscreen to invisible and viceversa. any hints?. BTW i have a main view that works like evernote with multiple tabs, and i can already switch between them but i want to put different return buttons on each view, don't know where to begin.

A: You can find out the size of the window with self.view.window.bounds and test it against the frame of your ViewControllers' view with:
CGRectContainsRect(self.view.window.frame, myViewController.view.frame)

This will return true if the view is on screen and false otherwise.


text:
Q: Changing column datatype from Timestamp to datetime64 I have a database I'm reading from excel as a pandas dataframe, and the dates come in Timestamp dtype, but I need them to be in np.datetime64, so that I can make calculations.
I am aware that the function pd.to_datetime() and the astype(np.datetime64[ns]) method do work. However, I am unable to update my dataframe to yield this datatype, for whatever reason, using the code mentioned above.
I have also tried creating an acessory dataframe from the original one, with just the dates that I wish to update the typing, converting it to np.datetime64 and plugging it back onto the original dataframe:
dfi = df['dates']
dfi = pd.to_datetime(dfi)
df['dates'] = dfi

But still it doesn't work. I have also tried updating values one by one:
arr_i = df.index
for i in range(len(arr_i)):
    df.at[arri[l],'dates'].to_datetime64()

Edit
The root problem seems to be that the dtype of the column gets updated to np.datetime64, but somehow, when getting single values from within, they still have the dtype = Timestamp
Does anyone have a suggestion of a workaround that is fairly fast?

A: Pandas tries to standardize all forms of datetimes by storing them as NumPy datetime64[ns] values when you assign them to a DataFrame. But when you try to access individual datetime64 values, they are returned as Timestamps.
There is a way to prevent this automatic conversion from happening however: Wrap the list of values in a Series of dtype object:
import numpy as np
import pandas as pd

# create some dates, merely for example
dates = pd.date_range('2000-1-1', periods=10)
# convert the dates to a *list* of datetime64s
arr = list(dates.to_numpy())
# wrap the values you wish to protect in a Series of dtype object.
ser = pd.Series(arr, dtype='object')

# assignment with `df['datetime64s'] = ser` would also work
df = pd.DataFrame({'timestamps': dates,
                   'datetime64s': ser})

df.info()
# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 10 entries, 0 to 9
# Data columns (total 2 columns):
# timestamps     10 non-null datetime64[ns]
# datetime64s    10 non-null object
# dtypes: datetime64[ns](1), object(1)
# memory usage: 240.0+ bytes

print(type(df['timestamps'][0]))
# <class 'pandas._libs.tslibs.timestamps.Timestamp'>

print(type(df['datetime64s'][0]))
# <class 'numpy.datetime64'>

But beware! Although with a little work you can circumvent Pandas' automatic conversion mechanism,
it may not be wise to do this. First, converting a NumPy array to a list is usually a sign you are doing something wrong, since it is bad for performance. Using object arrays is a bad sign since operations on object arrays are generally much much slower than equivalent operations on arrays of native NumPy dtypes.
You may be looking at an XY problem -- it may be more fruitful to  find a way to (1)
work with Pandas Timestamps instead of trying to force Pandas to return NumPy
datetime64s or (2) work with datetime64 array-likes (e.g. Series of NumPy arrays) instead of handling values individually (which causes the coersion to Timestamps).


text:
Q: How view single data from listView in flutter? I fetched data from the database as a ListView.That's displayed perfectly.
output.

When clicking the view button then should display only that article's details.
Andalso for the fetch data I used model class.
All articles code
model
import 'dart:convert';

Articles articlesFromJson(String str) => Articles.fromJson(json.decode(str));

String articlesToJson(Articles data) => json.encode(data.toJson());

class Articles {
  Articles({
    required this.id,
    required this.url,
    required this.topic,
    required this.description,
  });
  String id;
  String topic;
  String description;
  String url;

  factory Articles.fromJson(Map<String, dynamic> json) => Articles(
        id: json["id"] ?? "",
        topic: json["topic"] ?? "",
        description: json["description"] ?? "",
        url: json["url"] ?? "",
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "topic": topic,
        "description": description,
        "url": url,
      };
}

View all articles
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:neerogi/screens/Articles/Admin/viewOne_articles.dart';

import '../articlesModel.dart';

class ViewArticlesScreens extends StatefulWidget {
  const ViewArticlesScreens({Key? key}) : super(key: key);

  @override
  State<ViewArticlesScreens> createState() => _ViewArticlesScreensState();
}

class _ViewArticlesScreensState extends State<ViewArticlesScreens> {
  @override
  Future<List<Articles>> fetchRecords() async {
    var records = await FirebaseFirestore.instance.collection('articles').get();
    return mapRecords(records);
  }

  List<Articles> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
    var _list = records.docs
        .map(
          (article) => Articles(
            id: article.id,
            topic: article['topic'],
            description: article['description'],
            url: article['url'],
          ),
        )
        .toList();

    return _list;
  }

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

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Column(
        children: [
          SingleChildScrollView(
            child: Column(
              //chip words
              children: <Widget>[
                const SizedBox(height: 10),
                SizedBox(
                    width: width * 0.94,
                    height: height * 0.90,
                    child: FutureBuilder<List<Articles>>(
                        future: fetchRecords(),
                        builder: (context, snapshot) {
                          if (snapshot.hasError) {
                            return Text('Error: ${snapshot.error}');
                          } else {
                            List<Articles> data = snapshot.data ?? [];

                            return ListView.builder(
                                itemCount: data.length,
                                itemBuilder: (context, index) {
                                  return (SizedBox(
                                    height: 100,
                                    child: Column(
                                      children: <Widget>[
                                        ListTile(
                                            leading: Image.network(
                                              data[index].url,
                                              height: 30,
                                              fit: BoxFit.cover,
                                            ),
                                            title: Text(data[index].topic),
                                            subtitle:
                                                Text(data[index].description),
                                            trailing: ElevatedButton(
                                              child: Text('View'),
                                              onPressed: () {
                                                Navigator.of(context).push(
                                                    MaterialPageRoute(
                                                        builder: (context) =>
                                                            ViewOneArticleScreen(
                                                              id: article.id,
                                                            )));
                                              },
                                            ))
                                      ],
                                    ),
                                  ));
                                });
                          }
                        }))
              ],
            ),
          ),
        ],
      ),
    );
  }
}

View one article code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../articlesModel.dart';

class ViewOneArticleScreen extends StatefulWidget {
  const ViewOneArticleScreen({Key? key}) : super(key: key);

  @override
  State<ViewOneArticleScreen> createState() => _ViewOneArticleScreenState();
}

class _ViewOneArticleScreenState extends State<ViewOneArticleScreen> {
  Future<List<Articles>> fetchRecords() async {
    var records = await FirebaseFirestore.instance.collection('articles').get();
    return mapRecords(records);
  }

  List<Articles> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
    var _list = records.docs
        .map(
          (article) => Articles(
            id: article.id,
            topic: article['topic'],
            description: article['description'],
            url: article['url'],
          ),
        )
        .toList();

    return _list;
  }

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

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Column(
          children: [
            Image.network(
              data[index].url,
              height: 30,
              fit: BoxFit.cover,
            ),
            Text($topic),
            Text($description),
          ],
          ),
    );
  }
}

How to view one article data from the list view?
Ex:- User when cleck article 1 view button then should redirect to the View one article page and in there should display article 1 image , topic , description.


text:
Q: Js: It is a program to make a kind of bill A shop will give discount of 10% if the cost of purchased quantity is more than 1000.
Ask the user for the quantity. Suppose, one unit will cost 100.
Judge and print total cost for user. Ask for name phone number as well as bill amount

const bill_maker = () => {
  const bill_format = {
    name_customer: prompt("Enter the customer's name"),
    phone_number: Number(prompt("Enter the customer's phone number")),
    total_bill_amount: Number(prompt("Enter the bill amount"))
  }

  // Conditions
  if (bill_format.total_bill_amount > 1000) {
    return (`${bill_format.total_bill_amount}.Oh! You have 10% discount so you have to pay:` (bill_format.total_bill_amount / 1000) * 100)
  } else {
    return `${bill_format.total_bill_amount}. You have to pay`
    `${bill_format.name_customer} Do visit us again!`
  }
}

console.log(bill_maker())

A: The issue is because your template literal syntax is invalid. In each case you've split them without declaring new variables for the second part.
To fix the problem, merges the template literals in both sides of your if condition:

const bill_maker = () => {
  const bill_format = {
    name_customer: prompt("Enter the customer's name"),
    phone_number: Number(prompt("Enter the customer's phone number")),
    total_bill_amount: Number(prompt("Enter the bill amount"))
  }

  console.log(bill_format.total_bill_amount);

  // Conditions
  if (bill_format.total_bill_amount > 1000) {
    return `${bill_format.total_bill_amount}.Oh! You have 10% discount so you have to pay: ${(bill_format.total_bill_amount / 1000) * 100}`;
  } else {
    return `${bill_format.total_bill_amount}. You have to pay: ${bill_format.name_customer}. Do visit us again!`
  }
}

console.log(bill_maker())


text:
Q: Uploaded images not displaying in network site I have a network of sites and have recently added another site. When I upload an image it uploads to the correct directory but is showing a broken image link when viewed within the library or on the site. I checked the site's setting and everything looks correct.
file actually uploads to
blogs.dir\7\files\2011\03\1551-oct-cable.png
broken image link location e.x.
http://apollo.site.net/mainsite/kb/files/2011/03/1551-oct-cable.png
I really have no idea where to go on this one.

A: Looks like I needed
        <rule name="WordPress Rule 1" stopProcessing="true">
            <match url="^index\.php$" ignoreCase="false" />
            <action type="None" />
        </rule>
        <rule name="WordPress Rule 2" stopProcessing="true">
            <match url="^([_0-9a-zA-Z-]+/)?files/(.+)" ignoreCase="false" />
            <action type="Rewrite" url="wp-includes/ms-files.php?file={R:2}" appendQueryString="false" />
        </rule>

Also here's a bit more information I was able to find. http://wordpress.org/support/topic/images-files-not-displaying


text:
Q: The value of the CheckBoxPreferences makes an effect only after the Activity is restarted I've got a question about CheckBoxPreferences. I've read through the number of related threads and tried some of them but as I am a beginner I am still struggling to find the solution for the issue I am facing up. Below code is to apply a polygon over the google-map and in general it does it:
public class ZurichGreifensee extends Activity implements OnClickListener {

    String latLngUster = "lat=47.348491&lon=8.717529";

    private final LatLng LOCATION_GREIFENSEE = new LatLng(47.348124, 8.681688);

    private GoogleMap mMap;
    Button fishActivity;
    ToggleButton mapView;
    Polygon Naturschutzgebiet, Seeschutzzone;
    CheckBoxPreference naturschutzgebiet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.lakes_info);

        NetworkConnectivityCheck checkit = new NetworkConnectivityCheck();
        Boolean conn = checkit.checkNow(this.getApplicationContext());
        if(conn == true){

        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        CameraUpdate updateZurichGreifensee = CameraUpdateFactory.newLatLngZoom(LOCATION_GREIFENSEE, 13);
        mMap.animateCamera(updateZurichGreifensee);
        mMap.setMyLocationEnabled(true);

        mapView = (ToggleButton) findViewById(R.id.tbSatNorMapView);
        fishActivity = (Button) findViewById(R.id.bWhereAmI);
        mapView.setOnClickListener(this);
        fishActivity.setOnClickListener(this);

        }else{
            connectivityMessage("Kein Netzwerk");
        }

        SharedPreferences getGewasserRevierKarte = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        boolean naturschutzgebiet = getGewasserRevierKarte.getBoolean("naturschutzgebiet", false);{
            if (naturschutzgebiet == true){
                addNaturschutzgebiet();}
        }

        boolean seeschutzzone_1 = getGewasserRevierKarte.getBoolean("seeschutzzone_1", false);{
            if (seeschutzzone_1 == true)
                addSeeschutzzone();
        }
    }

    private void connectivityMessage(String string) {
        // TODO Auto-generated method stub
        Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setText(string);
        toast.show();
    }

    private void addNaturschutzgebiet() {
        Naturschutzgebiet = mMap.addPolygon(new PolygonOptions()
            .add(new LatLng(47.366676,8.673754), new LatLng(47.367526,8.67236), new LatLng(47.369459,8.670965), new LatLng(47.371886,8.669538),
                 new LatLng(47.372525,8.669184), new LatLng(47.375453,8.661481), new LatLng(47.376819,8.657801), new LatLng(47.378032,8.652318),
                 new LatLng(47.375962,8.651159), new LatLng(47.378839,8.646846), new LatLng(47.378759,8.646739), new LatLng(47.375562,8.651449),
                 new LatLng(47.37432,8.650172), new LatLng(47.37291,8.652007), new LatLng(47.371639,8.650355), new LatLng(47.370403,8.650634),
                 new LatLng(47.368972,8.650859), new LatLng(47.368071,8.652973), new LatLng(47.368173,8.653337), new LatLng(47.368122,8.653788),
                 new LatLng(47.367904,8.654228), new LatLng(47.367947,8.654593), new LatLng(47.369829,8.653616), new LatLng(47.371057,8.653488),
                 new LatLng(47.372155,8.65588), new LatLng(47.372656,8.657597), new LatLng(47.373608,8.661545), new LatLng(47.37262,8.663927),
                 new LatLng(47.371145,8.666051), new LatLng(47.370098,8.667457), new LatLng(47.370055,8.668186), new LatLng(47.369386,8.66839),
                 new LatLng(47.369241,8.669044), new LatLng(47.367497,8.67074), new LatLng(47.367243,8.670557), new LatLng(47.367293,8.670836),
                 new LatLng(47.366792,8.671544), new LatLng(47.366836,8.671823), new LatLng(47.365935,8.672746))
                    .strokeWidth(2)
                    .strokeColor(Color.RED)
                    .fillColor(Color.argb(64, 255, 0, 0)));
        }

    private void addSeeschutzzone() {
        Seeschutzzone = mMap.addPolygon(new PolygonOptions()
            .add(new LatLng(47.367947,8.654593), new LatLng(47.369829,8.653616), new LatLng(47.371057,8.653488),
                 new LatLng(47.372155,8.65588), new LatLng(47.372656,8.657597), new LatLng(47.373608,8.661545), new LatLng(47.37262,8.663927),
                 new LatLng(47.371145,8.666051), new LatLng(47.370098,8.667457), new LatLng(47.370055,8.668186), new LatLng(47.369386,8.66839), new LatLng(47.369241,8.669044),
                 new LatLng(47.368187,8.670085), new LatLng(47.368412,8.669001), new LatLng(47.36964,8.667097), new LatLng(47.370715,8.665166),
                 new LatLng(47.371442,8.663599), new LatLng(47.371413,8.661239), new LatLng(47.371006,8.658149), new LatLng(47.369989,8.656261))
                     .strokeWidth(2)
                     .strokeColor(Color.MAGENTA)
                     .fillColor(Color.argb(64, 170, 0, 120)));
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
                case R.id.bWhereAmI:
                    String locationZurichGreifensee = latLngUster.toString();
                    Bundle basketZurich = new Bundle();
                    basketZurich.putString("location", locationZurichGreifensee);
                    Intent t = new Intent(ZurichGreifensee.this, MainActivity.class);
                    t.putExtras(basketZurich);
                    startActivity(t);
                    break;
                }

                //Switching between normal and hybrid view
                if (mapView.isChecked()) {
                    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                }else {
                    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                }
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu);
        MenuInflater gewasserMenu = getMenuInflater();
        gewasserMenu.inflate(R.menu.gewasserkarte, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
        case R.id.gewasserkarte:
            Intent gewasser_revier_karte = new Intent(ZurichGreifensee.this, GewasserRevierKarte.class);
            startActivity(gewasser_revier_karte);
            break;
        }
        return false;
    }
}

and this is my xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:key="naturschutzgebiet"
        android:title="Naturschutzgebiet"
        android:summaryOn="Wege nicht verlassen, Hunde an der Leine führen"
        android:icon="@drawable/naturschutzgebiet"
        android:defaultValue="false" />

    <CheckBoxPreference
        android:key="seeschutzzone_1"
        android:title="Seeschutzzone"
        android:summaryOn="Befahren mit Booten oder anderen Schwimmkörpern sowie Baden ganzjährig verboten"
        android:icon="@drawable/seeschutzzone_1"
        android:defaultValue="false" />

</PreferenceScreen>

To get one of above defined polygons displayed on the map, the appropriate check-box is to be ticked-in in the preference menu. Now, even if I do it the polygon is not visible after I close the preference menu. Instead, I have to restart ZurichGreifensee activity by closing it and starting it again. Only then the code applies the polygon over the map.
My question is, what I would need to change/add within the code above so that polygon gets displayed immediately after I tick-in the desired preference Check-Box and close/ exit the preference menu?
Many thanks in advance.

A: You need to override the onResume method and check if the user has pressed the CheckBox there
@Override
public void onResume () {
    super.onResume();
    //if user has checked the box
    //is rectangle isn't already drawn
    //draw rectangle
}


text:
Q: Connection closed when saving blob I'm having a problem when uploading files on a weblogic application.
Once the fileuploader has finished saving the file, the following exception appears:
java.sql.SQLException: Conexión cerrada
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
at oracle.sql.BLOB.getDBAccess(BLOB.java:882)
at oracle.sql.BLOB.freeTemporary(BLOB.java:584)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.jdbc.support.lob.OracleLobHandler$OracleLobCreator.close(OracleLobHandler.java:412)
at org.springframework.jdbc.support.lob.SpringLobCreatorSynchronization.afterCompletion(SpringLobCreatorSynchronization.java:76)
at org.springframework.transaction.support.TransactionSynchronizationUtils.invokeAfterCompletion(TransactionSynchronizationUtils.java:133)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.invokeAfterCompletion(AbstractPlatformTransactionManager.java:951)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerAfterCompletion(AbstractPlatformTransactionManager.java:926)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:678)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:319)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy74.guardarFichero(Unknown Source)

At other environments this problem doesn't appear, so I think it must be some configuration on the JDBC driver but I'm not sure wich one I have to modify.
The invoking struts
    private void adjuntarFichero()throws Exception {
    logger.debug("uploadFileName = "+uploadFileName);
    if (uploadFileName!=null && !uploadFileName.equals("")) {
        HttpSession session = request.getSession();
        HashMap<Long,String> ficheros = (HashMap<Long,String>)session.getAttribute("ficheros");
        if (ficheros == null) ficheros = new HashMap<Long,String>();

        Fichero file = new FicheroImpl();
        file.setNombre(uploadFileName);
        file.setFichero(getBytesFromFile(upload));
        file = gestorFichero.guardarFichero(file);

        ficheros.put(file.getId(), uploadFileName);
        session.setAttribute("ficheros", ficheros);
    }
}

the error is produced inside the "guardarFichero" method, who invokes a DAO class that takes care of the saving
public abstract class gestorFichero
    extends org.springframework.orm.hibernate3.support.HibernateDaoSupport{
public Fichero guardarFichero (Fichero fichero){
    Debug.prec(fichero, "El fichero no puede ser nulo");
    return (Fichero)create(TRANSFORM_NONE, fichero);
}
public java.lang.Object create(final int transform, final    com.aena.sgc.Fichero fichero)
{
    if (fichero == null){
        throw new IllegalArgumentException("Fichero.create - 'fichero' can not be null");
    }
    this.getHibernateTemplate().save(fichero);
    return this.transformEntity(transform, fichero);
}

A: Finally I discovered wich was the problem.
It was related to the driver class. Originally we had the datasource configured to use the XA driver oracle.jdbc.xa.client.OracleXADataSource and whenever we finished uploading a file, the exception was thrown.
Once I changed the driver to oracle.jdbc.OracleDriver these errors dissapeared.


text:
Q: Angular Material - show mat-error on button click I am trying to do validation using the <mat-form-field> and <mat-error>. This works fine when user tabs out of the input without filling. But how do I force this error to show when I click a button? I am not using submit. Also, using template-driven forms.
This is my code:
HTML:
<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>

TS:
dueDateValidator: FormControl =  new FormControl('', [Validators.required]);

A: This works for me. :) On button's click:
this.nameControl.markAsTouched();

A: I am providing 3 different solutions for different scenarios, use the one which suits you.

*

*If you are using a form, then do
this.form.markAllAsTouched();

*If you need a particular field to be affected inside form, then filter that nameControl and do
nameControl.markAsTouched();

*If you are not using forms, then specify a ref for the input element and initialize variable in ts file & do as follows,
@ViewChild('myInputRef') myInputRef; // Initialize the ref of input element
.
.
this.myInputRef.control.markAsTouched()

A: See how to use a form with a custom ErrorStateMatcher

If you wish to override this behavior (e.g. to show the error as soon
  as the invalid control is dirty or when a parent form group is
  invalid), you can use the errorStateMatcher property of the matInput.
  The property takes an instance of an ErrorStateMatcher object. An
  ErrorStateMatcher must implement a single method isErrorState which
  takes the FormControl for this matInput as well as the parent form and
  returns a boolean indicating whether errors should be shown. (true
  indicating that they should be shown, and false indicating that they
  should not.)

I would make a separate file such as default.error-matcher.ts
/** Error when invalid control is dirty or touched*/
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.dirty || control.touched));
  }
}

Then in the TS file add:
matcher = new MyErrorStateMatcher();

Then change the input to use matcher:
<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>

A: Either you can do as "Kyle Pfromer" suggested or as you are using form group, you can mark element as touched on submit with
onSubmit(){ this.formName.get('formControlName').markAsTouched(); }

A: Since you want to show mat error on button's click, please try the below:
For Angular6 version:

*

*Import the required classes

import { FormControl, FormBuilder, FormGroup } from '@angular/forms';

*Declare form control in your component.ts file:

nameControl = new FormControl('');

*Add the control in html:

<mat-form-field  style="width: 100%" floatPlaceholder="never">
    <input matInput placeholder="your placeholder text" [formControl]="nameControl" required/>
    <mat-error *ngIf="nameControl.errors?.required">name is required</mat-error>
</mat-form-field>

*Add this to your button click event handler:

this.nameControl.markAsTouched();

It's important to check how you are using the form control, ".markAsTouched()" on point 4 will show the mat error for the corresponding form control.

A: Based on Kyle Pfromer's post, I found my solution (to the same problem):
In the TS file I added the StateMatcher after I found an invalid form, eg.
if (this.myFormGroup.invalid) {
  this.matcher = new MyErrorStateMatcher();
  return;
}

In the MyErrorStateMatcher class I changed as following:
    return !!(control && control.invalid);

I find it confusing that Angular Material is not detecting the error anyway.

A: Angular 8 has a new forms method: markAllAsTouched();
This will mark a control/form and ALL DESCENDANTS as touched!!!
So:
this.form.markAllAsTouched();

Is the solution.

A: GLOBALLY: Show mat-error while typing or touched:
Unlike the provided solution, this method will take care of all mat-errors in the app without applying the matcher to each input.
1- Create touched-error-state.matcher.ts file:
import {FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

export class TouchedErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        return !!(control && control.invalid && (control.dirty || control.touched));
    }
}

2- In app.module import:
import { ErrorStateMatcher } from '@angular/material/core';
import { TouchedErrorStateMatcher } from './your-folder-path/touched-error-state.matcher';

3- Now provide it into the providers:
@NgModule({
  providers: [
    AuthService,
    UserService,
    { provide: ErrorStateMatcher, useClass: TouchedErrorStateMatcher }
  ],
})

4- Re-Serve the app.

A: You can also easily call the AbstractControl.updateValueAndValidity() function on button click. This will run the validation process on the corresponding ForControl again and show errors, if there are some (based on your Validators).
So, in your example:
    checkForErrorsOnButtonClick(): void {
      dueDateValidator.updateValueAndValidity();
    }

A: the easiest way is call markUserNameTouched() method as below on button click on template. We use markAsTouched() on formControl.
public staffLoginForm: FormGroup;
ngOnInit(){
this.staffLoginForm = new FormGroup({
username: new FormControl(null),
password: new FormControl(null)});

markUserNameTouched():void{
  this.staffLoginForm.get('username').markAsTouched();
}


text:
Q: Return JsonResult from web api without its properties I have a Web API controller and from there I'm returning an object as JSON from an action.
I'm doing that like this:
public ActionResult GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return new JsonResult { Data = result };
}

But this way the JsonResult object including its Data attribute is serialized as JSON. So my final JSON that is return by the action looks like this:
{
    "ContentEncoding": null,
    "ContentType": null,
    "Data": {
        "ListItems": [
            {
                "ListId": 2,
                "Name": "John Doe"
            },
            {
                "ListId": 3,
                "Name": "Jane Doe"
            },
        ]
    },
    "JsonRequestBehavior": 1,
    "MaxJsonLength": null,
    "RecursionLimit": null
}

I can't serialize this JSON string because the JsonResult object added all kinds of other properties to it. I'm only interested in ListItems, nothing else. But it automatically added things like: ContentType, MaxJsonLength etc...
Now this won't work for me because of all the other properties in the JSON string...
var myList = JsonConvert.DeserializeObject<List<ListItems>>(jsonString);

Is there a way to send a JSON object from the action so that it won't add all the properties that I dont need?

A: As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!
ActionResult is bad because as you've discovered.
Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.
Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.
public HttpResponseMessage GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return Request.CreateResponse(HttpStatusCode.OK, result);
}

In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:
 public class ResponseResultExtractor
    {
        public T Extract<T>(HttpResponseMessage response)
        {
            return response.Content.ReadAsAsync<T>().Result;
        }
    }

var actual = ResponseResultExtractor.Extract<List<ListItems>>(response);

In this way, you've achieved the below:

*

*Your Action can also return Error Messages and status codes like 404 not found so in the above way you can easily handle it.

*Your Action isn't limited to JSON only but supports JSON depending on the client's request preference and the settings in the Formatter.

Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

A: When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.
I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;
public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.
P.S
WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

A: I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)
Here is how I solved it. First I declared a utility class
public class RawJsonActionResult : IHttpActionResult
{
    private readonly string _jsonString;

    public RawJsonActionResult(string jsonString)
    {
        _jsonString = jsonString;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = new StringContent(_jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
        return Task.FromResult(response);
    }
}

This class can then be used in your controller. Here is a simple example
public IHttpActionResult Get()
{
    var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
    return new RawJsonActionResult(jsonString);
}

A: return JsonConvert.SerializeObject(images.ToList(), Formatting.None, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

using Newtonsoft.Json;


text:
Q: Configured Half-ninja android FFMPEG project I have configured android-halfninja project completely and i manage to build
refered to this link
libs/armeabi/libvideokit.so  and
libs/armeabi/ffmpeg
libs  from the given source
But  i had to make some changes to the .sh files in order to build .so files.
But now i tried to execute following ffmpeg command in my android project it doesn't run properly
    String var[] = {"ffmpeg","-i",input};

12-24 10:34:44.569: I/VideoKit(14374): Loading native library compiled at 14:43:51 Dec 18 2013
12-24 10:34:44.599: I/ActivityManager(290): Process uk.co.halfninja.videokit (pid 14374) has died.
12-24 10:34:44.599: W/ActivityManager(290): Force removing ActivityRecord{2bea3e28 uk.co.halfninja.videokit/.MainActivity}: app died, no saved state

Can any one tell me what might be th issue to have this error in half-nonja project
here is  my configure_ffmpeg.sh file
    #!/bin/bash
pushd `dirname $0`
. settings.sh

if [[ $DEBUG == 1 ]]; then
  echo "DEBUG = 1"
  DEBUG_FLAG="--disable-stripping"
fi

# I haven't found a reliable way to install/uninstall a patch from a Makefile,
# so just always try to apply it, and ignore it if it fails. Works fine unless
# the files being patched have changed, in which cause a partial application
# could happen unnoticed.
patch -N -p1 --reject-file=- < redact-plugins.patch
patch -N -p1 --reject-file=- < arm-asm-fix.patch
patch -d ffmpeg -N -p1 --reject-file=- < \
    ARM_generate_position_independent_code_to_access_data_symbols.patch
patch -d ffmpeg -N -p1 --reject-file=- < \
    ARM_intmath_use_native-size_return_types_for_clipping_functions.patch
patch -d ffmpeg -N -p1 --reject-file=- < \
    enable-fake-pkg-config.patch

pushd ffmpeg

./configure \
$DEBUG_FLAG \
--arch=arm \
--cpu=cortex-a8 \
--target-os=linux \
--enable-runtime-cpudetect \
--prefix=$prefix \
--enable-pic \
--disable-shared \
--enable-static \
--cross-prefix=$NDK_TOOLCHAIN_BASE/bin/$NDK_ABI-linux-androideabi- \
--sysroot="$NDK_SYSROOT" \
--extra-cflags="-I../x264 -mfloat-abi=softfp -mfpu=neon" \
--extra-ldflags="-L../x264" \
\
--enable-version3 \
--enable-gpl \
\
--disable-doc \
--enable-yasm \
\
--disable-everything \
--enable-decoder=mjpeg \
--enable-demuxer=mjpeg \
--enable-parser=mjpeg \
--enable-demuxer=image2 \
--enable-muxer=mp4 \
--enable-encoder=libx264 \
--enable-decoder=rawvideo \
--enable-protocol=file \
--enable-hwaccels \
--enable-filter=buffer \
--enable-filter=buffersink \
--disable-demuxer=v4l \
--disable-demuxer=v4l2 \
--disable-indev=v4l \
--disable-indev=v4l2 \
\
--disable-indevs \
--enable-indev=lavfi \
--disable-outdevs \
\
--enable-hwaccels \
\
--disable-ffmpeg \
--disable-ffplay \
--disable-ffprobe \
--disable-ffserver \
--disable-network \
\
--enable-libx264 \
--enable-zlib \
--enable-muxer=md5

popd; popd

#--enable-decoders \
#--enable-encoders \
#--enable-muxers \
#--enable-demuxers \
#--enable-parsers \
#--enable-protocols \
#--enable-filter=buffer \
#--enable-filter=buffersink \
#--enable-avresample \
#--enable-faac \


text:
Q: Does the Back Button fail to call stop()? My app currently has only one Form, which listens to the accelerometer sensor. In my start() method, I turn the listener on, and in the stop() method, I turn it off. I have verified that the listener turns off when I hit the Android's home button, but when I hit the back button, the application exits and the Android returns to the home screen, but the listener keeps going, which means the stop() method never got called. Is it my responsibility to handle the back button with code to call the stop() method? Or is this a bug in CodenameOne's framework? It seems to me that when the back button returns the user to the home screen, it should call stop() for me.

A: I am not sure about all the details of your issue, however you can resolve it by calling the setBackCommand on that one form.
yourForm.setBackCommand(
                        new Command("closing the sensor listener"){
                            @Override
                            public void actionPerformed(ActionEvent ev){
                                // your code to close the listener
                            }
                        }
                );

A: I don't know about CodenameOne framework, but I know the Android SDK.
Activity.onBackPressed() should be invoked when you use the back button.  Just because your Activity is no longer visible does not mean it has been reaped, and this might explain why Activity.stop() is not invoked (immediately).
Depending upon your use case, Activity.onPause() might also work better.
HTH.  Good luck w/your project.

A: I don't know about CodenameOne framework, but When app is visible and you press back button it calls all four methods in following order
1)onBackPressed()
2)onPause()
3)onStop()
4)onDestroy()

and when you press home button it calls only
1)onPause()
2)onStop()

methods
so, when you press back button onStop must be called.
You please put source code so that people can understand your problem clearly.

A: This has been fixed. I've verified it, and it works correctly now.


text:
Q: Reference to a static 2D array? I have some 2D arrays of a static size:
double quickStats[NUM_REPETITIONS][NUM_TRIALS];
double mergeStats[NUM_REPETITIONS][NUM_TRIALS];
double bstStats[NUM_REPETITIONS][NUM_TRIALS];

Later, I want a reference to one of them:
double stats[NUM_REPETITIONS][NUM_TRIALS];

    if(i == 0) {
        stats = quickStats;
    }
    else if(i == 1) {
        stats = mergeStats;
    }
    else if(i == 2) {
        stats = bstStats;
    }

However, this does not work.
What can I do to do what I am trying to do without nested for loops to manually copy each element into the reference array?
I just need to read from stats, it is to avoid redundant code.
Thanks

A: Try this:
#define NUM_REPETITIONS 10
#define NUM_TRIALS 10
double quickStats[NUM_REPETITIONS][NUM_TRIALS];
double mergeStats[NUM_REPETITIONS][NUM_TRIALS];
double bstStats[NUM_REPETITIONS][NUM_TRIALS];

int main(){
    double (* ptr)[NUM_TRIALS] =quickStats;
}

A: Create a pointer to it like this:
double (*stats)[NUM_REPETITIONS][NUM_TRIALS];

Since your dimensions are known at compile time you can use std::array<> which is more versatile and readable:
std::array<std::array<double, NUM_TRIALS>, NUM_REPETITIONS> stat;

A: References have to be initialized upon declaration so you cannot assign it later on. Your best bet is using a pointer or declare the reference inside the if branches.
constexpr unsigned int N = 100;

double a[N][N] = {0};

/* Pointer. In your case, N should be NUM_TRAILS here */
double (*a_ptr)[N] = a;

/* Specified Reference Type */
double (&a_ref)[N][N] = a;

/* C++11 Auto Reference */
auto &a_autoref = a;

Test here: Coliru


text:
Q: Numbers, Pages, and Keynote crash immediately on launch (2020 M1 Mac Mini) Just got a brand new M1 Mac Mini (2020) today. I opted for a clean install and did not restore from Time Machine. To my surprise, I'm experiencing a nearly immediate crash on launch for Keynote, Pages, and Numbers. If starting by clicking on the application, I get as far as the document select screen. If starting by opening an existing document, I'll see a brief glimpse of the document before the crash. All other apps seem to work normally (so far), from other Apple apps like GarageBand and iMovie, to heavier stuff like Steam and Blender. The crash appears to be specific to these applications, with no flashing screen or other signs of hardware trouble.
Remedies I have tried, to no avail:

*

*Boot into Safe Mode (same behavior)

*Delete (including the relevant contents of ~/Library/Containers/ for each app) and reinstall each app from the App Store

*Font Book > Restore Standard Fonts

*Unmount external drives before app launch

*Creating a new user account

A representative crash log:
Process:               Numbers [1389]
Path:                  /Applications/Numbers.app/Contents/MacOS/Numbers
Identifier:            com.apple.iWork.Numbers
Version:               11.1 (7031.0.102)
Build Info:            Numbers-7031000102000000~2 (1A104)
App Item ID:           409203825
App External ID:       842170571
Code Type:             ARM-64 (Native)
Parent Process:        ??? [1]
Responsible:           Numbers [1389]
User ID:               501

Date/Time:             2021-06-07 21:57:18.380 -0400
OS Version:            macOS 11.2.3 (20D91)
Report Version:        12
Anonymous UUID:        2A5CC66F-07E0-4395-A43D-BE7770D7436D

Time Awake Since Boot: 1900 seconds

System Integrity Protection: enabled

Crashed Thread:        1  Dispatch queue: com.apple.CoreText.fontdescriptorMatching

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       EXC_ARM_BREAKPOINT at 0x0000000196b687bc (brk 1)
Exception Note:        EXC_CORPSE_NOTIFY

Termination Signal:    Trace/BPT trap: 5
Termination Reason:    Namespace SIGNAL, Code 0x5
Terminating Process:   exc handler [1389]

Application Specific Backtrace 1:
0   CoreFoundation                      0x000000019406e320 __exceptionPreprocess + 240
1   libobjc.A.dylib                     0x0000000193d9cc04 objc_exception_throw + 60
2   CoreFoundation                      0x0000000194135064 -[__NSCFString characterAtIndex:].cold.1 + 0
3   CoreFoundation                      0x000000019413530c -[__NSCFBoolean compare:].cold.1 + 0
4   CoreFoundation                      0x0000000193fc6c10 -[__NSCFNumber objCType] + 0
5   CoreFoundation                      0x0000000193fc6a10 -[__NSCFNumber isEqualToNumber:] + 32
6   CoreText                            0x000000019566a1f0 +[FontAssetDownloadManager filterIncompatibleAsset:] + 832
7   CoreText                            0x000000019566a5cc +[FontAssetDownloadManager availableMobileAssetsWithOptions:error:] + 848
8   CoreText                            0x000000019566ab2c +[FontAssetDownloadManager availableMobileAssetsWithOptions:manager:error:] + 76
9   CoreText                            0x0000000195668a68 -[FontAssetDownloadManager mobileAssetsForUnmatched:] + 148
10  CoreText                            0x0000000195668790 -[FontAssetDownloadManager downloadFontAssets] + 84
11  CoreText                            0x000000019566cf94 __CTFontDescriptorMatchFontDescriptorsWithProgressHandler_block_invoke + 36
12  libdispatch.dylib                   0x0000000193d478bc _dispatch_call_block_and_release + 32
13  libdispatch.dylib                   0x0000000193d49420 _dispatch_client_callout + 20
14  libdispatch.dylib                   0x0000000193d5077c _dispatch_lane_serial_drain + 580
15  libdispatch.dylib                   0x0000000193d512cc _dispatch_lane_invoke + 408
16  libdispatch.dylib                   0x0000000193d5b3fc _dispatch_workloop_worker_thread + 708
17  libsystem_pthread.dylib             0x0000000193ef2060 _pthread_wqthread + 276
18  libsystem_pthread.dylib             0x0000000193ef0d94 start_wqthread + 8

A: The machine was on macOS 11.2.3. After checking for software updates (which I had forgotten to do), I found 11.4 available. Software runs as expected.


text:
Q: React Native and sqlite migrations It's difficult to find a lot of examples of people using sqlite with their react native apps.
I'm going to be using this library : https://github.com/craftzdog/react-native-sqlite-2
Is there a good option out there for managing the client db schema post-launch? On our server apps we have a migration lib that does the work of deciding which "migrations" should be run. Is there something similar for RN or is it a "do it yourself" situation?

A: I believe it's a "do it yourself" situation in React Native. I've made a migration table which tracks which migrations have already been run along with a timestamp. All migrations not in the table get run upon launch.


text:
Q: Where to change GRASS GIS wxGUI language? I use GRASS 6.4.2 on Russian version of Windows 7 x64. As I start wxGUI it is shown in Russian. But I don't like its translation and want to work with English interface. I have no clues how to solve it.

A: We have recently added a language selector in the graphical interface. This is
currently under testing in GRASS 6.4.3.
For now, you can upgrade to GRASS 6.4.3svn but installing this version:
http://wingrass.fsv.cvut.cz/grass64/
In the wxGUI:
Settings --> Preferences --> Appearance --> Language Settings
It should solve your problem.


text:
Q: Correct way to test Rails version for gem authoring What is the correct way to manage conditional flow in a gem based on Rails version?
Rails 4 changes some things so I need to conditionally flow based on Rails major version being 4 vs. 3 or prior.
The closest I've come is:
if Rails.version.split(".").first.to_i < 4
    # Do the Rails 4 thing
else
    # Do it the old way
end

A: Rails defines constants under Rails::VERSION for the various patch levels: MAJOR, MINOR, TINY and PRE (if applicable). The version string is constructed from these integers, and you can use them directly:
if Rails::VERSION::MAJOR >= 4
  # Do the new thing
else
  # Do it the old way
end

These go back to at least Rails 2.0.x so they should be safe to use for your gem's permitted dependency spec.

A: Personally, I think Rails.version =~ /^4/ reads much better.

A: Safest simple way is to use for example
Gem::Version.new(Rails.version) >= Gem::Version.new('5.1')

Unless you really need to only compare the major version.
Credits to https://stackoverflow.com/a/3064161/520567


text:
Q: 'C' Segmentation fault with 2d array Can anybody explain me why this code doesn't work?
#include <stdio.h>
#include <stdlib.h>

void findAndPrint(char *arr[], int year, int month, int day);

int main()
{
    char *dayTab[] = {
        {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    };
    findAndPrint(dayTab, 3, 3, 3);
    getchar();
    return 0;
}

void findAndPrint(char *arr[], int year, int month, int day ){
    int d = 0;
    if(month > 12 || month < 1 || day > 31 || day<1)
        return;
    int leap = ((year%4==0 && year%100!=0) || year%400 == 0)?1:0;
    int i;
    for(i=0; i<month-1; i++){
        d += arr[leap][i];
    }
    d+= day;
    printf("Day = %d", d);
}

IDE(Code::Blocks) writes "Program received signal SIGSEGV. Segmentation fault."

A: First you need a 2d array of characters, not an array of pointers to characters.
char dayTab[][12] = {
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

Then you have to change the function to accept that type.
void findAndPrint(char arr[][12], int year, int month, int day ) ;

The rest looks ok.
Trying with parameters:
findAndPrint(dayTab, 2014, 10, 12);

Gives us day: 285
Which is correct, yaaay!

A: If I properly understood your intent, you wanted those nested {31, 28, ... } sequences to serve as char[] arrays, to which the pointers in the upper level array would point to.
Despite what the other answer(s) states, it is not correct to say that you necessarily need a literal 2D array (even though in this case a 2D array might be a better idea than what you attempted to do). You original attempt will work too, as long as you use the proper syntax.
Now, you can't just plant a {31, 28, ... } sequence in the middle of the code and expect the compiler to interpret it as an array. The language does not have such feature, but it has a similar one with slightly different syntax. The only way achieve the proper initialization of your char *dayTab[] array in that "inline" fashion is to use the compound literal feature. The initialization will look as follows
char *dayTab[] = {
    (char []) { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    (char []) { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};

Note the extra (char []) syntax. This is absolutely necessary. This is the only thing that you have to change in your original code to make it compile as intended.
What you currently have in your original code is not valid C. If some compiler accepted this code (GCC in CodeBlocks?), then only due to some compiler extension. That compiler extension happened to play a cruel joke on you in this particular case. I don't even know how it was interpreted by the compiler, but definitely not how you intended it to be interpreted.
P.S. In my experiments, GCC gave a wall of diagnostic messages in response to our original code. Did you get those messages from your compiler? Did you just ignore them?


text:
Q: How can I handle exceptions in WebAPI 2. methods? In my WebAPI 2.1 application I am processing inserts like this:
    [Route("Post")]
    public async Task<IHttpActionResult> Post([FromBody]City city)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        try
        {
            db.Exams.Add(city);
            await db.SaveChangesAsync(User, DateTime.UtcNow);
        }
        catch (Exception ex)
        {
            var e = ex;
            return BadRequest("Error: City not created");
        }
        return Ok(city);
    }

I use something similar for updates and deletes. I think I should do something more meaningfull with
the exceptions but I am not sure where to start with how to handle these. I looked at elmah but it said it deals with unhandled exceptions. Does this mean I should not be catching exceptions like this?
Can someone give me some
pointers as to if what I have is okay and also should I be logging exceptions and how?

A: What you are doing is not "bad", it's just a bit verbose and won't scale well if you have many try/catch blocks all over your code. When an exception is raised, you decide what to do so, returning a bad request response is fine if it's really a bad request. There are many things you can return, depending on what went wrong. But you have to handle what to do when exceptions are thrown all over your code, so maintaining this logic scattered all over your code can quickly become a problem.
It's better to utilise asp.net web api's exception handling framework. For example, take a look at these articles:

*

*http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

*http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling
The idea is to centralise your logic in a global exception handler and to use that as the only place in your code where you have to worry about this. The rest of your code will be throwing exceptions and everything will be coming through your exception handler/filter/etc., depending on what you decide.
For example, I have created my own exception types (e.g. CustomExceptionA, CustomExceptionB, etc.) and when I throw an exception of a type I know exactly how to handle it in one place and perform a certain bit of logic. If I want to change the way I handle a particular exception type, then there's only one place I have to make a change and the rest of the code will be unaffected.
The second article link above also includes a global exception logger to log such exceptions.


text:
Q: Try to modify the "Todo app" I'm starting on ruby on rails, first thing I want to try is modifying the "Todo app" example.
I do this by the tutorial: https://www.youtube.com/watch?v=fd1Vn-Wvy2w
After I finished, I saw that when I clicked on a todo_list, it will redirect to "show" form todo_list, but now I want the "show" display on the index with all the todo_list. I have tried to write
  <%= todo_items.content %>

on the index page but it got some errors. Is there any solution or should I modify something on the Controller page so that
todo_items.content
should be able to display on the Index page

A: You need to load those items in your controller action first:
def index
  @todo_items = TodoItem.all
end

then in index.html or whatever template you are rendering for this action you can render this collection:
<%= render @todo_items %>

that should render an todo_item partial that you should have created based on your video located at /app/views/todo_items/_todo_item.html.erb. Or you can do:
<% @todo_items.each do |item| %>
  <%= item.content %>
<% end %>

In controller:
def index
  @todo_lists = TodoList.all
end

in view:
<% @todo_lists.each_with_index do |list, index| %>
  List <%= index + 1 %> todos:
  <%= render list.todo_items %>
<% end %>


text:
Q: Django Have to ForeignKey to share a constraint I have the following model:
class Program(models.Model):
    name = models.CharField(max_length = 128)
    def __unicode__(self):
        return self.name
class Cheat(models.Model):
    program = models.ForeignKey(Program)
    shortcut = models.CharField(max_length = 64)
    description = models.CharField(max_length = 512)
    def __unicode__(self):
        return u"(%s) - %s" % (self.shortcut, self.description)
class Category(models.Model):
    #program = models.ForeignKey(Program)
    name = models.CharField(max_length = 128)
    def __unicode__(self):
        return self.name
class Sheet(models.Model):
    program = models.ForeignKey(Program)
    name = models.CharField(max_length = 128)
    def __unicode__(self):
        return self.name
class CategorizedCheat(models.Model):
    order = models.IntegerField(unique = True)
    sheet = models.ForeignKey(Sheet)
    cheat = models.ForeignKey(Cheat)
    category = models.ForeignKey(Category)
    def __unicode__(self):
        return unicode(self.cheat)

In the admin, I want to display a Sheet with CategorizedCheats inline.
The problem is that I'm unable to have only Cheat that are related to the same Program as the Sheet. Is there a way to filter thoses with the Sheet.program ? Or is there something wrong with my models ?

A: When filtering the available objects in ForeignKeys within Django's admin, the right answer is pretty much always ModelAdmin.formfield_for_foreignkey:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey
The docs there explain how to do almost exactly what you're looking for. Hope that helps!

A: Here is the final solution thanks to Gabriel:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "cheat":
        kwargs["queryset"] = Cheat.objects.filter(program=Sheet.objects.get().program)
        return db_field.formfield(**kwargs)
    return super(CategorizedCheatAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

The trick was to use Sheet.objects.get().program, this was the information I was lacking.


text:
Q: Oracle and possible constant predicates in "WHERE" clause I have a common problem with ORACLE in following example code:
create or replace procedure usp_test
(
  p_customerId number,
  p_eventTypeId number,
  p_out OUT SYS_REFCURSOR
)
as
begin

  open p_out for
    select e.Id from eventstable e
    where
      (p_customerId is null or e.CustomerId = p_customerId)
      and
      (p_eventTypeId is null or e.EventTypeId = p_eventTypeId)
    order by Id asc;

end usp_test;

The "OR" in "(p_customerId is null or e.CustomerId = p_customerId)" kills procedure performance, because optimizer will not use index (i hope for index seek) on "CustomerId" column optimally, resulting in scan instead of seek. Index on "CustomerId" has plenty of distinct values.
When working with MSSQL 2008 R2 (latest SP) or MSSQL 2012 i can hint the query with "option(recompile)" which will:

*

*Recompile just this query

*Resolve values for all variables (they are known after sproc is called)

*Replace all resolved variables with constants and eliminate constant
predicate parts

For example: if i pass p_customerId = 1000, then "1000 is null" expression will always be false, so optimizer will ignore it.
This will add some CPU overhead, but it is used mostly for rarely called massive reports procedures, so no problems here.
Is there any way to do that in Oracle? Dynamic-SQL is not an option.
Adds
Same procedure just without "p_customerId is null" and "p_eventTypeId is null" runs for ~0.041 seconds, while the upper one runs for ~0.448 seconds (i have ~5.000.000 rows).

A: One column index can't help as it's not stored in index definition.
Is creating index on (customer id, event id, id ) allowed? This way all needed columns are  in index...

A: CREATE INDEX IX_YOURNAME1 ON eventstable (NVL(p_customerId, 'x'));
CREATE INDEX IX_YOURNAME2 ON eventstable (NVL(p_eventTypeId, 'x'));

create or replace procedure usp_test
(
  p_customerId number,
  p_eventTypeId number,
  p_out OUT SYS_REFCURSOR
)
as
begin

  open p_out for
    select e.Id from eventstable e
    where
        (NVL(p_customerId, 'x') = e.CustomerId OR NVL(p_customerId, 'x') = 'x')
    AND (NVL(p_eventTypeId, 'x') = e.EventTypeId OR NVL(p_eventTypeId, 'x') = 'x')
    order by Id asc;
end usp_test;