text:
Q: Filtering data from parameters c# I'm facing a issue when trying to search my page when trying to filter from 5 parameters.
If the parameters is null then I would want to ignore that search and only return results if there is a value in the parameters.
At the moment i used separate parameters but i need something that caters for all 5 and if it has 2 out of 4 values then it should return based on the filter.:
if (name != null)
{
    report = report.Where(asd => asd.name == name).OrderBy(x => x.Id).ToList();
}
else if (Id != null)
{
    report = report.Where(x => x.Id == Id).OrderBy(x => x.Id).ToList();
}

So this works with only 1 in mind, how would i join all 4 together so it works together.
This is my full code:
[HttpGet]
public ActionResult Get(string Id = null, string name = null, string status = null, string startDate = null, string endDate = null)
{
    List<ReportModel> report = new List<ReportModel>();
    report = (from data in _context.ReportData
                //where data.Id== Id
                //&& data.name== name
                //&& data.Status == status
                //&& data.Date >= Convert.ToDateTime(startDate) && data.Date < Convert.ToDateTime(endDate)
                select new ReportModel
                {
                    Id = data.Id,
                    Name = data.Plant,
                    Status = data.Status,
                    Date = data.Date
                }).ToList();

    if (name != null)
    {
        report = report.Where(asd => asd.name == name).OrderBy(x => x.Id).ToList();
    }
    else if (Id != null)
    {
        report = report.Where(x => x.Id == Id).OrderBy(x => x.Id).ToList();
    }
    else if (status != null)
    {
        report = report.Where(x => x.Status == status).OrderBy(x => x.Id).ToList();
    }

    return Ok(report);
}

Kindly help.

A: If you care about performance, do not call ToList() early, because it will load whole table into the memory. IQueryable can be combined to produce desired result.
[HttpGet]
public ActionResult Get(string Id = null, string name = null, string status = null, string startDate = null, string endDate = null)
{
    var query = _context.ReportData.AsQueryable();

    if (name != null)
    {
        query = query.Where(asd => asd.name == name);
    }

    if (Id != null)
    {
        query = query.Where(x => x.Id == Id);
    }

    if (status != null)
    {
        query = query.Where(x => x.Status == status);
    }

    query = query.OrderBy(x => x.Id);

    var report = query
        .Select(data => new ReportModel
        {
            Id = data.Id,
            Name = data.Plant,
            Status = data.Status,
            Date = data.Date
        })
        .ToList();

    return Ok(report);
}

A: Intead of using if condition, you can add directly the condition in the Where clause
if (name != null)
{
    query = query.Where(asd => asd.name == name);
}
// replace by
query = query.Where(asd => asd.name == name || name == null);

when name will be null, the Where condition will always true.


text:
Q: title bar went missing after using oncreateoptionsmenu in android studio public class Profile extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
    }

    @Override //my code for action bar but it makes the action bar missing
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

A: Have you tried explicitly returning true?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Group By and Order -- retrieve detail for most recent entries in table I want to Make a SQL Query that returns the newest Entry for each bot_id.
My current request looks like this, but it ALWAYS returns the first Entry. DESC & ASC don't make any difference:
SELECT bot_id, id
FROM t_request_history
GROUP BY bot_id
ORDER BY request_time DESC

The Tables looks like this:

t_request_history

id
bot_id
request
response
error
request_time

1
usr_e74ae42b-080c-48e0-9e6c
a
a
0
2021-09-16 23:37:10

2
usr_e74ae42b-080c-48e0-9e6c
a
a
1
2021-09-16 23:37:35

3
usr_e74ae42b-080c-48e0-9e6c
a
a
1
2021-09-16 23:43:20

4
delete
1
1
1
2021-09-16 23:44:21

5
delete
1
1
0
2021-09-16 23:44:32

6
delete
1
1
0
2021-09-16 23:44:41

Wanted Result

bot_id
id

delete
6

usr_e74ae42b-080c-48e0-9e6c
3

Actual Result

bot_id
id

delete
4

usr_e74ae42b-080c-48e0-9e6c
1

Is there any way to make this query work?

A: It looks like your id values go up with time. That is, it looks like newer entries in your table have higher id values than older entries.  If this is true,
SELECT bot_id, MAX(id) id
FROM t_request_history
GROUP BY bot_id

gets you what you want.
If the id values don't go up with time, you have to use a subquery to find the latest time for each bot_id.
                 SELECT bot_id, MAX(request_time) request_time
                   FROM t_request_history
                  GROUP BY bot_id

Then you join that subquery to your table like this:
SELECT a.bot_id, a.id
  FROM t_request_history a
  JOIN (
                    SELECT bot_id, MAX(request_time) request_time
                      FROM t_request_history
                     GROUP BY bot_id
       ) b   ON a.bot_id = b.bot_id
            AND a.request_time = b.request_time

The ON condition of the JOIN chooses just the rows with the latest times from your table.

A: You could do this using a Window/Analytic function
SELECT distinct
 bot_id, MAX(request_time) OVER(PARTITION BY bot_id)
FROM t_request_history
;

SQLFiddle
You could also find more details on the usage @ MariaDB WindowFunction Max documentation


text:
Q: Brute force algorithm and string matching? I'm really confused with how to do the following:

Your main program should read in two strings from the user (one string at a time, so you will have two separate strings).  The first line (string) that is read is called the text string, and the second line (string) is called the pattern string.
Then you will implement a function, called match that implements the simple brute force pattern matching.  This function takes two strings (the text string and the pattern string), and returns True if the pattern string matches some portion of the text string: otherwise, the function returns False.
Your main program must keep doing the following task: ask the user for a text string and a pattern string and print a message that states whether the pattern was found in the text or not. The program stops when the user enters qqq as the text string (your program must stop regardless of the case of the letter).

So far, none of the codes I've typed out work. Please help me!

A: So I think I've written up a pretty helpful program that might help you out. As @Scovetta mentioned, we can use Python's in operator. However, if you're adamant on using a brute force method and not using Python's nice syntactic sugar, then you can definitely do that.
Here is an example program I wrote up. Let me know if this helps! Feel free to ask any questions that you might have.
# This program is just going to find if a string contains a substring

def match(text, pattern):
    '''
    Simple match program
    '''
    if pattern in text:
        return True
    else:
        return False

test_cases = [['ab', 'bab'], ['cat', 'catdog'], ['banana', 'apple'], ['tree', 'tree']]

def brute_match(text,pattern):
    '''
    We just want to check that our text has our pattern
    So let's just iterate over our text
    '''
    length_of_pattern = len(pattern)
    for i in range(len(text)):
        # Abuse python's splicing because we don't have to worry about end of the string nonsense
        if text[i:length_of_pattern+i] == pattern:
            return True
    return False

for case in test_cases:
    ans = match(case[1], case[0])
    bans = brute_match(case[1], case[0])
    print("{} is in {} (T/F): {}".format(case[0], case[1], ans))
    print("{} is in {} (T/F): {}".format(case[0], case[1], bans))

# Enter your main program
# We want to loop infinitely unless we get qqq
while True:
    text_string = raw_input("Please enter your text string: ")
    if text_string == 'qqq':
        break
    pattern_string = raw_input("Please enter your pattern string: ")
    print("Using 'in' operator:")
    print('-'*20)
    if match(text_string):
        print("IS a valid match")
    else:
        print("NOT a valid match")
    print("Using brute force:")
    print('-'*20)
    if brute_match(text_string):
        print("IS a valid match")
    else:
        print("NOT a valid match")

I realize the code is a bit messy, but I just wanted to write it up quick for ya!
Let me know if you have any questions.


text:
Q: Saving the values entered in the textbox to the xml file I am new to XML and I tried to create a window form that collects num, names, surnames, and ranks for each instructor, student, operator, and technician. But this code is going to be so long. Do you have any suggestions to create this XML on c#? Info will be taken from 4 text boxes for each employee's num, name, surname, and rank. also, the description will be taken from the textbox.
<Simulator>
    <Flight ID="1" Description="rainy_day">
      <Instructor Num="14213124">
        <Name>Jack</Name>
        <Surname>Sparrow</Surname>
        <Rank>General</Rank>
      </Instructor>
      <Student Num="56475679">
        <Name>Adam</Name>
        <Surname>Black</Surname>
        <Rank>Lieutenant</Rank>
      </Student>
      <Operator Num="75846474">
        <Name>Gabriel</Name>
        <Surname>Red</Surname>
        <Rank>Op</Rank>
      </Operator>
      <Technician Num="85425484">
        <Name>Samuel</Name>
        <Surname>Long</Surname>
        <Rank>Tec</Rank>
      </Technician>
    </Flight>
</Simulator>

this is the code i tried. It's gonna be so long if i write this again and again for each employee
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                XmlElement rootNode = xmlDoc.DocumentElement;
                xmlDoc.InsertAfter(xmlDeclaration, rootNode);

                XmlNode parentNode = xmlDoc.CreateElement("Users");
                XmlNode subNode = xmlDoc.CreateElement("Instructor");

                XmlAttribute numAtt = xmlDoc.CreateAttribute("Num");
                numAtt.Value = num.ToString();
                XmlAttribute nameAtt = xmlDoc.CreateAttribute("Name");
                nameAtt.Value = name;
                XmlAttribute surnameAtt = xmlDoc.CreateAttribute("Surname");
                surnameAtt.Value = surname;
                XmlAttribute rankAtt = xmlDoc.CreateAttribute("Rank");
                rankAtt.Value = rank;

                subNode.Attributes.Append(numAtt);
                subNode.Attributes.Append(nameAtt);
                subNode.Attributes.Append(surnameAtt);
                subNode.Attributes.Append(rankAtt);

                xmlDoc.AppendChild(parentNode);
                parentNode.AppendChild(subNode);

check for id part
var userElements = xDoc.Descendants("Flight").ToList();
            string lastID = userElements.Select(x => (x.Attribute("ID").Value))
                  .OrderByDescending(x => x)
                  .First()
                  .ToString();
            int lastID_int = Int16.Parse(lastID) + 1;
            if (lastID_int <= 0)
                lastID_int = 0;
            string current = lastID_int.ToString();
            Simulator sim = new Simulator(current, textbox_description.Text);

A: Here is class using XML Linq :
   public class Simulator
    {
        XDocument doc = null;
        public Simulator(string filename)
        {
            doc = XDocument.Load(filename);
        }
        public Simulator(string id, string description)
        {
            string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Simulator></Simulator>";
            doc = XDocument.Parse(ident);
            XElement flight = new XElement("Flight", new object[] {
                new XAttribute("ID", id),
                new XAttribute("Description", description)
            });

            doc.Root.Add(flight);
        }
        public string AddUser(string flightID, string role, string number, string name, string surname, string rank)
        {
            XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();

            if (flight != null)
            {
                XElement user = new XElement(role, new object[] {
                    new XAttribute("Num", number),
                    new XElement("Name", name),
                    new XElement ("Surname", surname),
                    new XElement("Rank", rank)
                });
                flight.Add(user);
                return "GOOD";
            }
            else
            {
                return "Flight ID doesn't exist";
            }
        }
        public string AddFlight(string flightID, string description)
        {
            XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
            if (flight == null)
            {
                flight = new XElement("Flight", new object[] {
                    new XAttribute("ID", flightID),
                    new XAttribute("Description", description)
                });
                doc.Root.Add(flight);
                return "Good";
            }
            else
            {
                return "Flight ID already exists";
            }
        }
        public string AddErrors(string flightID, XElement errorLog)
        {
            XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
            if(flight == null)
            {
                return "Flight ID doesn't exist";
            }
            else
            {
                flight.Add(errorLog);
                return "GOOD";
            }

        }

        public void WriteXml(string filename)
        {
            doc.Save(filename);
        }
    }

A: You should probably use the xmlSerializer instead of trying to manually create the xml tree.
This should let you create classes for your data and let the serializer worry about transforming the objects to xml:
public class Person{
    public string Num{get;set;}
    public string Name {get;set;}
    public string Surname {get;set;}
    public string Rank{get;set;}
}
public class Flight{
    public Person Instructor {get;set;}
    public Person Student {get;set;}
    ....
}

var serializer = new XmlSerializer(typeof(Flight));
var writer = new StreamWriter(filename);
serializer.Serialize(writer, myFlight);

This might not give you exactly the layout you are after, but that can often be controlled by attributes. See also Json .net for the more popular alternative to xml.


text:
Q: Changing div _rmc values In my div TAG there is a _rmc value.
well inside there is a variable called PreferValueIndex i need to change that value to one of the options (1, -1, -9999) 1 = true , -1 false , -9999 block.
i need some help on how to do this . and an explanation about what is _rmc means.
using:
import logging
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

A: You can change the attribute like this  :
driver.execute_script("arguments[0].setAttribute('_rmc','your new value')", element)

Where element is the webelement (the div )
Update :
value = "relative; background-color: rgb(215, 14, 82); cursor: url(""Images/cant.cur"")"
driver.execute_script(f"arguments[0].setAttribute('_rmc','{value}')", element)


text: Q: Numpy failed to import and Cache entry deserialization failed I am using RaspberryPis for a project (I am a really really really beginner with them) and I am facing few issue while installing the cv2 module. I ran a script that didn't work, issue was ImportError: numpy.core.multiarray failed to import. I saw on a previous respond to the solution was pip install -U numpy. So I did pip3 install -U numpy as I am running my script on python3. This works for one of my Pi but the other one didn't work showing a message error Cache entry deserialization failed, entry ignored. I saw on some other forum that we have to remove the cache of it which I tried but did not work. Anyone has any advices on it ? Would be extremely helpful, thanks in advance


text:
Q: Biggest volume parallelotope inside the union of two parallelotopes Given a parallelotope $P$ symmetric around the origin, and a vector $v$, such that $(P+v)∩(P−v)$ is not empty, is there a simple way to obtain a parallelotope $Q⊂(P+v)∪(P−v)$, symmetric around the origin, with the largest volume?
The dimension 2 case was answered here: https://mathoverflow.net/a/203239/39359, where Pietro argued that it is enough to look at the case where $P$ is a unit cube. It turns out that the best parallelograms will have an edge parallel to the original square. Is there a generalization of this result in more dimensions?
Thanks!


text:
Q: How to center the  vertically? This is my first ever project. I am using Bootstrap and some custom styling has been included.
This is my website: https://carwashwebsite.netlify.app/. If you refer to the image(taken from the website) below, I would like to make the rectangle at center vertically and horizontally for desktop and mobile views.
Website Image Snapshot
Another thing is, please advise on what I can do for my tablet view? It looks weird.
Thanks
I tried using justify-content and align-items but I can't achieve it.

A:     <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

i am vartrically centerd


text:
Q: Behavior from module SessionsHelper is not included in class I try to add sessions to my rails app and I have class SessionManager which is responsible for handling session related tasks
class SessionManager
  include SessionsHelper

  def log_in(user)
    session[:user_id] = user.id
  end

  def current_user
    @current_user ||= User.find_by_id(session[:user_id])
  end

  def logged_in?
    return false if current_user.nil?
    true
  end
end

as you can see I include SessionsHelper in order to use session method  to put some data into session, but when I try to use this code I get back:
NameError: undefined local variable or method `session' for <SessionManager:0xa790cfc>

What do I do wrong ?
Thanks in advance.

A: I am not sure what your SessionsHelper module looks like, but you may want to look at using self.included. This is sometimes known as a "mixin".
I believe structuring your module similar to this should help you:
module SessionsHelper
  def self.included(base)
    base.class_eval do

      def session
        # ...
      end

    end
  end
end

More info on included: http://ruby-doc.org/core-2.2.0/Module.html#method-i-included


text:
Q: Count number of individual lines from a text file c# I have a text file with 14000 lines however many of these are duplicates. I want to count the unique lines, however i only have access to framework 3.0 and below. Is it possible to do this without using.linq?

A: Of course it's possible, you can loop through each line using StreamReader.ReadLine and add each line to a HashTable structure using the line as the key and some dummy object as the value. Before adding the string though, you should check that the HashTable doesn't already have the key:
HashTable uniqueLines = new System.Collections.HashTable();
string line;

// Read each line of the file until the end
while ((line = reader.ReadLine()) != null)
{
  // Check that we have not yet seen this string before
  if(uniqueLines.ContainsKey(line) == false)
  {
    uniqueLines.Add(line, 0);

    // You can write the lines to another file in necessary
    writer.WriteLine(line);
  }
}

At the end the number of items in the HashTable should be equal to the number of unique lines in the file:
int count = uniqueLines.Count;
// And don't forget to close the reader (and writer)!

Why does this work? Because the HashTable uses the hash code returned by GetHashCode(0 and according to MSDN:

If two string objects are equal, the GetHashCode method returns
  identical values. However, there is not a unique hash code value for
  each unique string value. Different strings can return the same hash
  code.

Now I'm not sure how common it is when two different strings have the same hash code, but as I understand many LINQ methods use HashTable internally, so this may be the closest to what LINQ  would do.

A: I think you also could write it by linq .
     var result = from p in File.ReadAllLines(filepath)
         group p by p into g
         select new { Key = g.Key, Count = g.Count() };

It is intelligible.


text:
Q: Get count query results via getSingleScalarResult() and groupBy() - exception I want get results of my query (with limit 10) + count possible results.
I know there is similar questions and answers.
for example here
but if i trying get count possible rows (via getSingleScalarResult()) i will get excepton: The query returned multiple rows. Change the query or use a different result function like getScalarResult().
    $query = $repository
        ->createQueryBuilder('t')
        ->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');

    $query->where('t.visible = (:visible)')->setParameter('visible', 1);

    // + some wheres, where in, more than....

    $query->groupBy('t.hotel');
    $query->setMaxResults(10);

    echo $query->getQuery()->getSingleScalarResult();
    exit();

I just need one integer whitch represent all results from my query.
How can i get this count number? Ideal in one shot to db.

EDIT:
if i remove $query->groupBy('t.hotel'); and in select keep only ->select('count(t.katId)'); then it work.  But i need groupBy because it makes real count of results.

SOLUTION
I divided it on two queries so - to get results i rolled back changes to state before trying any count information, and make clone this query (before set setMaxResults and groupBy), change select (keep all wheres) and get count information.
I will be grateful if someone offers better solution

*

*Get results:

*

*removed COUNT() from select

*asking for results changed to 'normal' ->getArrayResults

*Get count:
$q = clone $query;

$q->select('count(distinct t.hotel) as count');
$r = $q->getQuery()->getArrayResult();

echo $r[0]['count'];
exit();

A: If you need keep the groupBy:
$query = $repository->createQueryBuilder('t')
$query->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->from(ENTITY STRING, 't', 't.hotel');  //here defined your array result key
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
$query->groupBy('t.hotel');
$query->setMaxResults(10);

echo $query->getQuery()->getScalarResult();
exit();

Edit : New edit works ?

A: You are only interested in COUNT(t.katId), so you should drop other returned fields 't.hotel', 't.title', etc.
The result will then contain a single return value (single scalar result), so $query->setMaxResults(10) is not needed.


text:
Q: Minimal distance between silkscreen text and edge? I'm maybe going to use JLCPCB to order a PCB (if I get it finished), but I'm wondering about the minimal distance between the edge and silk screen text.
If I look at the capabilities:
https://jlcpcb.com/capabilities/Capabilities
I find regarding silk screen text:

*

*Minimal height (32 mils)

*Minimal 'line' width (6 mils)

The only item that comes closest is 'edge rails' (3 mm), but I doubt that's related. 3mm seems big.
I'm intending so place small text and close to the border like below. I used several font types, but I am just playing around with it; I like to use the smallest possible.

A: It depends on the boardhouse, but likely they can go all the way to the edge since routing (the board cutting kind) is done after silkscreen.
I often have silkscreen marks that go past the edge of the board (in the gerbers at least) and the boardhouses I use have no problem with it.  The silkscreen goes right to the edge.
That said, if you are doing text, be aware of the tolerance to positioning so you don't end up with partial letters cut off.
Here is a recent example:

This is from PCBWay, a very low-cost Chinese boardhouse.  Notice how they stop the silkscreen about 0.1 mm from the edge.  They did that themselves, my gerbers have those lines go outside the board-edge.

A: Like the other answer says: it depends on the boardhouse.
Eurocircuits states:

In all cases we will clip away any legend text within 0.200mm (10mil) of the board edge.

Since JLCPCB doesn't mention it on their website, I think the best answer is:
don't speculate how other board houses do it, instead contact JLCPCB


text:
Q: Converting from set of Cartesian equations to Polar Equation Is it possible to convert the set of Cartesian equations:
$$x(t) = (20-30)*\cos(2t)+45*\cos(2t*(20-30)/20))$$
$$y(t) = (20-30)*\sin(2t)+45*\sin(2t*(20-30)/20))$$
where
$$t \in [0,2\pi)$$
Into a single Polar-Coordinates equation, so that $f(\theta) = r$?
If so, how?

A: We know that
$$r=\sqrt[]{x^2+y^2}.$$
Since you have equations for $x$ and $y$ in terms of the angle $t$, you can use the above formula to find a function of $t$ that gives $r$.

A: Your expressions simplify to $$x(t)=45 \cos (t)-10 \cos (2 t)$$ $$y(t)=-45 \sin (t)-10 \sin (2 t)$$ So, since  $$r^2(t) = x^2(t) + y^2(t)$$ after some minor expansions and simplifications, you should arrive to  $$r^2(t)=2125-900 \cos (3 t)$$ and then ...


text:
Q: Adjust table column width by percentage I want to set the width of each column based on the percentage.
I wrote the following CSS, but it does not apply to the column table
my code:

             select
<input id="SelectAllRows" class="selectallrows" type="checkbox">

             ...

                    <input class="select" id="36174" name="36174" type="checkbox" value="true"><input name="36174" type="hidden" value="false">

                ...

Why?

A: You can use style attribute in td to set width% of the column.

                    <input class="select" id="36174" name="36174" type="checkbox" value="true"><input name="36174" type="hidden" value="false">

                ...


text:
Q: How do I write a number as a string to an Excel file? I have a cell array in MATLAB which contains numeric data stored as a string. I would like to maintain this string format when I export the file. However, when I use xlswrite, Excel automatically converts these to double values. Does anyone know how to prevent this?
Here's an example of what I have written:
    C = {'123'};
    xlswrite('example.xls', C);

When I check the file, "123" is stored as a number.  Specifically, I can perform arithmetic operations on it.

A: Insert a single quotation in front of each number before writing to file. The single quotation at the beginning informs Excel that you wish to input a string regardless of its contents:
C = {'''123'};
xlswrite('example.xls', C);

You need to use two ' characters to symbolize a single quote to ensure MATLAB doesn't ambiguously think that you're trying to start a string... so to be sure we're on the same page:
C =  {'''123');
      |||   |
      abb   a

a denotes the starting and ending of the string and b denotes the declaration of a single quotation.


text:
Q: Accessing bind-at values from a snippet in Lift I have a template that looks like this:
<lift:surround name="default" at="page-content">
  <lift:bind-at name="page-title">Home</lift:bind-at>
  ...
</lift:surround>

The default template looks like this:

  <title>Title Prefix | </title>

<lift:bind name="page-title" />

      <lift:bind name="page-content" />

I want to use a snippet to replace the <title> content with a string that combines "Title Prefix" and the value of <lift:bind-at name="page-title"> (ie: "Home"). I want to contine to use that same value inside the
 in the
How can I access a bind-at value from within a snippet that's used in the surrounding template?

A: I don't believe you can do what you are looking to do with bind-at directives, or at least, I haven't found a way. You should be able to use a snippet to accomplish something similar though.
For example, if you are using SiteMap, the following should be roughly equivalent.
class TitleSnippet {
  //Store the value in a requestVar
  private var titleVar:String = ""

  def first = {
    //Retrieve the title for the current Loc as defined in the Sitemap
    val locTitle = for (request <- S.request;
      loc <- request.location) yield loc.title

    //Retrieve the text portion of the tag, and append it to the sitemap title.
    //If no sitemap title exists, just display the text
    "* *" #> { ns =>
      val myTitle = locTitle.map{ t =>
        "%s | %s".format(ns.text, t)
      } openOr ns.text
      titleVar = myTitle
      Text(myTitle)
    }
  }

  def title = {
    "* *" #> titleVar
  }
}

Then, in your template, all you'd have to do is say:
<title data-lift="TitleSnippet.first">Home</title>

So, if we had a page defined like this in the sitemap:
Menu("Sub Page 1") / "subpage"

If everything worked, you should see a title like: <title>Home | Sub Page 1</title> and if you need it elsewhere on the page, all you would have to do is:

.
If you need access from other snippets, you can also break out titleVar into a companion object and use a RequestVar.


text:
Q: Joining multiple excel defined name range (including pivot tables) in one pivot table I hope someone can answer the following question.
This is the scenario:
In Sheet1 I have a Pivot table from ColumnA to columnC with formulas running from ColumnD to ColumnZ.
Sheet2 has a Pivot table from ColumnA to ColumnE with formulas running from ColumnF to ColumnL
For both sheets I have created a dynamic name range called: Sheet1FullTable (Pivot+Formulas) and Sheet2FullTable
Both dynamic ranges have in common 1 field which is my "keyID"
Is there a way I can merge the 2 Dynamic ranges into a Pivot Table?
Or a way to query data out of the 2 dynamic range which I can later use for a pivot table?
Thank you,

A: You can use Name Manager to create a new named range with existing named ranges:

*

*Go to "Name Manager" (ctrl-F3)

*Click New...

*Name your range

*Refers to =namedrange1,namedrange2,etc


text:
Q: universal select(mysql) function using prepared statements using php language I am trying to create a universal method/function on php which uses any select statement with a where clause. However, something is not right. Can you give me a hand?
Example of using data:
DB inherit PDO class.
$db=new DB;
$db->select("SELECT count(*) FROM `login` WHERE Email='?'",
            "papa1980@gmail.com");

Here is function
public function select($sqlString,...$bindParameters)
{

   $stmt=$this->prepare($sqlString);
   foreach($bindParameters as $key=>$bindParameter)
   {

       $stmt->bindParam(($key+1),$bindParameter);
       echo '
' . print_r($stmt, true) . '
';
   }
   echo '
' . print_r($bindParameters, true) . '
';
   if($stmt->execute())
   {
       echo "execution was succesful";
   }
  echo '
' . print_r($stmt->fetchAll(), true) . '
';
}

Output
PDOStatement Object
(
    [queryString] => SELECT count(*) FROM login WHERE Email='?'
)
Array
(
    [0] => papa1980@gmail.com
)
execution was succesful
Array
(
    [0] => Array
        (
            [count(*)] => 0
            [0] => 0
        )
)
Why is it returning 0? I use
SELECT count(*) FROM `login` WHERE Email='papa1980@gmail.com'

in mysql and it returns 1. Something is not correct in my php code.

A: Function is working but
SELECT count(*) FROM login WHERE Email=? was wrong because ? shall be not in ''


text:
Q: Javascript not render in IE I have this script, it work fine in any browser except IE. I am using IE 11
let liItem = Array.from(document.querySelectorAll('#DeltaTopNavigation>div>ul>li>ul'));
alert(liItem[0].textContent);

liItem[0].style.borderTop='red';

I can't even get alert from code above.

A: According to this link Array.from() , Array.from is not supported in IE because its part of ES6 specifications which are not fully supported in IE 11. You need to polyfill it.
Try one of the below polyfills:
NPM link - array.from
ES6-shim
polyfill.js

A: Thank guys for feedback. i got working using this:
var divs = document.querySelectorAll('#DeltaTopNavigation>div>ul>li>ul'), i;

for (i = 0; i < divs.length; ++i) {
  divs[0].style.borderTop='red';
}


text:
Q: A word to describe meaningless exchanges in conversation I am looking for a word which describes meaningless exchanges in conversation e.g. "How are you doing?" "Good, good, you?" "Good." "See you later."
That is, in the asking of "How are you?" there is no expectation to find out how the person is actually doing - a perfunctory "good" is anticipated and expected. That is, passing exchanges where little to nothing is actually said or inquired.

A: There is actually a word that describes precisely this type of chitchat: you're looking for the word phatic.

phat·ic /ˈfatik/ adj.
  denoting or relating to language used for general purposes of social interaction, rather than to convey information or ask questions. Utterances such as hello, how are you? and nice morning, isn't it? are phatic.

(From Oxford Dictionaries Online, my emphasis)

A: While such exchanges are usually referred to as small talk, a single word that means much the same thing is chatter:

chatter, n.: continuous fast informal talk, usually about unimportant subjects

A: What you call meaningless conversation is a chapter in "social conventions".

A convention is a set of agreed, stipulated, or generally accepted standards, norms, social norms, or criteria, often taking the form of a custom. In a social context, a convention may retain the character of an "unwritten law" of custom (for example, the manner in which people greet each other, such as by shaking each other's hands). Wikipedia

A: des·ul·to·ry
ˈdesəlˌtôrē/Submit
adjective
lacking a plan, purpose, or enthusiasm.
"a few people were left, dancing in a desultory fashion"
synonyms:   casual, cursory, superficial, token, perfunctory, half-hearted, lukewarm; More
(of conversation or speech) going constantly from one subject to another in a halfhearted way; unfocused.
"the desultory conversation faded"

A: Banter

ban•ter (ˈbæn tər)
  n.
  1. an exchange of light, playful remarks; good-natured raillery.
  v.t.
  2. to address with banter; chaff.
  v.i.
  3. to use banter.

http://www.thefreedictionary.com/banter
If the banter is fairly banal then it can be referred to as meaningless banter


text:
Q: How to generate grid of dots from image array with interval x? Suppose I have an image 1000x1000, I want to put a red dot every 10 pixels. How to generate such an array?
M, N = 5, 8

x = np.linspace(0,1000,M+1)
y = np.linspace(0,1000,N+1)
X,Y = np.meshgrid(x,y)

positions = np.vstack([Y.ravel(), X.ravel()])

for x in positions:
    cv2.circle(img,(x[0], x[1]), 5, (0,255,0), 2)

A: You can try something like this,
x = np.linspace(0,1000, 1000/10)
y = np.linspace(0,1000, 1000/10)
X,Y = np.meshgrid(x,y)

positions = np.column_stack([X.ravel(), Y.ravel()]).astype(int)

for (x,y) in (positions):
    cv2.circle(img,(x,y), 1, (0,0,255), -1)

The following two lines will create a linespace of 100 pixels with a space of 10 pixels in each dimension
x = np.linspace(0,1000, 1000/10)
y = np.linspace(0,1000, 1000/10)

Then, create a grid from the spaces using np.meshgrid. Then, create stacked columns from the raveled vectors of the grid. Make sure to convert your positions to int, since open cv accepts the center of your circle to be an int. Finally, use cv2.circle to plot the points, open cv accepts color as BGR so (0,0,255) will give you a red color. Since it's a point you use a radius of 1 and a thickness of -1.


text:
Q: Excel Copy Paste 2 rows but only move one row Below is a picture of the set up I am trying to get.

CA2 is shown below and gets data from Column AX Row 2.

CA3 is shown below and gets data from Column AB Row 2 as well..

When I copy and paste the above cells they give me row 4, since I am skipping 2 rows that makes sense. What I would like to do is return 1 row back moving down the rows. So instead of copy/pasting and going to AX4, would like to keep the formula, copy both cells and return AX3 for both copied rows.. and so on down the sheet.
Is this possible?

A: If I got your problem right, you could try something like this :

=INDEX($E$2:$E$12,ROW()/2)
=INDEX($F$2:$F$12,ROW()/2)


text:
Q: Renaming Sheets from cells with a loop The code below is what i use to rename a bunch of sheets within a workbook. it works perfectly. It renames the sheet based off of a cell in that sheet. but now i have two sheets trying to use the same name. So i want to keep the same code but add a loop so if that happens, it will add a "2" to the second sheet. Ie cell contains "John Doe". Sheet will rename to "John Doe" and the next sheet that tries to use it will rename "John Doe 2"
Thank you
Sub RenameLaborLog()
    Dim rs As Worksheet
    For Each rs In Sheets
        rs.Name = Split(rs.Range("H4").Value, " ")(1) & ", " & Left(Split(rs.Range("H4").Value)(0), 1) & "."

    Next rs
End Sub

A: Use a controlled error to adjust the string containing the worksheet name until it find something it can use.
Sub RenameLaborLog()
    Dim rs As Worksheet, snam As String, idupe As Long

    On Error GoTo bm_Dupe_WS_Name

    For Each rs In Sheets
        idupe = 1
        snam = Split(rs.Range("H4").Value, " ")(1) & ", " & _
               Left(Split(rs.Range("H4").Value)(0), 1) & "."
        rs.Name = snam
    Next rs

bm_Dupe_WS_Name:

    If idupe > 8 Then
        Debug.Print Err.Number & ": " & snam & " - " & Err.Description
        Exit Sub
    ElseIf Right(snam, 1) = CStr(idupe) Then
        snam = Trim(Left(snam, Len(snam) - 1))
    End If
    idupe = idupe + 1
    snam = snam & Chr(32) & idupe
    Resume
End Sub

I have it set yo attempt a numerical suffix up to 9. It it reaches that, it reports the error and exits the sub. I would not recommend running this without an escape clause. If nothing else, you may run into an illegal character when parsing the string for the worksheet name.

A: Jeeped beat me to it, but here is another possible adjustment you could make:
Sub RenameLaborLog()

    Dim rs As Worksheet, wsName As String, wsCheck As Worksheet, i As Integer

    For Each rs In Sheets
        ' Get the sheet name
        wsName = Split(rs.Range("H4").Value, " ")(1) & ", " & Left(Split(rs.Range("H4").Value)(0), 1) & "."
        ' Check if it exists
        Set wsCheck = Nothing: On Error Resume Next: Set wsCheck = wsName: On Error GoTo 0
        ' Check if multiples already exist
        While Not wsCheck Is Nothing
            ' If even one exits, "i" will be iterated
            i = i + 1
            Set wsCheck = Nothing: On Error Resume Next: Set wsCheck = wsName & "_" & i: On Error GoTo 0
        Wend
        ' If at least one name already existed, name it with the current iteration.
        If Not i = 0 Then wsName = wsName & "_" & i
        rs.Name = wsName
    Next rs
    Set rs = Nothing: Set wsCheck = Nothing

End Sub

A: Based on the link @Scott Craner provided in his comment, I am providing another solution that I believe is a bit more functional and cleaner and easier to read.
Sub RenameLaborLog()

    Dim rs As Worksheet, sName As String
    For Each rs In Sheets

        sName = Split(rs.Range("H4").Value, " ")(1) & ", " & Left(Split(rs.Range("H4").Value)(0), 1) & "."

        i = 1

        Do

            If Not WorksheetExist(sName) Then
                rs.Name = sName
                Exit Do
            Else: sName = sName & "_" & i + 1
            End If

        Loop

    Next rs

End Sub

Function WorksheetExist(sName As String, Optional wb As Workbook) As Boolean

Dim wbCheck As Workbook, ws As Worksheet
If wb Is Nothing Then Set wbCheck = ThisWorkbook Else: Set wbCheck = wb

WorksheetExist = False

For Each ws In wbCheck.Worksheets
    If ws.Name = sName Then
        WorksheetExist = True
        Exit For
    End If
Next

End Function

A: just to show another way you can reach your goal
Sub RenameLaborLog()
  Dim rs As Worksheet, i As Long, str As String
  On Error Resume Next
  For Each rs In Sheets
    str = Split(rs.Range("H4").Value, " ")(1) & ", " & Left(Split(rs.Range("H4").Value)(0), 1) & "."
    rs.Name = str
    i = 1
    While Err.Number <> 0 And i < 20
      Err.Clear: i = i + 1
      rs.Name = str & i
    Wend
    If Err.Number <> 0 Then MsgBox "Error: " & rs.Name & " cant be set to any " & str: Exit Sub
  Next rs
End Sub

it tries to set the name (and if that is not working it sets the name & 2 - 19 (if that doesnt work, it pops up a message box and exits the sub)


text:
Q: c++ windows keep track of file writes by processes I need to track the creation/reading/writing/... of files by processes.
Tell me how can I implement this?
I found the ReadDirectoryChanges function, but it doesn't give the process name.
windows, C ++


text:
Q: How can I simplify a large scale NLP model in Gekko Python? I'm still new to Gekko optimization in Python, and I have a problem scaling up my NLP problem.
After trying to call several times (And in different ways) the function m.Sum, using m.Intermediate and using list comprehensions for reducing the size of the string representing my model, I still get this error while trying to optimize a model that only has 200 variables. The model works when I optimize for only 80 variables.
This is the error I get:
APM model error: string > 15000  characters
 Consider breaking up the line into multiple equations

 The may also be due to only using newline character CR
   instead of CR LF (for Windows) or LF (for MacOS/Linux)
 To fix this problem, save APM file with appropriate newline characters

 STOPPING...

Here's a snippet of the code that's getting me in trouble:
def function_to_minimize(variables0,m):
    somme = [ m.Intermediate(
                    variables0[0+(4*i)] * df['value1'][i] + \
                    variables0[1+(4*i)] * df['value2'][i] + \
                    variables0[2+(4*i)] * df['value3'][i] + \
                    variables0[3+(4*i)] * df['value4'][i]
     ) for i in range(0,hours)]

    somme = reduce(lambda a, b: a+b, somme)
    m.Obj(m.Intermediate(somme))

A: Try calling m.Obj() multiple times instead of creating a summation. Below is a minimal complete problem that demonstrates the issue. If v = m.Array(m.Var,100,lb=0,ub=10) is an array of more variables then the 15,000 equation length limit could be reached.
from gekko import GEKKO
m = GEKKO()
v = m.Array(m.Var,100,lb=0,ub=10)
hours = 24
def function_to_minimize(variables0,m):
    somme = [ m.Intermediate(
                    variables0[0+(4*i)] * 1 + \
                    variables0[1+(4*i)] * 2 + \
                    variables0[2+(4*i)] * 3 + \
                    variables0[3+(4*i)] * 4
     ) for i in range(0,hours)]
    somme = sum(somme)
    m.Minimize(m.Intermediate(somme))
function_to_minimize(v,m)
m.solve()

Use m.sum() to avoid the limit.
from gekko import GEKKO

m = GEKKO()
v = m.Array(m.Var,100,lb=0,ub=10)
hours = 24

def function_to_minimize(variables0,m):
    somme = [ m.Intermediate(
                    variables0[0+(4*i)] * 1 + \
                    variables0[1+(4*i)] * 2 + \
                    variables0[2+(4*i)] * 3 + \
                    variables0[3+(4*i)] * 4
     ) for i in range(0,hours)]

    m.Minimize(m.sum(somme))
function_to_minimize(v,m)
m.solve()

or call m.Obj() or m.Minimize() separately for each element with [m.Minimize(s) for s in somme].
from gekko import GEKKO

m = GEKKO()
v = m.Array(m.Var,100,lb=0,ub=10)
hours = 24

def function_to_minimize(variables0,m):
    somme = [ m.Intermediate(
                    variables0[0+(4*i)] * 1 + \
                    variables0[1+(4*i)] * 2 + \
                    variables0[2+(4*i)] * 3 + \
                    variables0[3+(4*i)] * 4
     ) for i in range(0,hours)]

    [m.Minimize(s) for s in somme]
function_to_minimize(v,m)
m.solve()


text:
Q: Symfony 2: How to build a really simple form, with just one field and use it in controller I'm building a get started procedure. It is really very simple: just one field for the email and a submit button.
HOW DOES THE PROCEDURE WORKS
I simply have one controller with two methods: indexAction() and endAction()
The indexAction simply set the route using annotations and displays the twig template with an handmade form:
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class GetStartedController extends Controller
{
    /**
     * @Route("getstarted")
     * @Template()
     */
    public function indexAction()
    {
        return array(
            // ...
        );
    }

    /**
     * @Route("getstarted/end", name="getStartedEnd")
     * @Template()
     */
    public function endAction(Request $request)
    {

    // ... other code

As you can see, currently the method really does nothing as the form is handmade directly in the twig template.
Here is the code to render the form (handmade in the twig template):
{% extends "::base.html.twig" %}

{% block title %}AppBundle:GetStarted:index{% endblock %}

{% block body %}
<form id="getStarted" action="{{ path('getStartedEnd') }}" method="post">

        <input type="email" name="userEmail" class="form-control input-lg" placeholder="Enter your e-mail (es.: your.name@example.com">

    <button type="submit" name="submit" class="btn btn-default btn-lg">Submit</button>
</form>
{% endblock %}

I know Symfony 2 can handle the creation of the form and its rendering on the page, but this is a very simple form and I know it never will be more complicate, so an handmade one is the simplest and fastest solution.
Now, what's the problem? The problem is I don't understand how to get the form and its submitted values in my controller, in the other method, endAction().
The form has as action the path to the other method, endAction() where, in my intentions, I will retrieve the submitted values and do some stuff with them.
Following the instructions in paragraph Using a Form without a Class, i came up with the following code for the method endAction() that, in my intentions, will retrieve the submitted email and do something with it - will create a user, obviously - (note the exit to simply print the results of the if)
/**
 * @Route("getstarted/end", name="getStartedEnd")
 * @Template()
 */
public function endAction(Request $request)
{
    $form = $this->createFormBuilder()
        ->add('userEmail', 'email')
        ->add('submit', 'submit')
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        $data = $form->getData();
        print_r($data);
    } else {
        echo 'no data submitted';
    }

    exit;

    return array(
            // ...
        );
}

The problem is that if ($form->isValid()) { ever returns false and I ever obtain as result the printing of echo 'no data submitted';
Clearly there is something wrong with my implementation of the form handling, but... What?
This is my question: what am I doing wrong? Why the form isn't "intercepted" in the controller?

A: You have two things to do:
First, edit your Form template and use the correct names (name="form[userEmail]" instead of name="userEmail"):
<form name="form" method="post" action="{{ path('getStartedEnd') }}">

            User email
            <input type="email" id="form_userEmail" name="form[userEmail]" required="required"/>

            <button type="submit" id="form_submit" name="form[submit]">Submit</button>

</form>

And second disable the csrf protection of the form:
/**
 * @Route("getstarted/end", name="getStartedEnd")
 * @Template()
 */
public function endAction(Request $request)
{
   $data = array();
    $form = $this->createFormBuilder($data, array(
        'csrf_protection' => false,
    ))
    ->add('userEmail', 'email')
    ->add('submit', 'submit')
    ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        $data = $form->getData();
        print_r($data);
    } else {
        echo 'no data submitted';
    }

    exit;

    return array(
        // ...
    );

 }

But recommend strongly not to render the form by hand!
It's not more than:
/**
 * @Route("getstarted")
 * @Template()
 */
public function indexAction()
{
    $data = array();
    $form = $this->createFormBuilder($data, array(
        'action' => $this->generateUrl('getStartedEnd'),
    ))
    ->add('userEmail', 'email')
    ->add('submit', 'submit')
    ->getForm();

    return array(
        'form' => $form->createView(),
    );
}

and in your template:
{# just this line #}
{{ form(form) }}


text:
Q: PySpark list() in withColumn() only works once, then AssertionError: col should be Column I have a DataFrame with 6 string columns named like 'Spclty1'...'Spclty6' and another 6 named like 'StartDt1'...'StartDt6'. I want to zip them and collapse into a columns that looks like this:
[[Spclty1, StartDt1]...[Spclty6, StartDt6]]
I first tried collapsing just the 'Spclty' columns into a list like this:
DF = DF.withColumn('Spclty', list(DF.select('Spclty1', 'Spclty2', 'Spclty3', 'Spclty4', 'Spclty5', 'Spclty6')))

This worked the first time I executed it, giving me a new column called 'Spclty' containing rows such as ['014', '124', '547', '000', '000', '000'], as expected.
Then, I added a line to my script to do the same thing on a different set of 6 string columns, named 'StartDt1'...'StartDt6':
DF = DF.withColumn('StartDt', list(DF.select('StartDt1', 'StartDt2', 'StartDt3', 'StartDt4', 'StartDt5', 'StartDt6'))))

This caused AssertionError: col should be Column.
After I ran out of things to try, I tried the original operation again (as a sanity check):
DF.withColumn('Spclty', list(DF.select('Spclty1', 'Spclty2', 'Spclty3', 'Spclty4', 'Spclty5', 'Spclty6'))).collect()

and got the assertion error as above.
So, it would be good to understand why it only worked the first time (only), but the main question is: what is the correct way to zip columns into a collection of dict-like elements in Spark?

A: .withColumn() expects a column object as second parameter and you are supplying a list.

A: Thanks. After reading a number of SO posts I figured out the syntax for passing a set of columns to the col parameter, using struct to create an output column that holds a list of values:
DF_tmp = DF_tmp.withColumn('specialties', array([
        struct(
         *(col("Spclty{}".format(i)).alias("spclty_code"),
         col("StartDt{}".format(i)).alias("start_date"))
        )
        for i in range(1, 7)
      ]
))

So, the col() and *col() constructs are what I was looking for, while the array([struct(...)]) approach lets me combine the 'Spclty' and 'StartDt' entries into a list of dict-like elements.


text:
Q: why this css selector is not working with fontawsome When i try to apply jquery event or css style on element  it does not work, instead if use a static one like id="delCoord" and change the css/jquery even listener, it works. Can someone explain why
note i use fontawsome free 5.6.3.
Thanks

$('body').on('click', 'span[id^="edit-delCoordSet"]', function() {
  alert('YOU SHOULD SEE ME !!!!!');
  return false; // i just set this up for tests !!!
  var coordsValueIdx = $(this).parent('.editCoords').attr('data-elNumber');
  console.log('try to delete: ' + $(this).attr('id'));
  jqEl = $(this);
  console.log('html element ' + jqEl);
  updateCaveCoords(coordsValueIdx, '', '', jqEl, add = false, del = true, modify = false)
});
span[id^="edit-delCoordSet"] {
  padding: 0.3em 1em 0.3em 1em;
}

span[id^="edit-delCoordSet"]:hover {
  background-color: grey;
}
<link href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" rel="stylesheet" />

  X:<input type="text" class="coords" data-elnumber="0" value="4.8552"> Y:
  <input type="text" class="coords" data-elnumber="1" value="43.32000"> Z:
  <input type="text" class="coords" data-elnumber="2" value="475">

  X:<input type="text" class="coords" data-elnumber="0" value="4.8552"> Y:
  <input type="text" class="coords" data-elnumber="1" value="43.32000"> Z:
  <input type="text" class="coords" data-elnumber="2" value="475">

A: Ok I found the culprit !
I was using fontawsome jquery extensions. So my  was replace by  tags (with the same id and settings of course).
I change fontawsome loading with this options :
data-auto-replace-svg="nest"
More info there https://fontawesome.com/how-to-use/on-the-web/using-with/jquery


text:
Q: how to pass python method and kwargs to boost python c++ function and call how do I pass a python method and kwargs to a boost C++ function and call the python method with kwargs.
python:
def py_method(**kwargs):
    for key in kwargs.keys():
        print 'Key: ', key, ', Value: ', kwargs[key]

cpp_method(py_method, arg1=1, arg2=2)

or

kwargs = {'arg1': 1, 'arg2': 2}
cpp_method(py_method, **kwargs)

C++: please help me to correct the below code.
using namespace boost::python;

void cpp_method(object py_method, object kwargs)
py_method(kwargs)

Thanks to Dan Mašek for pointing this link
Compiled on MacOS HighSierra and getting segmentation fault:
g++ -std=c++11 -I/Library/Frameworks/Python.framework/Versions/2.7/Headers -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"foo.d" -MT"foo.o" -o "foo.o" foo.cpp

g++ -L/usr/local/lib -L/Library/Frameworks/Python.framework/Versions/2.7/ -shared -o foo.so  ./foo.o   -lboost_python27 -lPython

$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> dir(foo)
['__doc__', '__file__', '__name__', '__package__', 'cpp_method']
>>> def py_method(**kwargs):
...     print 'from py_method'
...     print kwargs
...
>>> kwargs = {'arg1': 1, 'arg2': 2}
>>> foo.cpp_method(py_method, kwargs)
Segmentation fault: 11

Process:               Python [22790]
Path:                  /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Identifier:            Python
Version:               2.7.14 (2.7.14)
Code Type:             X86-64 (Native)
Parent Process:        bash [368]
Responsible:           Python [22790]
User ID:               501

Date/Time:             2018-10-04 16:54:51.618 -0700
OS Version:            Mac OS X 10.13.6 (17G65)
Report Version:        12
Anonymous UUID:        3A7BC812-2E65-69A4-936B-21E5CE648BCF

Sleep/Wake UUID:       E32B82BD-2B4C-4220-A9C2-F71FF57DDA56

Time Awake Since Boot: 580000 seconds
Time Since Wake:       2700 seconds

System Integrity Protection: disabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000048
Exception Note:        EXC_CORPSE_NOTIFY

Termination Signal:    Segmentation fault: 11
Termination Reason:    Namespace SIGNAL, Code 0xb
Terminating Process:   exc handler [0]

VM Regions Near 0x48:
-->
    __TEXT                 0000000100000000-0000000100001000 [    4K] r-x/rwx SM=COW  /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   org.python.python               0x00007fff3bfaec5c PyErr_Occurred + 14
1   org.python.python               0x00007fff3bf2bdf5 PyObject_IsInstance + 401
2   foo.so                          0x0000000100799aaf boost::python::converter::pyobject_type::check(_object*) + 31 (pyobject_type.hpp:24)
3   foo.so                          0x0000000100799918 boost::python::converter::object_manager_value_arg_from_python::convertible() const + 24 (obj_mgr_arg_from_python.hpp:69)
4   foo.so                          0x00000001007997e1 boost::python::detail::caller_arity::impl >::operator()(_object*, _object*) + 129 (local.hpp:37)
5   foo.so                          0x00000001007996e4 boost::python::objects::caller_py_function_impl > >::operator()(_object*, _object*) + 52 (py_function.hpp:38)
6   libboost_python27.dylib         0x000000010190e1a4 boost::python::objects::function::call(_object*, _object*) const + 820
7   libboost_python27.dylib         0x0000000101910d5a boost::detail::function::void_function_ref_invoker0::invoke(boost::detail::function::function_buffer&) + 26
8   libboost_python27.dylib         0x0000000101916f48 boost::python::handle_exception_impl(boost::function0) + 72
9   libboost_python27.dylib         0x0000000101910871 boost::python::objects::function_call(_object*, _object*, _object*) + 81
10  org.python.python               0x000000010000c2e2 PyObject_Call + 98
11  org.python.python               0x00000001000c30b1 PyEval_EvalFrameEx + 15777
12  org.python.python               0x00000001000cac23 PyEval_EvalCodeEx + 2115
13  org.python.python               0x00000001000cad46 PyEval_EvalCode + 54
14  org.python.python               0x00000001000ef7ec PyRun_InteractiveOneFlags + 380
15  org.python.python               0x00000001000efa4e PyRun_InteractiveLoopFlags + 78
16  org.python.python               0x00000001000f0261 PyRun_AnyFileExFlags + 161
17  org.python.python               0x00000001001071dd Py_Main + 3101
18  org.python.python               0x0000000100000f14 0x100000000 + 3860

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000000  rbx: 0x0000000000000002  rcx: 0x0000000000000001  rdx: 0x0000000000000003
  rdi: 0x00007fff8cc80458  rsi: 0x00000001007b4030  rbp: 0x00007ffeefbff210  rsp: 0x00007ffeefbff210
   r8: 0x00000001007b4030   r9: 0x8c8bb1dcac69804a  r10: 0x0000000000001002  r11: 0xffff8001c47c5769
  r12: 0x0000000000000000  r13: 0x0000000100702a70  r14: 0x0000000100728280  r15: 0x00007fff8cc784f0
  rip: 0x00007fff3bfaec5c  rfl: 0x0000000000010246  cr2: 0x0000000000000048

Logical CPU:     3
Error Code:      0x00000004
Trap Number:     14

Binary Images:
       0x100000000 -        0x100000fff +org.python.python (2.7.14 - 2.7.14)  /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
       0x100003000 -        0x100177fef +org.python.python (2.7.14, [c] 2001-2017 Python Software Foundation. - 2.7.14)  /Library/Frameworks/Python.framework/Versions/2.7/Python
       0x1002ec000 -        0x1002eeff7 +_locale.so (???)  /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so
       0x1002f2000 -        0x1002f4ff7 +readline.so (???)  /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/readline.so
       0x100730000 -        0x100784fe7 +libncursesw.5.dylib (5)  /Library/Frameworks/Python.framework/Versions/2.7/lib/libncursesw.5.dylib
       0x100795000 -        0x10079bfff +foo.so (0)  /Users/USER/*/foo.so
       0x101900000 -        0x10192dfff +libboost_python27.dylib (0)  /usr/local/opt/boost-python/lib/libboost_python27.dylib
       0x10c12a000 -        0x10c174acf  dyld (551.4)  /usr/lib/dyld
    0x7fff31701000 -     0x7fff31ba2fef  com.apple.CoreFoundation (6.9 - 1454.90)  /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
    0x7fff3bf21000 -     0x7fff3c010ff7  org.python.python (2.7.10 - 2.7.10)  /System/Library/Frameworks/Python.framework/Versions/2.7/Python
    0x7fff56da2000 -     0x7fff56dd5ff7  libclosured.dylib (551.4)  /usr/lib/closure/libclosured.dylib
    0x7fff56f66000 -     0x7fff56f67ff3  libDiagnosticMessagesClient.dylib (104)  /usr/lib/libDiagnosticMessagesClient.dylib
    0x7fff572dc000 -     0x7fff572ddffb  libSystem.B.dylib (1252.50.4)  /usr/lib/libSystem.B.dylib
    0x7fff57511000 -     0x7fff57567fff  libc++.1.dylib (400.9)  /usr/lib/libc++.1.dylib
    0x7fff57568000 -     0x7fff5758cff7  libc++abi.dylib (400.8.2)  /usr/lib/libc++abi.dylib
    0x7fff57ec3000 -     0x7fff57ee1ff7  libedit.3.dylib (50)  /usr/lib/libedit.3.dylib
    0x7fff5803c000 -     0x7fff58263ffb  libicucore.A.dylib (59180.0.1)  /usr/lib/libicucore.A.dylib
    0x7fff585c0000 -     0x7fff585f0ffb  libncurses.5.4.dylib (53)  /usr/lib/libncurses.5.4.dylib
    0x7fff58995000 -     0x7fff58d837e7  libobjc.A.dylib (723)  /usr/lib/libobjc.A.dylib
    0x7fff593ab000 -     0x7fff593bdffb  libz.1.dylib (70)  /usr/lib/libz.1.dylib
    0x7fff59459000 -     0x7fff5945dff7  libcache.dylib (80)  /usr/lib/system/libcache.dylib
    0x7fff5945e000 -     0x7fff59468ff3  libcommonCrypto.dylib (60118.50.1)  /usr/lib/system/libcommonCrypto.dylib
    0x7fff59469000 -     0x7fff59470fff  libcompiler_rt.dylib (62)  /usr/lib/system/libcompiler_rt.dylib
    0x7fff59471000 -     0x7fff5947affb  libcopyfile.dylib (146.50.5)  /usr/lib/system/libcopyfile.dylib
    0x7fff5947b000 -     0x7fff59500fff  libcorecrypto.dylib (562.70.1)  /usr/lib/system/libcorecrypto.dylib
    0x7fff59588000 -     0x7fff595c1ff7  libdispatch.dylib (913.60.2)  /usr/lib/system/libdispatch.dylib
    0x7fff595c2000 -     0x7fff595dfff7  libdyld.dylib (551.4)  /usr/lib/system/libdyld.dylib
    0x7fff595e0000 -     0x7fff595e0ffb  libkeymgr.dylib (28)  /usr/lib/system/libkeymgr.dylib
    0x7fff595ee000 -     0x7fff595eeff7  liblaunch.dylib (1205.70.9)  /usr/lib/system/liblaunch.dylib
    0x7fff595ef000 -     0x7fff595f3ffb  libmacho.dylib (906)  /usr/lib/system/libmacho.dylib
    0x7fff595f4000 -     0x7fff595f6ff3  libquarantine.dylib (86)  /usr/lib/system/libquarantine.dylib
    0x7fff595f7000 -     0x7fff595f8ff3  libremovefile.dylib (45)  /usr/lib/system/libremovefile.dylib
    0x7fff595f9000 -     0x7fff59610fff  libsystem_asl.dylib (356.70.1)  /usr/lib/system/libsystem_asl.dylib
    0x7fff59611000 -     0x7fff59611fff  libsystem_blocks.dylib (67)  /usr/lib/system/libsystem_blocks.dylib
    0x7fff59612000 -     0x7fff5969bff7  libsystem_c.dylib (1244.50.9)  /usr/lib/system/libsystem_c.dylib
    0x7fff5969c000 -     0x7fff5969fffb  libsystem_configuration.dylib (963.50.8)  /usr/lib/system/libsystem_configuration.dylib
    0x7fff596a0000 -     0x7fff596a3ffb  libsystem_coreservices.dylib (51)  /usr/lib/system/libsystem_coreservices.dylib
    0x7fff596a4000 -     0x7fff596a5fff  libsystem_darwin.dylib (1244.50.9)  /usr/lib/system/libsystem_darwin.dylib
    0x7fff596a6000 -     0x7fff596acff7  libsystem_dnssd.dylib (878.70.2)  /usr/lib/system/libsystem_dnssd.dylib
    0x7fff596ad000 -     0x7fff596f6ff7  libsystem_info.dylib (517.30.1)  /usr/lib/system/libsystem_info.dylib
    0x7fff596f7000 -     0x7fff5971dff7  libsystem_kernel.dylib (4570.71.2)  /usr/lib/system/libsystem_kernel.dylib
    0x7fff5971e000 -     0x7fff59769fcb  libsystem_m.dylib (3147.50.1)  /usr/lib/system/libsystem_m.dylib
    0x7fff5976a000 -     0x7fff59789fff  libsystem_malloc.dylib (140.50.6)  /usr/lib/system/libsystem_malloc.dylib
    0x7fff5978a000 -     0x7fff598baff7  libsystem_network.dylib (1229.70.2)  /usr/lib/system/libsystem_network.dylib
    0x7fff598bb000 -     0x7fff598c5ffb  libsystem_networkextension.dylib (767.70.1)  /usr/lib/system/libsystem_networkextension.dylib
    0x7fff598c6000 -     0x7fff598cfff3  libsystem_notify.dylib (172)  /usr/lib/system/libsystem_notify.dylib
    0x7fff598d0000 -     0x7fff598d7ff7  libsystem_platform.dylib (161.50.1)  /usr/lib/system/libsystem_platform.dylib
    0x7fff598d8000 -     0x7fff598e3fff  libsystem_pthread.dylib (301.50.1)  /usr/lib/system/libsystem_pthread.dylib
    0x7fff598e4000 -     0x7fff598e7fff  libsystem_sandbox.dylib (765.70.1)  /usr/lib/system/libsystem_sandbox.dylib
    0x7fff598e8000 -     0x7fff598e9ff3  libsystem_secinit.dylib (30)  /usr/lib/system/libsystem_secinit.dylib
    0x7fff598ea000 -     0x7fff598f1ff7  libsystem_symptoms.dylib (820.60.2)  /usr/lib/system/libsystem_symptoms.dylib
    0x7fff598f2000 -     0x7fff59905fff  libsystem_trace.dylib (829.70.1)  /usr/lib/system/libsystem_trace.dylib
    0x7fff59907000 -     0x7fff5990cff7  libunwind.dylib (35.3)  /usr/lib/system/libunwind.dylib
    0x7fff5990d000 -     0x7fff5993aff7  libxpc.dylib (1205.70.9)  /usr/lib/system/libxpc.dylib

External Modification Summary:
  Calls made by other processes targeting this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by all processes on this machine:
    task_for_pid: 577992
    thread_create: 0
    thread_set_state: 0

VM Region Summary:
ReadOnly portion of Libraries: Total=213.0M resident=0K(0%) swapped_out_or_unallocated=213.0M(100%)
Writable regions: Total=38.3M written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=38.3M(100%)

                                VIRTUAL   REGION
REGION TYPE                        SIZE    COUNT (non-coalesced)
===========                     =======  =======
Activity Tracing                   256K        2
Kernel Alloc Once                    8K        2
MALLOC                            29.5M       12
MALLOC guard page                   16K        5
STACK GUARD                       56.0M        2
Stack                             8192K        2
VM_ALLOCATE                        256K        2
__DATA                            4532K       57
__LINKEDIT                       193.6M       10
__TEXT                            19.4M       55
__UNICODE                          560K        2
shared memory                       12K        4
===========                     =======  =======
TOTAL                            312.0M      143

Model: MacBookPro12,1, BootROM MBP121.0177.B00, 2 processors, Intel Core i7, 3.1 GHz, 16 GB, SMC 2.28f7
Graphics: Intel Iris Graphics 6100, Intel Iris Graphics 6100, Built-In
Memory Module: BANK 0/DIMM0, 8 GB, DDR3, 1867 MHz, 0x02FE, 0x4544464232333241314D412D4A442D460000
Memory Module: BANK 1/DIMM0, 8 GB, DDR3, 1867 MHz, 0x02FE, 0x4544464232333241314D412D4A442D460000
AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x133), Broadcom BCM43xx 1.0 (7.77.37.31.1a9)
Bluetooth: Version 6.0.7f10, 3 services, 27 devices, 1 incoming serial ports
Network Service: Wi-Fi, AirPort, en0
Serial ATA Device: APPLE SSD SM0512G, 500.28 GB
USB Device: USB 3.0 Bus
USB Device: Bluetooth USB Host Controller
Thunderbolt Bus: MacBook Pro, Apple Inc., 27.1

A: I solved it with pybind11, much easier than boost-python
cpp.cpp:
#include <pybind11/pybind11.h>
#include <iostream>

namespace py = pybind11;

void cpp_method(py::object method, py::kwargs kw) {
    py::object obj = method(**kw);
    std::cout << "Printing from cpp: " << std::string(py::str(obj)) << std::endl;
}

PYBIND11_MODULE(cpp, mod) {
    mod.def("cpp_method", &cpp_method);
}

compilation:
c++ -O3 -Wall -shared -std=c++11 -fPIC `python -m pybind11 --includes` cpp.cpp -o cpp.so `python-config --ldflags`

python:
$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cpp
>>> dir(cpp)
['__doc__', '__file__', '__name__', '__package__', 'cpp_method']
>>> def py_method(**kwargs):
...     print 'Printing from python, kwargs: ', kwargs
...     return 'py_method return string'
...
>>> cpp.cpp_method(py_method, a=1, b=2, c=3)
Printing from python, kwargs:  {'a': 1, 'c': 3, 'b': 2}
Printing from cpp: py_method return string


text:
Q: Jenkins - Defining users I just installed jenkins in my pc. It is a Windows 7 and i used the
*.exe file.
Now i just run the msbuild using the targets: clean, init, compile,
test and coverage. After i have a windows batch command for run fxCop.
Now i want to configure security and users.
I'm using VisualSVN Server that has one user, sarasilva. I think
the best configuration in jenkins is to use the same users (?).
In the configuration i'm doing this:
http://s14.postimage.org/gvu930udd/security.png
In the people>sarasilva configuration i have this:
http://s15.postimage.org/y134g5q0b/security_sarasilva_config.png
If i save this configuration, when i try to log in with sarasilva user
this fails, i'm using the same password from the svn server.
What i'm doing wrong?

A: You have not created an account - just permissions. Go to http://<jenkins-host>/signup and create the account.


text:
Q: how to get current location instead off map latlng how can add current location on map default
show me only latlng show here
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
var map;

map_initialize(); // initialize google map

//############### Google Map Initialize ##############
function map_initialize()
{
        var googleMapOptions =
        {
            center: mapCenter, // map center
            zoom: 17, //zoom level, 0 = earth view to higher value
            maxZoom: 18,
            minZoom: 16,
            zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL //zoom control size
        },
            scaleControl: true, // enable scale control
            mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
        };

        map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);


text:
Q: why cant I use client in a cog? discord.py here is my code in my cog:
import discord
from discord.ext import commands
import random

class Basic(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        print("Logged In!")

    @commands.command()
    async def help(self, ctx):
        await ctx.send("placeholder text")

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f"Pong!, {round(client.latency) * 1000} ms")

def setup(client):
    client.add_cog(Basic(client))

I just get "unresolved reference "client" in client.latency, and the error message is "client is not defined" Why am I having this issue?

A: Instead of client.latency, use self.client.latency.
    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f"Pong!, {round(self.client.latency * 1000)} ms")

A: Use self.client instead of client.
Your code will however always return 0, the latency attribute returns the latency in milliseconds, for example: 0.124, if you round that it will become 0 (and 0 * 1000 = 0), you should multiply inside the round function
await ctx.send(f"Pong!, {round(self.client.latency * 1000)} ms")


text:
Q: How to derive instances in recursion schemes I am testing out some of the ideas in this article.
I want to derive an instance of Eq for the type Term:
{-# LANGUAGE DeriveFunctor #-}
data Tree a = Branch Int [a] | Leaf Int deriving (Eq, Functor, Show)
data Term f = Term (f (Term f)) deriving (Eq)

But get this error:
No instance for (Eq (f (Term f)))
      arising from the first field of 'Term' (type 'f (Term f)')
    Possible fix:
      use a standalone 'deriving instance' declaration,
        so you can specify the instance context yourself
    When deriving the instance for (Eq (Term f))

I tried adding a standalone deriving instance:
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
data Tree a = Branch Int [a] | Leaf Int deriving (Eq, Functor, Show)
data Term f = Term (f (Term f))
deriving instance (Eq f) => Eq (Term f)

But get this error:
The first argument of 'Term' should have kind '* -> *',
  but 'f' has kind '*'
In the stand-alone deriving instance for '(Eq f) => Eq (Term f)'

Now I'm stuck. How do I show that f has a kind * -> *? And why do I need a standalone deriving instance for Term but not Tree? Both have type variables that are not necessarily going to be instances of Eq? (a and f)

A: There are two solutions:
Using some GHC extensions StandaloneDeriving, UndecidableInstances and some others you can write:
deriving instance (Eq (f (Term f))) => Eq (Term f)

This is what recursion-schemes does at the moment
--
Alternatively, you can use Eq1 from transformers or base-4.9.0.0
class Eq1 f where
    liftEq :: (a -> b -> Bool) -> f a -> f b -> Bool

eq1 :: (Eq1 f, Eq a) -> f a -> f a -> Bool
eq1 = liftEq (==)

instance Eq1 f => Eq (Term f) where
    Term a == Term b = eq1 a b

Reference: https://github.com/ekmett/recursion-schemes/blob/ffada24f92efd5bcfe71f7f0af3b4af057f50bd0/Data/Functor/Foldable.hs#L392


text:
Q: LINQ to Entities does not recognize the method call within it I completely understand that this is because LINQ query requires the whole expression to be translated to a server , and therefore I cant call an outside method in it. but as I have looked at other answers there is not relative solution to this. the only approach that I thought about is to loop through all the items in the model and than passing them to the query one by one but even though this approach would not help so I am seeking help in here for anyone to help me to figure out how to call a method or a way of calling a method appendstr that initializes a.PostedDate before checking its actual equivalent value in the giving LINQ Query.
[HttpGet]
public ActionResult SearchResult(int? page, string searchTitle = null, string searchLocation = null, string last24 = "")
{

    ViewBag.searchTitle = searchTitle;
    ViewBag.searchLocation = searchLocation;
    ViewBag.page = page;
    ViewBag.last24 = last24;

    setUpApi(searchTitle, searchLocation);
    var result = new List<AllJobModel>().AsQueryable();
    if (!string.IsNullOrEmpty(ViewBag.searchTitle) || !string.IsNullOrEmpty(ViewBag.searchTitle) || !string.IsNullOrEmpty(ViewBag.last24))
    {
        setUpApi(searchTitle, searchLocation);
        DateTime now = DateTime.Now;

        result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation) &&
        appendstr(a.PostedDate).Equals(now.AddHours(-24).ToString("MM-dd-yyyy")));
    }
    else
    {
        result = from app in db.AllJobModel select app;
    }

    return View(result.ToList().ToPagedList(page ?? 1, 5));
}

The second method that gets called in the LINQ Query
public string appendstr(string str)
{
    var x = str.Split(' ');

    return  01 + "-" + x[1] + "-" + x[2];
}

A: I think you already understand that the .NET code you write in the Where clause is actually an expression that is parsed and converted to SQL. So if you have a funky string manipulation method, you can't use it directly.
The brute force option, as you seem to already understand, it to materialize the query first and then run the C# code over the results. You can do this with ToList() or AsEnumerable().
result = db.AllJobModel
    .Where
    (
        a => a.JobTitle.Contains(searchTitle)
          && a.LocationName.Contains(searchLocation)
    )
    .AsEnumerable()
    .Where
    (
        a => appendstr(a.PostedDate).Equals(now.AddHours(-24).ToString("MM-dd-yyyy")))
    );

However in your specific case you can try a trick. You are attempting a date comparison, which SQL is perfectly capable of doing... you just need to convert that funky PostedDate to a SQL DateTime so that you can compare it directly. The gimmick for that is to use SqlFunctions.DateAdd to add null interval (e.g. 0 days). This implicitly converts the string to DateTime, where you can now query on the SQL side:
var targetDate = DateTime.Now.AddHours(-24);
result = db.AllJobModel
    .Where
    (
        a => a.JobTitle.Contains(searchTitle)
          && a.LocationName.Contains(searchLocation)
          && SqlFunctions.DateAdd("DAY", 0, a.PostedDate) == targetDate
    );

Credit goes to this post for the workaround.


text:
Q: UWP POST request like GET I need to send POST request from my UWP app.
I read about it here.
I use one shared HttpClient.
 private Windows.Web.Http.HttpClient httpClient;

Initialization:
httpClient = new Windows.Web.Http.HttpClient();
var headers = httpClient.DefaultRequestHeaders;

string header = "Chrome/64.0.3282.140";
if (!headers.UserAgent.TryParseAdd(header))
{
    throw new Exception("Invalid header value: " + header);
}

I use this object for all request
But when I use it for POST request, it works like GET request or POST, but without parameters
Uri requestUri = new Uri("http://some_websit.ru");
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("par1", "val1");
pairs.Add("par2", "val2");
HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs)
var result = await httpClient.PostAsync(requestUri, formContent);
string resultContent = await result.Content.ReadAsStringAsync();

It ignore parameters which I give.
I tried to send POST request here http://seriyps.ru/postget/ and it works.

A: There is nothing wrong with your code, I have tested it locally with the same code, only a different URL, and the POST request is sent properly along with the passed in parameters:

I recommend you to install Telerik Fiddler 4 to see the network traffic and confirm that the parameters are indeed sent. I have used http://example.com just as a sample URL here. I would suspect the problem is rather on the side of the server than your app or that the server expect different parameters than what is being sent.


text:
Q: Strcmp and getchar I have written a small c program that displays text entered and if text entered is "show version", it displays the version.
Here is the sample code
#include<stdio.h>
#include<string.h>
void main(){
int i;
char j = (char) i;
while(i != '#'){
i = getchar();
if(strcmp(&j, "show version")) printf("v1");
else putchar(i);
}}

It prints v1 for every char+1.
Any suggestions.

A: Read the man pages for strcmp.
The return value of strcmp is 0 if both strings are equal, which in a C condition is considered equivalent to false.
Change your if..statement to the following:
if(strcmp(&j, "show version") == 0) printf("v1");

NOTE: In order for your code to parse a string, you will need to append each character you read onto a string.
#define LINE_SIZE 512

int main(){
    char *line = malloc(LINE_SIZE);
    while(fgets(line, LINE_SIZE, stdin)) {
        if(strncmp(line, "show version", strlen(line) - 1) == 0) {
            printf("v1\n");
        } else {
            continue;
        }

        break;
    }

    return 0;
}

The reason why I used strncmp (rather than strcmp) and strlen(line) - 1 is because fgets also captures the ENTER key / newline character when entered. This is just an example - do not forget to free your memory!


text:
Q: RoboGuice android injection module not working in test I have created a TestModule class to inject a test implementation class and it fails with a classCastException.
I am using Robolectric 2.4.
Here is my custom TestApplication that gets created via a custom robolectric runner
public class AppApplicationTest extends MyApplication {

@Override
protected void attachBaseContext(Context base) {
    configureModuleInjection();
    System.out.println(this.getClass().getSimpleName() + " attached and initialised AppApplicationTest ");

    try {
        MultiDex.install(base);
        super.attachBaseContext(base);
    } catch (RuntimeException ignored) {
        // Multidex support doesn't play well with Robolectric yet
        System.out.println(this.getClass().getSimpleName() + " runtime exception = " + ignored.toString());
    }
}

private void configureModuleInjection() {
//fails below with classCastException
    RoboGuice.getOrCreateBaseApplicationInjector(this,
            RoboGuice.DEFAULT_STAGE,
            RoboGuice.newDefaultRoboModule(this),
            new TestModule());
}
}

Here is my custom RobolectricTestRunner
    public class MyRoboTestRunner extends RobolectricTestRunner {

    ....

    @Override
    protected Class<? extends TestLifecycle> getTestLifecycleClass() {
        return ApplicationTest.class;
    }

    public  static class ApplicationTest extends DefaultTestLifecycle{
        @Override
        public Application createApplication(Method method, AndroidManifest appManifest, Config config) {
            return new AppApplicationTest();
        }
    }

    @Override
    protected ClassLoader createRobolectricClassLoader(Setup setup, SdkConfig sdkConfig) {
        return super.createRobolectricClassLoader(new ExtraShadows(setup), sdkConfig);
    }

    class ExtraShadows extends Setup{
        private  Setup setup;

        public ExtraShadows(Setup setup) {
            this.setup = setup;
        }

        @Override
        public boolean shouldInstrument(ClassInfo classInfo) {
            boolean shouldInstrument = setup.shouldInstrument(classInfo);
            return shouldInstrument || classInfo.getName().equals(MultiDex.class.getName());
        }
    }
}

Here is the full stacktrace error
    WARNING: no system properties value for ro.build.date.utc
java.lang.ClassNotFoundException: AnnotationDatabaseImpl
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.getByteCode(AsmInstrumentingClassLoader.java:172)
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.findClass(AsmInstrumentingClassLoader.java:126)
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.loadClass(AsmInstrumentingClassLoader.java:98)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:191)
    at com.google.inject.AnnotationDatabaseFinder.getAnnotationDatabaseInstance(AnnotationDatabaseFinder.java:73)
    at com.google.inject.AnnotationDatabaseFinder.<init>(AnnotationDatabaseFinder.java:36)
    at com.google.inject.Guice.setAnnotationDatabasePackageNames(Guice.java:133)
    at roboguice.RoboGuice.initializeAnnotationDatabaseFinderAndHierarchyTraversalFilterFactory(RoboGuice.java:288)
    at roboguice.RoboGuice.getOrCreateBaseApplicationInjector(RoboGuice.java:113)
    at com.jr.AppApplicationTest.configureModuleInjection(AppApplicationTest.java:33)
    at com.jr.AppApplicationTest.attachBaseContext(AppApplicationTest.java:20)
    at android.app.Application.$$robo$$Application_0b64_attach(Application.java:181)
    at android.app.Application.attach(Application.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.robolectric.internal.ReflectionHelpers$3.run(ReflectionHelpers.java:64)
    at org.robolectric.internal.ReflectionHelpers.traverseClassHierarchy(ReflectionHelpers.java:114)
    at org.robolectric.internal.ReflectionHelpers.callInstanceMethodReflectively(ReflectionHelpers.java:59)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:119)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:440)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:222)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
java.lang.IllegalStateException: Unable to use annotation database(s)
    at roboguice.RoboGuice.initializeAnnotationDatabaseFinderAndHierarchyTraversalFilterFactory(RoboGuice.java:292)
    at roboguice.RoboGuice.getOrCreateBaseApplicationInjector(RoboGuice.java:113)
    at com.jr.AppApplicationTest.configureModuleInjection(AppApplicationTest.java:33)
    at com.jr.AppApplicationTest.attachBaseContext(AppApplicationTest.java:20)
    at android.app.Application.attach(Application.java:181)
    at org.robolectric.internal.ReflectionHelpers$3.run(ReflectionHelpers.java:64)
    at org.robolectric.internal.ReflectionHelpers.traverseClassHierarchy(ReflectionHelpers.java:114)
    at org.robolectric.internal.ReflectionHelpers.callInstanceMethodReflectively(ReflectionHelpers.java:59)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:119)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:440)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:222)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

A: Because of this line
    java.lang.IllegalStateException: Unable to use annotation database(s)
Can you try to use RoboGuice.setUseAnnotationDatabases(false);
private void configureModuleInjection() {

    RoboGuice.setUseAnnotationDatabases(false);

    RoboGuice.getOrCreateBaseApplicationInjector(this,
        RoboGuice.DEFAULT_STAGE,
        RoboGuice.newDefaultRoboModule(this),
        new TestModule());

}


text:
Q: UnboundLocalError: local variable 'cursor' referenced before assignment So I am a newbie but working on a registration system form in flask/MYSQL
I am receiving this error (UnboundLocalError: local variable 'cursor' referenced before assignment)
After hours of playing with the code and research I need your help.
This is my file, please let me know if theres anything else I need to share.
thank you
from flask import Flask, render_template, json, request
from flask.ext.mysqldb import MySQL
from werkzeug import generate_password_hash, check_password_hash

app = Flask(__name__)
mysql = MySQL()

app.config['MYSQL_DATABASE_USER'] = 'x'
app.config['MYSQL_DATABASE_PASSWORD'] = 'x'
app.config['MYSQL_DATABASE_DB'] = 'x'
app.config['MYSQL_DATABASE_HOST'] = 'x'
mysql.init_app(app)

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call the MySQL

            conn = mysql.connect()
            cursor = conn.cursor()
            _hashed_password = generate_password_hash(_password)
            cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
            data = cursor.fetchall()

            if len(data) is 0:
                conn.commit()
                return json.dumps({'message':'User created successfully !'})
            else:
                return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'Enter the required fields'})

    except Exception as e:
        return json.dumps({'error':str(e)})
    finally:
        cursor.close()
    conn.close()

if __name__ == '__main__':
    app.run()

A: You only define conn and cursor inside the if block checking the form values.  If the block is not entered, they're not defined, but you still try to reference them to close them anyway.  You should only call close on both if you've defined them.  Either move conn = and cursor = to before the if block, or move the close calls to within the block.
However, the bigger problem is that you're misunderstanding/overcomplicating how to use Flask-MySQLdb.  It will automatically create the connection and close it when the request is done, which also closes the cursor.  Simply use the extension as described in the docs.
...
cur = mysql.connection.cursor()
cur.callproc('sp_createUser', (name, email, hashed_password))
data = cur.fetchall()
...

A: Personally I would recommend using a context manager to handle opening and closing of your cursor and connection. You can achieve this fairly simply and it is cleaner and easier to debug. This also would eliminate the problem of trying to close a connection or cursor before it is opened in your giant try except block.
from contextlib import closing

# do a bunch of stuff prior to opening connection
with closing(mysql.connect()) as conn:
    with closing(conn.cursor()) as cursor:
        # do a bunch of stuff and don't worry about running .close()

You can view the docs for closing here.
Using the closing would change your code to be something like this. Although it could use more refactoring, but that is a question for the code review site.
from flask import Flask, render_template, json, request
from flask.ext.mysqldb import MySQL
from werkzeug import generate_password_hash, check_password_hash
from contextlib import closing

app = Flask(__name__)
mysql = MySQL()

app.config['MYSQL_DATABASE_USER'] = 'x'
app.config['MYSQL_DATABASE_PASSWORD'] = 'x'
app.config['MYSQL_DATABASE_DB'] = 'x'
app.config['MYSQL_DATABASE_HOST'] = 'x'
mysql.init_app(app)

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call the MySQL

            with closing(mysql.connect()) as conn:
                with closing(conn.cursor()) as cursor:
                    _hashed_password = generate_password_hash(_password)
                    cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
                    data = cursor.fetchall()

                    if len(data) is 0:
                        conn.commit()
                        return json.dumps({'message':'User created successfully !'})
                    else:
                        return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'Enter the required fields'})

    except Exception as e:
        return json.dumps({'error':str(e)})

if __name__ == '__main__':
    app.run()


text:
Q: Targeting parent objects with jquery I must be losing my mind since something so simple is not working: http://jsfiddle.net/vB7Nd/
I'm trying to add up cost of items in a loop through a list and append the price to the title tag in the header, but I can't seem to target it:
HTML structure:

Total:

Car

Hat

Total:

Coffee

Milk

JS
    $('#holder ul').each(function(index, value) {
    var cost = 0;
    $(this).children().each(function(index,value) {

    var classification = $(this).attr('type');
    switch(classification) {

    case 'clothes':
    console.log(parseInt($(this).attr('cost')));
    cost +=  parseInt($(this).attr('cost'));
    //this line does not work:
    $(this).parents('.container').closest('title1').css('border','1px solid red');
     //neither does this:
    $(this).parent().parent().find('title1').append(cost);
    break;
    }
    });

    console.log('cost is' +cost);
});

A: From what I can see it can be as simple as
$('#holder .container').each(function (index, value) {
    var total = 0;
    $(this).find('li').each(function () {
        total += +$(this).attr('cost') || 0;
    })
    $(this).find('.title1').append(total)
})

Demo: Fiddle
Note: I have used the unary plus operator to convert the string value of cost to a number instead of using parseInt()

A: You are missing class selector in find.use:
$(this).parent().parent().find('.title1').append(cost);

Fiddle Demo


text:
Q: NVMe SSD slow write speed I have a NUC (BEH model) and a M.2 SSD PCIe gen3 NMVe card (Samsung 970 pro 512GB) and I have a slow and fast write speed result in Ubuntu 18.04.3 with two different kernels. I used ukuu for kernel switching and in kernel 5.0+ which comes standard with the Ubuntu installer I get around 600MiB ( sad ) write speed and with a previous kernel version of 4.9.190, I get around 2200MiB with the benchmark tool in Ubuntu. I have tried the latest 5.2 kernel and it is still a problem. I have tried Linux mint 19.2 and I also get the a slow write speed because it is using a later kernel than 4.9.
Here is my benchmark result on kernel 4.9.190.
I think this and this are related problems and a simple google search indicates lots of SSD write performance issues. Could it be a massive potential linux kernel performance issue?
Any help or fix would be greatly welcome!

A: It seems that the kernel itself might be ok but somewhere in the benchmark tool (Disks) of ubuntu could be the issue.
Solution (work-around): I created a directory in the disk to be tested and then terminal into the directory and ran two commands on it. The first commands creates a temp file (4GB in size) and tests the write speed of the disk and the second command reads that file and tests the read speed.
The commands: -write: dd if=/dev/zero of=tempfile bs=1M count=4096 conv=fdatasync,notrunc status=progress oflag=direct -read: dd if=tempfile of=/dev/null bs=1M count=4096 status=progress iflag=direct
Here is my result:

A: The problem described is about the same here.
I have a computer with ASUS Z10PE motherboard. That one has an in-built M2 NVMe slot.
I also added 1 PCIe card that supports 1 NVMe drive.
I also modded the BIOS to get bifurcation mode to have one PCIe slot to be divided in 4X4X4X4 so I can fit in the ASUS M2 Hyper PCIe card that allows up to 4 NVMe drives.
If I use GNOME-DISKS tool, that allows to run a performance test, the best case scenario is on the ASUS PCIe card with Samsung PM981 NVMe drives :

*

*3.3GB/s READ speed (as advertised)

*600MB/s WRITE speed (about 4 times less than what is advertised ; with a really significant crush in performance when cache get's filles at about 40GB).

I softraided the Samsung NVMe PM981 dirves on the ASUS PCIe card.
Speeds are now as follows :

*

*READ : 5.6GB/s (that is OK... even if not double of the single drive) ;

*WRITE : 1.2GB/s which exactly the double of the single drive performance.

It is like the kernel or MoBo sets the speed at AHCI speed (as it was a SATA drive).
Now if I use the above method, the results are quite different :
dd if=/dev/zero of=tempfile bs=1M count=16384 conv=fdatasync,notrunc status=progress oflag=direct
15183380480 octets (15 GB, 14 GiB) copiés, 5 s, 3,0 GB/s
16384+0 enregistrements lus
16384+0 enregistrements écrits
17179869184 octets (17 GB, 16 GiB) copiés, 5,63686 s, 3,0 GB/s

dd if=tempfile of=/dev/null bs=1M count=4096 status=progress iflag=direct
4096+0 enregistrements lus
4096+0 enregistrements écrits
4294967296 octets (4,3 GB, 4,0 GiB) copiés, 1,00056 s, 4,3 GB/s

So it is totally inconsistent between both tools : GNOME-DISKS and dd...
In real world : if I move a really large (about 20GB) file from one NVMe to another one, I hardly get more than 850MB/s even on the softraided drives, which is really MUCH MUCH MUCH slower than expected...
Theory would be : 2 X 2400MB/s = 4800MB/s.
Reality : 6/7 times less.
You ask me : I think there is a real problem either in MoBo or in Linux.
I'll have to install Windows just to check if the problem is with the MoBo or with OS.
Regards.

A: ISSUE VNMe slow write speed SOLVED
Hi all,
I got 2 nvme drives. Samsusng 970 and SiliconPower p34a80. Dual boot on the Samsung. In windows10 both speeds are perfect. In ubuntu the SiliconPower write speed is 250MB/s when is NTFS, and 2GB/s when is ext4.
Spent 2 days of playing but finaly got solution in my case. Added in fstab the big_writes option.
My fstab line:
/dev/disk/by-uuid/2AB1CB0844B0C2AD   /home/panayot/DATA-SSD   ntfs-3g nosuid,uid=1000,big_writes,nodev,nofail,x-gvfs-show,async,x-gvfs-name=DATA-SSD 0 0

Good luck hope I helped :)