text:
Q: Public override string more returns School asks me to use the public override string. I would like to have something like this:
lbl_Name.Text = ToString(*Field: Naam from class Gebruikerklasse*)
lbl_Surname.Text = ToString(*Field: Achternaam from class Gebruikersklasse*)

I have multiple fields in my class, but I want to return just a few of them. Do I need different methods or can I do it with just one method and more returns with some if statements and booleans?
This is what I have now:
 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace BurnThatFat
    {
        class Gebruikerklasse
        {
            public string Naam;
            public string Achternaam;
            public int Leeftijd;
            public string Geslacht;
            public int Huidiggewicht;
            public int Streefgewicht;
            public string Gebruikersnaam;
            public string Wachtwoord;

            public override string ToString()
            {
                return Naam;

            }
// I want to use the same method again but this time for another field.

 public override string ToString()
        {
            return Gebruikersnaam;
        }

    }

}

A: using System;

namespace BurnThatFat
{
    class Program
    {
        static void Main()
        {
            var g1 = new Gebruikerklasse1() { Naam = "Duncan", Geslacht = "Male", Huidiggewicht = 75, Gebruikersnaam = "DCarr" };
            var g2 = new Gebruikerklasse2() { Naam = "Duncan", Geslacht = "Male", Huidiggewicht = 75, Gebruikersnaam = "DCarr" };

            Console.WriteLine(g1);
            Console.WriteLine(g2);

            Console.ReadKey();
        }
    }

    class Gebruikerklasse1
    {
        public string Naam;
        public string Achternaam;
        public int Leeftijd;
        public string Geslacht;
        public int Huidiggewicht;
        public int Streefgewicht;
        public string Gebruikersnaam;
        public string Wachtwoord;
    }

    class Gebruikerklasse2
    {
        public string Naam;
        public string Achternaam;
        public int Leeftijd;
        public string Geslacht;
        public int Huidiggewicht;
        public int Streefgewicht;
        public string Gebruikersnaam;
        public string Wachtwoord;

        public override string ToString()
        {
            return string.Format("{0} - {1} - {2} - {3}", Gebruikersnaam, Geslacht, Huidiggewicht, Naam);
        }
    }
}

Output is:
BurnThatFat.Gebruikerklasse1
DCarr - Male - 75 - Duncan

i.e.
"g1" outputs default class-to-string output
"g2" outputs overriden format - which can include any members you like

Sorry if I have misunderstood.

A: I suggest implementing IFormattable interface:
    class Gebruikerklasse {
      ...

      // "A" - Achternaam
      // "G" - Gebruikersnaam
      // "N" - Naam
      // null, empty - default ToString format
      public string ToString(string format, IFormatProvider formatProvider) {
        if (string.IsNullOrEmpty(format))
          return ToString();
        else if ("N".Equals(format, StringComparison.OrdinalIgnoreCase))
          return Naam;
        else if ("A".Equals(format, StringComparison.OrdinalIgnoreCase))
          return Achternaam;
        else if ("G".Equals(format, StringComparison.OrdinalIgnoreCase))
          return Gebruikersnaam;
        else
          throw new FormatException($"Unknown format '{format}'");
      }

      public string ToString(string format) {
        return ToString(format, CultureInfo.CurrentCulture);
      }

      public override string ToString() {
        return Gebruikersnaam;
      }
    }

And so you can put:
    Gebruikerklasse instance = new Gebruikerklasse();

    lbl_Name.Text = instance.ToString("G");
    lbl_Surname.Text = instance.ToString("A");


text:
Q: Blank screen on ViewPager Comrades help please.
I created ViewPager, and it displays a blank screen.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_textgrid);
    viewPager = (ViewPager) findViewById(R.id.textpager);

    items = new ArrayList<RssItem>();

    LoadText loader = new LoadText();
    loader.execute();

}

private class LoadText extends AsyncTask<Void, Void, ArrayList<RssItem>> {

            @Override
        protected void onPostExecute(ArrayList<RssItem> result) {
            Log.i(LOG_TAG, "LOADED:" + result.size());
            Log.i(LOG_TAG, "CUUR_ITEM:" + viewPager.getCurrentItem());

            pd.dismiss();
            items.addAll(result);
            adapter = new TextAdapter(TextActivity.this, items);

            viewPager.setAdapter(adapter);

            adapter.notifyDataSetChanged();
            if (items.size() > 0) {
                viewPager.setCurrentItem(1);
                Log.i(LOG_TAG, "CUR_ITEM:" + viewPager.getCurrentItem());
            }

            super.onPostExecute(result);
        }
}

public class TextAdapter extends PagerAdapter {

    private Activity _activity;
    private ArrayList<RssItem> items;

    @Override
    public int getCount() {
        return items.size();
    }

    public TextAdapter(Activity activity, ArrayList<RssItem> items) {
        this._activity = activity;
        this.items = items;

    }

    private RssItem getItem(int pos) {
        return this.items.get(pos);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        LayoutInflater inflater = (LayoutInflater) _activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View viewLayout = inflater.inflate(R.layout.activity_text, container,
                false);

        RssItem item = getItem(position);
        TextView title = (TextView) viewLayout.findViewById(R.id.textTitle);
        TextView rating = (TextView) viewLayout.findViewById(R.id.textRating);
        TextView author = (TextView) viewLayout.findViewById(R.id.textAuthor);
        TextView content = (TextView) viewLayout.findViewById(R.id.textContent);

        content.setText(item.getContent());
        title.setText(item.getTitle());
        rating.setText(item.getRating());
        author.setText(item.getAuthor());
        content.setText(item.getContent());

        return viewLayout;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((RelativeLayout) object);

    }

}

The logs appear that a lot of data uploaded.
if you change the program page, it changes (in the logs can be seen).
A blank screen = (

A: try use:

viewPager.offscreenPageLimit = adapter.count

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete the first record from a fasta file in Python I have a small fasta file in the following format:
>gene_1 + other data
seq 1
>gene_1 + other data
seq2
>gene_1 + other data
seq3

I would like to remove the first element of the file. This is part of a large Python script, and once I have worked with that seq, and extracted the interesting part of it, I would like to remove it from the file. Eventually, the file will be emptied so I can delete it from the folder.
As I have been using Biopython, I was trying to see if I could find a function within Biopython to this but I cannot find any hints on how to delete records from a fasta file. As SeqIO has a kind of list, I tried with the list.remove(list[0]) method but it doesn't work. Any idea on this? I case someone ask me to post the script, the script is about 200 lines long.
Thanks.

A: Here's something simple to get you started:
import sys
from Bio import SeqIO

filename = sys.argv[1]

sequences = []

for not_first, record in enumerate(SeqIO.parse(filename, 'fasta')):
    if not_first:
        sequences.append(record)

SeqIO.write(sequences, 'truncated-' + filename, 'fasta')

It's not optimal for lengthy sequences nor a large number of sequences where we want to avoid reading them all into memory but rather just process one at a time.  But it's a place to get started.


text:
Q: I want to remove '202103' in a list I have this list :
['20210301', '20210302', '20210303']
and i want to remove '202103' to have this list :
['01', '02', '02'].
I haven't found the right solution. Can you please help me?
Thank you.

A: Is this your expected result?
lst  = ['20210301', '20210302', '20210303']
to_remove = '202103'
res = []

for i in lst:
    if to_remove in i:
        res.append(i.replace(to_remove, ""))

print(res)

Hope so this is useful to you and solves your question.


text:
Q: extract indexes with sed I have a file containing:
toto.tata0.titi=any1
toto.tata1.titi=any2
toto.tata2.titi=any2
toto.tata3.titi=any1
toto.tata4.titi=any1
toto.tata5.titi=any2

I want to extract all the tata references which equal to any2
How I can do it with only one command ( sed for example)?
I can do it with 2 commands grep and cut
$ cat file | grep "toto\.[^.]\+\.titi=any2" | cut -d. -f2
tata1
tata2
tata5

A: You can use awk:
awk -F'=' '$2=="any2"{print $1}' file
toto.tata1.titi
toto.tata2.titi
toto.tata5.titi

OR if you just want middle part then:
awk -F'[.=]+' '$NF=="any2"{print $2}'  fff
tata1
tata2
tata5

A: With sed you can search for any line that ends with any2 and use two substitution commands, the first one to delete all characters until first . and the second one to delete from next . until the end:
sed -ne '/any2$/ { s/^[^.]*\.//; s/\..*$//; p }' infile

It yields:
tata1
tata2
tata5


text:
Q: R rename columns in many CSVs I have 200 csvs with the same two columns (date and level). However, the columns don't currently have names. They all need to have the same column names for a package I'm using in R. Is there a way to loop through all of the CSVs and give them all column names (the same column names, date and level)? I am new to R and don't have much experience writing loops.
For example, currently the data in each CSV looks like this:
09/21/1299 | 23
09/22/1999 | 25
09/23/1999 | 25

but I'd like it to look like this:
date       | level
09/21/1299 | 23
09/22/1999 | 25
09/23/1999 | 25

A: *

*Use list.files(path = "./", pattern = "*.csv)) to get names of all csv files

*Create a loop where you:

*

*read in each file

*assign column names to the data frame or matrix

*write to a new file (or overwrite the original)

A: In following code please change wanted_colnames which you wanted to assign to all columns. This code (with fixes if required) should read all csv inside folder files_folder (change it to give full path). At last you can rbind_fill/rbindlist on dfs to get full dataframe.
wanted_colnames <- c('var1', 'var2', 'var3')
files_folder <- '/files/folder/path'

docs <- list.files(files_folder)
dfs <- list()
for(doc in docs) {
   full_path <- file.path(files_folder, doc)
   dfs[doc] <- read.csv(full_path)
   names(dfs[doc]) <- wanted_colnames
}

A: To access all files in a folder you can use list.files, then you can read each of them with read.csv and lastly you should write them to new files with write.csv.
Overall you will have a code similar to following:
files <- list.files("path/to/directory/")
sapply(files, function(file){
                      x <- read.csv(file)
                      colnames(x) <- c("Col1", "Col2")
                      write.csv(paste0("new_", file),x)
}

A: I assume that you do not simply want to read the files, but actually modify the files such that they contain column headers.
In order for the following code to work, you need to define two variables: path should point to the folder, where the original files are stored. out_path should be the path to a folder, where the modified files should be stored. If the folder out_path does not exist, it will be created.
This piece of code reads all the csv files in path, adds the headers and writes the modified files to the folder out_path:
# create the output folder
# showWarnings = FALSE ensures that the function does not complain,
# even if the folder already exists
dir.create(out_path, showWarnings = FALSE)

# get the names of the input files with their full path
files <- list.files(path, "\\.csv", full.name = TRUE)

# loop through all the input files
for (file in files) {

  # read the file, specify the correct separator
  data <- read.table(file, sep = "|")

  # set the column names
  names(data) <- c("date", "level")

  # define the output file name: the file should be written to
  # out_path and have the same name as the original file
  outfile <- file.path(out_path, basename(file))

  # write the file. You need to specify the separator (|), and
  # omit row names and quotes
  write.table(data, outfile, sep = "|", row.names = FALSE, quote = FALSE)
}

The example file from your question will be turned into:
date|level
09/21/1299 |23
09/22/1999 |25
09/23/1999 |25

Note that the headers are not nicely aligned. If the files are read as csv files, this should not be a problem.


text:
Q: Calling Controller Class and passing value I am trying to create a menu using <ui>

</ui> tags. I am reading from an XML file and storing it in a List of(menu) object.
Menu Object:
Public Class MenuVM

#Region "Properties"
    Public Property ID As Integer
    Public Property Description As String
    Public Property Comments As String
    Public Property UserControlName As String
    Public Property AssemblyName As String
    Public Property ModelName As String
    Public Property SortOrder As Integer
    Public Property IsSelected As Boolean
#End Region

End Class

HomeController Class:
    Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        Dim oMenuHelper As New MenuHelper
        Return View("index", oMenuHelper.BuildMenu())
    End Function

    <HttpPost()> _
    Function Index(ByVal iSelect As Integer) As ActionResult
        Dim oMenuHelper As New MenuHelper
        Return View("index", oMenuHelper.BuildMenu())
    End Function

    Function About() As ActionResult
        Return View()
    End Function
End Class

ASPX PAGE:
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of List(OF MVCApp.MenuVM))" %>
<%@ Import Namespace ="MVCApp" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

    <% Using Html.BeginForm("Index", "Home")%>

        <% For Each item As MVCApp.MenuVM In Model%>

<%: Html.ActionLink(item.Description, "Index", "Home", New With {item.ID}, Nothing)%>

        <%Next%>

        <% End Using %>

</asp:Content>

The output:

When You click on view source the output is as follow:
<!DOCTYPE html>

<title>

    Home Page

</title><link href="Content/Site.css" rel="stylesheet" type="text/css" />

My MVC Application

        [ Log On ]

Home

About

    <form action="/" method="post">

Ballot Language

Assisting Absentee Voter

Instructions

Ballot Questions

        </form>

ERROR: When I Click on the link I am getting following error:

Could any one help with it. My intension is to pass menu id to controller and load appropriate usercontrol. I cannot use Javascript or jquery in this project as user might have javascript disabled on machine.

A: Try the link as /Home/Index/1 not /HomeController/Index/1

A: You should remove "controller" word from the links. The url should be:"/Home/Index/1".
To do so, modify the ActionLink code:
Html.ActionLink(item.Description, "Index", "Home", New With {item.ID}, Nothing)%>


text:
Q: C#: Create a generic method that can return an enum as List How can I create a generic method that receives an enum type and return its values and names as a list of strings, so I could loop this list and for each iteration I'll be able to print each of the enum values. For example, consider the next pseudo:
enum MyEnum { A=5, B=6, C=8 }

List<string> createEnumStrings(AnyEnum(??))
{
  List<string> listResult;

  // ??
  // a code that will generate:
  // listResult[0] = "Value 5 Name A"
  // listResult[1] = "Value 6 Name B"
  // lsitResult[2] = "Value 8 Name C"

  return listResult;
}

Again, note that this method can get any type of an enum

A: public List<string> GetValues(Type enumType)
{
    if(!typeof(Enum).IsAssignableFrom(enumType))
        throw new ArgumentException("enumType should describe enum");

    var names = Enum.GetNames(enumType).Cast<object>();
    var values = Enum.GetValues(enumType).Cast<int>();

    return names.Zip(values, (name, value) => string.Format("Value {0} Name {1}", value, name))
                .ToList();
}

now if you go with
GetValues(typeof(MyEnum)).ForEach(Console.WriteLine);

will print:
Value 5 Name A
Value 6 Name B
Value 8 Name C

Non-LINQ version:
public List<string> GetValues(Type enumType)
{
    if(!typeof(Enum).IsAssignableFrom(enumType))
        throw new ArgumentException("enumType should describe enum");

    Array names = Enum.GetNames(enumType);
    Array values = Enum.GetValues(enumType);

    List<string> result = new List<string>(capacity:names.Length);

    for (int i = 0; i < names.Length; i++)
    {
        result.Add(string.Format("Value {0} Name {1}",
                                (int)values.GetValue(i), names.GetValue(i)));
    }

    return result;
}


text:
Q: Barrels in College of Winterhold were reset, I lost tons of items
Possible Duplicate:
Where can I safely store my stuff?
How can I find a lost item?

I thought that the College dorm room was a "safe stash" area. I put all of my spare potions and ingredients in the right most barrel in the cluster of three barrels in the back of the room. Not only that but the entire room was reset and everything I took was replaced. I've read that barrels and rooms may be reset if you don't return frequently, but that was not the case for me. I'd only been away from my dorm room for two (in game) days.Is there a way to get my stashed items back now? If not, how the HELL do I prevent this from happening again aside from entering my room once per day?
Thanks!

A: I don't believe the College dorm room is a 'safe' area for storage. The UESP Wiki lists safe locations for storage in Skyrim, and the College dorm room area is not among them. Try one of the other locations there for storing your items, instead.
The comments in an answer at this related question to yours also state that the College dorm room area is not safe for storage.


text:
Q: How to return error from Rxjava Flowable when using LiveDataReactiveStreams? I am trying to return error from Rxjava stream but it shows error in return type.
Here is the code.

    private fun getCategories(): Flowable<Resource<List<Category>>> {
        return shopRepo.getCategories()
            .subscribeOn(Schedulers.io())
            .onErrorReturn { Resource.error(it.message) }
            .doOnSubscribe { Resource.loading(true) }
            .map{
                Resource.success(it)
            }
    }

    fun observeCategories(): LiveData<Resource<List<Category>>> {
        return LiveDataReactiveStreams.fromPublisher(getCategories())
    }

}

Here is my Resource Class
data class Resource<out T>(val status: Status, val data: T?, val message: String?) {
    enum class Status {
        SUCCESS,
        ERROR,
        LOADING
    }
    companion object {
        fun <T> success(data: T?): Resource<T> {
            return Resource(SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T?): Resource<T> {
            return Resource(ERROR, data, msg)
        }

        fun <T> loading(data: T?): Resource<T> {
            return Resource(LOADING, data, null)
        }
    }
}

I am unable to find any reference regarding this issue.

A: onErrorReturn would expect return type same as that of shopRepo.getCategories().
If you move the chain call for onErrorReturn after map, it would work as the map will transform the type.
shopRepo.getCategories()
        .subscribeOn(Schedulers.io())
        .map{ Resource.success(it) }
        .observeOn(AndroidSchedulers.mainThread()) // You'll need this probably to move it the UI thread.
        .onErrorReturn { Resource.error(it.message) }
        .doOnSubscribe { Resource.loading(true) }


text:
Q: MCE chunk size when reading from STDIN I'm writing a Perl program that processes a high number of log entries. To speed things up I'm using MCE to create a number of worker processes to handle processing in parallel. So far things are great, but I've found myself trying different chunk sizes in a very unscientific manner. Here's some background before I get to my question.
We're receiving logs from a number of syslog sources and collecting them at a central location. The central syslog server writes these log entries to a single text file. The program in question picks up the logs from this text file, does some munging, and ships them elsewhere. The raw log files are then archived.
To read the log files I'm doing this:
my $tail = 'tail -q -F '.$logdir.$logFile;
open my $tail_fh, "-|", $tail or die "Can't open tail\n";

I'm then using mce_loop_f to iterate over the file handle:
mce_loop_f { my $hr = process($_); MCE->gather($hr); } $tail_fh;

This works well for the most part, but if there is a spike in log activity the program starts to get bogged down. While there are a number of factors to make things "go faster" one of those factors I'm a little unsure of is chunk_size in MCE.
I understand that chunk_size has an "auto" value, but how would that work on a file handle that is a pipe from tail? Would auto be appropriate here?
What factors should I consider when adjusting the chunk_size? Log entries occur at a rate of 1000-2000 events per second depending on time of day (1000 at night, 2000 during the day).
I'm also a neophyte when it comes to MCE, so if mce_loop_f is a bad idea for this use case, please let me know.


text:
Q: Ext.Msg.confirm - Object [object Window] has no method '...' I am trying to set up a confirmation message on push of a logout button, where if the users clicks 'yes' then is redirected to panel control in a container called 'myContainer'. The message appears fine but when I select 'yes' I get an error (assuming because the container is not initialized). I have a reference set up on my controller to the container, but that does not seem to help. Any advise on how to handle confirmation correctly like this is appreciated. Thanks
Confirmation message:
onLogoutTap: function(button, e, options) {
Ext.Msg.confirm("Logout", "Do you wish to continue?", function(button){
    if (button == 'yes') {
    //doesn't work:
        this.getMyContainer().setActiveItem(1);
    } else {
        return false;
    }
});
}

myContainer reference in Controller
myContainer: '#myContainer'

Error message:
Uncaught TypeError: Object [object Window] has no method 'getMyContainer'

A: A little trick I often use is this
onLogoutTap: function(button, e, options) {
  var controller = this;
  Ext.Msg.confirm("Logout", "Do you wish to continue?", function (button) {
    if (button == 'yes') {
    //doesn't work:
        controller.getMyContainer().setActiveItem(1);
    } else {
        return false;
    }
  });
}

Like so, you can still access the function object with the keyword this.
Hope this helps

A: Here:
function(button){
    if (button == 'yes') {
    //doesn't work:
        this.getMyContainer().setActiveItem(1);
    } else {
        return false;
    }

this refers to your function object, not controller.
If you want to call that method of your controller, try:
Ext.getApplication().getController("your_controller_name").getMyContainer();
Hope it helps.

A: another way is
onLogoutTap: function(button, e, options) {
    Ext.Msg.confirm("Logout", "Do you wish to continue?", function(button){
        if (button == 'yes') {
        //DOES WORK!!
            this.getMyContainer().setActiveItem(1);
        } else {
            return false;
        }
    }, this);
}

just add the 'scope' parameter after function definition.


text:
Q: Where can I find good level creation tutorials for Little Big Planet 2? I would like to know how to create better/more advanced levels in little big planet 2. However, the in-game tutorials don't explain some things (like how to create cars, gates, etc). I think that the in-game tutorials just overview what tools you can use, not how to use them.
I would like to have something I can print to read while I create.

A: LittleBigPlanet Central has a pretty comprehensive list of tutorials.


text:
Q: How can I get the last value from a table using the generator with the best performance I want to get the last ID from table Client with the best performance without using MAX(). I have an ASC index for ID. I'm considering that my generator has a higher value than the last ID so I'm using this select:
SELECT FIRST 1 c.id FROM client c WHERE c.id <= GEN_ID(GEN_CLIENT_ID,0)

This select returns the first id from the table, I'm pretty sure that if I use AND after this select, I can get the last id, I just don't know how to do it.
I know that if I use ORDER BY DESC, I can get what I want, but it will not use the index and it will read all the values on the table.
I'm using Firebird 2.5.


text:
Q: Django: Field missing when queried I'm having some trouble querying for my CalculatedAmt field in my database. In fact, according to the error code, the field does not even exist. However, I have included it in my Models.py and it can even be seen in my admin interface on Django.
Here are my codes:
Model.py - I didn't join the tables because I didn't need the join for my queries
class Customer(models.Model):
    Customer_Name_P = models.CharField(max_length=30, default="missing")
    Customer_TelNo = models.CharField(max_length=8, default="missing")
    Postal_Code = models.CharField(max_length=6, default="missing")

def __str__(self):
        return "%s" % self.Customer_Name_P

class Transaction(models.Model):
    DocRef = models.CharField(max_length=10,default="missing")
    DocDate = models.DateField()
    AcCrIsMinus1 = models.CharField(max_length=10,default="missing")
    AcCurWTaxAmt = models.CharField(max_length=10,default="missing")
    HomeWTaxAmt = models.CharField(max_length=10,default="missing")
    CalculatedAmt = models.CharField(max_length=10, default="missing")
    ProjectCode = models.CharField(max_length=10,default="missing")
    Location = models.CharField(max_length=10,default="missing")
    Sales_Person = models.CharField(max_length=10,default="missing")
    AcCode = models.CharField(max_length=8,default="missing")
    Customer_Name = models.CharField(max_length=30,default="missing")

    def __str__(self):
        return "%s" % self.id

class Salesperson(models.Model):
    Sales_Person_P = models.CharField(max_length=10,default="missing",primary_key=True)
    Sales_Person_Name = models.CharField(max_length=10,default="missing")
    Sales_Person_Contact = models.CharField(max_length=10,default="missing")

    def __str__(self):
        return "%s" % self.Sales_Person_P

class Account(models.Model):
    AcCode_P = models.CharField(max_length=8, default="missing",primary_key=True)
    Customer_Name = models.CharField(max_length=30,default="missing")
    AcCur = models.CharField(max_length=3, default="missing")

    def __str__(self):
        return "%s" % self.AcCode_P

Query in shell (for a table):
Transaction.objects.all().filter(Sales_Person=Sales_Person).values('DocRef','DocDate','AcCrIsMinus1','HomeWTaxAmt','ProjectCode','Customer_Name','Location')

Error Message:
django.core.exceptions.FieldError: Cannot resolve keyword 'CalculatedAmt' into field. Choices are: AcCode, AcCrIsMinus1, AcCurWTaxAmt, Customer_Name, DocDate, DocRef, HomeWTaxAmt, Location, ProjectCode, Sales_Person, id

Here's a screenshot of a Transaction instance from the admin interface:
screenshot
Screenshot of the output for python manage.py showmigrations:
screenshot
Screenshot of migrations 0001_initial file
screenshot
Thank you!

A: This error does not say that the field is missing. The FieldError exception is raised when there is a problem with a model field. This can happen for several reasons:

*

*A field in a model clashes with a field of the same name from an
abstract base class

*An infinite loop is caused by ordering

*A keyword cannot be parsed from the filter parameters

*A field cannot be determined from a keyword in the query parameters

*A join is not permitted on the specified field

*A field name is invalid A query contains invalid order_by arguments

Just for your information, for a field which does not exist there is a FieldDoesNotExist exception. It is raised by a model's _meta.get_field() method when the requested field does not exist on the model or on the model's parents.
The error is because you are fetching all() first then try to filter. When you fetch all you get all fields and then not include CalculatedAmt in your values.
t = Transaction.objects.filter(Sales_Person__iexact=Sales_Person)

t object will be containing all the field of Transaction so no need for .values, you can retrieve them by t.CalculatedAmt for example. P.s. ixact means exact matching without caring for case-sensitiveness.
Moreover, I assume you have tried to connect 2 models together with Sales_Person field. But you are doing it in the wrong way.
You should use one of the OnetoOne, ForeignKey or ManytoMany relationships. I will use ForeignKey assuming that a salesperson can have many transactions but each transaction can only belong to one person.
class Transaction(models.Model):
DocRef = models.CharField(max_length=10,default="missing")
DocDate = models.DateField()
AcCrIsMinus1 = models.CharField(max_length=10,default="missing")
AcCurWTaxAmt = models.CharField(max_length=10,default="missing")
HomeWTaxAmt = models.CharField(max_length=10,default="missing")
CalculatedAmt = models.CharField(max_length=10, default="missing")
ProjectCode = models.CharField(max_length=10,default="missing")
Location = models.CharField(max_length=10,default="missing")
Sales_Person = models.ForeignKey('Salesperson', on_delete=models.CASCADE)
AcCode = models.CharField(max_length=8,default="missing")
Customer_Name = models.CharField(max_length=30,default="missing")

def __str__(self):
    return "%s" % self.id

class Salesperson(models.Model):
    Sales_Person_P = models.CharField(max_length=10,default="missing",primary_key=True)
    Sales_Person_Name = models.CharField(max_length=10,default="missing")
    Sales_Person_Contact = models.CharField(max_length=10,default="missing")

    def __str__(self):
        return "%s" % self.Sales_Person_P


text:
Q: RestKit managed object created on GET returns false for bool always I am doing a GET call with rest kit with an entity mapping which has a boolean isPrimary. The call is successful and the mapping array also has the correct value for isPrimary when i nslog it. But when i retrieve the entity form core data using a simple fetch request with out any predicate the value is always "false". All non boolean vars are correct. Any help is much appreciated.cheers
The Header:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "StringBase.h"

@class MaterialPlantRel, PriceList, SalesOrder;

@interface Currency : StringBase

@property (nonatomic, retain) NSNumber * baseCurrency;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) SalesOrder *billingCurrencyInv;
@property (nonatomic, retain) PriceList *currencyTOInv;
@property (nonatomic, retain) MaterialPlantRel *ledgerCostCurrencyInv;
@property (nonatomic, retain) SalesOrder *paymentCurrencyInv;
@property (nonatomic, retain) MaterialPlantRel *replacementCostCurrencyInv;

// Returns a dictionary representation of the
// object with var keys and values;
-(NSDictionary*) getDictionaryRepresentation;

/** Override to map the values to object **/
-(void) setValuesForKeysWithDictionary:(NSDictionary *)keyedValues;

@end

output JSON on success:
        Sucess Currency (
        "<Currency: 0xda70f30> (entity: Currency; id: 0xb07e980 <x- coredata://C145A537-         5E8B-4E4E-95C1-BDFF10C84B05/Currency/p151> ; data: {\n    active = 1;\n    baseCurrency =    1;\n    billingCurrencyInv = nil;\n    code = BRL;\n    createdBy = nil;\n    currencyTOInv = nil;\n    ledgerCostCurrencyInv = nil;\n    modifiedBy = nil;\n    name = \"Brazilian Riaz\";\n    paymentCurrencyInv = nil;\n    replacementCostCurrencyInv = nil;\n    version = 1;\n})",
       "<Currency: 0xda6c0b0> (entity: Currency; id: 0xb07d000 <x-coredata://C145A537-5E8B-4E4E-95C1-BDFF10C84B05/Currency/p152> ; data: {\n    active = 1;\n    baseCurrency = 0;\n    billingCurrencyInv = nil;\n    code = USD;\n    createdBy = nil;\n    currencyTOInv = nil;\n    ledgerCostCurrencyInv = nil;\n    modifiedBy = nil;\n    name = \"US Dollars\";\n      paymentCurrencyInv = nil;\n    replacementCostCurrencyInv = nil;\n    version = 1;\n})"
        )

CoreData fetch :

        NSFetchRequest* fetchRequest = [NSFetchRequest        fetchRequestWithEntityName:@"Currency"];
       // get the managed object context
       NSManagedObjectContext* l_MOC = [[[RestKitConfig ConfigManager] AppDelegateSales] managedObjectContext];
       // setup entity description
       NSEntityDescription* entityDescription = [NSEntityDescription
                                              entityForName:@"Currency"
                                              inManagedObjectContext:l_MOC];
       // fetch the request
      [fetchRequest setEntity:entityDescription];

    // Set example predicate and sort orderings...
    NSError* error;
    NSArray* array = [l_MOC executeFetchRequest:fetchRequest error:&error];

    if ([array count] > 0)
    {
        // copy of the retrieved data
        self.data = [array copy];
#ifdef _DEBUG
        NSLog(@"Currency Data retrieved : %i Objects",[array count]);
        for (int i = 0; i < [array count]; i++)
        {
            Currency* l_currency = [array objectAtIndex:i];
            NSLog(@"base currency -> %@",l_currency.baseCurrency);
        }
#endif

Output :
2014-05-28 13:07:03.187 Sales[2110:1003] base currency -> 0
2014-05-28 13:07:03.187 Sales[2110:1003] base currency -> 0

A: When using a managed object context in a multi-threaded environment you need to be careful to use the context only on the intended thread. The main thread has a specific context and each background thread must have a new context created for it. If you use the wrong context for a thread (or access a private queue context without using the private queue) then you will see strange issues and / or exceptions. The type of issues you will see depend on what is already saved into the context and what operations you try to perform, but it will generally never be correct.
So, take care to use only the appropriate context and that the relationships between contexts ensure that newly saved data is notified and updated where you need it.


text:
Q: clamd PING give ERROR: initgroups() failed? My ubuntu version is 12.04.
I have installed clamav as root user using the below commands.
apt-get install clamav
apt-get install clamav-daemon

But when I use the below command
clamd PING

It gives below error message.
ERROR: initgroups() failed

Am I missed anything?


text:
Q: Swift 3: How to retry Firebase upload on failure I'm initializing some data in Firebase that I will use to track a user's activity. I need to make sure this data is written to Firebase so I'm wondering what the best practice is for ensuring a critical upload was successful?
static func createUserActivityCounts(uid: String) {
        DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + .seconds(5)) {
            let databaseReference = Database.database().reference()
            let userCounts: [String: Any] = ["posts": 0,
                                             "comments": 0,
                                             "likes": 0]
            databaseReference.child("userActivity").child(uid).child("counts").setValue(userCounts) { (error, ref) -> Void in
                if error != nil {
                    print(error!.localizedDescription)
                }
            }
        }
    }

A: I think the best way to resolve this issue is to check if the value exists whenever you attempt to query a critical upload. If the value isn't there then you initialize it. Here is the function I wrote to handle this.
private func getUserActivityCounts() {
    if let uid = Auth.auth().currentUser?.uid {
    userRef.child("userActivity").child(uid).child("counts").observeSingleEvent(of: .value, with: { snap in
            if !snap.exists() {
                // create user counts
                if let uid = Auth.auth().currentUser?.uid {
                    DatabaseFunctions.createUserActivityCounts(uid: uid)
                }
            }
            if let counts = snap.value as? [String: Any] {
                if let numberOfLikes = counts["likes"] as? Int, let commentCount = counts["comments"] as? Int, let postCount = counts["posts"] as? Int {
                    DispatchQueue.main.async {
                        self.headerRef.postCount.text = String(postCount)
                        self.headerRef.commentCount.text = String(commentCount)
                        self.headerRef.likeCount.text = String(numberOfLikes)
                        self.collectionView.reloadData()
                    }
                    self.numberOfUserPosts = postCount
                    self.commentCount = commentCount
                    self.likeCount = numberOfLikes
                }
            }
        })
    }
}


text:
Q: Format syntax when adding values I am trying to add several values of a tuple together using format(). I wrote a function that returns a tuple with 12 values.
My tuple looks like this:
In[86]results
Out[86]: (15.24, 2527.4, 2812.59, 7.87, 2389.72, 1795.39, 594.33, 98.34, 68.84, 60.0, 132, 5)
I have been printing to stdout like this (based on format examples from docs.python.org):
print('-Sponge Yeast: {0[0]}g'.format(results))
print('-Sponge Flour: {0[1]}g'.format(results))
print('-Sponge Water: {0[2]}g'.format(results))
I want to print another line that is the sum of the first 3 values in results.
In the past, I could do it like this:
print('-Total Sponge Weight: {:n}g'.format(a+b+c))
where a, b, c...,i equal the 12 values respectively.
Instead of creating 12 variables for the 12 values of the tuple, I want to use a single variable for the tuple. But, how can I sum several values in the tuple and use the format()? I've tried:
print('-Total Sponge Weight: {0[0] + 0[1] + 0[2]}g'.format(results))
print('-Total Sponge Weight: {:n}g'.format(0.results + 1.results + 2.results))
But this does not work. I do know I can simply have my function output the correct value, and I can refer to it as {0[xx]}. Just wondering if there is another way.

A: You might be able to use pprint. I've never used it myself, but it is designed for formatted printing of data.

A: Using Python 3's f-Strings, this is easy.
values = (1, 2, 3)
In[1]: f'The sum of values is {values[0]+values[1]+values[2]}!
Out[1]: 'The sum of values is 6!


text:
Q: finding overlap between two large lists I have two very large lists P and Q and would like to find items in P that are also in Q. I read other threads that suggest using sets, but I'm not sure if that's necessary. I think the following line satisfies the need:
overlap = [l for l in P if l in Q]

However, I'm wondering if this is a reasonable and fastest way to find the overlap or you would suggest using sets?
Thanks.

A: As suggested by @AChampion sets are more efficient for this purpose. Here is the code for those who are interested. You just need to convert the larger list, say Q, to a list, then
 larger_list_set = set(Q)
 overlap = [l for l in P if l in larger_list_set]

is more efficient.


text:
Q: How to accept feign response in application/xml I am invoking 3rd party API which returns a response in XML format.
As I have not created any POJO to hold response in my consumer service I am using java.lang.Object for same.
I am getting the below error.
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.Object] and content type [application/xml]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:126) ~[spring-web-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.cloud.openfeign.support.SpringDecoder.decode(SpringDecoder.java:59) ~[spring-cloud-openfeign-core-2.2.5.RELEASE.jar:2.2.5.RELEASE]
    at org.springframework.cloud.openfeign.support.ResponseEntityDecoder.decode(ResponseEntityDecoder.java:62) ~[spring-cloud-openfeign-core-2.2.5.RELEASE.jar:2.2.5.RELEASE]

My feign client code
@FeignClient(value = "SERVICE", url = "https://goog.dummyservice/api1/v1", decode404 = true)
public interface UserFeign {

    @GetMapping(value = "/docs/{profile}/{protocol}", consumes = MediaType.APPLICATION_XML_VALUE)
    Object getUserData(@RequestHeader("Authorization") String token,
                         @PathVariable("profile") String profile,
                         @PathVariable("protocol") String protocol);
}

I wanted to know how to hold XML response through feign.

A: FeignClientConfiguration.java
@Configuration
@RequiredArgsConstructor
public class FeignClientConfiguration {

private final ObjectFactory<HttpMessageConverters> messageConverters;

@Bean
public Encoder feignFormEncoder() {
    return new FormEncoder(new SpringEncoder(messageConverters));
}

/*@Bean
public Decoder feignDecoder() {
    MappingJackson2XmlHttpMessageConverter c = new MappingJackson2XmlHttpMessageConverter();
    ObjectFactory<HttpMessageConverters> objectFactory = () ->new HttpMessageConverters(c);
    return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}*/

}

ConsultaClient.java
    @FeignClient(url = "${api.serpro.url}",
            name = "name",
            configuration = FeignClientConfiguration.class)
    public interface ConsultaClient {

    @PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    @Headers("Content-Type: application/x-www-form-urlencoded")
    List<DocumentoDTO> getData(ParamsDTO params);
}

A: The steps sequence below helped me to solve this problem:
1 - Add the jackson-dataformat-xml dependence to your pom.xml
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.14.1</version>
</dependency>

2 - Add this customized Config in UserFeign.java
@FeignClient(value = "SERVICE", url = "https://goog.dummyservice/api1/v1", decode404 = true, configuration = UserFeign.Configuration.class)
public interface UserFeign {

@GetMapping(value = "/docs/{profile}/{protocol}", consumes = MediaType.APPLICATION_XML_VALUE)
Object getUserData(@RequestHeader("Authorization") String token,
                     @PathVariable("profile") String profile,
                     @PathVariable("protocol") String protocol);

class Configuration {
    @Bean
    public Decoder feignDecoder() {
        return (response, type) -> {
            String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
            JavaType javaType = TypeFactory.defaultInstance().constructType(type);
            return new XmlMapper().readValue(bodyStr, javaType);
        };
    }
}

}


text:
Q: Gluster Arbiter-3 StorageClass volumetype in kubernetes-gluster? What volumetype would I use in my kubernetes-gluster StorageClass for arbiter-3 volumes?

A: In the parameters section of the StorageClass you can
volumeoptions: user.heketi.arbiter true

Any PVCs provisioned through that StorageClass will have one arbiter and two data bricks.

A: If you want to configure Gluster volumes manually, there is no difference for Kubernetes what to mount - the regular GlusterFS volume or the GlusterFS Arbiter-3 volume. So, Volume Type should be glusterfs and you need to provide only the Volume name. Here is the example, more information is here:
"volumes": [
  {
    "name": "glusterfsvol",
    "glusterfs": {
      "endpoints": "glusterfs-cluster",
      "path": "kube_vol",
      "readOnly": true
    }
  }
]

If you want Kubernetes to provision Gluster volumes automatically, you need to dig deeper. Use these instructions from GitHub.


text:
Q: Problem writing 'pipe' symbol on danish keyboard (Ubuntu 12.04 server, console) I just installed Ubuntu 12.04 Server (32-bit) on an old machine, and have problems writing the | (pipe) symbol. I have no graphical UI installed.
My keyboard has danish layout, and all other symbols than |, that I have needed, work perfectly. If I change to e.g. US layout, I can write |, but of course through a combination that makes little sense on my keyboard, and makes be unable to write special danish symbols that I need.
In /usr/share/X11/xkb/symbols/dk, under section xkb_symbols "basic" there is the line
key <AE12> { [ dead_acute, dead_grave, bar, brokenbar ] };

which, as I see it, points to the correct key (5th row from bottom, 13th key from left, just to the left of backspace). Also the acute and grave keys works.
I also tried changing to 'eliminate dead keys' (which has a similar line) to no avail.
It's not that AltGr is broken either, since it works well on other key combinations.
Any suggestions as to what may be wrong?

A: Seems to have been an old-crappy-keyboard-issue - just connecting another keyboard fixed it. Hope I didn't waste anyone's time on this.


text:
Q: Are token elements required in MathML? As the question title states, is it okay to write just
<math>a <msup>x 2</msup> + b x + c</math>

or do you really need to write
<math>
  <mrow>
    <mi>a</mi> <mo></mo> <msup><mi>x</mi><mn>2</mn></msup>
    <mo>+</mo><mi>b</mi><mo></mo><mi>x</mi>
    <mo>+</mo><mi>c</mi>
  </mrow>
</math>

As far as Firefox goes it doesn't render a

Invalid Markup

error, but that hardly means other browser might not in the future if the spec actually prohibits it officially.

A:
As the question title states, is it okay to write just
<math>a <msup>x 2</msup> + b x + c</math>

No, it isn't.

do you really need to write
<math>
  <mrow>
    <mi>a</mi> <mo></mo> <msup><mi>x</mi><mn>2</mn></msup>
    <mo>+</mo><mi>b</mi><mo></mo><mi>x</mi>
    <mo>+</mo><mi>c</mi>
  </mrow>
</math>

Yes, see http://www.w3.org/TR/MathML3/chapter2.html#fund.syntax.

As far as Firefox goes it doesn't render a "Invalid Markup" error, but that hardly means other browser might not in the future if the spec actually prohibits it officially.

At the begin browsers render a "Invalid Markup" error for anything that doesn't follow the spec. Today browsers try to correct the markup. For example

foo

bar

is invalid since you need to use

foo

bar

but no browser will stop rendering the page because of it.

A: MathML is intended for mathematics presentation markup. It is aimed to provide all information needed for correctly typesetting a mathematical formula.
In mathematical typesetting, identifiers (or, simply "variables"), operators and numbers are typeset differently. There are a lot of subtle differences, but to name a few: identifiers are normally italic style (and use a mathematical serif font), whereas numbers are roman style. Operators use subtle spacing rules on either side. These are just a few examples.
As presentation MathML is not intended to describe the meaning of a formula, merely how it looks, all this information must be encoded in the markup. The MathML renderer does not interpret the formula, either. It looks at the markup and renders accordingly.
Authoring MathML directly is not easy, and, in fact, it is mostly done programmatically, rather than inputting directly. If you need a more straightforward way, try ASCIImath or LaTeX. A renderer like MathJax renders those as well.


text:
Q: what does it mean by 'invalid command name ".!canvas"' import turtle

wn = turtle.Screen()
wn.title("ping pong")
wn.bgcolor("black")
wn.setup(width=800, height= 600)
wn.tracer(0)

#Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.penup()
paddle_a.goto(-350, 0)

#Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.penup()
paddle_b.goto(350, 0)

#Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2

# Function
def paddle_a_up():
    y = paddlea.ycor()
    y += 20
    paddle_a.sety(y)

def paddle_a_down():
    y = paddlea.ycor()
    y -= 20
    paddle_a.sety(y)

def paddle_b_up():
    y = paddlea.ycor()
    y += 20
    paddle_b.sety(y)

def paddle_b_down():
    y = paddlea.ycor()
    y -= 20
    paddle_b.sety(y)

#Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")

#Main game loop
while True:
    wn.update()

    #move the ball
    ball.setx(ball.xcor() +ball.dx)
    ball.sety(ball.ycor() + ball.dy)

    #Border checking
    if  ball.ycor() > 290:
        ball.sety(290)
        ball.dy *= -1

    if  ball.ycor() < -290:
        ball.sety(-290)
        ball.dy *= -1

    if ball.xcor() > 390:
        ball.goto(0,0)
        ball.dx *= -1

    if ball.xcor() < -390:
        ball.goto(0,0)
        ball.dx *= -1

    #Paddle and ball collisions
    if (ball.xcor() > 340 and ball.xcor() < 350) and
(ball.ycor() <
paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() -40):
        ball.setx(340)
        ball.dx *= -1

    if (ball.xcor() < -340 and ball.xcor() > -350) and
 (ball.ycor() <
  paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() -40):
        ball.setx(-340)
        ball.dx *= -1

I am unable to move paddle b completely it allows me to move paddle b up or down by only 5 pixels and how should I change the speed of the ball which is too fast. I am using the community version of visual studio 2019. as soon as I end the process it takes me to the ball part of the code displays  'invalid command name ".!canvas"'

A: You're trying to reference paddlea but it is defined as paddle_a so you need to be consistent and use paddle_a like it is named above.
As for paddle speed, it looks like the ball speed is controlled here:
    #move the ball
    ball.setx(ball.xcor() +ball.dx)
    ball.sety(ball.ycor() + ball.dy)

So, the position gets modified by dx and dy, so, modifying those variables where they're set above to
ball.dx = 2
ball.dy = 2

would adjust the speed of the ball.


text:
Q: Java Filter URL pattern specific to request params We have a situation where we want to use filter for URL's containing some specific request parameters, e.g:

http://mydomain.com/?id=78&formtype=simple_form&.......
http://mydomain.com/?id=788&formtype=special_form&.......

and so on, id are fetched at run time, I want configure filter in web.xml only if formtype=special_form. How should achieve the solution? Can Filter be configured with regex patterns?

A: As far as I know there is no solution for matching requests to filters by query string directly in web.xml. So you could register the filter in your web.xml using init-params to make the filter configurable and set a pattern via void init(FilterConfig filterConfig) in your javax.servlet.Filter implementation.
package mypackage;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class MyFilter implements Filter {

    private String pattern;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // check whether we have a httpServletRequest and a pattern
        if (this.pattern != null && request instanceof HttpServletRequest) {
            // resolve the query string from the httpServletRequest
            String queryString = ((HttpServletRequest) request).getQueryString();
            // check whether a query string exists and matches the given pattern
            if (queryString != null && queryString.matches(pattern)) {
                // TODO do someting special
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.pattern = filterConfig.getInitParameter("pattern");
    }

}

The configuration would look like this in your web.xml:
<!-- MyFilter -->
<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>mypackage.MyFilter</filter-class>
    <init-param>
        <param-name>pattern</param-name>
        <param-value>{{PATTERN HERE}}</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Further readings:
http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html

A: You must parse the URL params in the body of the filter, not in web.xml;
I made such a thing, but I used a phase listener, a configuration entry (in a configuration file) that mapped URL params to FQN of classes that handle a particular "action" (by action I mean a URL param from a GET/POST); than, the phase listener would parse all the URL params from each GET/POST and send each of them to a Dispatcher. The Dispatcher's job is to call the right handler (singleton object corresponding to the FQN for that URL param). The handler then just does the specific thing with the URL value he receives.
The same thing can be made by using a filter instead of phase listener.


text:
Q: Collision between kinematic bodies in Bullet Physics I'm working with Bullet Physics Engine.
My created world is based on:

*

*Static Object --> Ground

*Dinamic Object --> Is going to be moved by other objects.

*2 Kinematic objects --> They are going to move the dinamic one. I need to control them from outside, so that I need kinematic objects.

The collision between each kinematic and the dinamic works as expected.
However, when one kinematic collide with the other, it oversteps and I need them to collide and "react" to that collision (like a Dinamic body)
I've been looking for an answer but I have not found any solution.
What can I do?
Thanks

A:
I need to control them from outside, so that I need kinematic objects

This assertion isn't entirely accurate. Dynamic objects can also be controlled.

However, when one kinematic collide with the other, it oversteps and I need them to collide and "react" to that collision (like a Dinamic body)

Kinematic bodies don't collide/react with each other within the engine. One could reproduce that code externally to make them react but lets not go there. If you have to have those bodies that you've created as kinematic bodies react with other bodies that are also kinematic, then I suggest using dynamic bodies instead.

What can I do?

Instead of creating those bodies as kinematic bodies:

*

*Create them as dynamic bodies; and

*use a force/impulse-based constraint mechanism to "control" them.


text:
Q: Bootstrap collapse accordion with full height panels (without JqueryUI) How can I use collapse panels with full heights?

Like this question: Twitter Bootstrap accordion full height panes
But without jquery UI and only with bootstrap?
I tried this: http://jsfiddle.net/5xdp9prh/
$('#collapseTwo').collapse('show').height('auto');

But it doesn't work.

A: I found this quick trick :
.collapse.in{
    height: 100vh;
}

The vh means view height, it also works with vw for for view width if you want an element to be as wide as the window.
One unit represents 1/100 of the size of the viewport you are using :)
Here is a working example.
https://jsfiddle.net/bebwgwj0/
Moreover this is supported by all modern browsers.


text:
Q: Set maskedinput for wordpress Hello, I make site on the WordPress and I need to set phone mask on checkout page.
I got file jquery.maskedinput.min.js from GitHub and uploaded it on the hosting on the way:
wp-content/themes/woodmart-child/js/

Then I added script in the function.php of Child Theme:
add_action('wp_enqueue_scripts', 'my_maskedinput', 10);
function my_maskedinput() {
    if (is_checkout()) {
        wp_enqueue_script('maskedinput', '/wp-content/themes/woodmart-child/js/jquery.maskedinput.min.js', array('jquery'));
        add_action( 'wp_footer', 'masked_script', 999);
    }
}
 function masked_script() {
    if ( wp_script_is( 'jquery', 'done' ) ) {
?>
    <script type="text/javascript">
        jQuery( function( $ ) {
            $("#billing_phone").mask("+7(999)999-99-99");
        });
    </script>
<?php
    }
}

But the phone mask doesn't show on the checkout page. I check in the DevTools, the code
<script type="text/javascript">
    jQuery( function( $ ) {
        $("#billing_phone").mask("+7(999)999-99-99");
    });
</script>

is added in the html file. But where is mistake? What do I do wrong?
upd: I so tried make it through str_replace (and it doesn't work too):
add_filter( 'woocommerce_form_field', 'my_maskedinput', 20, 4 );
function my_maskedinput( $field, $key, $args, $value ) {
    // Only on checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ) {
        $phone = ' <input type="tel" class="input-text " name="billing_phone" id="billing_phone" placeholder="Номер телефона" value autocomplete="tel">';
        $field = str_replace( $phone, ' <input type="tel" class="input-text" name="billing_phone" id="billing_phone" placeholder="Номер телефона" value autocomplete="tel" mask="+7 (999) 999-99-99">', $field );
    }

    return $field;
}

A: I check file jquery.maskedinput.min.js and it doesn't contain right script.
I got file from here and uploded it on the hostin. Then it work!


text:
Q: HoloEverywhere: Dark action bars and dialogs I'm using HoloEverywhere library, I need action bars and dialogs (ProgressDialog and AlertDialog) to be styled with the Holo Dark theme and the rest of the controls with the Holo Light.
I set the application theme to Holo.Theme.Light.DarkActionBar (this is the closest to what I need so far) but with this I get Light dialogs.
How can I achieve this?
Thanks in advance.

A: Create new context wrapper for dialogs:
Context dialogContext = new ContextThemeWrapper(this, R.style.Holo_Theme);
Dialog dialog = new AlertDialog.Builder(dialogContext).create();


text:
Q: How do I use Doctrine2 to work with GeoSpatial Queries using PostGIS? I have a public facing app that is based on Postgres and PostGIS.
I have tried Googling for hours but have been unable to find any documentation that can show some basic geospatial stuff like getting distance between two points using Doctrine2. Not being able to use an ORM is a big deal for me in terms of determining my database of choice.
Can someone show me a basic example of lets say showing all points within a radius of lets say 10 miles using Doctrine?

A: I wrote an article on my blog, explaining how to use Doctrine 2 (version 2.2+) and Postgis. The article is in French, but the code is PHP, which an international language :
http://web.archive.org/web/20161118060448/http://blog.fastre.info:80/2012/02/doctrine2-2-2-et-types-geographiques/
As you will see, importing data from database to an object need some conversion:

*

*The data are converted to geojson by postgis (json is readable by php, using json_decode function)

*The data are transformed into a Point object

And from the object's world to database:

*

*The object Point is converted into WKT. Why WKT and not json ? Because Postgis has a ST_GeogFromWKT function, but not (yet) a ST_GeogFromGeoJson function.

*The data are inserted into the database.

I also wrote a custom DQL function class which dealt with the "covered" operation in DQL queries. This is not exactly what you ask, but you may inspire from this and adapt the code.
namespace Progracqteur\WikipedaleBundle\Resources\Doctrine\Functions;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;

/**
*
* @author Julien Fastré <julien arobase fastre point info>
*/
class Covers extends FunctionNode {

    private $polygon = null;
    private $point = null;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) {
        return 'ST_Covers('.$this->polygon->dispatch($sqlWalker).', '.$this->point->dispatch($sqlWalker).')';
    }

    public function parse(\Doctrine\ORM\Query\Parser $parser) {

        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->polygon = $parser->StringExpression();

        $parser->match(Lexer::T_COMMA);

        $this->point = $parser->StringPrimary();

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);

    }
}

and this function is added to doctrine using app/config/config.yml :
        dql:
          string_functions:
            covers: Progracqteur\WikipedaleBundle\Resources\Doctrine\Functions\Covers

Be careful: to use this function, you will have to create other functions which will use the 'ST_FromWKT' function before, and convert your point to WKT in your getSql (using the __toString function ?). I did not need it in my application, so I do not have code for this to present to you.
This is an example of using my function : ($entity->getPolygon() return the postgis's string, without any conversion - i do not need to dealt with a polygon's object in my app.)
$em->createQuery('SELECT p from MyEntity p where covers(:polygon, p.geom) = true)
            ->setParameter('polygon', $entity->getPolygon());

A: I know this is a little bit old but may help others.
I've found this library:
https://github.com/djlambert/doctrine2-spatial
They support Postgis and MySQL.
The Postgis functions are:

*

*ST_Area

*ST_AsBinary

*ST_AsText

*ST_Centroid

*ST_ClosestPoint

*ST_Contains

*ST_ContainsProperly

*ST_CoveredBy

*ST_Covers

*ST_Crosses

*ST_Disjoint

*ST_Distance

*ST_Envelope

*ST_GeomFromText

*ST_Length

*ST_LineCrossingDirection

*ST_StartPoint

*ST_Summary


text:
Q: If statement missing ( in function main. cant get passed this error #include <stdio.h>

int main()
{
int khm;

printf("Please enter how fast the vehicle was going in km//h: ");
scanf("%d%*c", &khm);

    if khm>60 khm<65
    {
        printf("Issue a warning: ");
    }
    else

        if khm>65 khm<70
        {
            printf("Issue a fine of $80: ");
        }
        else

            if khm>70 khm<80
            {
                printf("Issue a fine of $150: ");
            }
            else

                if khm>80
                {
                    printf("Issue a fine of $500: ");
                }
                else
                {
                    printf("This vehicle is not speeding: ");
                }

        return(0);
}

A:  #include <stdio.h>

 int main()
{
 int khm;

 printf("Please enter how fast the vehicle was going in     km//h: ");
 // error
 scanf("%d", &khm);
// this is how we should write..
if (khm>60 && khm<65)
{
    printf("Issue a warning: ");
}
else

    if (khm>65 && khm<70)
    {
        ("Issue a fine of $80: ");
    }
    else

        if( khm>70 &&  khm<80)
        {
            printf("Issue a fine of $150: ");
        }
        else

            if( khm>80)
            {
                printf("Issue a fine of $500: ");
            }
            else
            {
                printf("This vehicle is not speeding: ");
            }

    return(0);
 }

A: Besides the fact you didn't use parantheses (),
This is the correct syntax for an AND operator in C:
if ((khm > 60) && (khm < 65))
{
   // code
}

A: *

*if khm>60 khm<65

*if khm>65 khm<70

*if khm>70 khm<80

*if khm>80
These 3 if-statements are syntactically incorrect for 2 reasons:
Firstly:

If statement missing ( in function main

The compiler is telling you in this error message that you need to use parentheses (like ()) to enclose the conditional statement of an if-statement. In general, this also applies while-loop condition statements and for-loop condition statements.
Secondly, in the if-statements where you have multiple conditions (like khm>70 khm<80), you need to specify a logical AND or OR operator in between these 2 conditions. These 2 conditions tell the compiler whether you want both the conditions satisfied to enter the body of the if-statement (this is done with the AND operator), or you simply want one of these conditions to be satisfied (this is done with the OR operator).

*

*The AND operator has the following symbol: &&

*The OR operator has the following symbol: ||
Judging from your case, you will need the && operator.
As an aside, you can shorten your code a lot and make it easier to read of you put the else and if-statement on the same line. Instead of doing:
else
    if (khm > 65 && khm < 70)

You can do:
else if (khm > 65 && khm < 70)

Therefore, change your code to:
if (khm > 60 && khm < 65)
    // Add your code here

else if (khm > 65 && khm < 70)
    // Add your code here

else if (khm > 70 && khm < 80)
    // Add your code here

else if (khm > 80)
    // Add your code here

else
    // Add your code here


text:
Q: Synonym for character (as in a person in a book) A story normally consists of several characters (i.e. the protagonist, the antagonist, and so forth), but is there a good synonym for the word character? I've often used "people", but it seems overly general.

A: You can try 'personage', or 'figure'.
If you were to refer to the cast in general, maybe you could use 'dramatis personae', although that seems a bit grand / presumptuous.
For example, if you were writing a sordid piece of tabloid gossip, then 'dramatis personae' won't lend you a patina of respectability. Instead it looks overdone, like gaudy cheap jewelry. :D
On the other hand, if it was a review of a stage play or a novel, then dramatis personae is acceptable, though a bit heavy and somber (which may or may not be what you want).

A: Most of the answers seem to refer to a play, rather than a book. I shall also, but I offer less formal alternatives:

*

*players

*
*

*major players

*
*

*minor players

*
*

*bit players

In addition you might, if appropriate, refer to a cameo appearance.  https://en.m.wikipedia.org/wiki/Cameo_appearance
(by the way, the above work best for fiction; for non-fiction you might prefer figures, as was suggested earlier.)

A: I can't think of a close synonym for character in this sense. To refer to all the characters collectively, you can use dramatis personæ

Dramatis personæ (Latin: "persons of the drama") is a phrase used to refer collectively, in the form of a list, to the main characters in a dramatic work. Such lists are commonly employed in various forms of theater, and also on screen. Typically, off-stage characters are not considered part of the dramatis personæ. It is said to have been recorded in English since 1730, and is also evident in international use. However, the term is closely associated with the works of William Shakespeare and appears in the original publication of the First Folio, published in 1623.

It is usually applicable to plays, but can be loosely used for other works.
Example sentences from Vocabulary.com:

*

*The draw of "Scandal" has always been its schizophrenic pacing and the elaborate, interconnected backstories of its dramatis personae.

*Perhaps the most fascinating of these dramatis personae is Zukor, nicknamed "Creepy" by his employees for his habit of speaking sparingly and softly.
The second sentence shows how you can use the term for a singular character by paraphrasing a little.

A: I understand your hesitation with the terms protagonist, antagonist, character. The terms are Greek, mainly referring to drama and from an older time. Today when we talk about novels such terms look like anachronisms.
I speak of central figure or central person of a novel. The term dramatis personae, Latin, refers only to a theater play and it is an old term as well.

A: Although I support the usage of 'figure', I will propose an alternative other than those already suggested.
Although mainly used in plays or scripts, the term 'Actor' can be used in the same context. This can be seen in other usages such as video games where it is sometimes common practice to term all people in the game as 'actors'. I think it is applicable in this usage due to many games being broken into 'scenes' or levels.
I would hesitate to use this terminology in terms of books, but it is could be used in consideration to that parts the (character/figure/etc) has to play in the story. The 'actor' may play a very minor part, or a major part, but they still influence the experience in some way.


text:
Q: Is it impossible to use "the current" domain for "Header add Access-Control-Allow-Origin"? I currently use this which works perfectly in allowing cross-domain Ajax requests.
SetEnvIf Origin "^http(s)?://(.+\.)?(my-specified-domain\.com)$" origins_is=$0
Header add Access-Control-Allow-Origin %{origin_is}e env=origin_is�
Header add Access-Control-Allow-Credentials: true�

However, is it possible to do this without hard-coding the domain name?
I believe you can't embed a variable inside SetEnv and I just can't see a way to allow the alternative scheme, whatever domain you are hosting the site on.
Surely this is an obvious and essential requirement. Who wants to hard-code the domain every time?
Maybe the best way would be to match up against the ServerName setting (e.g. in the virtual host). If the URL matches that (regardless of scheme) then allow the cross-domain request.

A: You can:
Header add Access-Control-Allow-Origin *

But I think it's too permissive, I dont recommend it for a production website.
Edit:
I havent tried but with something similar you should get the origin based on http Origin header:
SetEnvIfNoCase Origin ^(.*)$ origin=$1


text:
Q: Robolectric (Android): Using ShadowLocationManager ? Is it configurable? I have been using Robolectric quite successfully up until now. I have an activity that gets the location manager. Now according to the documentation the robolectric framework incorporates a shadow class called "ShadowLocationManager" to make a kind of mock.
My question really is, how can I control this mock, can I control what will be returned? If so how?
Or do I have to create my "OWN" shadow class and implement "ShadowLocationManager".
I have been searching for documentation but I just can't find anything to confirm what I am asking.
If robolectric does contain a shadow for location manager how do I control what providers are enabled? I didn't want to implement my own shadow class if one already exists and can be configured and controlled.

A: The shadow classes in Robolectric are substitutes of the various Android classes and can only be changed depending on their implemented functionality.
Looking at the source for ShadowLocationManager, you have some methods you can use to tweak the behavior of the fake:
    public void setProviderEnabled(String provider, boolean isEnabled);
    public void setProviderEnabled(String provider, boolean isEnabled, List<Criteria> criteria);
    public boolean setBestProvider(String provider, boolean enabled);
    public boolean setBestProvider(String provider, boolean enabled, List<Criteria> criteria);
    public void setLastKnownLocation(String provider, Location location);

You can get the shadow instance for LocationManager with:
LocationManager instanceOfLocationManager = Robolectric.newInstanceOf(LocationManager.class);
ShadowLocationManager slm = Robolectric.shadowOf(instanceOfLocationManager);

Note: in the example I'm using Robolectric to create the instance of LocationManager. Depending on your test setup, this instance might come from your injection framework or directly from calling Context.getSystemService(..). Bottom line is, make sure the instance in your test is the same instance used by the code that is being tested.


text:
Q: encode URI of downloaded image of S3 I have upload a image on AWS S3 server with following path :
https://dummy_momain/FeetPort/277/294/93/harwindersingh/2015-07-24/harwindersingh_2015-07-24_15:03:34:0660.jpeg
as i download it with S3 browser. it download the image and convert it into following format:
http://192.168.21.145/277/93/harwindersingh/2015-07-24/harwindersingh_2015-07-24_15%253A03%253A34%253A0660.jpeg
as i used javascript function escape,encodeURI and encodeURIComponent it convert the path into:
http://192.168.21.145/277/93/harwindersingh/2015-07-24/harwindersingh_2015-07-24_15%3A03%3A34%3A0660.jpeg
both the strings are not mached. i need help on converting
harwindersingh_2015-07-24_15:03:34:0660.jpeg into harwindersingh_2015-07-24_15%253A03%253A34%253A0660.jpeg format.

A: Looks like if you do encodeURIComponent two times, you can achieve that. I think in the process of uploading and downloading the encoding happens two times.

var string = encodeURIComponent(encodeURIComponent('harwindersingh_2015-07-24_15:03:34:0660.jpeg'));

document.getElementById('a').innerHTML = string;


text:
Q: LDAP Force Password Change Through HTTPS We have a "master" server running Suse Enterprise with LDAP that controls user's access to our systems. We want to implement a 90 day expiration policy, but the issue is that most of our servers are accessed via HTTPS by end users who are not technical. They won't know how to ssh in and run "passwd" before their passwords expire.
I'm concerned that once their passwords expire, they'll need to come to me. Is there a way to force them to change their passwords once they're expired if they're logging in to our SVN or Jira via HTTPS?

A: Basic and digest authentication basically works by requiring a valid username/password to access a page, giving the browser a 401 unauthorized the first time the it tries to get the page. When your browser realizes it needs a password to get in it prompts the user for what password to give the web server. So there's no real opportunity to do what you're wanting that way. All the browser knows is "I give the web server a username/password and it starts returning success."
I don't know what SuSE uses for LDAP but if you're using FreeIPA there are typically self-service options that you can look into, with password management being one of them. You can also send out an email to users just prior to their password expiration directing them either to FreeIPA or some other homegrown web application for self-service.


text:
Q: How can I get rid of afterimages and rendering problems in Unity URP pipeline? When I attempt to build my project, the renderer renders only the UI and none of the actual 3D content of the game. In addition, when any animation takes place, afterimages form where the UI changes. Here are a couple images of what is expected to happen and what actually happens.
Expected:
expected menu screen
expected menu screen 2
Actual:
buggy menu screen
We are using URP and we are attempting to deploy on WebGL. We saw that others solved this issue when they turned off the skybox. However, when we tried to do this, it did not solve the problem. Please let us know what additional information is needed and if you've had this problem before. Thank you.


text:
Q: Creating a geoserver layer with curl (but with a bounding box) I'm attemping to load a layer into Geoserver from a PostGIS database using cURL.
It works, but I also need to set the bounding box to -180,-90,180,90.  Does anyone know how to add the bounding box to the below command?
curl -v -u xxx:xxx -X POST -H "Content-type: text/xml" -d "<featureType><name>Airports</name></featureType>" http://xxx.xx.com:8080/geoserver/rest/workspaces/PostGIS/datastores/PostGIS/featuretypes
Thanks for your help!

A: Ended up solving the problem like this...
curl -v -u xx:xx -X POST -H "Content-type: text/xml"
-d "<featureType><name>Airports</name><latLonBoundingBox><minx>-180</minx><maxx>180</maxx><miny>-90</miny><maxy>90</maxy><crs>EPSG:4326</crs></latLonBoundingBox></featureType>"
http://xx.xxx.com:8080/geoserver/rest/workspaces/PostGIS/datastores/PostGIS/featuretypes


text:
Q: Docker on Raspberry Pi 2: Could not reach any registry endpoint I installed docker on my Raspberry Pi 2 and want to pull some images. But when I try to pull with docker pull nginx, I get Could not reach any registry endpoint. My network connection is ok and even docker search nginx echos all images. I installed docker from the raspbian repository with sudo apt-get install docker.io so it is an older version. I wasn't able to install a newer version. The docker version is 1.3.3.
Also asked in:
https://raspberrypi.stackexchange.com/questions/51029/docker-on-raspberry-pi-2-could-not-reach-any-registry-endpoint

A: As @jarvis11 said, Docker stopped supporting client versions below 1.5.
At the same time, the current version available for raspbian jessie is 1.3, so you will have to install from source or one of the binaries.
Basically, step 4 here:
https://github.com/umiddelb/armhf/wiki/Get-Docker-up-and-running-on-the-RaspberryPi-(ARMv6)-in-four-steps-(Wheezy)

A: Docker stopped supporting client versions below 1.5, so make sure you have client v1.5 and above.
Docker engine is not able to connect with the registry.
I have faced these issues a year back, its due to the load on docker hub. (https://status.docker.com/)
Public registry should work just fine now.


text:
Q: What does "run of house" mean with regard to hotel room type I have seen a room type at a hotel like below;

Family Room 2 Bedrooms & Living Room Run of The House

Everything is OK except the Run of The House thing. What does it exactly mean here? AFAIK, it is whatever room is available when you check-in. Is that true? Or does that have some other meanings?

A: It is not like the lottery.
ROH means that you will get the room you requested, or better.
Say the hotel has Junior Suites, Standart Suites and Master Suites and you book a Standart Suite (the middle size)
You will probably get a Standart Suite, but you might get a Master Suite with no extra charge. But you will NEVER get a Junior Suite because it will be less that what you have booked (and paid)

A: Run of House, or ROH, generally means you will be staying in a room decided upon by the hotel. In it's simplest form, ROH means you will get whatever room is available at the time you check-in.
If the hotel has a deluxe room or a suite available, you "could" get a nicer room than you would have if you had requested a specific type of accommodation, but you could be booked into a lesser valued room. It all depends on the hotel and how the hotel handles Run of House.
Sometimes, a hotel will have a specific type of room which is their standard Run of House room, which will be booked to those that do not request a specific room type.
If you want a specific room, view, or location, go ahead and choose it unless you are choosing the most basic room the hotel offers, then you might be better off to choose ROH, and hope for something a step or more better than the basic room.


text:
Q: Why $L^1$ is not reflexive We already known that $$ (L^p(\Omega))^* = L^q(\Omega), $$ for all $1\le p < \infty $ and $q$ is the exponent conjugate to $p$. So that, $L^p(\Omega)$ is reflexive with $1<p<\infty$. However, $L^1(\Omega)$ is not, due to $$ (L^\infty(\Omega))^* \supset L^1(\Omega), $$
but I don't know why. Can we find a element $f\in (L^\infty(\Omega))^*$ and $f \notin L^1(\Omega)$?

A: Yes. Here are two examples.
1) Let $\Omega=\mathbb{N}$, so that $L^\infty(\Omega)=\ell^\infty$. Let $\mathcal{c}$ be the subspace of convergent sequences. The linear functional $f(\{x_n\})=\lim_{n\to\infty}x_n$ is bounded on $\mathcal{c}$. By the Hann-Banach theorem it can me extended to $\ell^\infty$. This extension is not represented by any $\ell^1$ sequence.
2) $\Omega\subset\mathbb{R}^n$ open. Fix $x_0\in\Omega$ and define on $C_c(\Omega)$, the set of continuous functions with compact support, the linear functional  $T\colon C_c(\Omega\to\mathbb{R}$ as $T(f)=f(x_0)$. Clearly $|T(f)|\le\|f\|_\infty$. Again by the Hann-Banach theorem, $T$ can be extended to a bounded linear functional on $L^\infty(\Omega)$. It is not represented by any $L^1(\Omega)$ function.
You can find a description of the dual of $L^\infty$ here.

A: I assume $\Omega\subset\mathbb{R}^n$ with the usual Lebesgue measure.
Fix $x\in\Omega$ and take for example $f(g)=g(x)$ for $g\in L^\infty(\Omega)\cap C(\Omega)$. Then $|f(g)|\le \|g\|_\infty$. Extend $f$ to $L^\infty(\Omega)$ by Hahn-Banach, so that $f\in (L^\infty(\Omega))^*$, but of course $f\not\in L^1(\Omega)$ ($f$ is the Dirac measure at $x$).


text:
Q: CSS just on mobile I am trying to make and edit to my css just on the mobile side but it doesn't work.
If i don't include the @media it works on pc and mobile but if i put the @media it doesn't change anything on pc as it should not do but it also doesn't do anything on mobile.
@media (max-width: 991px)
#products .product-miniature .product-container div.left-block .product-image img, .featured-products .product-miniature .product-container div.left-block .product-image img, .product-accessories .product-miniature .product-container div.left-block .product-image img, .product-miniature .product-container div.left-block .product-image img, .category-products .product-miniature .product-container div.left-block .product-image img {
    width: 70%;
    height: 70%;
}

@media (max-width: 991px)
#products .product-miniature, .featured-products .product-miniature, .product-accessories .product-miniature, .product-miniature, .category-products .product-miniature {
    height: 295px;
}

A: You can try this :
    @media (max-width: 991px){
#products .product-miniature .product-container div.left-block .product-image img, .featured-products .product-miniature .product-container div.left-block .product-image img, .product-accessories .product-miniature .product-container div.left-block .product-image img, .product-miniature .product-container div.left-block .product-image img, .category-products .product-miniature .product-container div.left-block .product-image img {
    width: 70%;
    height: 70%;
}
}
@media (max-width: 991px){
#products .product-miniature, .featured-products .product-miniature, .product-accessories .product-miniature, .product-miniature, .category-products .product-miniature {
    height: 295px;
}}


text:
Q: Unable to send Error level logs to elasticsearch I am new to fluentd and I am using 2 .conf file 1 for aggregator and 1 for forwarder. I want to send only error level logs to elasticsearch but even after using the @loglevel error. It still showing me info level logs to elasticsearch. I am adding the conf files as there can be misconfiguration in the conf files.
----> aggregator.conf <------
<match fluent.**>
  @type null
</match>

<source>
  @type http
  port 9880
</source>

<match fluentd.healthcheck>
  @type stdout
</match>

<source>
  @type tail
  @id in_tail_container_logs
  path /var/log/containers/*.log
  exclude_path ["/var/log/containers/fluentd*"]
  pos_file /var/log/fluentd-containers.log.pos
  tag kubernetes.*
  read_from_head true
  format /^(?<time>.+) (?<stream>stdout|stderr)( (?<logtag>.))? (?<message>.*)$/
  time_format %Y-%m-%dT%H:%M:%S.%L%z
</source>

<match **>
  @type forward
  <server>
    host fluentd-0.fluentd-headless.infra-fluentd.svc.cluster.local
    port 24224
  </server>

  <buffer>
    @type file
    path /opt/bitnami/fluentd/logs/buffers/logs.buffer
    flush_thread_count 2
    flush_interval 5s
  </buffer>
</match>

-----> forwarder.conf <-----
<source>
  @type prometheus
  port 24231
</source>

<source>
  @type prometheus_monitor
  <labels>
    host ${hostname}
  </labels>
</source>

<source>
  @type prometheus_output_monitor
  <labels>
    host ${hostname}
  </labels>
</source>

<match fluent.**>
  @type null
</match>

<source>
  @type forward
  bind 0.0.0.0
  port 24224
</source>

<source>
  @type http
  bind 0.0.0.0
  port 9880
</source>

<match fluentd.healthcheck>
  @type stdout
</match>

<filter kubernetes.**>
  @type kubernetes_metadata
</filter>

<match **>
  @type elasticsearch
  include_tag_key true
  host "#{ENV['ELASTICSEARCH_HOST']}"
  port "#{ENV['ELASTICSEARCH_PORT']}"
  logstash_format true

  <buffer>
    @type file
    path /opt/bitnami/fluentd/logs/buffers/logs.buffer
    flush_thread_count 2
    flush_interval 5s
  </buffer>
</match>


text:
Q: Count Frequency of the nth item of each List within Larger List I have seen solutions for counting of values within a simple list, but what if you have a list of lists?
Example:
list = [[Frank, 23],[Mary, 55],[Craig, 17],[Nancy, 34],[Ben, 55],[Cindy, 47]]

How would I count the number of times the second value of each sublist is 55?

A: Given:
>>> li = [['Frank', 23],['Mary', 55],['Craig', 17],['Nancy', 34],['Ben', 55],['Cindy', 47]]

You can invert the matrix:
>>> zip(*li)
[('Frank', 'Mary', 'Craig', 'Nancy', 'Ben', 'Cindy'), (23, 55, 17, 34, 55, 47)]

And count the 55's in the nth element:
>>> zip(*li)[1].count(55)
2

OR, you can use itemgetter and get the nth item:
>>> from operator import itemgetter
>>> map(itemgetter(1), li)
[23, 55, 17, 34, 55, 47]
>>> map(itemgetter(1), li).count(55)
2

If you want ALL the counts, use a Counter:
>>> from collections import Counter
>>> Counter(zip(*li)[1])
Counter({55: 2, 17: 1, 34: 1, 47: 1, 23: 1})

A: Make a new generator out of it and pass it to sum():
>>> l = [['Frank', 23],['Mary', 55],['Craig', 17],['Nancy', 34],['Ben', 55],['Cindy', 47]]
>>> sum(item[1]==55 for item in l)
2

Also, don't name it list, or that masks the built-in function list().


text:
Q: Why is this type union resolved as an intersection, in typescript? I'm having trouble understanding the mechanism behind a typescript error I'm getting - I'm convinced there's something basic doing a "whoosh" sound as it flies over my head.
I've only found this question on the topic, but while the error looks the same, the setup seems quite different to me.
This is the definition I'm referencing, cut for brevity.
type ApexAxisChartSeries = {
  // ...
  data:
    | (number | null)[]
    | {
        x: any;
        y: any;
        // ...
      }[]
    | [number, number | null][]
    | [number, (number | null)[]][];
}[]

And this is the bad function, which takes an {x:number, y:number} array.
function composeSeries(input: { x: number; y: number }[]) {
  const series: ApexAxisChartSeries = [
    { name: "A", data: [] },
    { name: "B", data: [] },
  ];

  input.forEach((datum) => {
    series[0].data.push(datum); // <-- This line right here gives the error.
  });

  return series;
}

Now, what's confusing me is that given the type definition, I would expect a {x:number, y:number} object to be a perfectly valid element of data, but typescript is complaining that

Argument of type '{ x: number; y: number; }' is not assignable to parameter of type number & { x: any; y: any; fillColor?: string | undefined; strokeColor?: string | undefined; meta?: any; goals?: any; } & [number, number | null] & [number, (number | null)[]]'.
Type '{ x: number; y: number; }' is not assignable to type 'number'.

And I'm here like, where in the bleep bloop are those intersections in the error coming from, if the type definition uses unions?
As additional context:

*

*It's not only the object that gives an error. If I use [x,y] tuples or just a number array, the compiler still perks up

*I'm using TS 4.5.4

*I'm quite positive the issue exists in this code: the TS playground gives the same error

For reference, this is the full type definition:
type ApexAxisChartSeries = {
  name?: string
  type?: string
  color?: string
  data:
    | (number | null)[]
    | {
        x: any;
        y: any;
        fillColor?: string;
        strokeColor?: string;
        meta?: any;
        goals?: any;
      }[]
    | [number, number | null][]
    | [number, (number | null)[]][];
}[]

Any clarification is deeply appreciated!
Edit: an example of the error can be found on the TS playground here, courtesy of @jcalz

A: There is a difference between (T | U)[] and T[] | U[].  In the first, each array element can be of type T or U.  In the second (which corresponds with your case) the array can only have elements of one of either type.
The question you have to ask yourself is this:  How can TypeScript know what elements are allowed when it doesn't know which type of an array a variable is?
const myArray: string[] | number[] = [];
myArray.push(5); // Argument of type 'number' is not assignable to parameter of type 'never'.

Take the example above.  TypeScript will throw an error no matter because whatever you push to that array will not comply with one of the possible types.
The good thing is that the TypeScript compiler is clever has heck and figured out in your case that a type can be derived that will comply with every possible condition.  This type happens to be the intersection of all possible element types, which is the most basic type that would meet the requirements.
Your options are either make the array allow any of the possible types, or make the series a generic that extends any one of the types.
Option A: Array element can be one of many types
type ApexAxisChartSeries = {
  name: string,
  data:
    (number
      | null
      | { x: any; y: any; }
      | [number, number | null]
      | [number, (number | null)[]]
    )[]
};

Option B: Generic type parameter can be one of many types
type ChartDataType = (number | null)
  | { x: any; y: any; }
  | [number, number | null]
  | [number, (number | null)[]];

type ApexAxisChartSeries<T extends ChartDataType> = {
  name: string,
  data: T[]
}[];

function composeSeries<T extends ChartDataType>(input: T[]) {
  const series: ApexAxisChartSeries<T> = [
    { name: "A", data: [] },
    { name: "B", data: [] },
  ];

  input.forEach((datum) => {
    const index = (true) ? 0 : 1;
    series[index].data.push(datum);
  });

  return series;
}

composeSeries([{ x:1, y: 1}]); // returns { name, data: { x, y }[] }[]


text:
Q: Neo4j-shell query result size in MB Is there any way to get from Neo4j a size in KB/MB/GB of a cypher query achieved result ?

A: Don't know a way to do this in Neo4j shell. However you can use a command line tool like curl using the option -w to emit the download size:
curl -s -o /dev/null -H "Content-Type: application/json"
-d '{"statements" : [ {"statement" : "Match (n:Person) return n limit 10"}]}'
 http://localhost:7474/db/data/transaction/commit
-w "result size %{size_download}\n"


text:
Q: cakephp facebook api, FB->api('/me') returns empty value I use Webtechnick Facebook plugin for cakephp 1.3 website. I implemented it about a year ago. And it worked fine until now. But today I found out that when I try to login(as a new user) it does not save facebook user data, because $this->Connect->user() (which result is taken from $this->FB->api('/me'), /plugins/facebook/controller/components/connect.php, line 194) returns nothing. I tried also, this facebook plugin on another cakephp 2.0 website, but the same thing was there.
I think, that there was some change in facebook api, because I did not absolutely make any change on the website, which could bring to that result.
this is user function in connect.php component
function user($field = null){
    if(isset($this->uid)){
        $this->uid = $this->uid;
        if($this->Controller->Session->read('FB.Me') == null){
            $this->Controller->Session->write('FB.Me', $this->FB->api('/me'));
        }
        $this->me = $this->Controller->Session->read('FB.Me');

    }
    else {
        $this->Controller->Session->delete('FB');
    }

    if(!$this->me){
        return null;
    }

    if($field){
        $retval = Set::extract("/$field", $this->me);
        return empty($retval) ? null : $retval[0];
    }

    return $this->me;
}

and my beforeFacebookSave() function in app_controller
public function beforeFacebookSave() {
    $fbUser = $this->Connect->user ();

           //debug($fbUser);  // outputs nothing

        $this->Connect->authUser ['User'] ['email'] = $fbUser ['email'];
        $this->Connect->authUser ['User'] ['first_name'] = $fbUser ['first_name'];
        $this->Connect->authUser ['User'] ['last_name'] = $fbUser ['last_name'];

            return true;

}

Thank you !

A: There was a certificate change on Facebook that wasn't reflected in the SDK (because it used the old certificate). Since the plugin is based on PHP SDK, you should just fetch the latest version of the repo https://github.com/webtechnick/CakePHP-Facebook-Plugin. The author has pushed the commit to include the new PHP SDK with the new certificate.
https://github.com/webtechnick/CakePHP-Facebook-Plugin/tree/master/Vendor
Your error log should have a Facebook Exception due to SSL problems which chokes the API calls causing /me to return empty.

A: try this, it work for me
$infos = $facebook->api('/me?fields=id,first_name,last_name,picture,email');


text:
Q: How to add an input to a radiobutton selection in Shiny? I am pretty new to Shiny and for the app I am building, I need to add an input to a radioButton selection.
This is the code for my radioButton:
values <- c("Carbs" = "carbs", "Proteins" = "prots", "BMI" = "bmi"),
radioButtons("plotVal", "What value do you want to plot?", choices = values)

I would like to add an input field. If the user doesn't find the right choice, he could enter his own value. The end result would be something like that:

What value do you want to plot?
O Carbs
O Proteins
O BMI
O [Other...   ]

The [Other... ] choice would be a textInput.
I've searched the web and read all the tutorials for inputs that I found but I didn't find this specific case of figure. Can anyone help me out? Thank you.

A: You could use updateRadioButtons:
library(shiny)

values <- c("Carbs" = "carbs", "Proteins" = "prots", "BMI" = "bmi")

ui <- fluidPage(
  radioButtons("plotVal", "What value do you want to plot?", choices = values),
  textInput("other", "Type in additional category"),
  actionButton("add", "Add category")
)

server <- function(input, output, session) {
  observeEvent(input$add, {
    req(input$other)
    otherVal <- "other"
    names(otherVal) <- input$other
    updatedValues <- c(values, otherVal)
    updateRadioButtons(session, "plotVal", choices = updatedValues)
    })
}

shinyApp(ui = ui, server = server)


text:
Q: How to deal with long script tags in HTML5? I'm using django for my web application and I'm suffering from verbose, long tags in HTML5.
Is there any way to line break the verbose tags like other languages does?
For example, in python, it will be far much easy to read
if a and b and \
   c and d and e and f:
   print 'line breaking makes me easy to read'

than
if a and b and c and d and e and f ...:
    print 'verbose expression without line break makes me hard to read'

So is there any way to break long lines in HTML5 tags?
For example, is it right syntax to do like
<script
data-main="{% static 'my-long-application-name/app.js' %}"
src="{% static 'my-long-application-name/require.js' %}">
</script>

instead of
<script data-main="{% static 'my-long-application-name/app.js' %}" src={% static 'my-long-application-name/require.js' %}></script>

And what is the most general way to deal with these verbose tags?

A: You can freely split verbose tag into lines, you know, Humans should not have to grok XML ;)
Also you can apply django-htmlmin (HTML minifier) automatically on request to convert:
<script
data-main="{% static 'my-long-application-name/app.js' %}"
src="{% static 'my-long-application-name/require.js' %}">
</script>

To:
<script data-main="{% static 'my-long-application-name/app.js' %}" src={% static 'my-long-application-name/require.js' %}></script>


text:
Q: Как выкачать байты из базового потока System.IO.stream используя powershell Есть такая функция
[System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create('URl')
$webRequest.Timeout = 3000
$webRequest.Method = 'POST'
$webRequest.ContentType = 'multipart/form-data'
$webRequest.ContentLength = $data.Length;
$requestStream = $webRequest.GetRequestStream()
$requestStream.Write($data, 0, $data.Length)
$requestStream.Flush()
$requestStream.Close()
[System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()

аналог
$webclient = new-object system.net.WebClient;
$streamReader =  $webclient.UploadData($url ,"POST",$data);

как с помощью первой функции выкачать байты из базового потока System.IO.stream при условии что свойство длиный базового потока не показывает количество принимаемых байтов от сервера(сервер не отдает длину передаваемых байтов) из-за этого не получается воспользоваться стандартными методами
$streamReader = New-Object IO.BinaryReader($webResponse.GetResponseStream())
$streamReader.ReadBytes($streamReader.BaseStream.Length)

т.е. мы не знаем длину базового потока $streamReader.BaseStream.Length.
был придуман костыль как выкачать байты
Try{
    While(1){
        [byte[]]$bytes+=[byte[]]$streamResponse.ReadByte()
    }
    }Catch{}

т.е. когда мы выкачиваем все байты из потока в конце ловим -1 что указывает на конец потока и этот -1 генерирует ошибку тем самым мы выходить из цикла.
Метод рабочий но не совсем правильный при передачи большого потока данных, данный цикл перегружает процессор и зависает скрипт. Можеть быть есть какие то более правильные решения, при условии что мы не знает длину передаваемого потока?

A: Одним из самых простых вариантов будет скопировать поток в MemoryStream:
$rs = $webResponse.GetResponseStream()
$ms = New-Object IO.MemoryStream
$rs.CopyTo($ms)

Если используется PowerShell 2.0 и метод CopyTo недоступен, то можно реализовать его самому:
function CopyTo-Stream {
    param(
        [IO.Stream] $Source,
        [IO.Stream] $Destination
    )
    $Buffer = New-Object Byte[] 64kb
    while($Read = $Source.Read($Buffer, 0, $Buffer.Length)) {
        $Destination.Write($Buffer, 0, $Read);
    }
}

$rs = $webResponse.GetResponseStream()
$ms = New-Object IO.MemoryStream
CopyTo-Stream $rs $ms