text:
Q: Parcelable vs public static. Android patterns I used to use public static member variables in order for the starting Activity to be able to read the values from the previous Activity. I know that it is not a good practice and that it involves risks and limitations like having several instances of the current Activity and get the wrong value from the static variable.
Now I use Parcelable and pass the parameters in Bundle, but it is a burden sometimes. For example, in my current project I have a ExpandableListView and the groups/children stored in a Map<group name, List<child>>. This list is in a Fragment which is inside a TabHost in a FragmentActivity. Clicking on a child in the list will launch another FragmentActivity with the same structure (TabHost and a Fragment inside). From this Fragment you can edit the child. The problem comes when I need to notify the list that the child has changed. Following the best practices I decided to use a Broadcast to send the modified child to the first Activity, and let it update the list.
If, instead of a Parcelable, I'd use a public static variable I just would need to call notifyDataSetChange() in the list to refresh because the actual object instance in the Map was modified. With the Parcelable, even if the object is the same, when it is modified is a different variable in a different memory region. When the first Activity receives the Broadcast, it needs to loop through all the childs in all the groups to check if it's the same object and replace itself with the broadcasted Parcelable.
What am I doing wrong? Or is it supposed to be like this? With this kind of issues I am really tempted to go the public static way :-P

PS: Something like this. Long arrow is Broadcast, short arrow is Activity telling the Fragment to replace the child in the Map and refresh the list.
Fragment Activity  <----
             |         |
TabHost      |         |
             |         |
Fragment  <--|         |
                       |
Fragment Activity      |
                       |
TabHost                |
                       |
Fragment  --------------

A: From your first activity, you can startActivityForResult. Your second activity can then return the updated dataset. Your first activity can then reassign the data map to whatever onActivityResult picks up and you can use notifyDataSetChanged.


text:
Q: closed ball with topological boundary For n dimension closed ball $\bar{B}$ as subset of $\mathbb{R}^n$ has topological boundary $S^{n-1}$.Since topological boundary is $\bar X - $Int$X$.
For closed ball $\bar B$ as topological space of its own right it has empty topological boundary.
The question is why as topological space of its own right it has empty topological boundary.

A: In any space $X$ the boundary $\partial X$ is empty as $X$ is both open and closed in any space, so the  closure is $X$, and so is the interior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect requests that return an HTML page in an ASP.NET MVC web app I'm trying to set some caching HTTP headers for all requests that return an "HTML page".
I could do that in some global place such as BeginRequest or in a global MVC filter (as suggested in that question).
For that to work I must differentiate HTML pages from other requests that are supposed to be cached (mostly resources I think but I'm not sure).
I am unsure how to define "HTML page" in a rigorous way so that I could put it into an algorithm. How could I detect such requests?
I really do not want to mark up all MVC actions that I write individually. That's tedious and I could forget something.

A: I think the best way is with filters, then I'd use a regex to check if the result has HTML:
Create a filter:
public class NoCacheForHTMLResult : IActionFilter
{

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Regex tagRegex = new Regex(@"<[^>]+>");

        string response = filterContext.RequestContext.HttpContext.Response.Output.ToString();
        bool hasHtml = tagRegex.IsMatch(response);

        if (hasHtml)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();
        }
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {

    }

}

...and add in the Global Filters (inside your App_Start):
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new NoCacheForHTMLResult());
    }
}

I'm not a regex expert, I got this regex from this question, but it looks we need to improve this, by checking if there is at least an HTML tag, otherwise if the result was XML, it looks the regex would match (though you might want to set no cache for XML as well, it's up to you).
The code for disabling cache I got in this answer, you might have a different code.
Hope this helps you.


text:
Q: Delete dynamically created nodes in Angular2 Dynamically creating nodes:
 var div = $('#imgDiv');
          div.css("column-count","5");
          for (var i = 0; i < this.fileSize; i++)
          {
            var nav = $('');
            var img = $('').css("max-width","200px").css("max-height","200px").css("padding","5px");
            var button = $('<button  id="dynamicButton" >Add to collection</button>')
            img.attr('src', this.returnFile[i]);

            img.appendTo(nav);
            button.appendTo(nav);
            nav.appendTo(div);
          }

Delete Nodes:
for(var i = 0; i < this.fileSize; i++)
       {
         $('#imgDiv').closest('#holder').html('');
       }

HTML:

        <input type="text" #query>Enter search term:
        <button (click) = "loadImage(query.value)">Search!</button>

        <button routerLink = '/login' (click) = "logout()">Logout</button>

I am trying to delete the nodes that I have created in my dynamically created nodes section. When I do something like $('#imgDiv').html('') it only deletes the src part of the image. The button and img tag are still there.


text:
Q: If insert statement gives duplicate key exception(row id=1 found in table) how to update the statement in JDBC(Postgresql) I have Stored bunch of insert statements in ArrayList.like below
List<String> script=new ArrayList<String>;
script.add("INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (1, 'Madhava'));
script.add(INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (2, 'Rao'));
script.add(INSERT INTO PUBLIC.ADDRESS(ID, CITY) VALUES(1, 'Bangalore'))
script.add(INSERT INTO PUBLIC.ADDRESS(ID, CITY) VALUES(2, 'Hyd'));

I created connection to the postgresql using jdbc i get executed statments using for loop like below
try{
        Connection con=DBConnections.getPostgresConnection();
         Statment statment=con.createStatment();
        for(String query:script){
           executeUpdate(query);
        }
    }catch(Exception e){
     e.printStackTrace();
    }

If i get duplication key exception(i.e.Already record exist in postgresDB).
org.postgresql.util.PSQLException: ERROR: duplicate key value
  violates unique constraint "reports_uniqueness_index"

How to update the same statment(record) with update query into Postgres.
Is there any way to solve this ?
Is there any other better way to solve this?
Could you please explain...

A: Execute update sends a DML statement over to the database. Your database must already have a record which uses one of the primary keys either in the employees or address table.
You have to ensure you don't violate the primary key constraint. Violating the constraint is resulting in the exception.
Either change your query to an update statement, or delete the records which are causing conflict.

A: There is no way to get the key that caused the exception (though you can probably parse the error message, which is certainly not recommended).
Instead, you should try preventing this from ever happenning. There are at least 3 easy ways to accomplish this.

*

*Make the database update the column
(in Postgresql you should use a serial type (which is basically an int data type)
CREATE TABLE employee
(
 id serial NOT NULL,
 --other columns here )

Your insert will now look like
   script.add("INSERT INTO PUBLIC.EMPLOYEE(NAME) VALUES ('Madhava'));//no ID here

*Create a sequence and have your JDBC code call the sequence' nexval method.
script.add("INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (YOUR_SEQ_NAME.NEXTVAL(), 'Madhava'));

*Create a unique ID in Java (least recommended)
script.add("INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (UUID.random(), 'Madhava'));//or Math.random() etc


text:
Q: Create a python object with a date field 3 months from now I'm learning python, hence this is probably an obvious solution for some, but I am trying to create a class that, whenever created, has a test field with a date value of three months from now.
My class is as follows:
class Something(models.Model):
    test = models.DateTimeField(default=self.get_date())

    def get_date(self):
        today = datetime.date.today()
        return today + relativedelta(months=1)

I thought that I could define it as a function and then call it to set the date. Can someone advise what's wrong here? Any links to relevant documentation would also be appreciated, thank you.

A: If you want a subclass to have a specific attribute, like the "test field" you could define it in the parents class like so:
import models

class Class:
  test = models.DateTimeField()

class Subclass(Class)

With this solution every "Sublass-Object" would have the attribute "test" in it when initialized.


text:
Q: Login with either email or username and ignore upper/lower cases for UserName during login I'm wokring in a Asp.Net MVC5 web app with EntityFramework 6.
I added the UserName attribute to the AspNetUser db table, more exactly I made the UserName to be user chosen, not to be the email.
But in this tutorial ASP.NET Identity 2.0.0 – UserName and Email separation
it says: "although login page requires an email address to log in it actually uses model.UserName to validate provided email.". So why does it require the UserName even while it says it's using the Email property, where is that rule being setup and where/how can I change it?
And more important: How can I make the login to work with either email or username like in facebook and also to ignore upper/lowercases during login?
Edited; the code changes I made:
I added this property in the RegisterViewModel
[Required]
[Display(Name = "UserName")]
public string UserName { get; set; }

Added this code in the Register view:

@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })

    @Html.TextBoxFor(m => m.UserName, new { @class = "form-control " })

Changed the Register action method to use the also UserName when creating a new user:
// (...)
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
// (...)

Replaced the Email attribute in the LoginViewModel with:
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }

And also in the login view I replaced the Email with UserName:

                @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })

                    @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

And also changed the Login action method to use the UserName instead of the Email to login:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
    return View(model);
}

// This doesn't count login failures towards lockout only two factor authentication
// To enable password failures to trigger lockout, change to shouldLockout: true
var result = await SignInHelper.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
// (...)

A: If you are comfortable with making and additional call to the database in the case of it being an email address, here is an example of what you can try.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {
    if (ModelState.IsValid) {
        string username = model.UserName;
        ApplicationUser user = null;
        // CHECK FOR EMAIL
        if(IsValidEmail(username)) {
            user = await userManager.FindByEmailAsync(username);
            if(user != null) username = user.UserName;
            else {
                // If user with email address does not exists, here is a good place
                // to exit as we have already ascertained that the user is not in the system
                ModelState.AddModelError("", "Invalid user name or password provided.")
                return View(model);
            }
        }
        // END CHECK FOR EMAIL
        user = await userManager.FindAsync(username, model.Password);
        if (user != null) {
            var result = await SignInHelper.PasswordSignIn(username, model.Password, model.RememberMe, shouldLockout: false);
            switch (result) {
                //...code removed for brevity
            }
        } else {
            ModelState.AddModelError("", "Invalid user name or password provided.")
        }

    }

    // If we got this far, something failed, re-display form
    return View(model);
}

private static bool IsValidEmail(string email) {
    string MatchEmailPattern =
       @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
       @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
       @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
       @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

    if (!string.IsNullOrWhiteSpace(email)) {
        string pattern = MatchEmailPattern;
        return System.Text.RegularExpressions.Regex.IsMatch(email, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    } else {
        return false;
    }
}


text:
Q: Can a user see the source of a js call in an html 5 app for iphone or android? If I create a html 5 application for a phone (using phonegap or Icenium) that calls a webservice which needs a username/password, can a person look at the code somehow or is the JavaScript compiled away or obstructed  in some manner?
Assume in this case that the url is in a javascript file with username and password.

A: Neither Phonegap nor Icenium (both based on Apache Cordova) obfuscate or compile the JavaScript code of your app.
You can take any Cordova app for iOS or Android and simply unzip the .ipa or .apk package to reveal the HTML, CSS and JavaScript code that powers the app.

A: If its a regular user, then most-likely not.
But if you are asking this question because you want to prevent someone that is skilled want needs to see your app for code. Then the answer is:

Nothing is safe in your clients device. Not sqlite database, not built-int storage , and not source code( weather its compiled or not);


text:
Q: Split the data of splunk query with number pattern I am preparing a dashboard the type of URLs been invoked for my service in Splunk dashboard.
the URLs are like below in my splunk query .
Query - index=myIndex serviceName="serviceName" | eval _raw=replace(_raw, "\\", "") | eval URI=mvindex(split(URI,"?"),0) | stats values(URI),count  by HttpStatus
 /myIndex/v1/serviceName/actuator/health
/myIndex/v1/serviceName/service/order
/myIndex/v1/serviceName/service/account
/myIndex/v1/serviceName/service/getData
/myIndex/v1/serviceName/service/lookupService/%2086406
/myIndex/v1/serviceName/service/lookupService/01364
/myIndex/v1/serviceName/service/lookupService/01840
/myIndex/v1/serviceName/service/lookupService/01906
/myIndex/v1/serviceName/service/lookupService/02119
/myIndex/v1/serviceName/service/lookupService/02148
/myIndex/v1/serviceName/service/lookupService/02382

Can you suggest me how to consider  the URL till lookupService by ignoring the different numbers after that .
Ideally for  lookupService I need to get the count as 7 here like below
/myIndex/v1/serviceName/service/lookupService - 7

A: I would use rex and extract the base URL without the trailing slash and digits (and percent from encoded space %20)
index=myIndex serviceName="serviceName"
| eval _raw=replace(_raw, "\\", "")
| eval URI=mvindex(split(URI,"?"),0)
| rex field=URI "(<?URI>.+)(\/[%0-9]+)?"
| stats values(URI), count by HttpStatus


text:
Q: Entity object not updating I created a static class that I want to use in various projects. I am trying to make this as independent as I can but it's not updating and I'm getting no error messages. I am using .Net Framework 4.0 client.
Here is the code:
using System;
using System.Linq;

namespace SSS.ServicesConfig.data
{
  public partial class GlobalSetting
  {

    public static GlobalSetting GetGlobalSetting()
    {
      try
      {
        using (var context = new SuburbanEntities())
        {
          return (from gs in context.GlobalSettings
                  select gs).FirstOrDefault();
        }
      }
      catch (Exception ex)
      {
        Logging.Log("An error occurred.", "GetGlobalSetting", Apps.ServicesConfig, ex);
        throw new Exception(string.Format("Unable to retrieve data: [{0}].", ex.Message));
      }
    }

    public static void SaveGlobalSettings(GlobalSetting globalSetting)
    {
      using (var context = new SuburbanEntities())
      {
        context.Attach(globalSetting);
        context.SaveChanges();
      }
    }
  }
}

Is the attach not done the right way? If not, how should I be saving it when it comes back in?

A: You have to set the state to modified:
  context.Attach(globalSetting);
  context.Entry(globalSetting).State = EntityState.Modified;
  context.SaveChanges();

A: If i understand you correctly, I suggest you try removing the using statement in both methods and declare the context in this manner or better still a private varialbe to hold the local context variable.
     var context = new SuburbanEntities())
     context.Attach(globalSetting);
     context.SaveChanges();

A: I understand you're in the ObjectContext API, so the way to mark an entity as changed is:
context.ObjectStateManager
       .ChangeObjectState(globalSetting, EntityState.Modified);

after you attached the object to the context.

A: must mark it modified, try
context.Attach(globalSetting);
var gs = context.Entry(globalSetting);
gs.State = EntityState.Modified;
context.SaveChanges();


text:
Q: How do I copy a file from one rails application to aws ec2 instance I want to copy a file from my one rails application to a remote/ another application hosted on an aws ec2 instance. I have my security group TCP ports 21 and 21 open for ssh and sftp. But I'm not able to figure out any way to do it. I've tried scp so far and, it does not work.
I tried this:
scp -i ec2-keypair.pem myfile.txt ubuntu@my-public-ec2-ip:/home/ubuntu/my_new_file.txt

It prompts this: Using /home/ubuntu/.rvm/gems/ruby-1.8.7-p334 and exit. But file transfer doesn't happen. What could be the possible issue??
And also if, you know any better solution to do the same then, please help me with your knowledge. Thanks
EDIT : It would be great if, the solution is available in ruby or ruby on rails. Cause ultimately I have to transfer a file from one rails application to another.
EDIT : When I do scp -v -i ~/.ec2/ec2-keypair.pem Gemfile.lock ubuntu@175.41.140.84:/home/ubuntu/apps/ I get this: http://pastie.org/3613259
and  see here: http://pastie.org/3613269 for more verbose output with -vvv

A: So I found this thread, and the last item might be relevant. http://centos.org/modules/newbb/viewtopic.php?topic_id=30515&forum=42
(btw, ssh -vvv will get you debug level 3, with even more inscrutable details).
So to be sure, the most common problem is that the permissions on the .ssh directory (on both local and remote hosts) somehow get overly permissive and ssh will refuse to use the credentials.  Perms on the .ssh directory should be rwx for user only (octal chmod 700), rw for user on the private key and .pem keypairs, and group/all readable for other files.
drwx------  11 tharrison  staff   374 Mar  1 16:37 .
drwxr-xr-x+ 79 tharrison  staff  2686 Mar  8 10:43 ..
-rw-r--r--   1 tharrison  staff   128 Aug 16  2010 .ssh-agent
-rw-r--r--   1 tharrison  staff   132 Dec 29 14:42 config
-rw-------   1 tharrison  staff  1675 Apr 20  2009 id_rsa
-rw-r--r--@  1 tharrison  staff   405 Apr 20  2009 id_rsa.pub
-rw-r--r--   1 tharrison  staff  2805 Mar  5 08:33 known_hosts
-rw-------@  1 tharrison  staff  1693 Apr 27  2011 my-aws-keypair.pem

SSH is (properly) paranoid about what it will send to any log -- it doesn't want to give away any hints about what is or is not working as those hints could be used to discover vulnerabilities, etc.  So the logs can be helpful ... occasionally.
But I am not sure any of this is right, because I think you said you're able to log in successfully from the command line using ssh, and that scp doesn't work -- this kind of rules out ssh authentication issues (as I said, scp is really just ssh), which is why it's worth making sure that the user you're logging in as remotely has proper permissions to write the file to the location you're sending it.
Maybe try ssh -i mykeypair.pem myuser@myremote.host 'touch ~/foo'  All values starting "my" need to be replaced with the correct values, e.g. mykeypair.pem will need to have the path and name of the keypair you use to log in.  If this works, it will create a file named foo in myuser's home directory on the server myremote.host -- log in using ssh without the command and check -- then you have proper permissions, at least to that directory.  Now try to the real directory.
If it fails there, then check that all the directories in the path are group-x or all-x and the target directory is group or all rwx.
EDIT: corrected test ssh command and expanded on procedure and clarified.


text:
Q: How to solve "Connection reset by peer: socket write error"? When I am reading the file content from server it returns the following error message:
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:462)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:366)
at org.apache.coyote.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:240)
at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:119)
at org.apache.coyote.http11.AbstractOutputBuffer.doWrite(AbstractOutputBuffer.java:192)
at org.apache.coyote.Response.doWrite(Response.java:504)
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:383)
... 28 more

and my servlet program is
 response.setContentType("application/octet-stream");
 response.setHeader("Content-Disposition","attachment;filename="+filename);
 FileInputStream in = new FileInputStream(new File(filepath));
 ServletOutputStream output=response.getOutputStream();
 byte[] outputByte=new byte[4096];
 while(in.read(outputByte,0,4096)!=-1){
     output.write(outputByte,0,4096);//error indicates in this line
 }
 in.close();
 output.flush();
 output.close();

How to solve this issue?

A: The socket has been closed by the client (browser).
A bug in your code:
byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
   output.write(outputByte,0,4096);
}

The last packet read, then write may have a length < 4096, so I suggest:
byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
   output.write( outputByte, 0, len );
}

It's not your question, but it's my answer... ;-)

A: I've got the same exception and in my case the problem was in a renegotiation procecess. In fact my client closed a connection when the server tried to change a cipher suite. After digging it appears that in the jdk 1.6 update 22 renegotiation process is disabled by default. If your security constraints can effort this, try to enable the unsecure renegotiation by setting the sun.security.ssl.allowUnsafeRenegotiation system property to true. Here is some information about the process:

Session renegotiation is a mechanism within the SSL protocol that
  allows the client or the server to trigger a new SSL handshake during
  an ongoing SSL communication. Renegotiation was initially designed as
  a mechanism to increase the security of an ongoing SSL channel, by
  triggering the renewal of the crypto keys used to secure that channel.
  However, this security measure isn't needed with modern cryptographic
  algorithms. Additionally, renegotiation can be used by a server to
  request a client certificate (in order to perform client
  authentication) when the client tries to access specific, protected
  resources on the server.

Additionally there is the excellent post about this issue in details and written in (IMHO) understandable language.

A: The correct way to 'solve' it is to close the connection and forget about the client. The client has closed the connection while you where still writing to it, so he doesn't want to know you, so that's it, isn't it?

A: It seems like your problem may be arising at
while(in.read(outputByte,0,4096)!=-1){
where it might go into an infinite loop for not advancing the offset (which is 0 always in the call).  Try
while(in.read(outputByte)!=-1){
which will by default try to read upto outputByte.length into the byte[]. This way you dont have to worry about the offset. See FileInputStrem's read method

A: I had the same problem with small difference:

Exception was raised at the moment of flushing

It is a different stackoverflow issue. The brief explanation was a wrong response header setting:
response.setHeader("Content-Encoding", "gzip");
despite uncompressed response data content.
So the the connection was closed by the browser.


text:
Q: PowerShell Keeping track of updated and rejected rows while cleaning up files Add-Member, hashtables, arrays and such confuse me a bit so I'm not sure the best way to approach this. My goal is to take an input.CSV, perform clean up and send those cleaned rows to Fixed.CSV, and send any 'reject rows' that couldn't be handled to reject.CSV with an explanation of why they were rejected.
My original script was splitting the 'good' from the 'bad' based on a single characteristic (e.g. a missing Account ID), but as a I get into the clean-up, there are other things that would cause a row to error out and I don't want to read the data into memory with .Where() and continually 'split' it - especially considering I'd like to finish with only 3 files total (OG-input.CSV, Fixed.CSV, Junk-reject.CSV).
$data, $rejectData = (Import-CSV $CSV).Where({![string]::IsNullOrEmpty($_."Account ID")}, 'Split')
If($rejectData){
    $rejectData | Add-Member -NotePropertyName "Reject Reason" -NotePropertyValue "Account ID missing"
    $rejectData | Export-CSV -LiteralPath "$($CSV.DirectoryName)\$($CSV.BaseName)_reject.csv" -NoTypeInformation

My output file was basically created after I had performed a bunch of steps on each row of $data above.
$outputFile = New-Object System.Collections.ArrayList
Foreach($row in $data){
    # Do stuff, check using If, make updates, etc.
    [void]$outputFile.Add($row)
    }
$outputFile | Export-CSV -LiteralPath "$($CSV.DirectoryName)\$($CSV.BaseName)Fixed.csv" -NoTypeInformation

What I'm thinking at this point is instead of splitting the data initially, I should just iterate through all rows and if I can update them; I will and send to $outputFixed. If there is an error that can't be corrected, I'll send them to $outputReject - but here's the caveat, I want to add a new column for "Reject Reason" and then update that as I go. What I mean by this is, there could be multiple reasons a row gets rejected and I'd like to track each one. I've gotten it somewhat close, but creating the new column is giving me trouble. I was originally going to use Add-Member for the first time I add the column, and then just update the value in that column for each $row; something like $row."Reject Reason" = "$($row."Reject Reason")|New Reason" as this gets me a pipe-delimited list of reasons a row rejected. Then I found Powershell add-member. Add a member that's an ArrayList? that got me thinking maybe I could have the reasons within Reject Reason be a list themselves rather than just delimited. However, I'm not sure I quite understand the nuances of the answers proposed and can't figure out what might work best for me.

A: Without seeing any of your CSV, You could do something like this:
$csvPath  = 'X:\Temp'
$original = Import-CSV -Path (Join-Path -Path $csvPath -ChildPath 'OG-input.CSV')
# create a List object to collect the rejected items
$rejects = [System.Collections.Generic.List[object]]::new()

$correct = foreach ($item in $original) {
    $reason = $null
    if ([string]::IsNullOrWhiteSpace($_.'Account ID'))  { $reason = "Empty 'Account ID' field" }
    elseif ($_.'Account ID'.Length -gt 20) { $reason = "'Account ID' field exceeds maximum length" }
    # more elseif checks go here

    # after all checks are done
    if (!$reason) {
        # all OK for this row; just output so it gets collected in $correct
        $item
    }
    else {
        # it's a rejected item, add an object to the $rejects list
        $obj = $item | Select-Object *, @{Name = 'Reason'; Expression = {$reason}}
        $rejects.Add($obj)
    }
}

# save both files
$correct | Export-Csv -Path (Join-Path -Path $csvPath -ChildPath 'Fixed.CSV') -NoTypeInformation
$rejects | Export-Csv -Path (Join-Path -Path $csvPath -ChildPath 'Junk-reject.CSV') -NoTypeInformation

You need to fill in the rest of the checks and reasons for rejection of course

A: Nested arrays/lists are great, but you'll have to consider how you want to store and display your data.
A CSV file, like a table, doesn't properly handle nested objects like lists or arrays. This can be fine if you know your data, and don't mind converting your RejectReason field from/to a delimited string when you read it. For example, you could use Where-Object's filter block to find all the entries in $outputRejected with a specific reason:
# similar to what you had before
$csv = Import-Csv $path
$report = foreach ($row in $csv) {
  $row | Add-Member -NotePropertyName 'RejectCode' -NotePropertyValue ''

  if ($row.id -lt 5) { $row.RejectCode = $row.RejectCode+'Too Low|' }
  if ($row.id -gt 3) { $row.RejectCode = $row.RejectCode+'Too High|' }

  # Output the finalized row
  $row
}

# Example: filter by reason code
$OutputRejected | Where-Object {($_.Reason -split '\|') -contains 'Too High'}

ID RejectCode
-- ----------
4  Too Low|Too High|
5  Too High|

For what you are doing, this usually works just fine. You have to be careful of your additional separator characters, but since you're defining the RejectCode yourself, it shouldn't be an issue.

For anything more complicated, I tend to create a PSCustomObject from each $row and set each property to what I need. This tends to work a little better for me than using Add-Member:
$report = foreach ($row in $csv) {

  # custom object with manually defined properties
  $reportRow = [PSCustomObject][Ordered]@{
    ID = $row.ID
    Name = $row.Name
    Data = # run some commands to fix bad data
    Reasons = @() # list object
  }

  # can edit properties as normal
  if ($row.id -lt 5) { $reportRow.Reasons += $row.RejectCode+'Too Low|'  }
  if ($row.id -gt 3) { $reportRow.Reasons += $row.RejectCode+'Too High|' }
  $reportrow
}

Just be aware that powershell's CSV commands tend to squish properties into the unhelpful system.object[] text when your properties aren't simple values like strings or ints. A better option for saving nested objects like this is a structured format like JSON. e.g.: $report | ConvertTo-Json | Out-File $path.

A: Here's what I ended up going with. I think it works, as the output looks about like I expected.
Foreach($row in $data){
    #Process all reject reasons first and reject those rows
    If([string]::IsNullOrEmpty($row."Account ID")){
        $row | Add-Member -NotePropertyName "Reject Reason" -NotePropertyValue ("$($row."Reject Reason")", "Missing Account ID" -Join "|").TrimStart("|") -Force
    }
    If([string]::IsNullOrEmpty($row."Service Start Dates") -And ([string]::IsNullOrEmpty($row."Service End Dates"))){
        $row | Add-Member -NotePropertyName "Reject Reason" -NotePropertyValue ("$($row."Reject Reason")", "Missing Both Service Dates" -Join "|").TrimStart("|") -Force
    }
    If(Get-Member -InputObject $row "Reject Reason"){
        [void]$outputReject.Add($row)
        Continue
    }
    If([string]::IsNullOrEmpty($row."Birth Date")){
        $row."Birth Date" = $dte
    }
    If([string]::IsNullOrEmpty($row."Gender")){
        $row."Gender" = "Female"
    }
    If( [string]::IsNullOrEmpty($row."Service Start Dates") -And !( [string]::IsNullOrEmpty($row."Service End Dates"))){
        $row."Service Start Dates" = $row."Service End Dates"
    }
    [void]$outputFixed.Add($row)
    }
$outputFixed | Export-CSV -LiteralPath "$($inputFile.DirectoryName)\$($inputFile.BaseName)Fixed.csv" -NoTypeInformation
If($outputReject){
    $outputReject | Export-CSV -LiteralPath "$($inputFile.DirectoryName)\$($inputFile.BaseName)RejectedRows.csv" -NoTypeInformation
}

Basically I'm still collecting each row in an ArrayList that will be output once the entire file has been processed. I'm using Add-Member with -Force to 'overwrite' the reject reason(s) and a -Join of the text with a .TrimStart("|") to get rid of the leading pipe. This will definitely work for me (plus was easy to implement with what I already had written)


text:
Q: XPath - All following siblings except first specific elements Let's say I'm querying an xhtml document, and I want to query all of the siblings following a table with id='target'. Also, I neither want the first <table> sibling nor the first <ol> sibling of this particular element. Here's the best I could come up with:
//table[@id='target']/following-sibling::*[not(self::table[1]) and not(self::ol[1])]

However, this isn't returning any results when it should. Obviously I'm not understanding some of the syntax for this (I couldn't find a good source of information). I would certainly appreciate it if someone more experienced with XPath syntax could give me a hand. Also, for purely academic purposes, I'd be curious what the above is actually doing.
UPDATE:
See LarsH's answer for the explanation of why my XPath wasn't working, and see Dimitre's answer for the accepted solution.

A: Answering the second question first: what the above is doing is selecting all following siblings that are neither table nor ol elements.
Here's why: self::table[1] selects the context node's self (iff it passes the table element name test) and filters to select only the first node along the self:: axis. There is at most one node on the self:: axis passing the element name test, so the [1] is redundant. self::table[1] selects the context node whenever it is a table element, regardless of its position among its siblings. So not(self::table[1]) returns false whenever the context node is a table element, regardless of its position among siblings.
Similarly for self::ol[1].
How to do what you're trying to do:
@John Kugelman's answer is almost correct, but misses the fact that we must ignore sibling elements before and including table[@id='target']. I don't think it's possible to do correctly in pure XPath 1.0. Do you have the possibility to use XPath 2.0? If you're working in a browser, the answer is generally no.
Some workarounds would be:

*

*Skip the first following table sibling and the first following ol sibling by filtering on some other basis, such as their attributes;

*Select //table[@id='target'] as a nodeset, return it to the host environment (i.e. outside of XPath, e.g. in JavaScript), loop through that nodeset; inside the loop: select following-sibling::* via XPath, iterate through that outside of XPath, and test each result (outside of XPath) to see if it is the first table or ol.

*Select //table[@id='target'] as a nodeset, return it to the host environment (i.e. outside of XPath, e.g. in JavaScript), loop through that nodeset; inside the loop: select generate-id(following-sibling::table[1]) and generate-id(following-sibling::ol[1]) via XPath, receive those values into JS variables t1id and o1id, and construct a string for the XPath expression using the form 'following-sibling::*[generate-id() != ' + t1id + ' and generate-id() != ' + o1id + ']'. Select that string in XPath and you have your answer! :-p

Update: A solution is possible in XSLT 1.0 - see @Dimitre's.

A: Use:
 /table[@id='target']/following-sibling::*[not(self::table) and not(self::ol)]
|
 /table[@id='target']/following-sibling::table[position() > 1]
|
 /table[@id='target']/following-sibling::ol[position() > 1]

This selects all the following siblings of the table that are not table and are not ol and all the following table siblings with position 2 or greater and all the following ol siblings with position 2 or greater.
Which is exactly what you want: all following siblings with the exception of the first table following sibling and the first ol following siblings.
This is pure XPath 1.0 and not using any XSLT functions.

A: There's only going to be one node when you use the self:: axis, so I believe self::*[1] will always be true. Every node is going to be the first (and only) node on its own self:: axis. This means your bracketed expression is equivalent to [not(self::table) and not(self::ol)], meaning all the tables and lists get filtered out.
I don't have a test environment set up, but off the top of my head this might do better:
/table[@id='target']/following-sibling::*
    [not(self::table and not(preceding-sibling::table)) and
     not(self::ol    and not(preceding-sibling::ol))]

It'll need some tweaking, but the idea is to filter out tables that do not have preceding-sibling tables, and ols that do not have preceding-sibling ols.


text:
Q: How to perform ctrl+j in ruby for chrome browser. I am using RubyMine and WatirWebdriver Tried below code to click ctrl+J but did not work for chrome browser.
@browser.driver.action.key_down(:control).send_keys("j").key_up(:control).perform
Also tried
@browser.driver.action.send_keys(:control,"J").perform
I read in one blog, above code would work for Firefox browser but not for Chrome.

A: First off,
The way you send control+j is wrong. The way to send the control+j is,you have to give control+k inside the [] like [:control,"j]
b.send_keys([:control,"j"])

Second off,
it's not possible to send the [:control,"j] via chromedriver because of the following issue
https://bugs.chromium.org/p/chromedriver/issues/detail?id=903
The exact answer lies here
This is a limitation in the way we simulate keyboard input in ChromeDriver. Keys get sent directly to the render process, bypassing the browser process. So any keyboard shortcut handlers in the browser process will not be invoked by sendKeys().


text:
Q: initialize character array on the fly I want to initialize a char array using pointers, on the fly.That is user giving input do not know the size of array.User keeps on giving input until return is pressed.Condition here is to:

*

*Use pointers to initialize

*Not to pass size of array  in advance.

A: Assuming a C question, how about (untested):
char *arr = malloc(10);
size_t size = 10, index = 0;
int ch;
while ((ch = getc(stdin)) != EOF && ch != '\n' && ch != '\r') {
    if (index >= size) {
        size *= 2;
        arr = realloc(arr, size); /* XXX check it first. */
    }
    arr[index++] = ch;
}
arr[index] = 0;

If it's really a C++ question you want std::getline with a std::string.

A: The std::string has a method push_back also std::vector would do the job. Still if you are REALLY forced to use a dynamic array and char pointers I would advice you to implement reallocation strategy similar to the one used in vector - double the size each time the number of elements is more then the current size.


text:
Q: Does this set family have a name? A colleague of mine recently asked me if this set family had a name (see definition of this below) .  I didn't know the answer, so I thought I would consult the MO oracle.
Let $\mathcal{S}:=\{ S_1, \dots, S_k \}$ be a family of subsets of $[n]$.  Consider the family $\mathcal{F}_{\mathcal{S}}$ formed by taking all sets of the form
$
S_1' \cap \dots \cap S_k'
$
where each $S_i'$ is either $S_i$ or the complement of $S_i$.  Note that we are forced to intersect exactly $k$ such sets.

Do set families arising in this way have a well-established name?

A: I am not sure how standard this is, but It makes sense to call this family the atoms of the corresponding lattice of sets obtained from $\mathcal S$. They can be illustrated as the different regions in a Venn diagram.

A: In my class of probability and measure theory I am calling it the partition generated by the family.


text:
Q: To Convert CST to IST timezone My actual requirement is,
This is the input which we have in the .txt file,
The below line is having (Emp ID, Date, HH:MM:SS (that is time), Status, Site number, Reader number
123,"20/02/2019",00:00:50,IN,23,1
In the above, I have to take 123 as Emp ID and have to assign it into one variable called tv_emp_id.
then, have to take date and HH:MM ("20/02/2019",02:30) and convert it into IST date & time (21-02-2019,14:00)), then put date (21-02-2019 format) alone in one variable called tv_date and HHMM in another variable called tv_time (14:00 it will be 1400) by Oracle query.

Finally required it with, tv_emp_id= 123;
           tv_date = 21-02-2019
           tv_time = 1400

Please help me to solve it.
Thanks

A: If you mean Central Standard Time and India Standard Time, and you're starting from a plain timestamp:
alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS';
alter session set nls_timestamp_tz_format = 'YYYY-MM-DD HH24:MI:SS TZD';

select timestamp '2019-03-20 02:00:00'  as original,
  from_tz(timestamp '2019-03-20 02:00:00', 'America/Chicago') as cst,
  from_tz(timestamp '2019-03-20 02:00:00', 'America/Chicago') at time zone 'Asia/Calcutta' as ist
from dual;

ORIGINAL            CST                     IST
------------------- ----------------------- -----------------------
2019-03-20 02:00:00 2019-03-20 02:00:00 CDT 2019-03-20 12:30:00 IST

If you want to end up with a plain timestamp (or a date), rather than a timestamp with time zone, then case the result to the data type you want.
If you're starting from a date then you'll need to cast it to a timestamp inside the from_tz() call.


text:
Q: List elements within a list I generated a list of data from a CSV file. It came out as format as a list within a list:
Wind = [['284'], ['305'], ['335'], ['331'], ['318'], ['303'], ['294'], ['321'], ['324'], ['343']]

I need to list as regular list. So here is my attempt at solving this problem:
i = 0
for ii in Wind:
    Wind[i] = Wind[i][i]
    i += 1
    return Wind

My output is:
return Wind
   ^
SyntaxError: 'return' outside function

A: You want to flatten the list, which can be done in python using a list comprehension (essentially a shorter, faster, version of a for loop).
Wind = [x for y in Wind for x in y]

The equivalent code using nested for loops would be:
newWind = []
for y in Wind:
    for x in y:
        newWind.append(x)

A: Another option, using itertools:
import itertools
newWind = list(itertools.chain.from_iterable(Wind))

and another one using numpy:
import numpy
newWind = numpy.array(Wind).transpose()[0].tolist()

and one using a list comprehension that assumes there will always be only one element in the inner lists:
newWind = [x[0] for x in Wind]

and one using map making the same assumption:
newWind = map(lambda x:x[0], Wind)

take your pick!

A: The syntax error results because you are trying to execute a return statement when you aren't in a function.  If you just want to print the contents of Wind, use print(Wind) instead of return Wind


text:
Q: Extension error handler I have extension which I declared in separate swift file which I use to handle errors when user fill out registration information. But instead to return String in my debug are I want to use some alerts or imageViews to display depends on the error. The problem is that I'm not sure how can I pass IBOutlet or create alert in return section of this extension. For example if firstName is empty, red circle alert (imageView) will be displayed near the firstName textfield. Maybe my architecture of handling errors is wrong or maybe there is a way how to do it?
I would be very grateful if you give me a right direction where to find solution.
Here is the extension
import UIKit

enum RegistrationErrors: Error {
    case invalidFirstName
    case invalidLastName
    case invalidCountry
}

extension RegistrationErrors: CustomStringConvertible {
var description: String {
    switch self {
    case .invalidFirstName:
        return "FirstName cannot be empty"

    case .invalidLastName:
        return "LastName cannot be empty"

    case .invalidCountry:
        return "Country cannot be empty"
    }
}

}
Here is my code where I use this extension
func registrationUser(firstName: String, lastName: String, country: String) throws -> (String, String, String)   {
    guard let firstName = firstNameTextField.text , firstName.characters.count != 0 else {
        throw RegistrationErrors.invalidFirstName
    }

    guard let lastName = lastNameTextField.text , lastName.characters.count != 0 else {
        throw RegistrationErrors.invalidLastName
    }

    guard let country = countryTextField.text , country.characters.count != 0 else {
        throw RegistrationErrors.invalidCountry
    }

    return (firstName, lastName, country)
}

// MARK: Actions

@IBAction func continueBtnTapped(_ sender: Any) {

    do {
        let (firstName, lastName, country) = try registrationUser(firstName: firstNameTextField.text!, lastName: lastNameTextField.text!, country: countryTextField.text!)
        if let currentUser = FIRAuth.auth()?.currentUser?.uid {
            DataService.instance.REF_BASE.child("users").child("profile").setValue(["firstName": firstName, "lastName": lastName, "country": country, "userId": currentUser])
            performSegue(withIdentifier: "toUsersList", sender: self)
        }
    } catch let error as RegistrationErrors {
        print(error.description)
    } catch {
        print(error)
    }
}

A: Your RegistrationErrors CustomStringConvertible extension is not a bad idea. I think you'll want to handle showing the error to the user right in that do..catch block.
You can catch specific errors like:
do {
  ... try registerUser(...)
} catch RegistrationErrors.invalidFirstName {
  view.invalidFirstName()
} catch ...

You can also capture the error when it is a RegistrationError, like you are doing, then handle the specific error in a switch:
// ...
catch let error as RegistrationErrors {
  print(error)
  switch error {
    case .invalidFirstName:
        view.invalidFirstName()
    // ...
  }

A: Instead of deriving your error from Error, derive it from LocalizedError. This allows you to provide an errorDescription property, and you can even localize it later if you like:
enum RegistrationErrors: LocalizedError {
    case invalidFirstName
    case invalidLastName
    case invalidCountry
    var errorDescription : String? {
        switch self {
        case .invalidFirstName: return NSLocalizedString(
            "First name cannot be empty", comment:"First name cannot be empty")
        case .invalidLastName: return NSLocalizedString(
            "Last name cannot be empty", comment:"Last name cannot be empty")
        case .invalidCountry: return NSLocalizedString(
            "Country cannot be empty", comment:"Country cannot be empty")
        }
    }
}

This becomes the error's localizedDescription at the catch point:
do {
    throw RegistrationErrors.invalidLastName
} catch {
    let problem = error.localizedDescription
    // "Last name cannot be empty"
    // ... now present your alert ...
}

This is a universal solution. No special code is necessary; the catch point does not have to be aware of any extra property of the error, and it even works if the catch point is Objective-C code, because the localized description just carries over into the NSError version.


text:
Q: How to refer to someone who has depression(A noun for someone who has depression)? What do we call a person who is suffering from depression?
Usually I hear "X has depression" but can I say *"X is a 'depressive'"?
I have heard the word depressive used as a noun before; but I'm not sure if it is right.
We do use diabetic to describe someone who has diabetes, so is there a parallel word there?

A: Edit: as commented by Brian Donovan, the two words suggested below seem to be archaic. The best candidate could be a depressed person or depressed people in plural which are more broadly used nowadays.
Melancholiac is a person:

suffering from melancholia or depression: He argues that the melancholiac's self-loathing disguises a hostility towards the lost, beloved object, indicating an underlying ambivalence towards it.

Depressive could also be used:

A person suffering from or tending to suffer from depression:
  Phase-advancing sleep may be a useful treatment for depressives who eschew medication.

[Oxford Online Dictionary]
Melancholia:

a mental condition and especially a manic-depressive condition
  characterized by extreme depression, bodily complaints, and often
  hallucinations and delusions

[Merriam-Webster]

A:
I have heard the word depressive used as a noun before but I'm not sure it is right.

Yes, it is right (especially in the plural). For example:

Depressed mood is often associated with a variety of physiological maladies, and many depressives are burdened with an assortment of ailments ranging from migraine, colitis, and allergies, to endocrine disorders and menstrual disturbances. [link]


text:
Q: Why does authentication behave differently between IIS7 and IIS8 Express I have a mostly empty MVC4 project running on windows 7 using VS2012. In my web.config I have a reference to an external file that configures my authentication mode. I've tried removing this and declaring the mode inline but it produces the same result. In the web.config there's this line
<authentication configSource="Authentication.config" />

In the Authentication.config file there's these lines:
<authentication mode="Forms">
    <forms name=".AuthCookie" loginUrl="~/Account/LogOn" timeout="180" slidingExpiration="true" protection="All" path="/" />
</authentication>

When I access the project in IIS7 I am correctly redirected to /Account/LogOn when I try to access this through the IIS8 Express built into to Visual Studio 2012 this option appears to be ignored.


text:
Q: How to call the method finished() to exit the whole PreferenceActivity I use the official SettingsActivity as my activity's templete,and my preferenceactivity have two static class "preferencefragment1" and "preferencefragment2".
While the App click the headers of the preferenceactivity, it switch to the specified preferencefragment.Then I call the finished() method in the onkeydown() method with the KEYCODE_BACK event.It will back to the headers view.
However,what I want is it back to the mainactivity from preferencefragment view,make the whole PreferenceActivity to finish instead of just the preferencefragment1 view.
Because I want to use the the preferenceActivity to set the parameters of a bluetooth comunication device,and after parameters finished setting, it can immediately send the parameteres to the deivce in the onActivityResult() method.
But now, I must click the BACK button twice to back to the mainactivity.Is that a possible to skip the header view to show or jump into the preferencefragment view directly?
program flow
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
    private static List<Header> headers;
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);
            }
            if (preference instanceof EditTextPreference) {
                EditTextPreference editTextPreference = (EditTextPreference) preference;
                editTextPreference.setSummary(stringValue);
            }
            if (preference instanceof SwitchPreference) {
                SwitchPreference switchPreference = (SwitchPreference) preference;
                switchPreference.setSummary(stringValue);
            }
            return true;
        }
    };

    private static boolean isXLargeTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Confirm to update system paras?");
            builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    setResult(RESULT_OK);
                    finish();

                }
            });
            builder.setNegativeButton("CANCELED", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.show();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data)
    {
        System.out.print(resultCode);
    }

    private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // addPreferencesFromResource(R.xml.pref_system);
        setupActionBar();
    }

    private void setupActionBar() {
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
           // actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onIsMultiPane() {
        return isXLargeTablet(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.pref_headers, target);
        headers=target;
    }

    /**
     * This method stops fragment injection in malicious applications.
     * Make sure to deny any unknown fragments here.
     */
    protected boolean isValidFragment(String fragmentName) {
        return PreferenceFragment.class.getName().equals(fragmentName)
                || SystemPreferenceFragment.class.getName().equals(fragmentName);

    }

    /**
     * This fragment shows general preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    public static class SystemPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_system);
            setHasOptionsMenu(true);
            bindPreferenceSummaryToValue(findPreference("pref_key_ip"));
            bindPreferenceSummaryToValue(findPreference("pref_key_port"));
            bindPreferenceSummaryToValue(findPreference("pref_key_output1_level"));
            bindPreferenceSummaryToValue(findPreference("pref_key_output2_level"));
            bindPreferenceSummaryToValue(findPreference("pref_key_output3_level"));
            bindPreferenceSummaryToValue(findPreference("pref_key_noportrait"));
            bindPreferenceSummaryToValue(findPreference("pref_key_closeeye"));
            bindPreferenceSummaryToValue(findPreference("pref_key_yawn"));
            bindPreferenceSummaryToValue(findPreference("pref_key_distract"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

        /*
        @Override
        public void onStop()
        {
            super.onStop();
            AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
            builder.setTitle("Confirm to update system paras?");
            builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                   SystemPreferenceFragment.this.getActivity().setResult(RESULT_OK);
                }
            });
            builder.setNegativeButton("CANCELED", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SystemPreferenceFragment.this.getActivity().setResult(RESULT_CANCELED);
                }
            });
            builder.show();
            this.getActivity().finish();
        }*/

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class RealtimePreferenceFragment extends PreferenceFragment {
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_realtime);
            setHasOptionsMenu(true);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
}

A: Use getActivity().finish(); to finish the activity
or
expose a method using interface from fragment to activity to notify back is being pressed

A: Problem solved!!
step 1:In the MainActivity, add flag "FLAG_ACTIVITY_NO_HISTORY" to the Intent, then start the SettingsActivity.
step 2: Override the onBuildStartFragmentIntent() method of SettingsActivity(PreferenceActivity) for adding flag FLAG_ACTIVITY_FORWARD_RESULT,so that the activityresult can return to the MainActivity.
Like below: @Override

public Intent onBuildStartFragmentIntent (String fragmentName,
                                       Bundle args,
                                       int titleRes,
                                       int shortTitleRes)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClass(this, getClass());
        intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName);
        intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
        intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, titleRes);
        intent.putExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, shortTitleRes);
        intent.putExtra(EXTRA_NO_HEADERS, true);
        intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);//the new statement
        return intent;
    }


text:
Q: How can I show the count of points in the particular latitude and longitude in Mapboxgl? I want to show the marker as well as the number of points available in a particular latitude and longitude.

I expect something Similar as above.
But i have added another 2 layers to show different color and number on it. If I do this way, I am getting "undefined" error while showing popup. Since the data takes from the other layer. If it takes from layer "locations" it works as expected. But when we have multiple occurences popup content shows "undefined". Below is my implementation output and code

 map.on('load', function () {

  map.addSource("place", {
    type: "geojson",
    data: liveData,
    cluster: true,
    clusterMaxZoom: 14,
    clusterRadius: 50
  });

 map.addLayer({
    "id": "locations",
    "type": "circle",
    "source": "location",
    "paint": {
      "circle-radius": 7,
      "circle-color": "#FFF000",
      "circle-stroke-width": 4,
      "circle-stroke-color": "#FFFFFF"
    }

  });

     map.addLayer({
      id: "clusters",
      type: "circle",
      source: "location",
      filter: ["has", "point_count"],
      paint: {
          "circle-color": {
              property: "point_count",
              type: "interval",
              stops: [
                  [0, "#FFF000"],
                  [2, "#DC143C"],
              ]
          },
          "circle-radius": {
              property: "point_count",
              type: "interval",
              stops: [
                  [0, 7],
                  [2, 7],
              ]
          }
      }
  });

  map.addLayer({
      id: "cluster-count",
      type: "symbol",
      source: "location",
      filter: ["has", "point_count"],
      layout: {
          "text-field": "{point_count_abbreviated}",
          "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
          "text-size": 12,
          "text-offset": [0, 5]
      }
  });

 map.on('click', 'locations', function (e) {
    let htmlString = "";
    for (let i = 0; i < e.features.length; i++) {
      htmlString = htmlString + e.features[i].properties.description;
      if (i != e.features.length - 1) {
        htmlString = htmlString + "</br>";
      }
    }
    new mapboxgl.Popup()
      .setLngLat(e.features[0].geometry.coordinates)
      .setHTML(htmlString)
      .addTo(map);

  });
 }

My working fiddle
I want to achieve this as first picture or popup should work in my approach?

A: As far as I know getting all features that get combined in the cluster is currently not possible via mapbox's cluster feature.
See here: https://github.com/mapbox/mapbox-gl-js/issues/3318


text:
Q: intranet dns lookup fetching incorrect ip We have a host entry on our server in /etc/hosts file. So there is an entry as follows:
10.74.74.76 foo

But on the same machine, via SSH I do the following:
$ host -t a foo
foo.internal.domain.com has address 10.43.55.23

Why is this not referencing the ip in /etc/hosts?

A: host is a (simple) DNS lookup utility.
Any data in your /etc/hosts file is NOT DNS.
That means that the host command will always query the DNS servers you have configured and it does not honor the typical precedence your system resolver uses  in first querying the local hosts database before attempting to resolve the host/FQDN.

A: The host command is a DNS lookup utility that always uses DNS as a resolver; never /etc/hosts file.
From host(1) man page:

host is a simple utility for performing DNS lookups.
server is an optional argument which is either the name or IP address of the name server that host should query instead of the server or servers listed in /etc/resolv.conf.


text:
Q: Android - Sorting TextView with another Java class I want to sort some TextViews in an activity abstracting a Class that i've already made in which there's my sorting method, then the result of the sorting has to be written inside a new TextView.
EDIT:
The content of my TextViews are numbers, now i want to sort these numbers and the result of this sorting has to be written inside a new TextView.
For example :
TextView1 content : 23
TextView2 content : 41
TextView3 content : 3
TextView4 (that will contain the rules of sorting)  : 3, 23, 41

A: Assuming I understood your question correctly this should work for you:
List<Integer> data = new ArrayList<Integer>();
data.add(Integer.parseInt(TextView1.getText().toString()));
data.add(Integer.parseInt(TextView2.getText().toString()));
data.add(Integer.parseInt(TextView3.getText().toString()));
Collections.sort(data);
TextView4.setText(data.toString());


text:
Q: Как разделить функционал администратора от клиента в приложении? Есть идея создать мобильное приложение для взаимодействия клиентов с администратором, как отделить функционал админа от клиента? тобишь и клиент и администратор
Устанавливают одно приложение в котором есть клиентская и админ часть , клиенту не доступна админ часть?


text:
Q: Quantifying inter-rater reliability with CFA After reading this question and Jeremy Miles's answer I'm interested in the idea of using CFA to quantify inter-rater reliability. To make it more concrete, imagine a situation where I have one latent variable (LV) with three indicators (ind1, ind2, and ind3). If I have a pair of raters (a and b), who each rate subjects on all three indicators and then I fit a two-factor CFA as follows, using Lavaan syntax:
LVa =~ ind1a + ind2a + ind3a
LVb =~ ind1b + ind2b + ind3b

LVa ~~ LVb

where LVa is the latent variable as measured by rater a and LVb is that as measured by rater b. Then does the standardised covariance between the two latent variables represent inter-rater reliability in the same way that, say, a Pearson correlation between each rater's sumscore would?
If so, do I also have to equate the factor loadings for each indicator (i.e. for ind1a and ind1b), and impose covariances between each pair?

A: Yes.
You need to covary the equivalent errors (as you say).
You should also test for equivalence of the loadings across raters - this is called invariance. It's a bit weird to correlate two different things when they are not equivalent (because they have different loadings).


text:
Q: How do you add Ctrl-T information to a program? When you press ctrl-t when dd(1) is running it tells you how much data it transfered and how long it has been running.  If you press it during a cp(1) you can see which file it is up to and the percent done copying.
I'd like to add the same type of feature to my program.  How can I do that?


text:
Q: Knowing the rates of gain and loss, estimate the average amount. This question was presented to me as such:

Say that people grow 100 hairs a day and lose 100 hairs a day and hairs have a lifespan of 100 days. Estimate how much hair an average person would have.

I thought to answer this I would assume there were no hairs to start, so each day 100 more hairs show up until the first 100 hairs' lifespans end, at which point there would be equilibrium, so the estimate would be around 100 * 100 = 10,000 hairs. I feel as though this answer is incomplete or that I am missing something. Any help would be appreciated. Thanks.
(Forgive me if I put an improper tag)


text:
Q: Conflicts between `height: 100%` and `` windows In my project I have to set height: 100% on the <html> and <body> tags to make center elements and to have the <md-sidenav> over full page height.
This somehow breaks the <md-autoselect> directive. In my case I have lots of autoselects below each other. As soon as I click on one of the lower ones the whole page turns white.
This is caused by the disableBodyScroll-method in $mdUtils which gets called when autoselects, sidenavs etc. are opened.
The primary problem seems to be that body.scrollHeight in our case is the same as body.clientHeight.
$mdUtils.disableBodyScroll code:
var clientWidth = body.clientWidth;
if (body.scrollHeight > body.clientHeight + 1) {
    applyStyles(body, {
        position: 'fixed',
        width: '100%',
        top: -scrollOffset + 'px'
    });

    applyStyles(htmlNode, {
        overflowY: 'scroll'
    });

 if (body.clientWidth < clientWidth) applyStyles(body, {overflow: 'hidden'});
}

This is caused by the 100% height. Removing the height property from the body and html tag solves the problem with the autoselects. But if we remove the height, pages that are smaller than 100% show a wrong sidenav behaviour (the sidenav is only as tall as the page).
We temporarily fixed the problem by monkey patching $mdUtils.disableBodyScroll.
We replaced
if (body.clientWidth < clientWidth) applyStyles(body, {overflow: 'hidden'});
with
applyStyles(body, {'overflow': 'visible'});
It is hard to create a plnkr for this example as the structure is quite complicated and the problem does not occur as soon as I try to simplify the code.
Has anybody encountered this problem?
Also check the issue on the AngularJS Material GitHub page:
https://github.com/angular/material/issues/7158


text:
Q: Базы данных Здравствуйте. В университете будем проходить такой предмет как "Базы данных" и хочется узнать:
а) какую литературу почитать по данной теме, хочу уже придти с каким то багажом, ну и для себя.... надеяться на то, что мне все там разжуют полный бред, т.к. все знают какое у нас высшее образование по IT направлению.
б) что вообще будет включать данный курс,  я понимаю, что программы могут отличаться, но в общих чертах, я думаю, все же можно объяснить ?
A: Первые несколько занятий Вы, скорее всего, будете изучать общую теорию БД: архитектуры БД по модели данных (иерархическая, сетевая, реляционная), архитектуры БД по виду реализации (локальная, файл-серверная, клиент-серверные: "толстый" ("сильный") клиент, "тонкий" ("слабый") клиент), нормализацию БД и нормальные формы, ещё, возможно, услышите пару слов про ER-диаграммы. Возможно, Вам скажут в двух словах о механизмах доступа к данным (это зависит от среды программирования, которая изучается в Вашем университете, если это Delphi или C++ Builder, то: BDE, ADO (dbGo), dbExpress), хотя, это вряд-ли. Ну, конечно же, основы языка SQL - в БД без него никак. А, вот, насчёт литературы, я думаю, лучше с преподавателем посоветоваться, т. к. это зависит от того какую именно среду для разработки БД Вы будете использовать, как правило, во многих книгах, посвящённых БД, сначала идёт общая теория. Можете взять что-нибудь по языку SQL для начинающих или книгу по общей теории БД - не ошибётесь. Или, как вариант, пройдите какой-нибудь курс на ИНТУИТЕ: http://www.intuit.ru/. Только перед прохождением бывает очень полезно почитать отзывы, а-то там иногда попадаются очень сложные курсы (один такой есть и по БД).


text:
Q: Keep getting errors from apport_python_hook.py I keep getting this error message when trying to do any apt-get command, or almost any command in general, it also shows up when I open the terminal. I also cannot open the Software Center and Software Updater. Even when I try to reinstall python to fix the error it gives me this error.. would love any suggestions!
Traceback (most recent call last):
  File "/usr/lib/command-not-found", line 5, in <module>
    from __future__ import absolute_import, print_function
ImportError: No module named '__future__'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
    if not enabled():
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
    import re
ImportError: No module named 're'

Original exception was:
Traceback (most recent call last):
  File "/usr/lib/command-not-found", line 5, in <module>
    from __future__ import absolute_import, print_function
ImportError: No module named '__future__'


text:
Q: Different type of \sum symbol This is what I have:

and this is what I need (picture taken from a beamer document):

I'd like to know the font that is being used in the second picture for the \sum command. Some of my code is this:
\documentclass[11pt, oneside]{book}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{amsthm}

\renewcommand\sfdefault{cmss}
\renewcommand{\familydefault}{\sfdefault}

\begin{document}
    \begin{gather*}
        \alpha = \sum_{i=1}^n x_i \alpha_i
    \end{gather*}
\end{document}


text:
Q: WavesurferJS in a VueJS app, audio can be played but waveform never loads on IOS Safari? I'm using WavesurferJS in my VueJS application, and i've been trying to solve this issue for the past week. On IOS Safari (and IOS Safari only, as far as i can tell), my wavesurfer component can't finish decoding the audio/loading the waveform, and a thin straight line just shows up. Without using backend: "MediaElement", the component just shows up blank. Using the backend however, i can play the audio, but the waveform still never loads.
I read into the wavesurfer doc a bit and according the the FAQ: "if you use the backend: 'MediaElement' option... The audio will start playing as you press play. A thin line will be displayed until the whole audio file is downloaded and decoded to draw the waveform.". This is exactly what i'm experiencing, audio can be played and a thin line shows up, but i assume waveform never finishes downloading/decoding.
My Vue method that handles audio loading:
setupRecentRecordingandSave(data, num, name) {

  var url = window.URL.createObjectURL(data);

  if (this.wavesurfer[num] == null) {
    this.createWaveSurfer(num);
    this.wavesurfer[num].load(url);
    this.showRecent = true;
  } else {
    this.wavesurfer[num].load(url);
  }
  this.$store.commit("addCough", { key: name, val: data});
}

I'm using an array of wavesurfer elements, this method is called after a recording is made by the user, and the blob data is sent to this method.
My create wavesurfer code:
createWaveSurfer(num) {
  Vue.set(
    this.wavesurfer,
    num,
    WaveSurfer.create({
      container: "#waveform-" + num,
      waveColor: "#f7931e",
      progressColor: "#824500",
      fillParent: true,
      hideScrollbar: true,
      backend: "MediaElement"
    })
  );
},

I've been struggling with this for a while now, any help is appreciated. Thanks.

A: Turns out my issue wasn't with WaveSurfer, but with the way i was recording user audio on IOS. After fixing and making sure the audio recorded properly, the waveform displayed correctly.


text:
Q: Hide Toolbar on login component without having to refresh (Angular 11) I created a simple Authentication service that works well at the start of the web app , however in a user-case scenario where the user decides to log-out and relog-in the toolbar/navbar remain visible when switching back to the login page, in order for it to become invisible the page needs to be refreshed so the ngIf method would work; my idea was to show the toolbar/navbar whenever the user is logged in, which means if there is a token cached in localStorage.

this is the code that applies the toolbar/navbar

app.component.html

    <mat-toolbar  *ngIf="userToken">

          <button mat-icon-button style="margin:auto" color="primary" (click)="opened=!opened" aria-label="Example icon button with a menu icon">
            <mat-icon>menu</mat-icon>
          </button>

        <button mat-raised-button color="primary" routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</button>

        <button mat-stroked-button id="Users" style="margin-right: 16px" routerLink="/users" routerLinkActive="active">Profile</button>
        <button mat-raised-button color="accent"  (click)="logout()">Logout</button>

    </mat-toolbar>

    <mat-sidenav-container class="container" >
      <mat-sidenav mode="push"  [(opened)]=opened >

Working

      </mat-sidenav>
        <mat-sidenav-content>

            <alert></alert>
            <router-outlet></router-outlet>

        </mat-sidenav-content>

    </mat-sidenav-container>

app.component.ts
import { Component,ChangeDetectorRef } from '@angular/core';

import { AccountService } from '../app/services/account.service';
import { User } from '../app/models/user';
import { Token } from '@angular/compiler/src/ml_parser/lexer';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'FrontEnd';
  userToken: Token;

  opened=false;

    constructor(private accountService : AccountService) {
      this.userToken = this.accountService.userToken;

    }

    logout() {

      this.accountService.logout();

    }

}

app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './authentification/login/login.component'
import { MainComponent } from './main/main.component';
import { UsersModule } from './Users CRUD/users.module';
import { AuthGuard } from './_helpers/auth.guard';

const authModule=()=> import('./authentification/authentification.module').then(x => x.AuthentificationModule);
const usersModule = () => import('./Users CRUD/users.module').then(x => x.UsersModule);

const routes: Routes = [
  { path : '', component: MainComponent , canActivate: [AuthGuard]},
  { path: 'users', loadChildren: usersModule, canActivate: [AuthGuard] },
  { path : 'auth',loadChildren: authModule},

  { path : '**', redirectTo:''}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

account.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { environment } from '../../environments/environment';
import { User } from '../models/user';

@Injectable({ providedIn: 'root' })
export class AccountService {
    private userSubject: BehaviorSubject<User>;
    public user: Observable<User>;
    readonly BaseURL ='https://localhost:44381/api';
    public subj = new BehaviorSubject({});

    constructor(
        private router: Router,
        private http: HttpClient
    ) {
        this.userSubject = new BehaviorSubject<User>(null);
        this.user = this.userSubject.asObservable();

    }

    public get userToken() {
        return JSON.parse(JSON.stringify(localStorage.getItem('user')));
    }

    login(username, password) {
        return this.http.post<User>(`${this.BaseURL}/User/Login`, { username, password });
           /* .pipe(map(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('user', JSON.stringify(user));
                this.userSubject.next(user);
                return user;
            }));*/
    }

    logout() {
        // remove user from local storage and set current user to null
        localStorage.removeItem('user');
        this.userSubject.next(null);
        this.router.navigate(['/auth/login']);
    }

    GetUser()
    {
        return this.http.get(this.BaseURL+'/UserProfile');
    }

    register(user: User) {
        return this.http.post(`${this.BaseURL}/User/Register`, user);
    }

    getAll() {
        return this.http.get<User[]>(`${this.BaseURL}/users`);
    }

    getById(id: string) {
        return this.http.get<User>(`${this.BaseURL}/UserProfile/${id}`);
    }

}

A: The simplest way is clear the userToken when user logout
// app.component.ts
logout() {
    this.userToken = null;
    this.accountService.logout();
}

The best practice is use behavior subject to store your userToken.
Behavior subject is an object of RxJS.
20210309 update
The userToken is assigned inside of the constructor function of app.component.ts, which means it is only evaluated when Angular initialize appComponent.
So userToken is fixed after appCompoent initialized.
If you want to change userToken dynamically, you can subscribe the userSubject of AccountService.
20210310 update
It is the concept of RxJX, you can checkout the tutorial of RxJS.
// wherever component the login function in
public login(userObj){
    this.accountService.userSubject.next(userObj);
}

// app.component.ts
private user$: Subscription;
ngOnInit(){
    this.user$ = this.accountService.userSubject.subscribe((user)=>{
        this.userToken = user;
    });
}

ngOnDestroy(){
    this.user$.unsubscrible();
}

A: Thanks to @kin I was able to understand the code better and come up with a solution to my problem.
I Fixed this by setting the user token in localstorage inside the login method in the service.ts file then subscribing to the user in the component.ts file
here's the code :
account.service.ts
...
login(username, password) {
        return this.http.post<User>(`${this.BaseURL}/User/Login`, { username, password }).pipe(map(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('user', user.token);
            this.userSubject.next(user);
            return user;
        }));
    }
...

app.component.ts
...
constructor(private accountService : AccountService) {

      this.accountService.user.subscribe(x => this.user = x);

    }
...

app.component.html

    <mat-toolbar  *ngIf="user" >

          <button mat-icon-button style="margin:auto" color="primary" (click)="opened=!opened" >
            <mat-icon>menu</mat-icon>
          </button>

        <button mat-raised-button color="primary" routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" (click)="opened=false">Home</button>

        <button mat-stroked-button id="Users" style="margin-right: 16px" routerLink="/users" routerLinkActive="active" (click)="opened=false">Profile</button>
        <button mat-raised-button color="accent"  (click)="logout()">Logout</button>

    </mat-toolbar>

    <mat-sidenav-container  >
      <mat-sidenav mode="push"  [(opened)]=opened >

Working

      </mat-sidenav>
        <mat-sidenav-content>

            <alert></alert>
            <router-outlet></router-outlet>

        </mat-sidenav-content>

    </mat-sidenav-container>

I hope this helps anyone with a similar problem


text:
Q: PHP best way to search a string for values in an array? I have a string and an array, the array contains all kinds of parts of a string I want to find in the original string (this is for basically reading a error log and identifying what line there is a "Could not find", or "Error", etc.)
Is the foreach preg_match the best method?

A: The easiest and speediest way is using strpos(). If it returns FALSE it didn't find the substring, otherwise it did. Make sure you use === as it might return 0:
$found_substring = (strpos($text, $substring) !== FALSE);

For case-insensitivity, use stripos(). If you need more matching power, use preg_match().


text:
Q: CSS Grid layout not covering the entire website I have this problem that my CSS Grid Layout isn't covering the entire website and so my footer for example isn't going all the way down. I don't know what's the problem so i need some help please. Thank you.
This is how it looks like my grid. See below the footer that there is a blank space <--/  /(Click the link so you can see my jpg image of what my website looks like) / /
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/contact.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&family=Ubuntu:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
    <title>TRV ECOLOGICO SRL</title>

TRV ECOLOGICO SRL

INICIO

PRODUCTOS

EMPRESA

CONTACTO

Estamos para ayudarlo

Información de Contacto

Teléfono

123 - 4567 - 8911

123 - 4567 - 8911

Email

asd@asdfghi.com.ar

asdtas@asdfhi.com.ar

Dirección

Morón, Buenos Aires, Argentina

Contacto

                    <form>
                        <input type="text" placeholder="Nombre Completo" class="contact-in-input">
                        <input type="text" placeholder="Nombre Completo" class="contact-in-input">
                        <input type="text" placeholder="Nombre Completo" class="contact-in-input">
                        <textarea placeholder="Mensaje" class="contact-in-textarea"></textarea>
                        <input type="submit" value="SUBMIT" class="contact-in-btn">
                    </form>

TRV ECOLOGICO SRL - Todos los derechos reservados

CSS:
*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body{
    font-family: 'Poppins', sans-serif;
    background: #fff;
}
/*GRID CONTENEDOR*/
.contenedor{
    width: 100%;
    margin: 0 auto;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(4, auto);
    grid-template-areas: "nav nav"
                         "section section"
                         "form form"
                         "footer footer";
}
.contenedor .contenedor-nav{
    /*grid-column-start: 1;
    grid-column-end: 3;*/
    grid-area: nav;
}
.contenedor .contenedor-section{
    /*grid-column-start: 1;
    grid-column-end: 3;*/
    grid-area: section;
}
.contenedor .contenedor-form{
    /*grid-column-start: 1;
    grid-column-end: 3;*/
    grid-area: form;
}
.contenedor .contenedor-footer{
    /*grid-column-start: 1;
    grid-column-end: 3;*/
    grid-area: footer;
}
/* MENU NAVEGACION */
nav{
    position: sticky;
    top: 0;
    z-index: 30;
}
.menu-navegacion{
    margin: auto;
    overflow: hidden;
    padding: 0;
    display: flex;
    height: 80px;
    justify-content: space-between;
    align-items: center;
    background-color: rgb(54, 54, 54);
}
.logo{
    padding-right: 10%;
    padding-left: 10%;
    height: 50px;
    width: 20%;
    display: flex;
    justify-content: center;
    margin-left: 1%;
    position: relative;
}
.contenedor-triangulo{
    height: 100%;
    position: absolute;
}
.triangulo{
    height: 0%;
    width: 0%;
    border-right: 30px solid transparent;
    border-left: 30px solid transparent;
    border-bottom: 50px solid red;
    display: block;
}
.contenedor-texto{
    display: flex;
    align-items: center;
    justify-content:center;
    height: 50px;
    width: 100%;
}
.textotriangulo{
    position: absolute;
    font-weight: 700;
    color: rgb(255, 255, 255);
    font-size: 1em;
    text-shadow: 3px 2px 1px rgba(54, 54, 54, 0.493);
}
.menu-lista{
    margin-right: 20%;
}
.menu-lista ul li{
    list-style: none;
    display: inline-block;
}
.menu-lista ul li a{
    text-decoration: none;
    color: white;
    padding-left: 20px;
}
/* SECTION */
.contenedor-section{
    display: flex;
    justify-content: center;
    line-height: center;
    align-items: center;
    height: 275px;
    background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.main{
    font-size: 3em;
    color: whitesmoke;
    text-shadow: 3px 2px 3px #000000;
    font-weight: 900;
}
/* FORM */
.contact-wrap{
    margin: auto;
    display: flex;
    flex-wrap: wrap;
}
.contact-in{
    padding: 40px 30px;
}
.contact-in:nth-child(1){
    flex: 30%;
    background: url(../images-form/1.jpg);
    color: #fff;
}
.contact-in:nth-child(2){
    flex: 45%;
    background: #c31432;
}
.contact-in:nth-child(3){
    flex: 25%;
    padding: 0;
}
.contact-in h1{
    font-size: 24px;
    color: #fff;
    text-transform: uppercase;
    font-weight: 500;
}
.contact-in h2{
    font-size: 20px;
    font-weight: 400;
    margin-bottom: 15px;
}
.contact-in h2 i{
    font-size: 16px;
    width: 40px;
    height: 40px;
    margin-right: 10px;
    background: #f5f5f5;
    color: #000;
    border-radius: 50px;
    line-height: 40px;
    text-align: center;
}
.contact-in p{
    font-size: 14px;
    font-weight: 300;
    margin-bottom: 20px;
}
.contact-in form{
    width: 100%;
    height: auto;
}
.contact-in-input{
    width: 100%;
    height: 40px;
    margin-bottom: 20px;
    border: 1px solid #fff;
    outline: none;
    padding-left: 5px;
    color: #fff;
    font-size: 12px;
    font-weight: 300;
    font-family:'Poppins', sans-serif;
}
.contact-in-textarea{
    width: 100%;
    height: 140px;
    margin-bottom: 20px;
    border: 1px solid #fff;
    outline: none;
    padding-top: 5px;
    padding-left: 5px;
    color: #fff;
    font-size: 12px;
    font-weight: 300;
    font-family:'Poppins', sans-serif;
}
.contact-in-btn{
    width: 100%;
    height: 40px;
    border: 1px solid #fff;
    outline: none;
    font-size: 12px;
    font-weight: 300;
    font-family:'Poppins', sans-serif;
    cursor: pointer;
}
.contact-in iframe{
    width: 100%;
    height: 100%;
}
/* FOOTER */
#footer{
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgb(54, 54, 54);
    height: 80px;
}
#footer p{
    color: white;
    font-weight: 400;
    font-family: 'Ubuntu', sans-serif;
    padding: 5px;
    border-bottom: solid white 1px;
}
/* RESPONSIVE */
@media only screen and (max-width:480px){
    .contact-in:nth-child(1){
        flex: 50%;
    }
    .contact-in:nth-child(2){
        flex: 50%;
    }
    .contact-in:nth-child(3){
        flex: 100%;
    }
}
@media only screen and (max-width:360px){
    .contact-in:nth-child(1){
        flex: 50%;
    }
    .contact-in:nth-child(2){
        flex: 50%;
    }
    .contact-in:nth-child(3){
        flex: 100%;
    }
}
@media screen and (max-width: 768px){
    .contenedor{
        grid-template-areas: "nav nav"
                            "section"
                            "form form"
                             "footer footer";
    }
}

A: I just found a solution.
Try not to set heights directly to the sections and set them in the grid-template-columns.
.contenedor {
    grid-template-rows: 8vh 23vh 60vh 9vh; /* this should sum 100 */
  }
  .contenedor-form {
    align-self: center;
  }
  .contenedor-section {
    /* height: 275px; */ /* remove property */
  }
  .menu-navegacion {
    height: 100%;
  }
  #footer {
    height: 100%;
  }


text:
Q: How can I return Many to One relation data joined with One to One data? I have a question concerning Laravel schema.
Was that a bad idea to create an additional one-to-one table user_description, to store additional user data? Here is my schema:

For example now I don't know how to use eager loading to get user_photos if at first I retrieve topics' data.
Here is the code I use to get the last topics with user data:
return  Topic::with('blog', 'user')->orderBy('topics.id', 'DESC')->get();

A: assuming your User-Model has a relation description() I suppose this does what you want.
return Topic::with('blog', 'user', 'user.description')->orderBy('topics.id', 'DESC')->get();

the concept is called sth. like eager loading of nested-relationships and is documented at the bottom of the eager loading documentation of laravel


text:
Q: Python redundancy If I have the code
i = 0
while i < N:
    print("Hello")
    i += 1

how many times will Hello be printed out? (assume that N is a defined integer)
Answers:

*

*0

*N

*N-1

*N+1

*more than N+1

and why? I never get this so I would appreciate of somebody could explain.

A: The best way to figure it out is to go through it by hand for a few manageable values of N. For instance, if N is 2:

*

*i == 0 and 0 < 2 → print "hello", increment i

*i == 1 and 1 < 2 → print "hello", increment i

*i == 2 and 2 < 2 → while-loop condition is no longer satisfied → loop ends

So for N = 2, "hello" is printed 2 times. See the pattern?

A: Hello will be printed out N times.
assume N is 3.
1st iteration
i = 0
i is less than N
print hello
i = i + 1; // i = 1

2nd iteration
i = 1;
i` is less thanN (3)`
print hello
i = i + 1; // i = 2

3rd iteration
i = 2;
i is less than N (3)
print hello
i = i + 1; // i = 3

4th iteration
i = 3;
i is equal to N (3)
break loop

A: As the other answers described, it would print N times, because it starts at 0 and goes until it is just before N, not equal to N.
In reality, though, this is very redundant in Python. A much easier way to do this, making it a bit more readable (and hopefully easier for you to understand):
N=3
for x in range(0,N):
    print "This is loop %d" % (x)

This loop will print from 0 to N, which is really just N amount of times.


text:
Q: How to remove black artifacts on map in QGIS How can I remove the black pixels on the shapefile below?
I have never seen this before after receiving a shapefile and categorizing it. This shapefile shows percentage of flooded area per municipality. I'm displaying polygons here (municipalities) but I can't get rid of the black pixels. Are they no data values?

A: The symbol most likely has a black outline. Go to the style configuration of the layer and set the stroke color to Transparent.
No data value is a term normally used with respect to raster data, while with vector data (like shapefiles) normally the term to use is NULL value for an attribute, but that's not related to anything that's going on here.


text:
Q: Python. import из файла main в один из пакетов
Есть проект, оконное приложение на python. Весь функционал прописал в файле main, но я хочу перенести его в module/data.py, при импорте возникает ошибка: ModuleNotFoundError: No module named 'main'. В файле init.py корня игры прописал from .main import.. А дальше не особо вникаю что и как.

A: Всё что ниже не является ответом на вопрос, я перепутал и подумал что main.py находится в ui. В вашем случае надо прописать в data.py:
import имя_коренной_папки.main

Для того чтобы в module/data.py импортировать ui/main.py, можно в ui/init.py прописать
from .main import *  # или что-то что нужно

и в module/data.py импортировать директорию
import ui

Если что, исправьте в комментариях, отредактирую ответ.
Вообще, в вашем конкретно случае заморачиваться с этим не надо (мне кажется этот способ подойдёт когда нужно импортировать много всего из многих файлов). Можно просто импортировать ui/main.py в module/data.py, то бишь в module/data.py прописать
import ui.main


text:
Q: Getting `POST requests require a Content-length header. ' when running Curl code I want to get an Auth2 token through this curl request:
define("CALLBACK_URL", "http://localhost/los/index");
define("AUTH_URL", "https://accounts.google.com/o/oauth2/auth");
define("ACCESS_TOKEN_URL", "https://oauth2.googleapis.com/token");
 define("CLIENT_ID", "**.apps.googleusercontent.com");
define("CLIENT_SECRET", "**");
define("SCOPE",
"https://www.googleapis.com/auth/admin.directory.device.chromeos"); // optional

 function getToken(){
 $curl = curl_init();

 $params = array(
CURLOPT_URL =>  ACCESS_TOKEN_URL."?"
                ."code=".$code
                ."&grant_type=authorization_code"
                ."&client_id=". CLIENT_ID
                ."&client_secret=". CLIENT_SECRET
                ."&redirect_uri=". CALLBACK_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_NOBODY => false,
CURLOPT_HTTPHEADER => array(
  "cache-control: no-cache",
  "content-type: application/x-www-form-urlencoded",
  "accept: *",
  "accept-encoding: gzip, deflate",
),
 );

  curl_setopt_array($curl, $params);

   $response = curl_exec($curl);
 $err = curl_error($curl);
  echo $response;
  curl_close($curl);

  if ($err) {
   echo "cURL Error #01: " . $err;
       } else {
 $response = json_decode($response, true);
    if(array_key_exists("access_token", $response)) return $response;
if(array_key_exists("error", $response)) echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
  }
 }

However, it gives me this error message:
POST requests require a Content-length header. That's all we know.
Ive tried to remove the newlines in the URL but that did not resolve it. (I followed this tutorial)
How can I fix this? Do I need to put the content-length header manually?

A: You need to add the Content-Length header to your CURLOPT_HTTPHEADER array.
The value usually is the size of the body (in bytes). Since you don't have any, I'd suggest trying 0 as a value.
CURLOPT_HTTPHEADER => array(
  "cache-control: no-cache",
  "content-type: application/x-www-form-urlencoded",
  "accept: *",
  "accept-encoding: gzip, deflate",
  "Content-Length: 0"
)