text:
Q: How to effectively use func.isnull in sql alchemy to get the two strings joined comma separated? Below is the code I have as part of a sqlalchemy query. Most of the time fist name is null. But Here in the case of below statement, always returns last name with a comma. Eg: lastName,
How to add comma only if there's first name?
(func.isnull(
            prv.last_name,
            '') +
         ', ' +
         func.isnull(
            prv.first_name,
            '')).label('MyName')

A: I don't know what database you use behind sqlalchemy but I believe what you are looking for is an equivalent of MySQL's CONCAT_WS

CONCAT_WS() stands for Concatenate With Separator and is a special
  form of CONCAT(). The first argument is the separator for the rest of
  the arguments. The separator is added between the strings to be
  concatenated. The separator can be a string, as can the rest of the
  arguments. If the separator is NULL, the result is NULL.

Using it in sqlalchemy should be a matter of calling
func.CONCAT_WS(',', prv.last_name,prv.first_name) (example)


text:
Q: How do I shorten the MySQL Connect Time Out - Failover Scenario I have a fail-over scenario in a Wordpress plugin, where a PHP script on my web server tries to connect to a backup database if the production one is offline.
Currently the fallback seems to take up to 60 seconds. Is this the PHP default? How would I set the time out to something like 10 seconds?
Here is the relevant portion of the script...
  try
        {
            $DBblue = new \PDO('mysql:host='.$samhost.';'.'dbname='.$DBblue, $samuser, $sampass);
            $DBgreen = new \PDO('mysql:host='.$samhost.';'.'dbname='.$DBgreen, $samuser, $sampass);
        }
        catch (\PDOException $pde)
        {
            // Fallback Database connection
            $althost = get_option('fallback_host');
            $altuser = get_option('fallback_user');
            $altpass = get_option('fallback_password');
            $DBblue = new \PDO('mysql:host='.$althost.';'.'dbname='.$DBblue, $altuser, $altpass);
            $DBgreen = new \PDO('mysql:host='.$althost.';'.'dbname='.$DBgreen, $altuser, $altpass);
        }

A: Try this:
$DBblue = new \PDO('mysql:host='.$samhost.';'.'dbname='.$DBblue, $samuser, $sampass, array(
    PDO::ATTR_TIMEOUT => "10",
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
 $DBgreen = new \PDO('mysql:host='.$samhost.';'.'dbname='.$DBgreen, $samuser, $sampass, array(
    PDO::ATTR_TIMEOUT => "10",
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));

PDO::ATTR_TIMEOUT => "10" ->>> Set timeout to 10 seconds.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ->>> Throw exception.
More Information : http://php.net/manual/en/pdo.setattribute.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: find a string with _id and exclude a value I have the following regex that I use to find a class:
about_class = about_key.match(/^(.+)_id$/)[1]

The above expression will match on user_id, contact_id etc.
I want to exclude the string author_id.
How can I update the expression to exclude author_id?

A: Add a negative lookahead:
/^(?!author_id$)(\w+)_id$/

> "foo_id".match(/^(?!author_id$)(\w+)_id$/)
["foo_id", "foo"]
> "author_id".match(/^(?!author_id$)(\w+)_id$/)
null


text:
Q: Have link in sharepoint open in iFrame on same webpapge In Sharepoint I have multiple links from various external links that I want to open on an iFrame within the same Sharepoint page.
Ex:
Link A |
Link B |
Link C
Regardless of whichever link is clicked it will open in the same iFrame

A: To open webpage in modal popup
<script type="text/javascript">
function OpenDialog(URL) {
   var NewPopUp = SP.UI.$create_DialogOptions();
   NewPopUp.url = URL;
   NewPopUp.width = 700;
   NewPopUp.height = 350;
   SP.UI.ModalDialog.showModalDialog(NewPopUp);
}
</script>

Call the Javascript on Button click and the modal Pop Up will pops up with the Page of Specified URL.
btnOpenPopUp.Attributes.Add("onClick", "javascript:OpenDialog('/_layouts/MyAppPage/MyPage.aspx');");

If still it not works try to execute delay like this
SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'sp.ui.dialog.js');


text:
Q: jquery/javascript content replace?how reusable http://img163.imageshack.us/img163/6248/93306989.jpg
the images above show what i want,
i'm using Facebox to do the pop up content,so how can i make the pop up content dynamic?

the code above work just fine,but how can edit to reusable???
<form>
<textarea id="exampleSource" class="expand">

Heading

paragraph.

</textarea>
<input type="Submit" value="Submit" class="openExample" />
<input type="reset" value="Reset" />
</form>

A: Create a function that accepts string or id of the element.
example:
function popWindow(elementID)
{

    $('.openExample').click(function() {
        $.facebox($(elementID).val());
        return false;
    });
}

call it like this popWindow('#exampleSource');


text:
Q: Subreport: Could not load object from location - getOutputStream() We have a Java EE aplicattion, JRE 6, MySQL 5.5, running on Tomcat 5.5. We have several JR reports working right but there is one of them that causes the following Tomcat error:
org.apache.jasper.JasperException: getOutputStream() ya ha sido llamado para esta respuesta
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:460)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:367)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1085)
    org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:263)
    org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:398)
    org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:318)
    org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:241)
    org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    com.tsystems.web.common.FiltroSeguridad.doFilter(FiltroSeguridad.java:79)

Eclipse's console:
Could not load object from location : ..\..\iReport\PDFInformeCuadroGestionSub1.jasper
net.sf.jasperreports.engine.JRException: Could not load object from location : ..\..\iReport\PDFInformeCuadroGestionSub1.jasper
    at net.sf.jasperreports.engine.util.JRLoader.loadObjectFromLocation(JRLoader.java:271)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:311)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:260)
    at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:275)
    at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:426)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:1380)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:692)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:255)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:113)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:888)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:810)
    at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:89)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:601)
    at com.tsystems.web.ModuloInformes.InformesNuevos.InformeGestion.Actions.InformeGestionAction.generarReporte(InformeGestionAction.java:1573)
    at com.tsystems.web.ModuloInformes.InformesNuevos.InformeGestion.Actions.InformeGestionAction.generarInformeGestion(InformeGestionAction.java:207)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
    at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at com.tsystems.web.common.FiltroSeguridad.doFilter(FiltroSeguridad.java:79)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
    at java.lang.Thread.run(Unknown Source)

The method to generate the report is this (uncomplete, only the call and few more things):
private void generarReporte(List info,
                            InformeGestionFormBean gestionBean,
                            HttpServletRequest request,
                            HttpServletResponse response,
                            String descripDispo) {
    try {
        ServletOutputStream out = response.getOutputStream();

        String centro = descripDispo;

        String imagenlogo = ".." + File.separator + ".." + File.separator + "images" + File.separator + "logo2.jpg";
        String imageninforme = ".." + File.separator + ".." + File.separator + "images" + File.separator + "finforme.jpg";
        String imagenflecha = ".." + File.separator + ".." + File.separator + "images" + File.separator + "flecha.jpg";

        String ruta = ".." + File.separator + ".." + File.separator + "iReport" + File.separator;

        Map parametros = new HashMap();
        parametros.put("TITULO", "INFORME CUADRO DE GESTION DE "+centro+"");
        parametros.put("FECHA_ANYO", gestionBean.getAnioPeriodo());
        parametros.put("CENTRO", centro);
        parametros.put("IMAGEN_LOGO", imagenlogo);
        parametros.put("IMAGEN_INFORME", imageninforme);
        parametros.put("IMAGEN_FLECHA", imagenflecha);
        parametros.put("SUBREPORT_DIR", ruta);

        InputStream is = null;

        String header = "";

        is = InformeGestionAction.class.getClassLoader().getResourceAsStream(ruta + "InformeCuadroGestion.jrxml");

        header = "attachment; filename=\"InformeCuadroGestion";

        JRExporter exporter = null;
        JasperReport reporte = JasperCompileManager.compileReport(is);

        JRDataSource aux = new JRBeanCollectionDataSource(info);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, aux);

This report worked fine few weeks ago, but now it doesn't. I've tried using code from the backup from the time when it worked ok, but the problem is still there. Maybe I changed configuration or something, I don't know.


text:
Q: Capture screenshot of a HorizontalScrollView including offscreen elements I have tried many methods. I am able to take screenshot of whole screen BUT my requirement is to take screenshot of whole HorizontalScrollView and save it as an image file. Here is the sample XML layout I am using:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/hsv" >

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/ll">

             <Button
                android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:onClick="click"
            android:id="@+id/b"
            android:text="capture"
            android:layout_margin="20dp"/>

            <ImageView
                android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/img1"
            android:src="@drawable/plug1"
            android:layout_margin="20dp"/>

            <ImageView
                android:layout_height="wrap_content"
            android:layout_width="200dp"
            android:id="@+id/img2"
            android:src="@drawable/plug3"
            android:layout_margin="20dp"/>

        </LinearLayout>

    </HorizontalScrollView>

</RelativeLayout>

Activity Code:
Button b;
    ImageView img1, img2;
    LinearLayout ll; View v;
    HorizontalScrollView s;
    int h,w;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        b = (Button)findViewById(R.id.b);
        img1 = (ImageView)findViewById(R.id.img1);
        img2 = (ImageView)findViewById(R.id.img2);

        ll = (LinearLayout)findViewById(R.id.ll);

        s = (HorizontalScrollView) findViewById(R.id.hsv);
        s.setDrawingCacheEnabled(true);

    }

     //Fired onClick of the button
       public void click(View v) {
           shoot();
       }

    // To capture layout, create a bitmap and replace an image with the resulting bitmap.
    public void shoot() {

        s.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

        int totalHeight = s.getMeasuredHeight();
        int totalWidth = s.getMeasuredWidth();

        s.layout(0, 0, totalHeight, totalWidth);
        s.buildDrawingCache(true);

        Bitmap b = Bitmap.createBitmap(s.getDrawingCache());
        s.setDrawingCacheEnabled(false);

        img1.setImageBitmap(b);
    }

I don't get correct layout height and width if I don't use MeasureSpec.
OnClick of the button I am getting image of half button only. I think this is happening as I am not using ViewTreeObserver. But when i use ViewTreeObserver, I am not getting the result. Also, the application crashes when I click the button twice - NullPointerException in Bitmap.
I have tried nearly everything available on StackOverFlow. Please help me to find a way to do this. Is it even possible ?

A: Found a SIMPLE way to do it.
XML
        <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:layout_gravity="center_vertical">

     <HorizontalScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >

         <LinearLayout
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:orientation="horizontal"
                  android:id="@+id/def"
                  >

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="capture"
        android:onClick="click"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/black"
        android:id="@+id/img"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/a"/>

    </LinearLayout>

    </HorizontalScrollView>

</LinearLayout>

Acivity Code:
public class CaptureBeyondActivity extends Activity {
/** Called when the activity is first created. */

LinearLayout def;
ImageView img;
HorizontalScrollView hsv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

def = (LinearLayout)findViewById(R.id.def);
img = (ImageView)findViewById(R.id.img);

}

public void click(View v) {
Bitmap bitmap;
def.setDrawingCacheEnabled(true);
def.buildDrawingCache(true);

        bitmap = Bitmap.createBitmap(def.getWidth(), def.getHeight(),
                Config.ARGB_8888);
        def.layout(0, 0, def.getLayoutParams().width,
                def.getLayoutParams().height);
        Canvas c = new Canvas(bitmap);
        def.draw(c);

def.setDrawingCacheEnabled(false);

if(bitmap!=null){
    img.setImageBitmap(bitmap);
    img.invalidate();
}
}}

Here I have placed some elements in a HorizontalScrollView. OnClick of the button a screenshot is taken and the second image is replaced by the screenshot taken.
It takes screenshots of the offscreen elements also. You can further enhance the code and save the final bitmap image on SD card.

A: it's the second time I see this same question (yes, here in stack overflow) and the simple answer is: There is no simple way to do it!
All the methods to save a screen shot uses the same principle of enabling the draw to the bitmap cache and obtaining this bitmap.
But if the views are not on screen, they won't be drawn.
You could create a very complex system that would auto-scroll the Horizontal screen view, taking several screen shots and stitching the different bitmaps together. Or maybe a very complex system that would create an infinite width canvas and ask the layout to draw on it, but it's likely that you would run out of memory on this situation. But as I said, none of those is a simple task.


text:
Q: C++ Add derived object of abstract class into another class without dangling pointers? I have a simple container class that points to an abstract class and I have functions to get/set the pointer in the container class. More concretely, the class looks like this:
class Container
{
    Abstract* thing;
public:
    void set(Abstract &obj)
    {
        thing = &obj; //danger of dangling pointer
    }

    Abstract* get()
    {
        return thing;
    }
};

Abstract is an abstract class. As can be seen already, there's a danger of a dangling pointer. I know that I could make a copy of the object (new) and then point to it. But I can't create an instance of an abstract class. What solutions to this are there?

The following are just more information:
Class definitions
class Abstract
{
public:
    virtual void something() = 0;
};

class Base : public Abstract
{
    int a;
public:
    Base() {}
    Base(int a) : a(a){}
    virtual void something()
    {
        cout << "Base" << endl;
    }
};

class Derived : public Base
{
    int b;
public:
    Derived() {}
    Derived(int a, int b) : Base(a), b(b){}
    virtual void something()
    {
        cout << "Derived" << endl;
    }
};

Simple tests
void setBase(Container &toSet)
{
    Base base(15);
    toSet.set(base);
}

void setDerived(Container &toSet)
{
    Derived derived(10, 30);
    toSet.set(derived);
}

int main()
{
    Container co;

    Base base(15);
    Derived derived(10, 30);

    Base *basePtr;
    Derived *derivedPtr;

    //This is fine
    co.set(base);
    basePtr = static_cast<Base *>(co.get());
    basePtr->something();

    //This is fine
    co.set(derived);
    derivedPtr = static_cast<Derived *>(co.get());
    derivedPtr->something();

    //Reset
    basePtr = nullptr;
    derivedPtr = nullptr;

    //Dangling pointer!
    setBase(co);
    basePtr = static_cast<Base *>(co.get());
    basePtr->something();

    //Dangling pointer!
    setDerived(co);
    derivedPtr = static_cast<Derived *>(co.get());
    derivedPtr->something();

    return 0;
}

A: What you need to do is to define your memory ownership concretely.
Container::set accepts an instance of Abstract by reference, which usually does not imply an ownership transfer:
 void set(Abstract &obj){...} // Caller retains ownership of obj, but now we have a weak reference to it

Then the onus of deletion is not on you.
Container::get returns a pointer which implies ownership, indicating that someone who calls set should not invalidate the passed object.
Abstract* get(){...}

This could be problematic, as you've stated.
You have a few options

*

*Encode these memory ownership semantics within Container with proper documentation (Code by contract)

*Use a smart pointer like std::shared_ptr
In the former case, whether it works or not depends on the user reading and understanding your API, and then behaving nicely with it. In the latter case, the pointer object owns itself, and will delete the allocated memory when the last instance goes out of scope.
 void set(std::shared_ptr<Abstract> obj){...}
// now Container participates in the lifetime of obj,
// and it's harder to nullify the underlying object
// (you'd have to be intentionally misbehaving)

A: If you are worried about the object being deallocated elsewhere resulting in a dangling pointer, you could use boost smart pointers.
Boost smart pointers would provide you the service of book keeping and help to avoid such a case.
Some information can be found here :
smart pointers (boost) explained

A: This is what std::unique_ptr is for:
class Container
{
    std::unique_ptr<Abstract> thing;
public:
    void set(std::unique_ptr<Abstract> obj)
    {
        thing = obj;
    }

    Abstract* get()
    {
        return thing.get();
    }
};

Now the Abstract object is "owned" by Container and will be cleaned up automatically when the Conatiner is destroyed.
If you want a pointer that might live longer, or might be shared between mulitple containers, use std::shared_ptr instead.


text:
Q: How to get all child objects of a class Is it possible to retrieve a list of child objects (of a cetain type) of an object ?
For example in this code I have an App with several available Commands. A function print all availible commands this way the user knows what he can do.
I want to iterate over each object of type Command found in App to print his doc, this way the doc updates itself automatically every time a Command is added in App.
class Command {
public:
    std::string Name;
    std::string Description;
    virtual void Compute() = 0;
};

class StartCommand : public Command {
    std::string Name = "start";
    std::string Description = "Start the process";
    virtual void Compute() {
        // Code to start the process
    }
};

class StopCommand : public Command {
    std::string Name = "stop";
    std::string Description = "Stop the process";
    virtual void Compute() {
        // Code to stop the process
    }
};

class App {
public:
    StartCommand StartCommand;
    StopCommand StopCommand;

    void PrintAvailibleCommands() {
        std::cout << "All availible commands are: " << std::endl;
        for (Command command : this.GetObjects<Command>()) {
            std::cout << command.Name << ": " << command.Description << std::endl;
        }
    }
};

It's the this.GetObjects<Command>() function which does not exist and which I would like to implement.
Do you have an idea ?

A: This may solve your problem.
#include <cassert>
#include <cstring>
#include <iostream>
#include <vector>

using namespace std;

class Command {
  public:
    std::string Name;
    std::string Description;
    Command(std::string Name, std::string Description)
        : Name(Name), Description(Description) {}
    virtual void Compute() = 0;
};

class StartCommand : public Command {
  public:
    StartCommand() : Command("start", "Start the process") {}
    virtual void Compute() {
        // Code to start the process
        cout << "startcmd compute" << endl;
    }
};

class StopCommand : public Command {
  public:
    StopCommand() : Command("stop", "Stop the process") {}
    virtual void Compute() {
        // Code to stop the process
        cout << "stopcmd compute" << endl;
    }
};

class App {
  public:
    App() {
        commands.push_back(&startCommand);
        commands.push_back(&stopCommand);
    }

    StartCommand startCommand;
    StopCommand stopCommand;

    vector<Command *> commands;

    void PrintAvailableCommands() {
        std::cout << "All available commands are: " << std::endl;
        for (Command *command : commands) {
            std::cout << command->Name << ": " << command->Description
                      << std::endl;
        }
    }
};

int main() {
    App app;

    app.PrintAvailableCommands();
    app.startCommand.Compute();
    app.stopCommand.Compute();

    return 0;
}

A: Often, I find it easier to put something into a collection directly when I want it to be there at some point.
#include <iostream>
#include <tuple>
#include <string>

struct Command {
    std::string Name;
    std::string Description;
    virtual void Compute() = 0;
};

struct StartCommand : Command {
    std::string Name = "start";
    std::string Description = "Start the process";
    virtual void Compute() {
        // Code to start the process
    }
};

struct StopCommand : Command {
    std::string Name = "stop";
    std::string Description = "Stop the process";
    virtual void Compute() {
        // Code to stop the process
    }
};

struct App {
    std::tuple<StartCommand, StopCommand> commands{};

    template<class Cmd>
    static void PrintCommand(const Cmd &cmd) {
        std::cout << cmd.Name << ": " << cmd.Description << std::endl;
    }

    void PrintAvailibleCommands() {
        std::cout << "All available commands are: " << std::endl;
        std::apply([](const auto &...cmds) { (PrintCommand(cmds), ...); }, commands);
    }
};


text:
Q: i want to use different menu as page I have a page made in wordpress.
The page contains 4 different menus but they have common menu item like "About us".
My problem is that when I click "About us" in any menu ,I want to open the elements of the menu which I clicked.
for example:
Menü - 1 :
About Us - Hair Transplant - Methods
Menu - 2:
About Us - Eye Care - Methods
for example: When I click "About us"  on Menu -2 , I want to show About us  on Menu - 2,
How can I do it ?
Thank you

A: If you want  " The page contains 4 different menus but they have common menu item like "About us". My problem is that when I click "About us" in any menu ,I want to open the elements of the menu which I clicked."
The you need to build different  page or post. If you build post then you need to creat 4 different category. And add those category on your menu.
Or;
If you build different page then you need to copy page link and then pate the link on your costume menu link.


text:
Q: CartoView Error I've installed CartoView on Windows 7 by default instruction. I've changed Postgres to my own DB (It was problem with default DB from install package). CartoView doesn't start with this error:

I see, that problem is Django, but have no idea how to solve it.
When I try to run listed script I get python error:


text:
Q: Getting a list of processes in ASP.NET As the title implies, is there any way I could do this?
I'm trying to do this in an .aspx, this is my current code:
    <script runat="server">
    //using System.Diagnostics;
    Process[] processes = System.Diagnostics.Process.GetProcesses();

    foreach(Process process in processes)
    {
        lbl = process.MainWindowTitle;
    }
</script>

But it's saying foreach isn't a valid token.

A: If you are using .NET, you can call System.Diagnostics.Process.GetProcesses() to retrieve an array of Process objects.
Note that this methods has overloads, and that perhaps one of the overloads may be more suitable to your situation.

A: Like everyone else said Process.GetProcesses()
If you use LinqPad you can run this in Statements mode to see how it works and play with it.
Process[] processes = Process.GetProcesses();
foreach(Process process in processes)
{
    Console.WriteLine(process.ProcessName);
}


text:
Q: Moving rows to another sheet with Apps Script, but doesn't work with shared document I have a script helping me both generate a started date by a conditional column, and also moving a row to another sheet by a "Done" Column. When I use the document it works without any issues, but when others use the document the rows aren't moved to the separate sheet. Anyone got any ideas what it could be?
`
function onEdit(e) {
first(e);
second(e);

function first(e) {
  var row = e.range.getRow();
  var col = e.range.getColumn();

if(
  e.source.getActiveSheet().getName() == 'B2B_LeadList'
  &&
 col === 22
  &&
  e.value == 'STARTED'
  &&
e.source.getActiveSheet().getRange(row,23).setValue(new Date()== ''
&&
 row > 1)){

e.source.getActiveSheet().getRange(row,23).setValue(new Date());
}}

function second(e){
var mainSheet = 'B2B_LeadList'
var targetSheet = 'B2B_Archive'

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveRange();

if(sheet.getName() == 'B2B_LeadList' && e.range.getColumn() == 35 && e.range.getValue() == 'YES'){
  var row = e.range.getRow();
  var numColumns = sheet.getLastColumn();
  var targetSheet = ss.getSheetByName('B2B_Archive');
  var target = targetSheet.getRange(targetSheet.getLastRow() + 1,1);
  e.source.getActiveSheet().getRange(row,36).setValue(new Date());
  sheet.getRange(row,1,1,numColumns).moveTo(target);
  sheet.deleteRow(row);
}
}

}

`
I am expecting that other users working in this document can move rows from current sheet to another sheet by selecting "YES" in a "Done?" column.

A: Try it this way:
function onEdit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == 'B2B_LeadList' && e.range.columnStart === 22 && e.range.rowStart > 1 && e.value == 'STARTED') {
    sh.getRange(e.range.rowStart, 23).setValue(new Date());
  }
  if (sh.getName() == 'B2B_LeadList' && e.range.columnStart == 35 && e.value == 'YES') {
    var tsh = e.source.getSheetByName('B2B_Archive');
    var trg = tsh.getRange(tsh.getLastRow() + 1, 1);
    sh.getRange(e.range.rowStart, 36).setValue(new Date());
    sh.getRange(e.range.rowStart, 1, 1, sh.getLastColumn()).moveTo(trg);
    sh.deleteRow(e.range.rowStart);
  }
}

If you are moving the script to their account make sure they authorize it.  Otherwise ensure that they have permission to edit the file.  Also note that this is a simple trigger and cannot perform functions which require permission.


text:
Q: How to get Sense Key in WordNet for NLTK Python? Hi Stackoverflow Community
I just started tinkering around with Python NLTK and have directed my attention to the Wordnet module.
I am attempting to get the Sense Ky for a given lemma and found the following:
s = wn.synset('skill.n.01')
s.lemmas # >>> [Lemma('skill.n.01.skill'), ... ]
s.lemmas[0].key # >>> 'skill%1:09:01::'

However, this implementation doesn't seem to be supported anymore.
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/momely/placementarchitect/testbench.py", line 59, in <module>
s.lemmas[0].key
TypeError: 'method' object is not subscriptable

I am wondering whether anyone would be able to point me in the right direction as to how I might be able to get the sense key given a lemma or synset?
Any advice would be highly appreciated!

A: Take a look at https://stackoverflow.com/a/27518899/610569 for the difference between, Synset.lemmas()[0].key and Synset.lemmas()[0].key():
>>> from nltk.corpus import wordnet as wn
>>> wn.synset('dog.n.1')
Synset('dog.n.01')
>>> wn.synset('dog.n.1').lemmas()
[Lemma('dog.n.01.dog'), Lemma('dog.n.01.domestic_dog'), Lemma('dog.n.01.Canis_familiaris')]
>>> wn.synset('dog.n.1').lemmas()[0]
Lemma('dog.n.01.dog')
>>> wn.synset('dog.n.1').lemmas()[0].name()
u'dog'

# To retrieve Princeton WordNet style keys.
>>> wn.synset('dog.n.1').lemmas()[0].key()
u'dog%1:05:00::'

For Open Multilingual WordNet, using the offset + pos keys would be easier, e.g.:
>>> from nltk.corpus import wordnet as wn
>>> ss = wn.synset('dog.n.1')
>>> ss.offset()
2084071
>>> ss.pos()
u'n'
>>> '{}-{}'.format(str(ss.offset()).zfill(8), ss.pos())
'02084071-n'

Searching the offset + pos key (e.g. 02084071-n) on the OMW interface: http://compling.hss.ntu.edu.sg/omw/cgi-bin/wn-gridx.cgi?gridmode=grid will get you to a nice visualization page of the synset.

A: If you look at an example of this module, e.g. in http://www.nltk.org/howto/wordnet.html, lemmas is a method - so you need to call it with () after it, for example:
s = wn.synset('skill.n.01')
s.lemmas() # >>> [Lemma('skill.n.01.skill'), ... ]

Then you can access the return value like so:
s.lemmas()[0].key # >>> 'skill%1:09:01::'

The TypeError: 'method' object is not subscriptable error message is telling you that you're trying to treat a method or function like a list  - when you see an error like that, look for something you have [0] or similar with that might be a function.

A: So I figured it out. After a bit of digging in NLTK's Wordnet API, I noticed that the API appears to require the key to be called like this:
s = wn.synset('skill.n.01')
print(s.lemmas) # >>> <bound method Synset.lemmas of Synset('skill.n.01')>

print(str(s.lemmas()[0]._key)) #>>>skill%1:09:01::

As such the call ._key successfully returns the Sense Key.
Thank you @bouteillebleu for pointing me in the right direction to start with.
M


text:
Q: C Socket Bind Failed with the Error: Operation not permitted I am writing a server-client program. My program creates the socket successfully, but when it tries to bind it, it generates error shows that the bind was not successful.
The error message is:

Faild to bind - in main: Operation not permitted

So what possibly went wrong? Is it the sockaddr_un struct? This is part of the code, I won't display all the code because I am getting many flags for that! So if additional code is needed please let me know.
//server log socket
struct sockaddr_un server = {AF_UNIX, "log_server"};
sl = socket (AF_UNIX, SOCK_STREAM, 0);
if(sl < 0) {
perror("Faild to create socket - in main");
    exit(1);
}
bn = bind (sl, (struct sockaddr *)&server, sizeof(server));
if(bn < 0){
    perror("Faild to bind - in main");
    exit(1);
}
lis = listen (sl, 1); //to be changed to 4
if (lis < 0) {
    perror("Faild to listen - in main");
}


text:
Q: I want to remove question mark & .php extension from the url using .htaccess I have a problem with redirect URL in .htaccess. I want to remove .php & question marks from the URL.
For Example: www.example.com/test.php?id=12  to  www.example.com/test/12 need like this format.
I tried using this code in my .htaccess
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

## hide .php extension snippet

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

This code just removes the .php extension from the URL. Also need to remove the question mark.

A: That code appears to be from one of my answers :)
Replace your code with this:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

## hide .php extension snippet

# To externally redirect /dir/foo.php?id=123 to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?id=([^&\s]+) [NC]
RewriteRule ^ %1/%2? [R,L]

# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/([^/]+)/?$ $1.php?id=$2 [L,QSA]

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\s [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*?)/?$ $1.php [L]

A: How about this? It requires mod_rewrite.
RewriteEngine On
RewriteRule ^test\/([0-9]+)$ test.php?id=$1


text:
Q: 64 bit vs 32 bit C code on Solaris 10 On my Solaris 10 update 9 system the following command yields:
#isainfo -b
64

But if I create the following program in C with limits.h is included I get:
#include <stdio.h>
#include <limits.h>

int main(void)
{
     printf("Maximum integer value on this system is = %d\n", INT_MAX);
}

gcc on64.c -o on64
./on64

Maximum integer value on this system is = 2147483647

I was expecting a much bigger result because the system runs on 64 bit. This seems like a 32 bit result. Is this a compiler issue?

A: There are a variety of programming models for 64-bit platforms, http://www.unix.org/version2/whatsnew/lp64_wp.html, including:

*

*ILP64 (where int, long, and pointers are 64-bit)

*LP64 (where int is 32-bit, while long and pointers are 64-bit)

64-bit Solaris 10 uses the LP64 model (http://www.sun.com/software/solaris/faqs/64bit.xml#q4):

Q: What is the data model used for the
Solaris Operating System?
A: LP64 is the de facto industry
standard. The L represents long and
the P represents pointer. Both are
64-bit, whereas int is 32-bit.

In addition to the "64-Bit Programming Models: Why LP64?" paper referenced above, you might want to look at Raymond Chen's explanation for why Win64 chose the LLP64 model, as it might help bolster the various rationales and arguments in the unix.org document: http://blogs.msdn.com/b/oldnewthing/archive/2005/01/31/363790.aspx

A: The "int" type is 32-bits on gcc regardless of the platform. The "long" type is 32 bits on 32-bit platforms, and 64 bits on 64-bit platforms.
To be less ambiguous, you could use C99 types:
#include <stdint.h>

int32_t i32;
int64_t i64;

A: From the gcc documentation:

The 64-bit environment sets int to 32
  bits and long and pointer to 64 bits
  and generates code for AMD's x86-64
  architecture.

A: If you want the size of the largest integral type, that's intmax_t:
#include <stdio.h>
#include <stdint.h>

int main(void)
{
     printf("Maximum integer value on this system is = %jd\n", INTMAX_MAX);
}

This will always be at least 2^63 - 1.

A: You can compile programs on Solaris 10 for 32-bit or 64-bit.  By default, they are compiled 32-bit.
Using both GCC and the more recent Sun compilers, the options '-m32' and '-m64' dictate which option is used.  Hence, try:
$ gcc -m64 -o on64-64 on64.c
$ gcc -m32 -o on64-32 on64.c

Then run:
$ file on64 on64-32 on64-64
...take a look see...
$ ./on64-64
...take a look see...
$ ./on64-32
...as you originally found...
$

A: Firstly, you have to make sure you are running your compiler in 64-bit mode. Some compilers default to 32-bit target platform mode, even if they are capable of generating 64-bit code.
Secondly, some compilers prefer to 64-bit type model where type int remains 32-bit. GCC is actually one of them. So, your expectations for int type becoming 64-bit type in 64-bit mode are completely unfounded.
Again, everything depends on the compiler and only on the compiler (and on the compiler settings). What you did to your OS is totally irrelevant. You can update your Solaris to 237-bit or 1001-bit version, but GCC will continue to generate 32-bit code, until the GCC default is changed or until you explicitly request a different target platform.

A: If you want to see the "long" type (which is 32bits on 32-bit architecture and 64-bits on 64-bit architecture, as opposed to "int" which is always 32-bit), you could have printed:
printf("max long = %ld", LONG_MAX);

that gives me this when compiled with '-m64'
Max long on this system is: 9223372036854775807

and this when compiled with '-m32'
Max long on this system is: 2147483647


text:
Q: How can I share an Object between a running Service and Activity I have an API Object that I made, and I would like to share it between a running Service and various Activities in my app, almost like if I was to make the class static.  How could I go about sharing the created object between the two?

A: You may find the following helpful.
Binding a Service to an android.app.Activity vs Binding it to an android.app.Application
Android Service interacting with multiple activities
Alternatives for Pushing data from an Android Service to an Activity

A: I figured out the best way to do this is to have a class that holds all the information that you want, and to use that class through each activity and service.


text:
Q: Como corrigir erro em tibble Estou tentando capturar notícias da Folha de SP, mas o código dá erro na metade.
Aparece o seguinte erro:

Erro: Tibble columns must have compatible sizes.
Size 25: Existing data.
Size 23: Column at position 2. i Only values of size one are recycled.

Este é o meu código:
url_base <- "https://search.folha.uol.com.br/search?q=%22regra%20de%20ouro%22&site=todos&periodo=todos&results_count=695&search_time=1%2C216&url=https%3A%2F%2Fsearch.folha.uol.com.br%2Fsearch%3Fq%3D%2522regra%2520de%2520ouro%2522%26site%3Dtodos%26periodo%3Dtodos&sr="

library(tidyverse)
library(rvest)

dados_pesquisa <- tibble()

for (i in 1:28) {
  print(i)

  x <- (i-1) * 25+1

  url_pesquisa <- paste(url_base, x, sep = "")
pagina <- read_html(url_pesquisa)

  nodes_titulos <- html_nodes (pagina, xpath = "//ol/li/div/div/a/h2[@class = 'c-headline__title']")
nodes_links <- html_nodes(pagina, xpath = "//ol/li[@id='view-view']/div/div/a")

  titulos <- html_text(nodes_titulos) %>%
    str_squish()
  titulos <- unique(titulos)

  links <- html_attr(nodes_links, name = "href")
  links <- unique(links)
  links <- links[!grepl("#foto-", links)]

  if(length(titulos)!=length(links)){
    links <- links[!grepl("/galerias/", links)]
  }

  tabela_titulos <- tibble(titulos, links)

  dados_pesquisa <- bind_rows(dados_pesquisa, tabela_titulos)

}

A: O problema está no seguinte trecho do código:
titulos <- html_text(nodes_titulos) %>%
  str_squish()
titulos <- unique(titulos)

links <- html_attr(nodes_links, name = "href")
links <- unique(links)
links <- links[!grepl("#foto-", links)]

Ao utilizar unique para os títulos e links da pesquisa, a fim de remover as entradas duplicadas, o nem sempre os tamanhos dos objetos titulos e links ficam compatíveis.
Houve uma tentativa de consertar isso, com o trecho de código a seguir:
if(length(titulos)!=length(links)){
  links <- links[!grepl("/galerias/", links)]
}

Entretanto, ele não considera todos os casos em que este tipo de erro pode ocorrer. Por isso, recomendo substituir o trecho de código acima pela minha sugestão abaixo:
if(length(titulos)!=length(links)){
  links <- links[!grepl("/galerias/", links)]
  links <- links[!grepl("aovivo.folha.uol.com.br", links)]
}

Ainda assim, o código não roda para anos anteriores a 2015. Isso se deve aos links da própria Folha. Por exemplo, diversos títulos únicos estão associados a dois links diferentes (resultados de títulos e links intercalados para ilustrar o problema):
 [1] "Primária mantém Cristina viva"

 [1] "http://www1.folha.uol.com.br/colunas/clovisrossi/2015/08/1663587-primaria-mantem-cristina-viva.shtml"
 [2] "http://www1.folha.uol.com.br/fsp/mundo/228236-primaria-mantem-cristina-viva.shtml"

###

 [4] "Ocidentalismo"

 [5] "http://www1.folha.uol.com.br/colunas/demetriomagnoli/2015/01/1576506-ocidentalismo.shtml"
 [6] "http://www1.folha.uol.com.br/fsp/poder/204318-ocidentalismo.shtml"

###

[11] "Diretor da OMC 'joga a toalha' em principal aposta comercial brasileira"

[15] "http://www1.folha.uol.com.br/mercado/2014/10/1533718-diretor-da-omc-joga-a-toalha-em-principal-aposta-comercial-brasileira.shtml"
[16] "http://www1.folha.uol.com.br/fsp/mercado/191026-diretor-da-omc-joga-a-toalha-em-principal-aposta-comercial-brasileira.shtml"

###

[14] "Queremos Lula e FHC como aliados, diz conselheiro econômico de Marina"

[20] "http://www1.folha.uol.com.br/poder/2014/08/1505301-queremos-lula-e-fhc-como-aliados-diz-conselheiro-economico-de-marina.shtml"
[21] "http://www1.folha.uol.com.br/fsp/poder/182333-queremos-lula-e-fhc-como-aliados-no-governo.shtml"

Para resolver este problema, é necessário encontrar uma forma de distinguir entre títulos iguais, mas com links ligeiramente diferentes. Infelizmente, eu não saberia como fazer isso sem ter que pensar muito a respeito.


text:
Q: "Shadowbox is not defined" error which suggests that Shadowbox.init(shadowbox_conf)? I am having a problem where i am getting the error "Shadowbox is not defined" and it suggests that Shadowbox.init(shadowbox_conf) is the problem.
I believe that this issue started occurring when I updated from wordpress 3.3.0 to 3.3.1.
I can't figure out why this has suddenly started to cause a problem. Unfortunately my javascript skills are lacking, so any help you could give me would be appreciated.
You can view the page in question here. (note I am using shadowbox JS plugin to use the shadowbox lightbox, and I have also integrated this with the javascript plugin isotope, which is use for layout and filtering.
http://www.imageworkshop.com/portfolio/

A: okay, i eventually tracked down the fix.
I am using the Shadowbox JS plugin. Turns out that this plugin has been removed from the repository at wordpress, and i had missed out on the latest update which fixed the compatibility issues. Follow the link below to find out more and download teh latest version if you require.
http://sivel.net/2011/12/shadowbox-js-plugin-pulled-from-the-wordpress-org-repository/


text:
Q: Error code 1, -110 in media player android I got the MediaPlayer error code as (1,-110)  on BeagleBoard Hardware running ICS.The code runs fine on android tablets with ICS but I get a dialog box as "Sorry,this video cannot be played" error on BeagleBoard only.Any suggestions.

A: This is a time out error from the MediaPlayer:
http://developer.android.com/reference/android/media/MediaPlayer.html#MEDIA_ERROR_TIMED_OUT
Also, it may happen with an issue with Samsung firmware on Android 4.1.2, I've seen it in Galaxy S2 mini and Galaxy S3. Take a look here:
https://stackoverflow.com/a/18378273/3032209
You could solve it if you play the file it with another library, which will have the adequate codecs, like aacdecoder-android

A: I know my answer is too late to your question and I think you were able to fix this problem by now, but if not and for those people who are struggling with the Media Player Error (1, -110) (like I did the whole day today, Android HTC Desire X Jelly Bean 4.1.1), maybe this is the solution for you:
Just reboot your android (or close all the apps, which are using the Media Player).
In my case it was not a programming error, I just had to many apps open using the Media Player Instance, which led to that time out and I could not use it anymore.


text:
Q: how do I understand the specific solution to one problem in hackerrank? It's about a solution to one problem in hackerrand. please click the link:
the link of problem description
string reverseShuffleMerge(string s) {
int n = s.length();
vector<char> sarr(s.rbegin(), s.rend());
int alpha_size = 26;
vector<int> freq(alpha_size, 0);
for (int i = 0; i < n; i++) {
    freq[sarr[i] - 'a']++;
}
vector<int> did_use(alpha_size, 0);
vector<int> can_use(freq.begin(), freq.end());
vector<char> A;
for (int i = 0; i < n; i++) {
    if (did_use[sarr[i] - 'a'] < freq[sarr[i] - 'a'] / 2) {
        while (A.size() > 0 && sarr[i] < A.back()
               && did_use[A.back() - 'a'] + can_use[A.back() - 'a'] - 1
               >= freq[A.back() - 'a'] / 2) {
            did_use[A.back() - 'a']--;
            A.pop_back();
        }
        A.push_back(sarr[i]);
        did_use[sarr[i] - 'a']++;
        can_use[sarr[i] - 'a']--;
    } else {
        can_use[sarr[i] - 'a']--;
    }
}
return string(A.begin(), A.end());

}
I don't get the point of this line: did_use[A.back() - 'a'] + can_use[A.back() - 'a'] - 1 >= freq[A.back() - 'a'] / 2
Could anyone help to shed some light on what part this line plays in the solution?

A: In this problem, frequency of all the character in string s will be even number. The answer will contain half of these characters. For example if s="aaaabbcc", then answer must contain 2 a, 1 b and 1 c.
So did_use[A.back() - 'a'] + can_use[A.back() - 'a'] - 1 >= freq[A.back() - 'a'] / 2 this is for if we remove A.back() character, can we add/make required number of A.back() character in later with the remaining string.


text:
Q: Как правильно разместить в одном блоке 2 фона? Не знаю насколько корректен мой вопрос, но в данном случае у меня переход с картинки на фон, при этом действие происходит в одном и том же блоке, как лучше сделать такую штуку и при этом ее адаптировать как-то, ведь как я понял, видимо придется с position absolute иметь дело. если можно, то с кодом, ибо не совсем понятен концепт как это реализовывать. Заранее спасибо <3

A: Пример

body {
  margin: 0;
}

video {
  display: block;
  width: 100%;
}

video::-webkit-media-controls-panel {
  background-image: linear-gradient(transparent, transparent) !important;
}

video::-webkit-media-controls {
  padding-bottom: 3rem;
}

.section-1 {
  position: relative;
}

.section-1::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50%;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, .4) 70%, rgba(0, 0, 0, 1) 100%);
  pointer-events: none;
}

.section-2 {
  background-color: #000;
  min-height: 100vh;
}

  <video controls>
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  </video>


text:
Q: Code signing entitlement errors: Same error-different cause I have an issue that is similar to this one. The solution doesn't work for me and I suspect that it's because Xcode and Apple have a different idea about what my Team ID is.
I get the same two entitlements errors as the cited post when validating my app.  If I look at the Team ID in my Account profile on developer.apple.com, it says something like F65F8MK8HE. The iPhone Distribution certificate in my Keychain says, S88MMLNF5T.
The entitlement error says that the key value is not allowed and uses S88MMLNF5T.com.mydomain.myapp. If I open the archive and look for the file archived-entitlements-expanded.xcent it has two lines with the Team ID. If I replace the Team ID with the one on the website, the archive validates. That's why I'm guessing the problem is that Xcode and the Apple site have different ideas about what the Team ID is. I'm guessing that I have to delete something to get them to synch up, but from past experience with deleting stuff, I'm hesitant to do anything without understanding what needs to be deleted.
I'm thinking that I should delete the iPhone Distribution certificate in my keychain and let Xcode regenerate what it needs? Does that sound reasonable?
Related to the issue, I can install apps on my devices and they all run. But all of the my old apps crash on launch. I suspect that it has something to do with the old apps using a different Team ID. So if I somehow get Xcode to use the new Team ID, will I be able to update apps in the store without them crashing?
This happens on Mavericks and Xcode 5.0 and 5.0.1.

A: I asked Apple Developer Support this question and the response I got fixed my problem. It might work for others too.
Basically, there is a bug in Xcode that affects a few developers. The workaround is to make my signing section look like this.

Unlike the case that others have had, I did not choose the provisioning profile specific to the app but chose my distribution profile for release.

A: If you're running an old project (3.1.5 or earlier) and migrating to XCode 5, you will have a manually created Distribution build target, which makes the Apple solution you're referring to impossible. In the answer I wrote to the question you're referring to I found a solution for that. (Leaving the links here for future visitors.)


text:
Q: Why is redux better than a simple object? I am learning Redux. As I understand, Redux in React helps us to manage state of React app. But why can't I just use empty object to hold all necessary state changes?
For example, I have root component with two subcomponents.
<App>
   <Label/>
   <Button/>
</App>

Inside Label I have state {numb: 1} and one function, that increase numb
increase() {
    setState(prevState => {
        return {numb: prevState.numb + 1}
    });
}

On top of this component I import Store.js file, that exports empty object, that I use to store all my change state functions.
import Store from './Store'

And in the constructor of Label, I just assign function from that component
Store.plusOne = this.increase

That helps me to import Store file inside Button component and use increase function to increase Label's numb property.
<button onClick={Store.increase}>Plus One to Label's numb</button>

So what is the point to use Redux, if I can store any state change function in a separate object?

A: I had the same feeling when I started with Redux a few years ago. "Man, this seems overly complicated". But then I realised while not using redux that I was doing the same things but less efficient and more error prone when doing things "manually".
Redux comes with a few powerful helper functions. The first one is connect which helps you to get those state properties into your components. You can literally connect your components to your state. You don't have to worry about anything else, change the state in a single place and watch the changes flow through your application.
Because you "plop" (yes, a technical term...cough) all the properties you need for that component from your state onto the props of your component you automatically get that the component refreshes when your state changes. Even while using pure functions or a PureComponent which might be very good for performance.
You can see it like this. If you want React + Redux to automatically reflow your application: use Redux. If you manually want to update a object and manually force your application to reflow, use a custom state object.
That being said, I think redux makes sense in bigger applications where multiple components depend on the same state. If you just have a single piece of data rendered in a single component or a demo app with a simple button click you might as well keep it simple with a small object.


text:
Q: Why are consistency rules spanning Aggregates allowed to be enforced at some later time? From:

Invariants, which are consistency rules that must be maintained
  whenver data changes, will involve relationships between members of
  the AGGREGATE. Any rule that spans AGGREGATES will not be expected to
  be up to date at all times. Through event processing, batch
  processing, or other update mechanisms, other dependencies can be
  resolved within some specified time. But the invariants applied within
  an AGGREGATE will be enforced with the completion of each transaction.

a) I interpret this as saying that rule designed to maintain consistency between several Aggregates, doesn't have to be enforced at the time one of these Aggregates is saving its changes to some persistence storage, but instead can be enforced at some later time when this Aggregate already completes its transaction with persistence storage?
b) But why is such behavior tolerated, since it will lead to inconsistent/corrupt data?
Thank you

A: a). Correct. An aggregate can be defined as a consistency boundary. Things outside of that boundary, such as other aggregates, are those entities which can be acceptably updated as part of a subsequent transaction. This is eventual consistency.
b). Often times, temporarily stale data is acceptable from the business perspective and should be discussed explicitly. Also, inconsistency actually manifests in places typically regarded as consistent. For instance, as soon as you request data from some service and receive it, the data has the potential to be inconsistent unless there is an ambient transaction. If the requested resource is remote, the transaction will have to be distributed and thus subject to all of the pitfals of 2PC.
Take a look at Udi Dahan's article on Event-Driven Architecture which discussed eventual consistency from the business perspective.


text:
Q: Using waitpid() to get only status information For my school assignment, my professor wants me to store the state of background processes that i've made with my program and stored in a process table with each process entry being either "in progress" or "completed". To check whether a process has been completed(terminated) my professor needs me to use waitpid() to do this.
I don't know how this can be done because if i loop through all the processes i've created in the background(a bunch of sleep()'s) and i check each process by checking if waitpid() with each process's id as an argument to waitpid() and it return something other than -1(not an error), then each process will jump to the foreground when i really just want to know if that process is terminated or not.
Professor's original question:
BACKJOBS: A command that prints a list of background jobs and their current status. This feature is similar to the jobs command when using tcsh. The current status (i.e., in progress or completed) of each job can be determined by using the waitpid system call (see man waitpid for more information). The calls that report an error will be those that have already completed, so their status will be "completed". The calls that do not result in an error will have a status of "in progress".


text:
Q: Why use the Accessed-Bit for the Least-Recently-Used algorithm? In our lecture, the LRU algorithm for page replacement was explained by looking wether a page has been accessed in the last "epoch" (not sure if that's the proper english term). After every epoch, the A-Bit is set back to 0 on all pages. Lazy me didn't listen correctly and implemented a simulator in a different manner during an assignment:
Just put the most recently used page on top of a stack so we have our pages in the order in which they were most recently used and it's obvious that both ideas are aquivalent.
This is done this way on wikipedia too so I'm wondering, why would you even do it the A-Bit-way? Is it just a naive implementation from the past or does it have better runtime? I would doubt that since you'd have those epochs and reset the A-Bit all the time.


text:
Q: Kong to have anonymous routing through jwt global plugin I have been using Kong db-less 1.4.1, runing on Kubernetes (OpenShift)
I have configured (enabled) JWT plugin as global to be used for all rest APIs behind the Kong but I also need to have anonymous in the same plugin as exceptions, I created the jwt plugin by below yaml.
apiVersion: configuration.konghq.com/v1
config:
anonymous: "this is an example of consumer_id"
kind: KongPlugin
metadata:
labels:
app.kubernetes.io/instance: kong
app.kubernetes.io/name: kong
global: 'true'
name: global-jwt
namespace: iot-kong
plugin: jwt

Moreover I have also created KongConsumer and KongCredential.
This plugin works perfectly but when I add anonymous in this configuration, it doesn't work anymore
Please do me a favor and send me an practical example to solve my problem.


text:
Q: PHP 5 - Securing an admin area of a site I'm currently writing a couple of MVC sites using Kohana as my framework.  Each has a simple admin area where the admin can upload and edit content.  I'm currently storing the admin's user model in a session and checking whether or not they're an administrator with the following method:
private function checkAdmin()
{
    if (!isset($_SESSION['admin']) || $_SESSION['admin']->Level !== 'admin')
    {
        header('Location: /admin');
        exit;
    }
}

I call this method in all of the other Admin controller methods, like so:
public function writeReview()
{
    $this->checkAdmin();

    // rest of the method
}

I'm just wondering if there's anything I can do to improve this.  It just seems like a single point of failure that's giving me a bad smell, so I'm a bit weary to move on before getting this nailed down.

A: If this is Kohana version 2.x, I would move the $this->checkAdmin(); into the constructor of your controller.  If this is version 3.x, I would put it in the before() method.  This will ensure that every route will be protected.

A: *

*Your function appears to be redirecting to /admin only if the user is not an administrator.  If that's the intended result, then fine.

*-- Forget this, my mistake.

*The checkAdmin() function, as it relies on a redirect, is only useful in situations where you want to redirect.  If, for example, you are using this in the processing script (and you should be checking if it's an administrator in the processing script), you just want a return true or return false.  I suggest that be the base function, and a redirect function call that, or alternative, accept and optional parameter to redirect.

A: If you want to let users share their logins fine, but otherwise generating a per session/login key and storing it in the DB will lock things down even further. This way, if someone logs in with your password, you'll get kicked out and instantly know that it's been compromised.
Other basic things to do - store dates of last login, IPs.. this kind of stuff. It's not just one single thing, but lots! :)


text:
Q: Python thread remaining in Multithreading To sumup my problem, I have made this little program which does nothing but create a series of threads which print something and should destroy themselves.
#!/usr/bin/env python

from time import sleep
from multiprocessing.pool import ThreadPool

def mythread(i):
    print 'i %s \n' % i
    sleep(1)

def start():
    i = 1
    while 1:
        pool = ThreadPool(processes=1)
        pool.apply_async(mythread, (i,))
        sleep(5)

# ----------------------
#          Main
# ----------------------

if __name__ == '__main__':
    start()

But when I run this program under the name of test.py, the command ps aux -T to get the list of process show something I did not expected.
10:04 azerty@3RMQP32 ~/Bureau $ ps aux -T | grep test | grep -v grep
azerty  9613  9613  0.2  0.0 322616  7520 pts/19   Sl+  10:04   0:00 python test.py
azerty  9613  9614  0.0  0.0 322616  7520 pts/19   Sl+  10:04   0:00 python test.py
azerty  9613  9615  0.0  0.0 322616  7520 pts/19   Sl+  10:04   0:00 python test.py
azerty  9613  9616  0.0  0.0 322616  7520 pts/19   Sl+  10:04   0:00 python test.py
azerty  9613  9617  0.0  0.0 322616  7520 pts/19   Sl+  10:04   0:00 python test.py

I was expected 2 processus for the first second, the main and the thread then only the main in sleep. Finally, one thread would pop for 1 sec every 5 sec and kill himself right after. But I don't observe that. The main processus generate 4 sub threads which never die and 5 seconds later,
4 new are created until I kill everything.
How can I make sure that at least the sub threads will finish themselves when they reach the end of their functions. I can't join() on the main because I need it to run and to launch threads continuously.
Thank you,


text:
Q: Shell command that cycles through lines? Lately, I've often found myself wanting to run some command on the output of another command that has output on several lines.
For example, let's say I have a command that returns a number of file paths each on a new line and I'd like to delete all these files.
Is there a command that can help me do this?

A: It sounds like you're looking for xargs. From the man page:

xargs reads arguments  from  the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash)  or  newlines,  and executes  the command (default is /bin/echo) one or more times with any initial-arguments followed  by  arguments  read  from  standard  input.

So you can do things like:
ls | grep -v '*.cpp' | xargs rm

The above command would delete everything in the current directory except *.cpp files.

A: In bash-like shells you can do:
rm `your command`

or
rm $(your command)

A: In Windows, CMD:
for /f "usebackq delims=" %i in (`your command`) @del "%i"

Powershell:
your command | Remove-Item

A: ls | xargs rm

one interesting use (to search a directory for a phrase inside a file)
find /path/to/dir | xargs grep "search text"

That one isn't related, but it shows how xargs works

A: Assuming a UNIX-like environment:
To handle spaces in names, use the -0 flag to xargs. With find:
find . -name '*.mp3' -print0 | xargs -0 dosomething

Some other commands have various switches for nul-separated output, usually -0 or -z. If your list is line-oriented, do something like:
cat filelist | tr -s '\012\015' '\000' | xargs -0 dosomething

Which uses tr to translate newlines and linefeeds to nuls, handling UNIX and DOS (and even Mac Classic) line ends and skipping blank lines.
Don't forget that newlines are valid filename characters on most UNIX-like filesystems.
If dosomething is complex, you can use bash functions:
dosomething() {
    while [ -n "$1" ] ; do
        out="$(basename "$1" .mp3).ogg"
        convert "$1" "converted/$out"
        shift
    done
}

export -f dosomething

and invoke xargs like:
cat filelist | tr -s '\012\015' '\000' | xargs -0 bash -c 'dosomething "$@"' --

Note the judicious use of double-quoting to preserve spaces, and that double-quoted strings can be nested inside double-quoted $() eval operators.
Within the function, you can write "$@" to get a properly quoted argument list to pass to a subprocess:
dosomething() {
    command1 preargs "$@" postargs | command2
    command3 "$@"
}

You can also use read to work line-by-line:
cat filelist | while read i ; do something "$i" ; done

but xargs gets you all of the args at once.

A: try
cat file | while read i; do echo "working on line $i"; done

Although you can have trouble with lines having spaces. I never remember how to fix that.
Please note that this command works for every manipulation on a line-by-line basis. Using xargs works only for the example case you asked (and similar cases), but if you can solve your problem with xargs, definitely go for it.


text:
Q: Solve a Boundary Value Problem with weird answer $$y''+2y'-8y=0$$
Where $0\leq x\leq2$, $y(0)=0$, and $y(2)=0$
At first I tried to solve it just like a normal differential equation and I got $y=Ae^{-4x}+Be^{2x}$
But when I input the condition $y(0)=0$, and $y(2)=0$ it became $y(x)=0$
Am I wrong? I feel it is weird. Or there is something special about $0\leq x\leq2$ ?
Thank you

A: The "responsible" is not the considered interval, but the choosen boundary values.
Consider a more general problem
$$y''+2y'-8y=0\\ y(0)=c, \; y(2)=d$$ with $0\leq x \leq 2, \; c,d\in \mathbb{R}.$
The constants $A,B$ in the general solution $$y=Ae^{-4x}+Be^{2x}$$ satisfy
$$A=\frac{d-ce^{4}}{e^{-8}-e^4},\; B=c-A.$$
If $c=d=0,$ as it is in your case, then $A=B=0.$


text:
Q: Xamarin добавление References Всем привет!
Подскажите, пожалуйста, возможно ли в Xamarin Forms Portable проект добавлять References ?
У меня почему-то список пустой, не могу даже подключить System.Data
Но в Андроид проекте все ссылки есть и подключить их можно
Или же в Portable нужно только вручную dll'ки добавлять из фолдера?
Заранее благодарен!

A: В Portable проекте нельзя добавлять в References System.Data
Если вам нужно работать с базой можно использовать MysqlLite как указано в документации.
К недостаткам PCL относится :

*

*Так как портативная библиотека классов разделяется между несколькими
приложениями, библиотеки специфичные для платформы нельзя добавлять
в references (например. Community.CsharpSqlite.WP7).

*PCL не должен включать в себя классы, которые могуть бы доступны в MonoTouch и Mono для Android сразу (например, DllImport или System.IO.File).


text:
Q: A quick way to rewrite variables with quotations marks I have this dataset
   > dput(head(data, 10))
structure(list(ID = c("01", "01", "01", "01", "01", "01", "01",
"01", "01", "02"), GR = c("RP", "RP", "RP", "RP", "RP", "RP",
"RP", "RP", "RP", "RP"), SES = c("L", "L", "L", "R", "R", "R",
"V", "V", "V", "L"), COND = c("NEG-CTR", "NEG-NOC", "NEU-NOC",
"NEG-CTR", "NEG-NOC", "NEU-NOC", "NEG-CTR", "NEG-NOC", "NEU-NOC",
"NEG-CTR"), `P3(400-450).FCz` = c(-13.733750856001, -11.0706676917232,
-8.4719202003519, -5.04318152659785, -6.25375875400145, -7.0474968134059,
-11.6312151716924, -11.1438413285935, -3.99591470944713, 8.71618523084192
), `P3(400-450).Cz` = c(-9.75024624896264, -8.42427447113084,
-5.61886494275071, 0.73152672768007, 1.11453058993788, -2.25104720773472,
-5.16524399006139, -5.53112490175437, 0.621502123415388, 10.0972150696175
), `P3(400-450).Pz` = c(2.65626156135631, 3.37360619561252, 5.4043480635031,
19.5226358864568, 18.5017390789352, 11.7844254386573, 11.8802266972569,
12.1053426662461, 12.955441582096, 13.9718285231429), `LPPearly(500-700).FCz` = c(-11.2145748677083,
-13.9481657323772, -12.0047623683783, -4.24372139176794, -7.38414465678688,
-6.61221718491095, -11.7785042972793, -9.14927207125904, -7.58190508537766,
14.2438131545118), `LPPearly(500-700).Cz` = c(-8.14861856277773,
-11.7645758007163, -9.16726244915301, 0.918751423320568, -0.674372568935879,
-2.47425935490564, -5.96429031525769, -5.10918437158799, -2.81732229625975,
18.1277616996079), `LPPearly(500-700).Pz` = c(3.4315211013568,
-1.55179922542943, 1.13509020104859, 16.3120391015512, 14.1694182774958,
9.04781409226351, 8.23981597718437, 9.51261484648731, 9.42367409925817,
20.6284861844249), `LPP1(500-1000).FCz` = c(-7.774797181711,
-8.40872060176111, -7.03235376576925, -0.65010821749741, -3.24350263682843,
-2.84832379590422, -5.67295796971287, -4.3918290080777, -2.96652960658775,
12.5228696634748), `LPP1(500-1000).Cz` = c(-5.0379636708446,
-6.36865552801825, -4.54670193355435, 4.05493850786385, 2.67516303169366,
1.02479302810681, -0.774461731301161, -0.650009462761383, 1.14010250644923,
15.0856583318757), `LPP1(500-1000).Pz` = c(4.67200616533014,
1.75888442936359, 2.49276476951357, 13.8997702651793, 13.2135623121441,
9.51479768101391, 9.99385579756163, 11.1212652173052, 10.6989716871958,
15.4011622649207), `LPP2(1000-1500).FCz` = c(-0.397250087672501,
1.01519755373062, -1.17300033366376, 0.663115370014327, -1.72160165493474,
0.0540027107377267, -0.198736254963744, -3.16101041766438, 0.895992279831378,
9.21248347391488), `LPP2(1000-1500).Cz` = c(2.91913936481813,
1.85489998202138, 0.694393606954545, 3.95694572160701, 2.36649557381131,
2.71292196345657, 2.96437294922766, -2.12913230708907, 2.94619035115619,
10.0673617448764), `LPP2(1000-1500).Pz` = c(8.38141924882334,
4.88842858528025, 5.0594399581601, 3.88831364571248, 5.83201076558185,
3.65113189260335, 6.28027312932027, 5.24535230966772, 7.68162285335806,
8.55827491190151), `LPP2(1000-1500).POz` = c(9.61455213192824,
7.21299011910717, 6.1861244061312, 6.46723813995257, 7.25962635499353,
7.92952342178602, 7.91468942320841, 9.94838815736199, 10.2186482048953,
5.76901446016799)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
>

Where as you could see there some variable with annoying quotations. I scripted down this code to get rid of them
data <- data %>%
  dplyr::rename("P3(400-450).FCz" = P3Fcz,
                "P3(400-450).Cz" = P3cz,
                "P3(400-450).Pz" = `P3(400-450).Pz`,
                "LPPearly(500-700).FCz" = `LPPearly(500-700).FCz`,
                "LPPearly(500-700).Cz" = `LPPearly(500-700).Cz`,
                "LPPearly(500-700).Pz" = `LPPearly(500-700).Pz`,
                "LPP1(500-1000).FCz"  = `LPP1(500-1000).FCz`,
                "LPP1(500-1000).Cz" =  `LPP1(500-1000).Cz`,
                "LPP1(500-1000).Pz" = `LPP1(500-1000).Pz`,
                "LPP2(1000-1500).FCz" =  `LPP2(1000-1500).FCz`,
                "LPP2(1000-1500).Cz"  =  `LPP2(1000-1500).Cz`,
                "LPP2(1000-1500).Pz"  = `LPP2(1000-1500).Pz`,
                "LPP2(1000-1500).POz" = `LPP2(1000-1500).POz`)

By the way I am quite sure that could there be some quicker alternatives to deal with them. Do you any suggestions about it?
Thanks in advance

A: You could do:
df %>%
  rename_with(~str_remove(.x, "\\W.+\\W"))

To be more precise:
 df %>%
    rename_with(~str_remove(.x, "\\(.+\\."))


text:
Q: Passing Route Specific Information To Children I have multiple routes in my webapp like normal.  I have a few questions regarding the best ways to pass information down the chain since I can't really find a solid answer:

*

*How would I pass what the current route is down to the children components?  I have a global component that is used across every page of my webapp.  On one of the page's, the content has to be different.  The only way I can do this is by knowing what page is being served.  Or am I thinking of this incorrectly and should just parse window.location on componentDidMount() to get everything I need?

*This is kind of tied in to the above point.  Let's say I have a parameterized route (/test/:id), and one of its child components needs to perform some ajax request when a button is clicked, and needs to pass in the :id to the endpoint.  How would I be able to get this done?
Maybe I have to pass things down as properties starting from the route level all the way down?
I'm just trying to figure out what the best option is.
Thanks!

A: You cant pass properties all the way down or you can put properties in store and connect your components to the store. If you want to go the store way you can try the redux branch of react-starter-kit. This is what I've done. On root paths I will put my parameters into store and all other children can read them. Here is the redux implementation of react-starter-kit:
https://github.com/kriasoft/react-starter-kit/tree/feature/redux


text:
Q: Xamarin.android studio, a simple synthesizer app with AudioTrack using c# csharp - what is it in Java: samples[i] = (short) (amp*Math.sin(ph));? Good day. I am currently making a music app for Android in Xamarin studio using csharp. First, I created a primitive synthesizer app in Java (in Eclipse) following this tutorial: A simple synth in Android: step by step guide using the Java SDK
It works well with Java SDK. Now, I am doing the same in C# using Xamarin.android studio.
So, from the above tutorial, the sound synthesis loop in Java is as follows:
while(isRunning){

for(int i=0; i < buffsize; i++){
samples[i] = (short) (amp*Math.sin(ph));
ph += twopi*fr/sr;
}
audioTrack.write(samples, 0, buffsize);
}

However, I do not understand this line (namely the syntax):
samples[i] = (short) (amp*Math.sin(ph));

So I can't do the same in C# unless I know what exactly it does. F.e. why is there (short) before (amp*Math.sin(ph))?
I figured out that in C# this line will correspond to :
samples[i] = (short) (amp*System.Math.Sin(ph));

I would be very grateful if you could either explain it to me or point me to some documentation that I could read up.

A: Re: Why is there a short before (amp*math...)?
I presume "samples" is an array of short integer values: Since System.Math.Sin() returns a double floating point number, you would have to truncate and cast the value to make it a short integer. The "(short)" keyword tells the compiler to do just that.


text:
Q: Body tag non behaving normally I have a body tag in my HTML which should fill the whole page (the whole html tag so), but it appears with some pixels between the top of the page and the top of the body tag.
Strange thing is that if I force body {padding: 0;} in my CSS, there's still this little bar at the top of the page which body doesn't manage to fill, while if I set padding to any non-zero value that little bar gets covered by body and the specified padding is applied.
This is my trivial CSS (which styles a body HTML tag filled with divs and ordinary stuff):
html {
    height: 100%;
    margin: 0;
    padding: 0; // this is ok, html fills the whole page
}

body {
    margin: 0;
    height: 100%;
    padding-top: 1px; // here, if I write padding:0;, space at the top will not be filled by body
}

Edit
Here's my HTML, I don't know if it can be useful.

        stuff

        stuff

        stuff

Note: I'm working with both Firefox and Chrome, same behavior.

A: You could try clearing both of the html and body tag CSS rules, and simply put:
/* basic CSS reset */
* {
  padding: 0;
  margin: 0;
}

html, body {
  height: 100%;
  width: 100%;
}


text:
Q: Warning: mysqli_query() expects parameter 1 to be mysqli, null given in D:\OSPanel\domains\localhost\proverki.php on line 120 Connection error1 Не понимаю, что ему не нравится?
<!DOCTYPE html>

    <meta charset=UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Библиотека WGNF</title>

    <link href='http://fonts.googleapis.com/css?family=Roboto:400,300,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.css" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <link rel="stylesheet" type="text/css" href="css/pluton.css" />

    <link rel="stylesheet" type="text/css" href="css/jquery.cslider.css" />
    <link rel="stylesheet" type="text/css" href="css/jquery.bxslider.css" />
    <link rel="stylesheet" type="text/css" href="css/animate.css" />

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/apple-touch-icon-72.png">
    <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57.png">
    <link rel="shortcut icon" href="images/ico/favicon.ico">

                <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

                </button>

            <-----Вернуться назад

            <form id="checking-form" action="#" method="post"></form>

                        <input type="text" name="checking" form="checking-form">

                        <button form="checking-form" type="submit">Введите дату</button>

                 День сдачи
                    Читатель
                    Книга
                <?

                        include("dbinsert.php");
                        $checking = $_POST["checking"];

                        $result = null;

                        if ($checking) {
                            $query = "SELECT `Date_vozvrata`,`ID_Zakazchika`,`Name_Book` from `zakaz` WHERE (Date_vozvrata <= '$checking')";
                            $result = mysqli_query($link, $query) or die("Connection error1");
                        }

                        if ($result) {
                            while ($row = mysqli_fetch_assoc($result))
                            {
                                ?>

                                    <? print $row['Date_vozvrata']?>
                                    <? print $row['ID_Zakazchika']?>
                                    <? print $row['Name_Book']?>
                                <?
                            }
                        }

                        mysqli_close($link);

                    ?>


text:
Q: Is Qt's meta system really that tedious? I would like to use Qt's reflection mechanism since C++ lacks of this feature. It seems to work, but calling all the macros and helper functions is very tedious. For example to register an enum as a proper meta type I had to go through all the following steps:

*

*Declare an enum inside of a wrapper class that contains the Q_GADGET macro.

*Register the enum using the Q_ENUM macro just after that.

*Register the class containing the enum: Q_DECLARE_METATYPE(MyClass)

*Call qRegisterMetaType<..>() for the type of the wrapping class and
for each declared enum.

Now I know that some of the steps can be omitted if part of the full functionality is not required. But that is not what I am looking for, I need to use enums within signals and I need to be able to get the the meta method of a signal and query it for it's parameters type.
But still I can't help thinking that there must be a better/simpler way to do this.

A: Unfortunately, you can't do less than that.

*

*Q_GADGET (or Q_OBJECT, for QObject subclasses) means "generate meta-object information for this class".

*Q_ENUM means "generate meta-enum information for this particular enum". Now one might argue that all (public?) enumerations in a registered class should be also automatically registered. But since this has a cost (binary size), and we use C++, we don't want to pay for enums we're never going to use in the meta-object system, so it's opt-in.

*Q_DECLARE_METATYPE (not needed on the enum itself if you're using Q_ENUM; not needed in general, in your scenario) enables the type to be used inside QVariants (Qt's C++98, RTTI-less incarnation of C++17's std::any). Whether you want this or not depends on the type. I would say that all "value types" should have it, but again, this generates extra code that you may not want to pay for. Also, this really applies to "value types" only -- this registration requires the type to have public default constructor, public copy constructor, public copy assignment, public destructor. If you've got a class which does not have these, you can't use this macro => you can't wrap it in a QVariant.

*qRegisterMetaType registers the aforementioned constructors/destructors in a table at runtime, enabling you to have an unique id for the type (required if you want to identify types in method signatures), dynamically create or destroy instances of the type (required, amongst other things, to implement queued connections: Qt needs a generic way to copy the signal's arguments into an event to be sent to the target thread, and destroy such arguments later), use the Q_PROPERTY subsystem.

Depending on what exactly you need to do you need a subset of all of this.


text:
Q: How to select the first value that is not NaN after using groupby().agg()? I have the following code:
df.groupby(["id", "year"], as_index=False).agg({"brand":"first", "color":"first"})

However, I have some values that are NaN. I want to select the first value that is not NaN.
Suppose my dataframe looks like this:

id
year
brand
color

001
2010
NaN
Blue

001
2010
Audi
NaN

001
2010
Audo
Blue

001
2011
Bmw
NaN

001
2011
NaN
NaN

001
2012
BMW
Green

002
2010
Tesla
White

I want to find all unique combinations of id and year,i.e. df.groupby(["id", "year"]) and then find the first non-NaN value. The motivation behind this is that a have a large and messy data set with many missing values and many typos. In the example table I also simulated a typo. Note that it is irrelevant whether the typo is first and gets chosen, as long as I keep track of the data per combination of id and year. Typos are a completely separate problem for now.
The desired output would be:

id
year
brand
color

001
2010
Audi
Blue

001
2011
BMW
NaN

001
2012
BMW
Green

002
2010
Tesla
White

A: This approach will produce the below output.
df1 = df.groupby(['id', 'year']).agg({
    'brand': lambda x: x.dropna().iloc[0] if x.dropna().any() else np.nan,
    'color': lambda x: x.dropna().iloc[0] if x.dropna().any() else np.nan,
}).reset_index()
print(df1)

Using a costume function:
def get_first_non_nan(x):
    return x.dropna().iloc[0] if x.dropna().any() else np.nan

df1 = df.groupby(['id', 'year']).agg({
    'brand': get_first_non_nan,
    'color': get_first_non_nan,
}).reset_index()
print(df1)

    id  year  brand  color
0  001  2010   Audi   Blue
1  001  2011    Bmw    NaN
2  001  2012    BMW  Green
3  002  2010  Tesla  White


text:
Q: How to disable prompt to store credentials in composer? When I update composer with private repositories running composer update, it prompts to store credential:
Do you want to store credentials for bitbucket.org
in /home/evgeny/.composer/auth.json ? [Yn]

How to surpress this question with answer no by default? I won't answer every update and I won't store this credentials.

A: You can globally disable all interactive questions by setting the COMPOSER_NO_INTERACTION env variable to 1.
Ref: https://getcomposer.org/doc/03-cli.md#composer-no-interaction


text:
Q: Is it possible to pass Kubernetes Cronjob status.lastScheduleTime timestamp to the container of scheduled job? I have a cronjob that should process events occurred since the last operation, for that I use DB to persist this timestamp, my question is whether or not it is possible to directly pass Kubernetes status.lastScheduleTime into the cronjob object as an environment variable?

A: I see the easiest way accomplish your goal via kubectl set env command, injecting into the particular Cronjob template object the desired status.lastScheduleTime field as environment variable LAST_SCHEDULE:
kubectl set env cronjob/name LAST_SCHEDULE=$(kubectl get cronjob name -o jsonpath='{.status.lastScheduleTime}')
env:
- name: LAST_SCHEDULE
  value: "2019-09-23T08:56:00Z"

You may also find a more comprehensive way achieving Cronjob resource patching, supplying target environment variable  in the corresponded template with most recent lastScheduleTime value via Init Containers or through postStart/preStop handlers.


text:
Q: Preview is not properly showing In Android Studio 3.0 in Ubuntu 17.10.
I am designing *.xml file in code view  and i have changed Root from ScrollView to RelativeLayout and the preview is suddenly corrupted like this...

and when i Run the project it gives correct output

This is my *.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <TextView
        android:id="@+id/tvJoinTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:layout_marginTop="@dimen/_10sdp"
        android:background="@color/white"
        android:text="@string/join_us"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="@dimen/_15ssp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tvJoinTitle"
        android:background="@color/white"
        android:padding="@dimen/_8sdp">

        <TextView
            android:id="@+id/country"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:lines="1"
            android:text="BUSINESS COUNTRY"
            android:textSize="@dimen/_12ssp" />

        <LinearLayout
            android:id="@+id/etcountryname"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_below="@+id/country"
            android:layout_margin="@dimen/_5sdp"
            android:background="@drawable/gray_border"
            android:orientation="horizontal"
            android:padding="@dimen/_1sdp">

            <LinearLayout
                android:id="@+id/llSelectCountry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/ivCountryFlag"
                    android:layout_width="@dimen/_35sdp"
                    android:layout_height="@dimen/_20sdp"
                    android:layout_marginStart="@dimen/_10sdp"
                    tools:src="@color/colorPrimary" />

            </LinearLayout>

            <View
                android:layout_width="@dimen/_1sdp"
                android:layout_height="@dimen/_23sdp"
                android:layout_gravity="center_vertical"
                android:background="@color/gray" />

            <EditText
                android:id="@+id/etcountryselect"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:background="@color/white"
                android:inputType="phone"
                android:maxLength="10"
                android:padding="@dimen/_5sdp"
                android:singleLine="true"
                android:textSize="@dimen/_12ssp" />
        </LinearLayout>

        <TextView
            android:id="@+id/tvJoinUsName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/etcountryname"
            android:layout_margin="@dimen/_5sdp"
            android:lines="1"
            android:text="@string/business_person_name"
            android:textSize="@dimen/_12ssp" />

        <LinearLayout
            android:id="@+id/llJoinUsName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tvJoinUsName"
            android:layout_margin="@dimen/_5sdp"
            android:background="@drawable/gray_border"
            android:orientation="horizontal"
            android:padding="@dimen/_1sdp">

            <EditText
                android:id="@+id/etJoinUsName"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:background="@drawable/product_black_border"
                android:inputType="text"
                android:padding="@dimen/_12sdp"
                android:singleLine="true"
                android:textSize="@dimen/_12ssp" />
        </LinearLayout>

        <TextView
            android:id="@+id/tvJoinUsMobile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/llJoinUsName"
            android:layout_margin="@dimen/_5sdp"
            android:lines="1"
            android:text="@string/mobile_number"
            android:textSize="@dimen/_12ssp" />

        <LinearLayout
            android:id="@+id/llJoinUsMobile"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_below="@+id/tvJoinUsMobile"
            android:layout_margin="@dimen/_5sdp"
            android:background="@drawable/product_black_border"
            android:orientation="horizontal"
            android:padding="@dimen/_5sdp">

            <LinearLayout
                android:id="@+id/llSelectCountryNum"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/ivCountryFlagNum"
                    android:layout_width="@dimen/_35sdp"
                    android:layout_height="@dimen/_20sdp"
                    android:layout_marginStart="@dimen/_10sdp"
                    android:src="@color/colorPrimary" />

                <TextView
                    android:id="@+id/txtCountryCode"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingEnd="@dimen/_10sdp"
                    android:paddingLeft="@dimen/_10sdp"
                    android:paddingRight="@dimen/_10sdp"
                    android:paddingStart="@dimen/_10sdp"
                    android:text="+9000"
                    android:textColor="@color/gray"
                    android:textSize="@dimen/_10ssp" />
            </LinearLayout>

            <View
                android:layout_width="@dimen/_1sdp"
                android:layout_height="@dimen/_23sdp"
                android:layout_gravity="center_vertical"
                android:background="@color/gray" />

            <EditText
                android:id="@+id/etJoinUsMobile"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_gravity="center_vertical"
                android:background="@color/white"
                android:inputType="phone"
                android:maxLength="10"
                android:padding="@dimen/_5sdp"
                android:singleLine="true"
                android:textSize="@dimen/_12ssp" />
        </LinearLayout>

        <TextView
            android:id="@+id/tvJoinUsPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/llJoinUsMobile"
            android:layout_margin="@dimen/_5sdp"
            android:lines="1"
            android:text="@string/password"
            android:textSize="@dimen/_12ssp"
            android:visibility="gone" />

        <TextView
            android:id="@+id/transportnumber"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/llJoinUsMobile"
            android:layout_margin="10dp"
            android:text="TRANSPORT REFERENCE NUMBER"
            android:textSize="@dimen/_12ssp" />

        <EditText
            android:id="@+id/ettransportnumber"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_below="@+id/transportnumber"
            android:layout_margin="10dp"
            android:background="@drawable/blue_dotted_border"
            android:inputType="number"
            android:padding="@dimen/_12sdp"
            android:singleLine="true"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textSize="20sp" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="@dimen/_38sdp"
            android:layout_alignParentBottom="true"
            android:layout_below="@id/ettransportnumber"
            android:layout_marginBottom="30dp"
            android:layout_marginEnd="@dimen/_10ssp"
            android:layout_marginStart="@dimen/_10sdp"
            android:onClick="goAndAddInfo"
            android:text="@string/next"
            android:textAlignment="center" />
    </RelativeLayout>

</RelativeLayout>

I have tried changing API level, Device, Theme, Orientation, Deleting build folders and even Invalid cache and Restart but no use.
i have faced this problem many times but dont know how to solve this.

A: Not an issue from your XML of course. Try changing API level or may be the selected theme in the menu above preview window.