text:
Q: cuando ejecuto una macro me crea un archivo actualmente lo que hago es correr unas macros desde python, por lo general me las ejecuta sin problema, pero en un archivo me da error, o bueno se comporta de una manera extraña cuando lo ejecuto por segunda vez, crea unos archivos temporales con números y me arroja una ventana para guardar, manualmente guardo estos archivos que me arroja, pero en si lo que espero es que solo ejecute la macro y cierre el archivo y ya. Sin embargo al validar este me ejecuta la macro en el archivo original y los que me arroja son copias.
def EjecutarMacro(ruta,archivo,modulo,macro):
    log = datetime.now()
    log_reg = log.strftime("%d/%m/%Y %H:%M:%S - ")
    print (log_reg+"Ejecutando Macro: "+macro+" en "+archivo+"")
    try:
        excel_macro = win32com.client.Dispatch("Excel.Application")
        excel_path = os.path.expanduser(ruta)
        workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
        excel_macro.Application.Run(""+archivo+".xlsm!"+modulo+"."+macro+"")
        time.sleep(30)
        workbook.Save()
        workbook.Close(SaveChanges=1)
        excel_macro.Application.Quit()
        excel_macro.Quit()
        del excel_macro
        print (log_reg+"Macro: "+macro+" ejecutada en: "+archivo+"")
    except Exception  as err:
        print("EjecutarMacro: Error tratando de ejecutar macro: "+macro+" en: "+archivo)
        print(err)

y estas son las dos macros que ejecuto por separado, que en sí no les veo algo raro.
Sub FM_Borrar()
    Sheets("Hoja1").Select
    Columns("A:G").Select
    Selection.Delete Shift:=xlToLeft
    Range("A1").Select
End Sub

Sub FM_BuscarV()
    'Toma la Hoja1 y ajusta formatos para la columna A y C
    Sheets("Hoja1").Select
    Columns("A:A").Select
    'en caso de encontrar la columna a vacia que se salte el error
    On Error Resume Next
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
        :=Array(1, 1), TrailingMinusNumbers:=True
    On Error GoTo 0
    Selection.NumberFormat = "0.00"
    Selection.NumberFormat = "0.0"
    Selection.NumberFormat = "0"
    Columns("C:C").Select
    Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
    Selection.NumberFormat = "0.00"
    Selection.NumberFormat = "0.0"
    Selection.NumberFormat = "0"
    Columns("E:G").Select
    Selection.NumberFormat = "m/d/yyyy"
    Range("A1").Select
    Sheets("faltantes").Select
    Columns("K:K").Select
    Selection.NumberFormat = "0.00"
    Selection.NumberFormat = "0.0"
    Selection.NumberFormat = "0"
   Range("K2").Select
    ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC5,Hoja1!C1:C7,3,FALSE),0)"
    Range("K2").Select
    Selection.AutoFill Destination:=Range("K2:K41")
    Range("K2:K41").Select
    Range("N2").Select
    ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC5,Hoja1!C1:C7,2,FALSE),0)"
    Range("N2").Select
    Selection.AutoFill Destination:=Range("N2:N41")
    Range("N2:N41").Select
    Range("K2").Select
    Range("K2:N41").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Range("K2:K41").Select
    Selection.TextToColumns Destination:=Range("K2"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
        :=Array(1, 1), TrailingMinusNumbers:=True
    Range("K2").Select
End Sub


text:
Q: Magento 2.0.2 Product image upload error I got an error like

error":"Unable to create directory
'/var/www/html/pub/media/tmp/catalog/product'.","errorcode" :0

While upload product images. I put 777 permission /var/www/html/pub/media folder. but i got the error. kindly help me.

A: Please check permission of media/catalog/products folder and try again.

A: Your issue in ownership.
Your web user .. ( CentOS: apache and www-data ) does not have the ownership  to create folder and files.
See http://devdocs.magento.com/guides/v2.0/install-gde/install/legacy-file-system-perms.html  , how to apply ownership  in magento2.
As you have using ,please check out http://devdocs.magento.com/guides/v2.0/install-gde/install/post-install-umask.html
https://github.com/magento/magento2/issues/2412
the 2.1 release candidate, and with 2.0.6+, if you need permissions for generated assets of 664 and 775
Little bad idea:
For a case, you can  change file permission from Magento\Framework\Exception\FileSystemException\DriverInterface You need change WRITEABLE_DIRECTORY_MODE = 0770; to WRITEABLE_DIRECTORY_MODE = 0775;and WRITEABLE_FILE_MODE = 0660 to WRITEABLE_FILE_MODE = 0664.It is working for You.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Differences between ConstraintLayout and RelativeLayout What is the difference between ConstraintLayout and RelativeLayout?

A: Officially, ConstraintLayout is much faster

In the N release of Android, the ConstraintLayout class provides similar functionality to RelativeLayout, but at a significantly lower cost.

A: The Conclusion I can make is
1) We can do UI design without touching the xml part of code, to be honest I feel google has copied how UI is designed in iOS apps, it will make sense if you are familiar with UI development in iOS, but in relative layout its hard to set the constraints without touching the xml design.
2) Secondly it has flat view hierarchy unlike other layouts, so does better performance than relative layout which you might have seen from other answers
3) It also have extra things apart from what relative layout has, such as circular relative positioning where we can position another view relative to this one at certain radius with certain angle which cant do in relative layout
I am saying it again, designing UI using constraint layout is same as designing UI in iOS, so in future if you work on iOS you will find it easier if you have used constraint layout

A: The real question to ask is, is there any reason to use any layout other than a constraint layout?  I believe the answer might be no.
To those insisting they are aimed at novice programmers or the like, they should provide some reason for them to be inferior to any other layout.
Constraints layouts are better in every way (They do cost like 150k in APK size.). They are faster, they are easier, they are more flexible, they react better to changes, they fix the problems when items go away, they conform better to radically different screen types and they don't use a bunch of nested loop with that long drawn out tree structure for everything. You can put anything anywhere, with respect to anything, anywhere.
They were a bit screwy back in mid 2016, where the visual layout editor just wasn't good enough, but they are to the point that if you are having a layout at all, you might want to seriously consider using a constraint layout, even when it does the same thing as a RelativeLayout, or even a simple LinearLayout. FrameLayouts clearly still have their purpose. But, I can't see building anything else at this point. If they started with this they wouldn't have added anything else.

A: In addition to @dhaval-jivani answer.
I've updated the project github project to latest version of constraint layout v.1.1.0-beta3
I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1
Here results:
Fresh start (first screen opening after application launch)
Relative Layout
OnCreate:       123ms
Last preformDraw time - OnCreate time:  311.3ms
Constraint Layout
OnCreate:       120.3ms
Last preformDraw time - OnCreate time:  310ms
Besides that, I've checked performance test from this article , here the code
and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.
As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?
As always: It depends
I wouldn't refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven't measured it lately, I haven't found any performance issues in the last releases. So I think you should be safe to use it. but – as I'v said – don't just migrate for the sake of migrating. Only do so, if there's a need for and benefit from it.
  For new layouts, though, I nearly always use ConstraintLayout. It's so much better compare to what we had before.

A: Reported by @davidpbr ConstraintLayout performance
I made two similar 7-child layouts, one each with a parent ConstraintLayout and RelativeLayout.
Based on Android Studio method tracing tool, it appears the ConstraintLayout spends more time in onMeasure and performs additional work in onFinishInflate.
Library used (support-v4, appcompat-v7…):
com.android.support.constraint:constraint-layout:1.0.0-alpha1
Devices/Android versions reproduced on:
Samsung Galaxy S6 (SM-G920A. Sorry, no Nexus atm). Android 5.0.2
Quick method tracing comparison:

Sample Github repo: https://github.com/OnlyInAmerica/ConstraintLayoutPerf

A: Following are the differences/advantages:

*

*Constraint Layout has dual power of both Relative Layout as well as Linear layout:  Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout).

*A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views.

*In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre.  ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .

*Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here:
https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior

*Provides power of automatic constraint applying by the use of Blue print and Visual  Editor tool which makes it easy to design a page.
All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.
Here is the best place to learn quickly:
https://codelabs.developers.google.com/codelabs/constraint-layout/#0

A: A big difference is that ConstraintLayout respects constraints even if the view is gone. So it won't break the layout if you have a chain and you want to make a view disappear in the middle.

A: The intention of ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.
The Rules are similar to RelativeLayout, for example setting the bottom edge to the bottom of some other view.
app:layout_constraintBottom_toBottomOf="@+id/view1"

Unlike RelativeLayout, ConstraintLayout offers a bias value that is used to position a view in terms of 0% and 100% horizontal and vertical offset relative to the handles (marked with a red circle). These percentages (and fractions) offer seamless positioning of the view across different screen densities and sizes.
app:layout_constraintHorizontal_bias="0.33" <!-- from 0.0 to 1.0 -->
app:layout_constraintVertical_bias="0.53" <!-- from 0.0 to 1.0 -->

The Baseline handle (a long pipe with rounded corners, below the circle handle) is used to align the content of the view with another view reference.
Square handles (on each corner of the view) are used to resize the view in dps.

This is totally opinion based and my impression of ConstraintLayout

A: Relative Layout and Constraint Layout equivalent properties

(1) Relative Layout:
android:layout_centerInParent="true"

(1) Constraint Layout equivalent :
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"

(2) Relative Layout:
android:layout_centerHorizontal="true"

(2) Constraint Layout equivalent:
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"

(3) Relative Layout:
android:layout_centerVertical="true"

(3) Constraint Layout equivalent:
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"

(4) Relative Layout:
android:layout_alignParentLeft="true"

(4) Constraint Layout equivalent:
app:layout_constraintLeft_toLeftOf="parent"

(5) Relative Layout:
android:layout_alignParentStart="true"

(5) Constraint Layout equivalent:
app:layout_constraintStart_toStartOf="parent"

(6) Relative Layout:
android:layout_alignParentRight="true"

(6) Constraint Layout equivalent:
app:layout_constraintRight_toRightOf="parent"

(7) Relative Layout:
android:layout_alignParentEnd="true"

(7) Constraint Layout equivalent:
app:layout_constraintEnd_toEndOf="parent"

(8) Relative Layout:
android:layout_alignParentTop="true"

(8) Constraint Layout equivalent:
app:layout_constraintTop_toTopOf="parent"

(9) Relative Layout:
android:layout_alignParentBottom="true"

(9) Constraint Layout equivalent:
app:layout_constraintBottom_toBottomOf="parent"

(10) Relative Layout:
android:layout_alignStart="@id/view"

(10) Constraint Layout equivalent:
app:layout_constraintStart_toStartOf="@id/view"

(11) Relative Layout:
android:layout_alignLeft="@id/view"

(11) Constraint Layout equivalent:
app:layout_constraintLeft_toLeftOf="@id/view"

(12) Relative Layout:
android:layout_alignEnd="@id/view"

(12) Constraint Layout equivalent:
app:layout_constraintEnd_toEndOf="@id/view"

(13) Relative Layout:
android:layout_alignRight="@id/view"

(13) Constraint Layout equivalent:
app:layout_constraintRight_toRightOf="@id/view"

(14) Relative Layout:
android:layout_alignTop="@id/view"

(14) Constraint Layout equivalent:
app:layout_constraintTop_toTopOf="@id/view"

(15) Relative Layout:
android:layout_alignBaseline="@id/view"

(15) Constraint Layout equivalent:
app:layout_constraintBaseline_toBaselineOf="@id/view"

(16) Relative Layout:
android:layout_alignBottom="@id/view"

(16) Constraint Layout equivalent:
app:layout_constraintBottom_toBottomOf="@id/view"

(17) Relative Layout:
android:layout_toStartOf="@id/view"

(17) Constraint Layout equivalent:
app:layout_constraintEnd_toStartOf="@id/view"

(18) Relative Layout:
android:layout_toLeftOf="@id/view"

(18) Constraint Layout equivalent:
app:layout_constraintRight_toLeftOf="@id/view"

(19) Relative Layout:
android:layout_toEndOf="@id/view"

(19) Constraint Layout equivalent:
app:layout_constraintStart_toEndOf="@id/view"

(20) Relative Layout:
android:layout_toRightOf="@id/view"

(20) Constraint Layout equivalent:
app:layout_constraintLeft_toRightOf="@id/view"

(21) Relative Layout:
android:layout_above="@id/view"

(21) Constraint Layout equivalent:
app:layout_constraintBottom_toTopOf="@id/view"

(22) Relative Layout:
android:layout_below="@id/view"

(22) Constraint Layout equivalent:
app:layout_constraintTop_toBottomOf="@id/view"

A: The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get.  However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around.  This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'.  Hope this helps


text:
Q: why facebook api post to users and not on the page itself? i'm using this code to post to my application page as the page and not the admin:
$page_info = $facebook->api("/344722062246773?fields=access_token");

 $attachment2 = array('message' => $row["nwmsg"],
                      'access_token'  => $page_info['access_token'],
                      'name' => $row["nwnm"],
                      'caption' => $row["nwsubject"],
                      'picture' => 'http://itradegame.com/itrade/' . $row["nwposter"],
                      'description' => $row["nwtext"],
                      'actions' => array(array ('name'=> 'Play!','link'=> 'https://apps.facebook.com/itradee/')));

$result = $facebook->api('/344722062246773/feed/','post',$attachment2);

but the wierd thing is the users who likes the page can see the post on thier news feed but can't see it on the page itself.
why?

A: Because of the new timeline feature, posts by users (all except the page itself) will be listed under 'Recent Posts by Others on { PAGE_NAME}' section.
Please check the section.


text:
Q: Having Trouble Drawing With An ArrayList I am having a little bit of trouble drawing components from an ArrayList I have created. If I screw around with it, I can either get the first element or the second element and if I am lucky, neither, to show up!
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;

public class FaceShortCode {
ArrayList<CreateCircles> faceCircles = new ArrayList<CreateCircles>();

public FaceShortCode() {
    JFrame main = new JFrame();
    main.setTitle("Face Frame");
    main.setSize(new Dimension(600, 600));
    main.setLocationRelativeTo(null);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setVisible(true);

    Container c = main.getContentPane();
    // c.setLayout(null);

    faceCircles.add(0, new CreateCircles(100, 50, 400, 350, Color.red));
    faceCircles.add(1, new CreateCircles(200, 100, 65, 65, Color.black));
    c.add(faceCircles.get(0));
    c.add(faceCircles.get(1));

}

class CreateCircles extends JComponent {
    double x, y, width, height;
    Color myColor;

    public CreateCircles(double x, double y, double width, double height,
            Color myColor) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.myColor = myColor;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D circle = new Ellipse2D.Double(x, y, width, height);
        g2.setColor(myColor);
        g2.fill(circle);

    }
}

static class Run {
    public static void main(String[] args) {
        new FaceShortCode();
    }
}

}
I have tried throwing in a main.repaint() after every addition to the Container c,tried a repaint() in my painting method but nothing seems to be working. Is there any were else to put a repaint() that I am just missing?

A: You need to put all your logic before you setVisible() or else your frame will become visible before the logic is performed.
public FaceShortCode() {

    Container c = main.getContentPane();
    // c.setLayout(null);

    faceCircles.add(0, new CreateCircles(100, 50, 400, 350, Color.red));
    faceCircles.add(1, new CreateCircles(200, 100, 65, 65, Color.black));
    c.add(faceCircles.get(0));
    c.add(faceCircles.get(1));

    JFrame main = new JFrame();

    main.setTitle("Face Frame");
    main.setSize(new Dimension(600, 600));
    main.setLocationRelativeTo(null);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setVisible(true);
}

Consider making FaceShortCode extends JFrame.
public class FaceShortCode extends JFrame {
    private ArrayList<CreateCircles> faceCircles = new ArrayList<CreateCircles>();

    public FaceShortCode {
        setLayout(new Girdlayout(1, 2));

        faceCircles.add(0, new CreateCircles(100, 50, 400, 350, Color.red));
        faceCircles.add(1, new CreateCircles(200, 100, 65, 65, Color.black));

        add(faceCircles.get(0));
        add(faceCircles.get(1))

        setTitle("Face Frame");
        setSize(new Dimension(600, 600));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

A: Your design is a bit confusing. There is no need for an ArrayList. When you use components you can just add the components directly to the panel. Normally you would only use an ArrayList when you are doing custom painting by painting Objects that are not components, for example when you want to paint a Shape. For an example of this approach take a look at Custom Painting Approaches.
When using components, a component needs a size and location in order to be painted automatically by Swing. Normally you would let a layout manager determine these properties. In your case you are doing random placement of your components so you would need to use a null layout and then set the size/location of each component.
So what you need to do is change how you paint your custom component. All painting should be done at location (0, 0) of your component. Then you would set the location of the component to be the x/y value. This means the component will be painted at the x/y location relative to the panel you add the component to. Then you need to set the size of your component which would be the width/height.


text:
Q: How to upload image/file from Vue js to Laravel7 using axios I want to upload an image file with vue component to laravel controller. My problem happens when I click submit button phone/address is saved but the image name not save
Vue Component :
data(){
        return{
            id : '',
            file: '',
            address : '',
            N_Phone : '',
        }
    },
    methods:{
        RemplirInfo(e){
            e.preventDefault();
            axios.put('http://127.0.0.1:8000/api/RemplirInfo/'+this.id , {
                address:this.address,
                N_Phone:this.N_Phone,
                file:this.file
            })
            .then(response=> console.log(response))
            .catch(error => console.log(error));
        },
        imgChange(e){
            this.file = e.target.files[0];
        }
    },

Laravel Controller :
public function RemplirInfo(request $request , $id)
{

    $request->validate([
        'address'       => 'required',
        'N_Phone'       => 'required',
        'file'       => 'required'
    ]);

    $image = $request->file('file');
    $new_name = rand() . '.' . $image->getClientOriginalExtension();
    $image->move(public_path('images/AgencyProfileImage'),$new_name);

    $agency = agency::where('user_id', $id)->first();
    $agency->address = $request->address;
    $agency->N_Phone = $request->N_Phone;
    $agency->img_Profile = $new_name;
    $agency->save();

    return response()->json($agency);
    //return redirect()->back()->with('success', 'File uploaded successfully.');
}

A: You have to use javascript's FormData API to post file to your Laravel app using vue.
Modify the code in your view component as follows
data(){
    return{
        id : '',
        file: '',
        address : '',
        N_Phone : '',
    }
},
methods:{
    RemplirInfo(e){
        e.preventDefault();

        var form = new FormData();
        form.set('address',this.address);
        form.set('N_Phone',this.N_Phone);
        form.set('file',this.file);

        axios.put('http://127.0.0.1:8000/api/RemplirInfo/'+this.id , form)
        .then(response=> console.log(response))
        .catch(error => console.log(error));
    },
    imgChange(e){
        this.file = e.target.files[0];
    }
},


text:
Q: How to update data with useState? I'm trying to update the data of an array of objects with a specific index. I get the correct names with console.log(item.name) but it doesn't change the name to 'Test' for instance. Any help is appreciated.
 const [data, setData] = useState(content);
 const content = [
    {
      id: 1,
      name: "First",
    },
    {
      id: 2,
      name: "Second",
    },
    {
      id: 3,
      name: "Third",
    },
  ];

  setData(
      content.map((item) =>
        item.id == dataIndex
          ? { ...item, name: "Test" }
          : console.log(item.name)
      )
    );


text:
Q: python firebase realtime listener Hi there I'm new in python.
I would like to implement the listener on my Firebase DB.
When I change one or more parameters on the DB my Python code have to do something.
How can I do it?
Thank a lot
my db is like simple list of data from 001 to 200:
"remote-controller"
001 -> 000
002 -> 020
003 -> 230

my code is:
from firebase import firebase
firebase = firebase.FirebaseApplication('https://remote-controller.firebaseio.com/', None)
result = firebase.get('003', None)
print result

A: It looks like this is supported now (october 2018): although it's not documented in the 'Retrieving Data' guide, you can find the needed functionality in the API reference. I tested it and it works like this:
def listener(event):
    print(event.event_type)  # can be 'put' or 'patch'
    print(event.path)  # relative to the reference, it seems
    print(event.data)  # new data at /reference/event.path. None if deleted

firebase_admin.db.reference('my/data/path').listen(listener)

A: As Peter Haddad suggested, you should use Pyrebase for achieving something like that given that the python SDK still does not support realtime event listeners.
import pyrebase

config = {
    "apiKey": "apiKey",
    "authDomain": "projectId.firebaseapp.com",
    "databaseURL": "https://databaseName.firebaseio.com",
    "storageBucket": "projectId.appspot.com"
}

firebase = pyrebase.initialize_app(config)

db = firebase.database()

def stream_handler(message):
    print(message["event"]) # put
    print(message["path"]) # /-K7yGTTEp7O549EzTYtI
    print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."}

my_stream = db.child("posts").stream(stream_handler)

A: If Anybody wants to create multiple listener using same listener function and want to get more info about triggered node, One can do like this.
Normal Listener function will get a Event object it has only Data, Node Name, Event type. If you add multiple listener and You want to differentiate between the data change. You can write your own class and add some info to it while creating object.
class ListenerClass:
    def __init__(self, appname):
        self.appname = appname

    def listener(self, event):
        print(event.event_type)  # can be 'put' or 'patch'
        print(event.path)  # relative to the reference, it seems
        print(event.data)  # new data at /reference/event.path. None if deleted
        print(self.appname) # Extra data related to change add your own member variable

Creating Objects:
listenerObject = ListenerClass(my_app_name + '1')
db.reference('PatientMonitoring', app= obj).listen(listenerObject.listener)

listenerObject = ListenerClass(my_app_name + '2')
db.reference('SomeOtherPath', app= obj).listen(listenerObject.listener)

Full Code:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

# Initialising Database with credentials
json_path = r'E:\Projectz\FYP\FreshOnes\Python\PastLocations\fyp-healthapp-project-firebase-adminsdk-40qfo-f8fc938674.json'
my_app_name = 'fyp-healthapp-project'
xyz = {'databaseURL': 'https://{}.firebaseio.com'.format(my_app_name),'storageBucket': '{}.appspot.com'.format(my_app_name)}

cred = credentials.Certificate(json_path)
obj = firebase_admin.initialize_app(cred,xyz , name=my_app_name)

# Create Objects Here, You can use loops and create many listener, But listener will create thread per every listener, Don't create irrelevant listeners. It won't work if you are running on machine with thread constraint

listenerObject = ListenerClass(my_app_name + '1') # Decide your own parameters, How you want to differentiate. Depends on you
db.reference('PatientMonitoring', app= obj).listen(listenerObject.listener)

listenerObject = ListenerClass(my_app_name + '2')
db.reference('SomeOtherPath', app= obj).listen(listenerObject.listener)

A: As you can see on the per-language feature chart on the Firebase Admin SDK home page, Python and Go currently don't have realtime event listeners.  If you need that on your backend, you'll have to use the node.js or Java SDKs.

A: You can use Pyrebase, which is a python wrapper for the Firebase API.
more info here:
https://github.com/thisbejim/Pyrebase
To retrieve data you need to use val(), example:
users = db.child("users").get()
print(users.val())

A: Python Firebase Realtime Listener Full Code :
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

def listener(event):
    print(event.event_type)  # can be 'put' or 'patch'
    print(event.path)  # relative to the reference, it seems
    print(event.data)  # new data at /reference/event.path. None if deleted

json_path = r'E:\Projectz\FYP\FreshOnes\Python\PastLocations\fyp-healthapp-project-firebase-adminsdk-40qfo-f8fc938674.json'
my_app_name = 'fyp-healthapp-project'
xyz = {'databaseURL': 'https://{}.firebaseio.com'.format(my_app_name),'storageBucket': '{}.appspot.com'.format(my_app_name)}

cred = credentials.Certificate(json_path)
obj = firebase_admin.initialize_app(cred,xyz , name=my_app_name)

db.reference('PatientMonitoring', app= obj).listen(listener)

Output:
put
/
{'n0': '40', 'n1': '71'} # for first time its gonna fetch the data from path whether data is changed or not

put # On data changed
/n1
725

put # On data changed
/n0
401


text:
Q: Как задать значение css-свойству из props компонента React? Задача - необходимо присваивать компоненту React css-класс, в котором значение конкретного свойства будет равным значению передаваемому в props. Пример для наглядности:
<FlexBox
    flexGrow="1"
>
    helloWorld
<FlexBox/>

На выходе получаем

helloWorld

.flex-grow {
    flex-grow: 1;
}

Возможно ли это не прибегая к использованию inline-стилей, используя SASS? Необходимо именно назначение конкретному свойству к конкретном css-классе значения передаваемого в props.
Styled components и CSS Modules, как я понял, не мой вариант. Может существуют другие средства которые помогут реализовать данную идею? Возможно существует какой то способ связать переменную в SASS-миксине со значением flexGrow из props?

A: предлагаю такой вариант:
import classnames from 'classnames';

const FlexBox = ({ props }) => {
  const classesToApply = classNames({
    'flex-grow': props.flexGrow,
    'test-class': props.testClass
    // тут мапим нужные классы и пропсы
  });

  return <ChildComponent className={classesToApply}>Hello world!</ChildComponent>
}

const ChildComponent = ({ props }) => (

    {props.children}

);

Обращаю внимание, что значение пропсы flexGrow будет приводится к булеву типу (т.е. независимо от того будет там 1 или 2 -> на выходе мы получим класс flex-grow.


text:
Q: Does this look cryptographically sound? I'm making an encryption/decryption device in python 2.7. The ultimate goal is to allow for encrypted communication between 2 nodes using this encryption. I really just want to know if it looks like it won't easily be decrypted. I'm using system.random for this one, so the randomness of the numbers generated should be pretty good. But is the actual algorithm not too simple?
It generates a lot of random integers between 0 and 255, this is the keystream. Each character is then expressed as an integer between 0 and 255. The first character in the message is added to the first integer, the second to the second, etc. This should render the encrypted message as random as the keystream integers. I just thought I'd explain how it works instead of just posting the script.
def createkey():
    file = raw_input('file name to save key under:')
    maxcount = input("digits? Default is 2500.")
    if maxcount == '':
        maxcount = 2500

    digit = 0
    while digit < maxcount:
        rng=random.SystemRandom()
        key=rng.randint(100,356)
        print key
        with open(file, "a+") as myfile:
            myfile.write(str(key))
        digit = digit + 1
    myfile.close()

def encrypt():
    file_to_encrypt = raw_input('file name or path to encrypt:')

    destruct = raw_input('self destruct?')

    with open(file_to_encrypt, 'a+') as file:
        if destruct == 'y':
            file.write('\nThis message will self destruct.')

    with open(file_to_encrypt) as file:
        length = file.read()
        length = len(length)
        print length

    file_to_write = raw_input('Desired filename for encrypted info:')

    keyfile=raw_input('Key file:')

    num_chars = len(keyfile)

    count = 1
    paswd = raw_input('Enter password with which to encrypt file.')
    passum = 0
    charcount = 0
    counter = 0

    for letter in paswd:
        paschar = ord(letter)
        passum = passum + paschar
        charcount = charcount + 1
    if passum != 0:
        passum = int(math.sqrt((2 * passum) / charcount))
    else:
        pass

    with open(file_to_encrypt, 'r') as file:
        with open(keyfile) as key:
            while counter != length:
                txt = file.read(1)
                charnum = ord(txt)

                lines = key.read(3)
                x = lines
                x = int(x)
                x = x - 100
                keynum = (x)

                keynum = keynum + passum
                enmes = int(charnum) + (keynum)

                if enmes >= 256:
                    enmes = enmes - 256

                enmes = chr(enmes)
                print enmes

                enfile = open(file_to_write, 'a+')
                enfile.write(enmes)
                count = count + 1
                if count == num_chars:
                    count = 1
                counter = counter + 1

A: You have devised a Stream Cipher.  There are already tested and secure Stream Cyphers available, see eSTREAM for some examples.
The security of a Stream Cipher depends on the security of your keystream generation.  Unless you are a crypto expert, then your keystream generator is almost certainly insecure.  You appear to be using the standard system RNG.  Such RNGs are not secure.  At the very least use the secure RNG your system provides.
You might want to have a look at RC4, which is now obsolescent, but is a nice simple example of a Stream Cipher.  It will stop your kid brother reading your files, unless he works for the NSA.


text:
Q: Cannot find a way to replace last row inside excel files I am fighting with an excel file in which I would simple delete the last row.
I am using XLSXWRITER, and I tried several ways, but nothing is working. I am doing something wrong (maybe I have to take a break).
I tried
worksheet.write_blank(row, col, None)

but I found out that xlsxwriter cannot replace an old row with a new one. So if I use write_blank() to write on on an existing row, it won't work.
Could you please help me? I am looping through several XLSX file, open them and replace the last row with a blank.
Many thanks!

A: So, I found a way to achieve this step on my own.
Basically I wasn't able to do this with XLSXWRITER library, so I loop through my excel files opening them with OPENPYXL.
import openpyxl
from openpyxl import Workbook

## look for all excel files needed
filepath = r"C:\Users\name\Desktop\folder\folder\folder"
xlsxfiles = glob.glob(filepath + r"\**\*.xlsx")

## for each excel file open the workbook and spreadsheet
for file in xlsxfiles:
    wb = openpyxl.load_workbook(file)
    ws = wb.active
    ## for each excel file, count the maximum number of rows and store the value in last_row variable
    last_row = ws.max_row
    print("MAX NUMER OF ROW: ", last_row)
    ## replace the last row with None value
    ws.cell(last_row, 1).value = None
    ## save each excel file
    wb.save(file)

My need was quite specific but I think it can be easily modify to different purposes.


text:
Q: Datetimezone Error for website When I try to enter the site a white page appears
[Mon May 21 21:06:21.190385 2018] [:error] [pid 13340] [client 89.64.24.10:19041] PHP Notice:  Undefined property: object::$default_timezone in /var/www/html/frontend/lib/common.php on line 92
[Mon May 21 21:06:21.193439 2018] [:error] [pid 13340] [client 89.64.24.10:19041] PHP Notice:  date_default_timezone_set(): Timezone ID '' is invalid in /var/www/html/frontend/lib/common.php on line 92
[Mon May 21 21:06:21.193476 2018] [:error] [pid 13340] [client 89.64.24.10:19041] PHP Notice:  Undefined property: object::$default_timezone in /var/www/html/frontend/lib/common.php on line 93
[Mon May 21 21:06:21.193603 2018] [:error] [pid 13340] [client 89.64.24.10:19041] PHP Fatal error:  Uncaught Exception: DateTimeZone::__construct(): Unknown or bad timezone () in /var/www/html/frontend/lib/common.php:93\nStack trace:\n#0 /var/www/html/frontend/lib/common.php(93): DateTimeZone->__construct('')\n#1 /var/www/html/frontend/htdocs/index.php(4): include('/var/www/html/f...')\n#2 {main}\n  thrown in /var/www/html/frontend/lib/common.php on line 93

time zone line 92-93-94-95 (common.php)
date_default_timezone_set($CFG->default_timezone);
$dtz = new DateTimeZone($CFG->default_timezone);
$dtz1 = new DateTime('now', $dtz);
$CFG->timezone_offset = $dtz->getOffset($dtz1);


text:
Q: Is it portable to use os.getcwd() in a web (Flask) app? In a templates/index.html file I can write
<link rel="stylesheet" type="text/css"
      href={{ url_for('static', filename='css/main.css') }}>

and url_for retrieves the CSS file from a static folder just fine (FWIW, notwithstanding that css/main.css has a forward slash on Windows).
I would like to open a static file static/number.txt, read one number from it, and display that number.
app.py
from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/')
def number():
    filename = url_for('static', filename='txt/number.txt')
    with open(filename) as f:
        number = next(f)
    return render_template('index.html', number=number)

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

static/txt/number.txt
2345

templates/index.html
<body>
    {{ number }}
</body>

For this simple example, I am not attempting to optimize by running Nginx
and IIUC this simple task requires neither send_from_directory()
nor os.getcwd()
. There is also no need to tinker with app.static_folder nor to be worried about the folder separator by using os.join.path() (I happen to be on Windows, but ideally this should be invisible in the code). There is also no need to modify the default static
folder.
The code above gives me
c:\read-static>python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "C:\anaconda3\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  ...
  File "app.py", line 10, in number
    with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: '/static/txt/number.txt'
127.0.0.1 - "GET / HTTP/1.1" 500 -

What am I missing? Should I be using os.getcwd() to read a static file in Flask? Something in relying on os.getcwd() seems unpalatable/hackish.

A: Using
import os

and replacing the url_for(...) line with:
filename = os.path.join(os.getcwd(), 'static', 'txt', 'number.txt')

is a solution.
But the question stands. Isn't it perfectly all right to use url_for(...)?

A: To setup full path you do not have to use url_for in python.
So, my recomendation is to change you code:
from os import path # os needed for folder and file address
# receiving address of a current dirrectory
script_dir = path.dirname(path.abspath(__file__))
# adding address of your file
filename = script_dir.join('/static/txt/number.txt')

A: To answer your second question:
"But the question stands. Isn't it perfectly all right to use url_for(...)?"
url_for(static, filename='bla.txt') returns /static/bla.txt, and not static/bla.txt. Since the starting slash indicates the root of your computer, you try to open a static folder directly at the root of your PC (which is not there).
url_for(static, filename='bla.txt')[1:] should work I think, but I think it's a very hacky solution.
So no, it is definity not perfectly alright, and I would definitely not recommend using it. Site routes and folder structure are not the same thing, and should not be intermingled without a good reason (and this is not one).


text:
Q: How to maintain source versions and project tree structure in source control repository For a team of 4-5 developers using Visual Source Safe(VSS) 2005 what is best practice to maintain source versions?
Our requirement is to maintain and identify a version that is currently in production. This way at all times we will know what piece of code was pushed during deployment.
So far this is what I had in mind.

-trunk - Main solution and project
  -Dev branches - branch created for development and enhancements
-Dev (some enhancement)

-Release - release branches
-Release 2.1.0
-Release 2.1.1
-Release 3.0

Everything that starts with a dash(-) above is a folder in the repository.
I am thinking that each time we need to make an enhancement to our project, we make a dev branch from the main trunk of the entire project. This will be where the developers will work on. Once development is complete and UAT is done we proceed to the deployment.
After the project(in this case a web application) is deployed and confirmed that it is stable we make a Release(version #) branch of the Dev branch above. Lets say this is Release 3.0, we now know that in July 2010 deployment we pushed the code in the Release 3.0 folder.
We then merge(is this easy in VSS2005) the Release 3.0 code with the trunk. This way the trunk is always the latest deployed code and the next enhancement will be branched from trunk.
HotFix
Some things that I have not yet figured out is what happens when there exists a Dev branch that is being worked on and there is a hot-fix that is needed to be deployed immediately.
Perhaps, we make a separate branch from the latest Release folder, call it Hot-fix 3.0. Have the developers make the fix, merge it with Release 3.0 code after deploying the hot-fix and then merge with trunk again.
Clean up
After release there is really no need to have the dev branches. Should these be deleted?
Since we are branching, I read that in VSS deleting a branch does not free up the space in the database unless the original is deleted.
How should we delete, or should we delete the dev branches?
These are my thoughts, how do you manage your versions and what are your recommendations for my requirements.
We MIGHT be moving to TFS in the future, so anything I implement now in VSS should consider this move in the future.

A: *

*trunk -> should only contain stable code

*tag -> add tags to the trunk code to identify versions (e.g. releases 2.1.0, 2.1.1, 3.0, etc.)

*branch -> create a branch for every single issue

*update -> update branches often to keep the code as close as possible to the trunk (because meanwhile other fixes where committed)

*merge -> merge branches to trunk if the solution is stable (include the issue number so the code changes are related to the issue number)

Most important of all:

*

*use a source control system which supports you in doing all this -> VSS will not ;)

Also take a lok at this interesting article: http://betterexplained.com/articles/a-visual-guide-to-version-control/


text:
Q: Удалить пробелы в начале выбранной опции в селекте Chosen Всем привет!
Очень надеюсь на помощь знатоков.
На проекте используется плагин Chosen Select.
Есть селект. Опции внутри него имитируют древовидную структура за счет добавленных пробелов

При выборе определенной опции, в контейнере a.chosen-single результат должен отображаться без пробелов.
Я пробовала разобраться сама, но пока что новичок, не понимаю что делаю не так.
Спасибо заранее за помощь.

$(document).ready(function() {
  $(".chosen-select").chosen();
  $('.chosen-single').find('span').each(function() {
    $(this).html($(this).html().replace(/ /gi, ''));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">

<div>
  <select data-placeholder="Choose a Country..." class="chosen-select" style="width:350px;" tabindex="4">
    <option value=""></option>
    <option value="Any">[Any]</option>
    <option value="United States"> United States</option>
    <option value="United Kingdom">  United Kingdom</option>
    <option value="Afghanistan">    Afghanistan</option>
    <option value="Aland Islands"> Aland Islands</option>
    <option value="Albania">  Albania</option>
    <option value="Algeria">    Algeria</option>
    <option value="American Samoa">American Samoa</option>
  </select>
</div>

https://jsfiddle.net/kaintz/3roq54bf/7/

A: Просто Вы ищете и удаляете пробелы только при первом запуске, а надо при каждом изменении селекта:
$(document).ready(function(){

   $(".chosen-select").chosen();

  $(".chosen-select").change(function(){
    $('.chosen-single').find('span').html(function (i, html) {
      return html.replace(/ /g, '');
    });
  });

});

A: Попробуйте этот скрипт:
$(document).ready(function(){
  $(".chosen-select").chosen().change(function() {
    $('.chosen-single').find('span').html($(this).val());
  });
});

Просто вставил val в span на событие change.

A: $(document).ready(function(){
    $(".chosen-select").chosen();
    $(".chosen-select").on("change", function() {
        let span = $(".chosen-single span");
        span.text(span.text().trim());
    });
});


text:
Q: How can I run from crontab a python script that needs python 3 when the installed python is version 2 I have a Linux machine that runs Python 2.6 and I have a python script A that uses some modules that need Python 3. If I want to run this script I use this command:
    scl enable rh-python36 bash
 and it switches to Python 3.6
Now I need to put in crontab this script and run it hourly but it doesn`t run because the version is 2.6
I wrote another script:
import os

os.system("scl enable rh-python36 bash")
os.system("python script.py")

If I manually run this script it only switches to python 3 but it doesnt run the second os.system command... another thing I tried is putting in crontab both commands with && between them but it doesn`t work also...
So how can I run from crontab a python script that needs python 3 when the installed python is version 2
Thanks in advance

A: You can run both commands in one session using the && operator. You also need to call the right version of Python (either python3 or python36)
import os

os.system("scl enable rh-python36 bash && python3 script.py")


text:
Q: What is the name of the default style for matplotlib 2.0.0? The default style of matplotlib 2.0 looks very different from all previous versions.
I know that I can switch to the classic style with mpl.style.use('classic'), but how do I switch back to the new v2.0 style?
Is the name of new default style listed in matplotlib.style.available ?

A: After having applied a style in matplotlib, you can switch back to the defaults by
plt.rcParams.update(plt.rcParamsDefault)

If this happens inside a jupyter notebook, you would then also need to recall the backend, e.g. %matplotlib inline.

A: Per the API documentation:

The style name of default is reserved for reverting back to the default style settings.

In my distribution, 'default' is not listed in matplotlib.style.available, nor is it a key in matplotlib.style.library.


text:
Q: After sync on gitlab code unable to compile and show no error in files but on webpage The error it shows on webpage-
Failed to compile
src/pages/Adminstration/IdentityAccess/CreateUserType.jsx
Syntax error: Unexpected token (31:2)

  29 |
  30 |

> 31 | <<<<<<< HEAD:src/web/src/pages/Adminstration/IdentityAccess/NewUserType.jsx
       |  ^
  32 |               <Breadcrumb {...{ context: "MANAGE_USERTYPES", leaf: "New User Type" }} />
  33 | =======
  34 |               <Breadcrumb {...{ context: "MANAGE_USER_TYPES", leaf: "new User Types" }} />

When I check code in file it is-
import React, { Component } from "react";
import { Header, Sidebar, Breadcrumb } from "../../../components";
import { startLoading, stopLoading } from "../../../components/Util";
import Select from "react-select";

class CreateUserType extends Component {
  constructor(props) {
    super();
    this.state = {
      loaded: true,
    };
  }

  componentDidMount() {
    document.title = "LIMS - Create User Types ";
  }

  upsert() {
    console.log("TBD....");
  }

  render() {
    !this.state.loaded ? startLoading() : stopLoading();
    return (
      this.state.loaded && (

          <Sidebar context="USER_TYPES" />

            <Breadcrumb {...{ context: "MANAGE_USERTYPES", leaf: "New User Type" }} />

User Type

Someone has changed the filename from NewUserType.js to CreateUserType so I changed the file name everywhere.

A: This is the product of a failed git merge, which is the default strategy Git makes when updating your local repository. If you see this, that means there are conflicts in a file, and it will always be a set format:
The line (or lines) between the lines beginning with <<<<<<< and ====== are what you already had in your local copy of the repository (HEAD points to your current branch or commit):
> 31 | <<<<<<< HEAD:src/web/src/pages/Adminstration/IdentityAccess/NewUserType.jsx
       |  ^
  32 |               <Breadcrumb {...{ context: "MANAGE_USERTYPES", leaf: "New User Type" }} />
  33 | =======

The line (or lines) between the lines beginning with ======= and >>>>>>> are what was pulled from the remote repository (where you git pull from) and is different to what Git expects to be in your file:
  33 | =======
  34 |               <Breadcrumb {...{ context: "MANAGE_USER_TYPES", leaf: "new User Types" }} />
  35 | >>>>>>>

You should pick the one which has the most relevance to your project (or projects) and ensure that you do not have any modified files when you do a git pull (google for git stash to find out about that)


text:
Q: How does PKG-CONFIG select between two .pc files? I have two .pc files for glib-2.0
/usr/lib/x86_64-linux-gnu/pkgconfig/glib-2.0.pc
/usr/local/lib/pkgconfig/glib-2.0.pc

They differ with where they point the location of include files.
/usr/lib/x86... points to /usr/include
/usr/local/lib... points to /usr/local/include

This causes a problem when I run:
pkg-config --cflags gtk+-3.0

this returns the following glib-2.0 search locations:
-I/usr/local/include/glib-2.0
-I/usr/local/lib/glib-2.0/include

whereas my package manager has installed the glib libraries to
/usr/include/glib

Question 1: Why is the PKG-CONFIG selecting the second location compared to the first? How can I change this?
Question 2: Is it abnormal to have two of the same .pc files?
Question 3: If I do want to delete one of the .pc files, can I do so safely?
Note:

*

*I do not wish to copy over the glib library to /local/ as the package manager will loose sight of this.

*I do not wish to add -I/usr/include in addition when running gcc as I expect PKG-CONFIG to work properly. (I also think this will cause other problems which I will have to manually modify)

A: You can use PKG_CONFIG_LIBDIR environment variable to override the default search directory.
There's also PKG_CONFIG_PATH that can be used as a colon-separated list of directories to search for .pc files.
See pkg-config's manual page for more info.


text:
Q: How to query all the points inside a geomtry object of wkt format i have a table named slope it contains the following columns X, Y, Z and geometry. the aforementioned values represents the x,y,z coordinates
of a geometry. i have also an object named fieldGeometry which is in WKT format.
my question is how can i query the all the points in terms of X, Y that are inside the object fieldGeometry.
as shown in the code below, it is my attempts but not successful.
please let me know how to query all the points inside a geometry object in wkt format
code:
def executeWithFetchallForST_Intersects(self, cursor, fieldAsPolygonsGeometry, gridPointsAsGeometry):
    #"SELECT ST_Intersects("+ fieldAsPolygonsGeometry + "," + gridPointsAsGeometry + ")"
    cursor.execute("SELECT ST_Intersects("+ fieldAsPolygonsGeometry + "," + gridPointsAsGeometry + ") FROM " + config['PostgreDB']['table_name'])
    return cursor.fetchall()

A: The PostGIS function is called ST_Contains. To check if the x,y,z coordinates are inside of the polygon on fieldGeometry just do:
SELECT
  ST_Contains(fieldGeometry,
  ST_SetSRID(ST_MakePoint(x,y,z),4326))
FROM slope;

Demo: db<>fiddle
CREATE TABLE slope (x numeric, y numeric, z numeric, fieldGeometry geometry(polygon,4326));
INSERT INTO slope VALUES
(-4.6726,54.1180,42,'SRID=4326;POLYGON((-4.52 54.32,-4.38 54.32,-4.38 54.26,-4.52 54.26,-4.52 54.32))'),
(-4.5449,54.1888,42,'SRID=4326;POLYGON((-4.59 54.21,-4.49 54.21,-4.49 54.17,-4.59 54.17,-4.59 54.21))');

SELECT
  ST_Contains(fieldGeometry,
  ST_SetSRID(ST_MakePoint(x,y,z),4326))
FROM slope;

 st_contains
-------------
 f
 t
(2 rows)

EDIT: see comments
PostGIS tries to parse the geometries using known formats, such as WKT, WKB, GeoJSON, etc. So you don't need to worry about using WKT in the ST_Contains function - no matter which programming language you're using, e.g.
WITH j (p) AS ( VALUES
 ('0101000000925CFE43FA2D12C00EBE30992A184B40'),
 ('POINT(-4.5449 54.1888)'),
 ('{"type":"Point","coordinates":[-4.5449,54.1888]}')
)
SELECT
  ST_Contains('POLYGON((-4.59 54.21,-4.49 54.21,-4.49 54.17,-4.59 54.17,-4.59 54.21))',p)
FROM j;

 st_contains
-------------
 t
 t
 t
(3 rows)

If you wanna force PostGIS to parse a specific format, let's say WKT, use the corresponding function ST_GeomFromText.


text:
Q: Netbeans + project groups: how can I tweak, where Netbeans stores information about created project groups? When coding, I use Dropbox to sync folder in which I keep my projects between 3 computers.
I use Netbeans as an IDE, and so - I create project groups very often. While creating them, I usually choose "Folder of Projects" option, so it includes all projects found in specific folder.
Is it possible to tweak Netbeans, that it would store information about created project groups in specific place? Is there any option which changes this setting?

A: Netbeans stores the groups information in:
{netbeans_user_root}/config/Preferences/org/netbeans/modules/projectui/groups
I doubt that this can be changed.


text:
Q: Why does wiring to a surge protective device need to avoid sharp bends? Here is an excerpt from some Schneider Electric installation instructions for their QO2175SB 240V single phase "SurgeBreaker" SPD:

NOTE: The SPD ... must be
installed as close to neutral assembly and main circuit breaker or
main lugs as possible. Keep wire lengths as short as possible with no
sharp bends.

(source)
What is the reason for avoiding sharp bends? Is this more likely to cause the wire to fail under surge conditions? Or would it somehow hurt the surge protection effectiveness?
And how small of a radius bend would be considered "sharp"?

A: Surges often approximate an "infinite impulse" and, as such, contain significant high-frequency components.  In order to be effective you want the surge protection device to shunt as much of that impulse as possible to ground so that it does what you installed it for, specifically to protect your equipment.
A bend of any kind in a transmission line affects its impedance and a sharp bend affects it significantly.  You might not think you are employing a t-line but considering the HF components of the surge, it is indeed one.
By keeping it as straight and short as possible you keep the impedance as constant as possible and therefore you reduce reflections which reduce the effectiveness of the surge protection device.


text:
Q: Electron post-scss webpack parser error on build This is a boilerplate from electron-react. I've tried to include scss mixins but it seems to spit out with the following error:
CssSyntaxError: C:\C:\app\scss\base\_theme.scss:30:17: Unknown word
You tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser

  28 | @mixin themed() {
  29 |     @each $theme, $map in $themes {
> 30 |       .theme--#{$theme} & {
     |                 ^
  31 |         $theme-map: () !global;
  32 |         @each $key, $submap in $map {

I've included postscss-loader to the webpack but the error still persist


text:
Q: how to provide keystore and trust store to spring ldap I need to provide truststore and keystore when trying to connect to ldap sever using spring LdapTemplate.
I can't  import the certification using keytool or set by system property javax.net.ssl.trustStore
Now I config in following way:
   <bean id="authenticationStrategy" class="org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy">
       <property name="sslSocketFactory">
            <bean class="com.sc.cops.common.auth.ssl.SslSocketFactoryBuilder">
                <property name="trustStoreLocation" value="${oud.ldap.keyTrustLocation}" />
                <property name="trustStorePassword" value="Password1" />
              <!-- <property name="trustStorePassword">
                   <enc:decrypt key="${common.encryption.key}" cipher-text="${common.ssl.mq.keystore.password}" />
                </property> -->
                <property name="keyStoreLocation" value="${oud.ldap.keyTrustLocation}" />
                <property name="keyStorePassword" value="Password1" />
            </bean>
        </property>
    </bean>

    <bean id="ldapContextSource"
        class="org.springframework.ldap.core.support.LdapContextSource">
        <property name="url" value="ldaps://${ldap.server}:${ldap.port}/" />
        <property name="userDn" value="${ldap.oud.userDn}" />
        <property name="password" value="${ldap.oud.password}" />
        <property name="authenticationStrategy" ref="authenticationStrategy"/>
    </bean>

    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
        <property name="contextSource" ref="ldapContextSource" />
    </bean>

In com.sc.cops.common.auth.ssl.SslSocketFactoryBuilder, we create SSLSocketFactory:
@Override
public SSLSocketFactory getObject() throws IOException, GeneralSecurityException {

    TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore trustStore = loadKeyStore(getTrustStoreLocation(), getTrustStoreType(), getTrustStorePassword());
    trustMgrFactory.init(trustStore);

    KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = loadKeyStore(getKeyStoreLocation(), getKeyStoreType(), getKeyStorePassword());
    keyMgrFactory.init(keyStore, toCharArray(getKeyStorePassword()));

    SSLContext sslContext = SSLContext.getInstance(SSL_VERSION);
    sslContext.init(keyMgrFactory.getKeyManagers(), trustMgrFactory.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}

I debug the code, I can see the keystore and truststore are loaded correctly. And the jks file I provided is correct.
But when I try to authenticate, I got error
Root exception is javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target.

A: I was unable to get it to work with the AuthenticationStrategy class.
We solved it by:

*

*implementing a custom socket factory

*add the this to the BaseEnvironmentProperties in the ldap context config.

*using an initializing bean to allow to stick to the spring like configuration.

Implement an initializing bean:
   public class SystemPropertyInitializer implements InitializingBean {
      @Value("${truststore.path}")
      private String truststorePath;

     @Value("${truststore.pass}")
     private String truststorePass;

     @Override
     public void afterPropertiesSet() throws Exception {
        System.setProperty(Utils.SOCKET_FACTORY_TSPATH, truststorePath);
        System.setProperty(Utils.SOCKET_FACTORY_TSPASS, truststorePass);
     }

*when setting up the ldap template:
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(getUrl());
contextSource.setBase(getBase());
contextSource.setUserDn(getUser());
contextSource.setPassword(getLdapPass());
Map<String, Object> baseEnvironmentProperties = new HashMap<String, Object>();
baseEnvironmentProperties.put("java.naming.ldap.factory.socket", "com.custom.LdapSocketFactory");
contextSource.setBaseEnvironmentProperties(baseEnvironmentProperties );
contextSource.afterPropertiesSet();

I could not find another way to pass the socket factory... ie via Autowired... So the
implementation of the socket factory loaded the trust information from the env variables.
The SSL exception occurs at the point when the initial context was initialized. From what I can see is that
prior to loading the initial context the authenticationStrategy.setupEnvironment(env, principal, credentials)
is called. In the class AbstractTlsDirContextAuthenticationStrategy this method does nothing. So the factory does
not get set there... Anyway, I think this is more of an authentication thing on the ldap server ie once the handshake has
occurred. I mean, it does say as much in the class name :-)
see also: how to accept self-signed certificates for JNDI/LDAP connections?

A: Very late response, but, for future developers facing the same issue:
Use the sslcontext-kickstart library which lets you use multiple sources for your truststores (e.g. JDK + one from the local filesystem + one from the classpath, etc.).
Source


text:
Q: What happens when I have an array as a property of ApplicationUser? I have added a property to my ApplicationUser class and made the migration but I don't see any change to my database schema.
If I add data to this array where would it be stored?

A: Arrays are not mapped. Actually the only enumerable that is mapped is ICollection. Anything else will be ignored by EF. As a result, the answer to your question is that it will not be stored. You can have an array property, and you can add stuff to that array, but as soon as the entity is out of scope, it will all be discarded. Nothing will be persisted to your database.


text:
Q: R - Dplyr - Comparing values from last row vs actual row I've this data frame:
    year    month    UserID
1   2014    11        3527
2   2014    12        4916
3   2015    1         2445

And want to add a "Variation" column: The formula would be: ActualRow/LastRow - 1.
This is my code:
UserID_unicos2 <- UserID_unicos1 %>%
                  mutate(variation=(UserID/lag(UserID) - 1)) %>%
                  mutate(prev=lag(UserID))

However, it just returns:
    year    month   UserID  variation   prev
1   2014     11      3527      NA        NA
2   2014     12      4916   0.3938191   3527
3   2015      1      2445      NA        NA

As you see, it just return values for 2014-12. And not for:  2015-01. How come? Thanks.
My data after applying "dput()":
structure(list(year = c(2014L, 2014L, 2015L), month = c(11L,
12L, 1L), UserID = c(3527L, 4916L, 2445L)), .Names = c("year",
"month", "UserID"), row.names = c(NA, -3L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), vars = list(year), drop = TRUE, indices = list(
    0:1, 2L), group_sizes = c(2L, 1L), biggest_group_size = 2L, labels = structure(list(
    year = 2014:2015), class = "data.frame", row.names = c(NA,
-2L), .Names = "year", vars = list(year)))

A: According to your dput, your data is grouped by year and that is why you see this outcome. Try this instead:
UserID_unicos1 %>%
  ungroup() %>%
  mutate(variation=(UserID/lag(UserID) - 1),
         prev=lag(UserID))

Also note that you can create both columns in the same mutate just separated by comma.


text:
Q: How to add s/mime certificate to existing contact in outlook2013 easily i was wondering if any of you know of an easy (and working) way of importing a new mail certificate to an already existing contact (holding an also already existing different mail cert) in Outlook 2013.
The problem was already discussed in https://social.technet.microsoft.com/Forums/office/en-US/a5fb1ee0-8abe-4581-ab03-857022783516/adding-an-smime-certificate-to-an-existing-contact-in-outlook-2013?forum=outlook . I tried all the solutions mentioned but the only one that seems to work properly is the painful path of exporting the cert and import it to the contact manually.
Does anybody know of an easier way to achieve that?


text:
Q: What is the expression to suggest a few dates and times to meet? Let's say a friend of mine tells me the following:

Nice! Let's meet up for a drink this week.

And I want to say, "Sure let's do it. I will propose a few ..., and you tell me if either of them works for you."
I cannot come up with an idiom or other expression that works.

A: I would say

I'll send a couple of dates and times. Let me know if any of them work for you.

A: There seems to be no standard idiom available for this job. What I hear and use most often is:

I'll send you some suggested dates and times.

You might say:

I'll send you some options and let me
  know what works for you.

A: The phrase pencil it in or pencil you in is sometimes used jokingly among busy friends in instances like this. See def. 2 From NOAD:

pencil something in 1 fill in an area or shape with pencil strokes : a lot of the outlines had been penciled in. 2 arrange, forecast, or note down something provisionally or tentatively : May 15 was penciled in as the date for the meeting. • (pencil someone in) make a provisional or tentative arrangement with or for someone : he was penciled in for surgery at the end of the month.

Pencil is used because the plan is tentative and pencil can easily be erased. In some circumstances this idiom can be used as a not-so-subtle way of saying the meeting will never happen (i.e. "Sure, I'll pencil that in next week") but among friends who obviously want to get together, it can be a way of gently poking fun at someone's busy schedule while letting them know you really want to get together. You could say:

Sure, let's do it. I'm free   Tuesday and Thursday evening. Can you pencil me in?

Re-reading your question, I realized the crux has more to do with what to call the dates and times you can meet. I think the wording of my example works well—just calling them the times that you're free. Of course, if there is some romantic interest, you could also call them the times you are available with a slight emphasis on that word.

A: I think it would be better to talk about schedule openings and time slots:

I have several openings in my schedule this week. I'll send you those time slots and you can see if any of them work for you.

A: A few sentences that seem reasonable
"Sure let's do it. I'll propose a few free days, and you tell me if either of them work for you."
"Sure let's do it. I'll let you know my availability over the next few days, and you let me know when best suits you.
(You can replace days with times, evenings, mornings etc to be more time specific)

A: Why not simply:

I'll propose a few days, and you tell me if either works for you...

A: I just say, "Great, how is Monday, November 20th at noon?"  I find the whole process goes quickly when someone takes that first step and gets literal with the date. :)


text:
Q: Как получить из ответа Яндекс геокодера запрашиваемый адрес? Я отправляю в геокодер несколько адресов для получения координат точек и потом отлавливаю его результаты в методе then примерно таким кодом:
var geocoder = new ymaps.geocode(
    'Абакан, ул.Некрасова, 23',
    { results: 1 }
);
geocoder.then(
    function( res ) {
        // обработка ответа
        coord = res.geoObjects.get(0).geometry.getCoordinates();
    }
);

Геокодер возвращает ответы асинхронно, а мне надо понять для какого адреса что я передал вернулись координаты. Я научился это делать когда данные возвращаются в формате json, а для способа описанного выше это возможно?

A:
мне надо понять для какого адреса что я передал вернулись координаты

Храните адрес в замыкании.
const address = 'Абакан, ул.Некрасова, 23';
ymaps.geocode(address, {results: 1}).then(function (res) {
    console.log({
        address: address,
        coordinates: res.geoObjects.get(0).geometry.getCoordinates()
    });
})


text:
Q: React.js not executing in simple local hello world So I've been reading the basic guide and have set up a hello world file with no npm or anything, just an html file.
According to ReactJS: "Uncaught SyntaxError: Unexpected token <" I should have the script type set to text/jsx or text/babel. Neither work, since neither print the "hi" or do anything.

What's going on and how do I get it to execute?

A: After much digging around, here's the high level of what's causing the issue.
The code in the question is in JSX which transpiles to javascript using a transpiler called Babel. The misunderstanding is that the transpiler is not built into the web browser. What you can do is however is import Babel at the top with

and then make sure the script type is set to text/babel and it should work.


text:
Q: PhalconPHP - Groups of Routes I am using Phalcon Framework and would like to learn how to group routes.
The official documentation did not help me that much.
This is how my routes look like:
$app->get('/users', function() {
   // do something
});

$app->get('/users/{id}', function($id) {
   // do something
});

$app->post('/users', function() {
   // do something
});

I would like to group these routes under "users" group so the code will be more clear and structured.
How can I do it?

A: I'm use collection to this. Code look something like.
$inbound = new Phalcon\Mvc\Micro\Collection();
$inbound->setHandler('InboundController', true);
$inbound->setPrefix('/v1/inbound');
$inbound->get('/{req_no}', 'readAction');
$inbound->post('/', 'createAction');
$inbound->put('/{req_no}', 'updateAction');
$inbound->delete('/{req_no}', 'deleteAction');


text:
Q: Is it recommended to use hashcode to determine equality in Java? Let's say we have a hashcode() function, which will then be used inside our equals() method to determine the equality of two objects. Is this an allowed/accepted approach?
Assume that we use a simple implementation of a hash code. (For example a few instance variables multiplied by prime numbers.)

A: This is a terrible way to check for equality, mostly since Objects don't have to be equal to return the same hashcode.
You should always use the equals method for this.
The general rule is:

If the equals method returns true for Objects a and b, the hashCode
  method must return the same value for a and b.
This does not mean, that if the hashCode method for a and b returns
  the same value, the equals method has to return true for these two
  instances.

for instance:
public int hashCode(){
  return 5;
}

is a valid, though be it inefficiënt, hashcode implementation.
EDIT:
to use it within an equals method would be something like this:
public class Person{

private String name;

public Person(String name){ this.name = name;}

public String getName(){ return this.name;}

@Override
public boolean equals(Object o){
  if ( !(o instanceof Person)){ return false;}
  Person p = (Person)o;
  boolean nameE = this.name == null ? p.getName() == null : this.name.equals(p.getName());
  boolean hashE = nameE ? true : randomTrueOrFalse();
  // the only moment you're sure hashE is true, is if the previous check returns true.
  // in any other case, it doesn't matter whether they are equal or not, since the nameCheck returns false, so in best case, it's redundant
  return nameE && hashE;
}

@Override
public int hashCode(){
  int hash = generateValidHashCode();
  return hash;
}

}

A: It is a very bad practice. Hashes are supposed to have a minimal amount of collisions, but usually you have more possibilities for objects than the amount of possible hashes and because of the pigeonhole principle a few distinct objects must have the same hash.
When comparing hashes, you have a certain chance of getting "false positives".

A: Actually, it is not a bad idea!
But make sure you use this method to determine inequality, not equality. Hashing code may be faster than checking equality, especially when hashcode is stored (for example in java.lang.String).
If two object have different hashcodes they must be different, else they may be the same. For example you may use this method as the following
Object a, b;
if(a.hashCode() == b.hashCode()){
    if(a.equals(b)) return true;
}

return false;

Be aware that in some cases code above may be slower than using only equals(), especially when in most cases a does equal b.
From documentation of Object.java:

*

*If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

*It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

A: Don't do this
While it is correct that you need to override equals() and hashCode() in pairs, having the same hash is not the same as having the same values.
Put some effort into really thinking the equality thing through. Don't shortcut here it will bite you later.


text:
Q: Angular 4 CanActivateChild doesn't work I'm trying to restrict access to my route system using CanActivateChild, however when I try to prevent user's navigation to a set of child states, the RouteGuard doesn't work, only on CanActivate. This is my routing module:
export const routes = [
    { path: "", redirectTo: "/signin", pathMatch: "full" },
    { path: "signin", component: SigninComponent },
    {
        path: "user",
        component: UserComponente,
        canActivate: [AuthGuard],
        canActivateChild: [AuthGuard],
        children: [
            { path: "profile", component: ProfileComponent, },
            { path: "address", component: AddressComponent, },
        ]
    },
    { path: "test", component: TestComponent, canActivate: [AuthGuard] },
];

In this example, if I try to access the route test, I can see the AuthGuard being executed, the function canActivate is called.
But when I try to navigate to any of the children routes (profile or address), nothing happens. Both, canActivate and canActivateChild doesn't get called on the AuthGuard.
This is my guard file:
import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
import { getString } from 'application-settings';
import { AppConfig } from './../config';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
    constructor() { }

    canActivate() {
        console.log('canActivate executing.');

        if (!getString(AppConfig.authToken)) {
            alert('You need to be logged in.');
            return false;
        }
        return true;
    }

    canActivateChild() {
        console.log('canActivateChild executing.');
        return this.canActivate();
    }
}

A: you need to Inject the Router in you constructor, also you need to import it.
import { Router } from '@angular/router'

constructor(
    private router: Router
  ) {}

Because you need to let the Router know of the changes. You can return boolean, observable or UrlTree, so the router can update its state.


text:
Q: What is the recommended methodology for debugging Angular app that causes 'page unresponsive'? I am an AngularJS newbie. I have an AngularJS app that causes the browser to report 'Page has become unresponsive'. What are the steps I should take to debug and find what is causing this behavior?
(I am asking this way, rather than posting code and having someone solve my problem, so I can learn how to solve similar problems for myself in the future)

A: you can check few things if page goes unresponsive

*

*check the page watch count or here (I prefer implementation in link 2)

*once you know the watch count, try reduce the watch count if its too much

*can you use one-time binding (hence reducing the watchers) read here

*if you have ng-repeat and need two way binding & use track by

A: Based on the information you provided, I think that the error isn't related to AngularJs itself. You might see some information on this site, which describes clearly how to solve this issue.

What are the steps I should take to debug and find what is causing this behavior?

Typically, the most common way to debug AngularJs application is to use Chrome Dev tools, inspect element. It allows you to put any breakpoints in order to verify your application.
Alternatively, if you are using Chrome, you could use AngularJS Batarang which is very great chrome extension to debug your AngularJs app.

A: Usually AngularJS causes the browser to be unresponsive when there are too many watches.
There is a Chrome extension AngularJS Batarang that allows the inspection of each binded expression.
You can view the time required for each expression to load (both in ms and as a percentage of total application load).
Take a look at these articles:

*

*Removing the Unneeded Watches

*Debugging performance problems in AngularJS with Batarang and Chrome DevTools
And at this module BindOnce.


text:
Q: Draw a transparent framebuffer onto the default framebuffer I'm facing this situation where I need to render the content of a framebuffer object onto the screen. The screen already has some contents onto it and I would like to draw the contents of my framebuffer onto this content.
I'm using Qt5 and QNanoPainter to implement this.
The rendering commands I've implemented essentially take a QOpenGLFramebufferObject and converts this into a QNanoImage (using this) and then calls QNanoPainter::drawImage.
This works ok but the problem is that when the content of the fbo is rendered onto the screen, the previously existing content of the screen becomes "pixelated".
So for example, before I draw the FBO the screen looks like this

Then when I draw the FBO onto the default render target, I get this (red is the content of FBO)

I assume this has something to do with blending and OpenGL, but I'm not sure how to solve this problem.

A: This happens when you over-draw a semi-transparent image over itself multiple times. The white pixels become whiter, the blue pixels become bluer, and, consequently, the anti-aliased edge disappears over a couple iterations.
I therefore deduce that your 'transparent framebuffer' already contains the blue line and the black grid lines. The solution thus will be to clear the 'transparent framebuffer' before you proceed with drawing the red line into in.


text:
Q: Calculating modulus by recursion without using modulo division I'm doing a problem with recursive functions for a class project.  I'm trying to write a program that uses a recursive function that calculates a modulus without actually using the modulus operator.  I'm trying to use a reference parameter because I think that's the easiest way to do this, however my program is not functioning as intended.
//Michael Hery
//COP 2001
//11/15/2017
//Recursive Modulus

#include <iostream>
#include <iomanip>

using namespace std;

int recursiveMod(int &, int);

int main()
{
    int num;
    int den;
    int displayNum;
    int total;

    cout << "Please input the numerator (an integer) >> ";
    cin >> num;
    while (num < 0)
    {
        cout << "Integer must be greater than or equal to zero. >> ";
        cin >> num;
    }
    displayNum = num;
    cout << "Please input the denominator (an integer) >> ";
    cin >> den;
    while (den <= 0)
    {
        cout << "Integer must be greater than zero. >> ";
        cin >> den;
    }
    cout << "You have entered " << num << " % " << den << endl;

    total = recursiveMod(num, den);

    cout << "Modulus result: " << displayNum << " % " << den << " = " << total << endl;

    system("PAUSE");
    return 0;
}

int recursiveMod(int &num, int den)
{
    if (num == 0)
        return 0;

    num = num - den;

    if ((num - den) > den)
    {
        recursiveMod(num, den);
    }
    return num;
}

A: There are two errors with your code. Firstly you need to include cstdlib for system("pause") to work.
#include <cstdlib>

Secondly, in your
int recusive mod(int &num, int den)

the condition should be num > den and return must be put.
if (num > den)
    {
        return recursiveMod(num, den);
    }

A: The problem is this line:
 if ((num - den) > den)

For example, if num is 4 and den is 3, then 4-3 is 1 and 1 is not greater than 3, so you will return 4. What you want is
 if (num > den)

A: Try this:
int recursiveMod(int num, int den)
{
    if (num < 0) return recursiveMod(num + den, den);

    // Don't forget the case of num = 2 and den = 7
    if (num < den) return num;

    return recursiveMod(num - den, den);
}


text:
Q: Prop types for children component Let's say I want to something as simple as this
<View style={[styles.container, { backgroundColor, bottom }]}>
    {this.props.children}
  </View>

Here, What should be the appropriate props type for children?
Where children can be react-native component consisting of scrollView, TextInput, Text etc
<MyComponent>
 <View>
  <Text> Could be text </Text>
</View>
</MyComponent>

A: The one i've always used for children is:
static propTypes = {
   children: PropTypes.oneOfType([
       PropTypes.arrayOf(PropTypes.node),  //as you can render an array of elements
       PropTypes.element                   //for a single component/element
   ]).isRequired
}


text:
Q: jQuery accordion-style FAQ with + and - I'm trying to make a FAQ accordion with + and - signs in front of the questions like this. It almost works except when I click the opened section again, the minus stays as a minus. Is there any way to make it a plus? I tried writing the first commented line for that, but it doesn't seem to work. Beware, I don't know what I'm doing with jQuery and am just winging it based on what I see and know in other languages.
$('#accordion').find('.accordion-toggle').click(function(){

  //Check if this panel is minus and change it to plus *** THIS DOESN'T WORK ***
  if($('img', this).attr('src') == 'minus.png'){
     $('img', this).attr('src', 'plus.png');
  }

  //Expand or collapse this panel
  $(this).next().slideToggle('fast');

  //Change this panel to minu
  $('img', this).attr('src','minus.png');

  //Hide the other panels
  $(".accordion-content").not($(this).next()).slideUp('fast');

  //Change other panels to plus
  $(".accordion-toggle img").not($('img', this)).attr('src', 'plus.png');

});

Question?

Content text

Question?

Content text

Question?

Content text

Question?

Content text

A: You might need to change the way you've called your img attribute inside every of your div.accordion-toggle DOM element(s)
$('#accordion').find('.accordion-toggle').click(function() {

    // Check if this panel is minus and change it to plus *** THIS DOESN'T WORK ***

    // @eeya: Change it like this: (Find every img elements
    // under the .accordion-toggle element that called
    // the event listener
    if ($(this).find('img').attr('src') === 'minus.png') {
        $(this).find('img').attr('src', 'plus.png');
    }

    //Expand or collapse this panel
    $(this).next().slideToggle('fast');

    //Change this panel to minu
    $('img', this).attr('src','minus.png');

    //Hide the other panels
    $(".accordion-content").not($(this).next()).slideUp('fast');

    //Change other panels to plus
    $(".accordion-toggle img").not($('img', this)).attr('src', 'plus.png');

});

Hope this helps for your case.


text:
Q: Read a sequence of images in openCV I got a problem with reading a sequence of images in opencv. I use the same code:
namedWindow("Source", CV_WINDOW_AUTOSIZE);
string pathToData("OpenCV Images/checkerboard1.pgm");

VideoCapture sequence(pathToData);

Mat src;
for (;;)
{
    sequence >> src;
    if(src.empty())
    {
        cout << "End of Sequence" << endl;
        break;
    }
    imshow("Source", src);
    waitKey(1000);
}
waitKey(0);

I run this code in window (visual studio) and in linux. In window, the program shows all images in the sequence, while in linux, the progam just shows the first image in the same sequence.
Furthermore, in window, the program loads images in grayscale while in lunix it loads images in color. Actually, I save the image as grayscale.
Is this a problem with openCV for window and linux OS? Or Do I need to do some setting? Or something else...
Can someone help me figure it out?
Thank!

A: pathToData contains a file name instead of path. This file is in .pgm format meaning that the image is of gray scale.
In my opinion, you will have to create a list of the image names present in the folder and call these names one by one later. The current code will only show checkerboard1.pgm image. Or you must give a video file as input instead of the image.


text:
Q: How to compare two JSON strings when the order of entries keep changing I have a string like - {"state":1,"cmd":1} , I need to compare this with generated output but in the generated output the order keeps changing i.e. sometimes its {"state":1,"cmd":1} other times its {"cmd":1,"state":1}.
Currently I was using equals() method to compare, What can be better way in this scenario to validate the two strings. My concern is just that both entries are present in string, order is not imp.

A: Jackson Json parser has a nice feature that it can parse a Json String into a Map.  You can then query the entries or simply ask on equality:
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class Test
{
    public static void main(String... args)
    {
        String input1 = "{\"state\":1,\"cmd\":1}";
        String input2 = "{\"cmd\":1,\"state\":1}";
        ObjectMapper om = new ObjectMapper();
        try {
            Map<String, Object> m1 = (Map<String, Object>)(om.readValue(input1, Map.class));
            Map<String, Object> m2 = (Map<String, Object>)(om.readValue(input2, Map.class));
            System.out.println(m1);
            System.out.println(m2);
            System.out.println(m1.equals(m2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output is
{state=1, cmd=1}
{cmd=1, state=1}
true

A: You can also use Gson API
 JsonParser parser = new JsonParser();
 JsonElement o1 = parser.parse("{\"state\":1,\"cmd\":1}");
 JsonElement o2 = parser.parse("{\"cmd\":1,\"state\":1}");
 System.out.println(o1.equals(o2));

A: Try this
 import java.util.*;
 import com.google.gson.*;

 public class CompareArray {
   static Set<JsonElement> setOfElements(JsonArray arr) {
      Set<JsonElement> set = new HashSet<JsonElement>();
      for (JsonElement j: arr) {
          set.add(j);
        }
        return set;
    }

    public static void main(String[] args) {
        JsonParser parser = new JsonParser();
        Set<JsonElement> arr1elems =
setOfElements(parser.parse(args[0]).getAsJsonArray());
        Set<JsonElement> arr2elems =
setOfElements(parser.parse(args[1]).getAsJsonArray());
        System.out.println("Arrays match? " + arr1elems.equals(arr2elems));
    }
}

$ java -cp .:gson-2.2.2.jar CompareArray '[{"key1":"value1"},
{"key2":"value2"}, {"key3":"value3"}]' '[{"key3":"value3"},
{"key1":"value1"}, {"key2":"value2"}]'
Arrays match? true

I trust this is helpful to you.

A: You can simply use a class to define your object and JSONObject to parse your JSON object and get its properties:
Java Class:
public class MyObject{
     private String state; //either int or String
     private String cmd;
     //getters and setters
}

Your parsing should be like this:
MyObject obj = new MyObject();
JSONParser jsonParser = new JSONParser();
 // input is your string here
JSONObject jsonObject = (JSONObject) jsonParser.parse(input);

//get properties here and set them in your object
obj.setState(jsonObject.get("state"));
obj.setCmd(jsonObject.get("cmd"));

And then when you have the two objects you can easily compare their properties.


text:
Q: How to disable user validation in ASP.NET MVC Identity? I am learning ASP.net MVC and want to know how to disable user validation in Microsoft Identity, when a user register. Please helpThis is the register screen I want to remove validation for

A: Since it appears that you've not changed much in the application so far I'd suggest creating a new one. You turn off Authentication when you create the application - rather than trying to remove all the code and configuration in place to enable authentication.
When you setup the project click 'Change Authentication' and set it to 'No Authentication'


text:
Q: What is the current state of the Scala Eclipse plugin? Is the current Scala Eclipse plugin (http://www.scala-lang.org/node/94) usable? I keep reading that its unstable and buggy, even unusable.
See previous thread: What is the current state of tooling for Scala?
I've tried it out briefly but only for trivial programs, so far it seems fine.
Thanks!
UPDATE: I'm going to dive in and get some stuff done with Scala and Eclipse, I'll try to report back and let you know what I find.
UPDATE: See my answer below about my experiences with Eclipse 3.5.1 and Scala 2.7.7 Final.

*

*Alex

A: I found it completely unusable. Syntax highlighting worked, but that was about it. JUnit couldn't find any tests written in Scala. The debugger couldn't find sources and threw up weird error messages after every step. I've also heard of people running into trouble with auto-completion and even cut-and-paste. Apparently it can slow down work with regular Java, too. This was with Scala 2.7.5 on Eclipse 3.5 in late July, so pretty recent.
It felt to me like whoever wrote the Eclipse plug-in just got it to compile and didn't try it out even once before shipping it. It sounds like it works well enough for some people though. Personally, I switched to Emacs/Ant and haven't really looked back.

A: I've been writing code in Scala using Eclipse now for just over a week, and my conclusion is that it does work, but is not production ready.
Background on my setup:

*

*Scala 2.7.7 final

*Eclipse for Java Developers, 3.5.1

*Ubuntu Desktop 9.04 x64

*Maven 2.2.1

*JUnit 4.7

I created a brand new project which I am using just Scala in, no Java:

*

*Created the project, using maven, referencing the scala-archetype-simple

*I generated an eclipse project for it using "mvn eclipse:eclipse"

*I then opened it in Eclipse

Here are some of the problems I face:

*

*I lose syntax highlighting all the time... closing and reopening the file helps

*Often, out of now where I get tons of compile errors, cannot find my classes, doing a CLEAN in eclipse solves this

*Eclipse crashes hard sometimes, requires me to kill -9 the java process, then start Eclipse again, see it complain about the workspace, then start it again

*I'm writing vanilla JUnit tests, and have a lot of trouble running them, most of the time Eclipse can't find them, restarting Eclipse and then opening each test file usually resolves this temporarily, the error I often get is No tests found with test runner 'JUnit 4'

*Lots of erroneous squigles appear under lines of code, they can be ignored it seems

*Intellisense works maybe 10% of the time, cleaning and/or reopening files seems to bring it back temporarily

*Sometimes I lose the ability to type in the text editor in Eclipse, if I fiddle enough it might come back, or I just close and re-open the file

*Sometimes basic things like highlighting and deleting a line of code fail, with errors like "Delete" did not complete normally.  Please see the log for more information.
So I push through all these issues, and the end result is that I restart Eclipse many times a day, and constantly close and re-open files in Eclipse, and clean often.

A: It got better in 2.7.4. It'll get substantially better in 2.8.0 (it's co-released with Scala itself).
It's not on the level of Java tooling, but it is constantly improving.

A: I can confirm that as of Scala 2.8.0.RC6, the Scala Eclipse plugin as of June 27 2010 does work fairly well.
What works:

*

*Syntax highlighting

*Some autocompletion

*Find definitions (Ctrl+Click to navigate)

*Building and syntax error highlighting

What doesn't work:

*

*Refactoring.

*Editor is very slow. Even switching between tabs takes up to 4 seconds.

That's just from using it for a few days though.
That said, I'm getting real work done, and with the Eclipse web tools added in for HTML, CSS, Javascript, and XML, it's a nice way to develop Lift 2.0 web applications.

A: As of July 2012, the plugin is in great shape and is extremely useful.

A: May 24, 2010
I have eclipse 3.5 and latest Scala plugin, scala 2.8.0 RC2
Still the same issues: no correct highlighting, i'm not talking about autocompletiong and stuff... I have JDT plugin enabled - if it matters...
It's a shame that for such an interesting language as Scala which is already so many years around there is still no good dev environment...

A: It works pretty well for me, but I'm looking forward to 2.8.0. There's a nice set of slides (pdf) outlining the very significant changes coming.

A: Totally unusable with Eclipse Indigo for J2EE and Scala IDE plugin 2.9.1.
Eclipse too slow, and even crashing. When it doesn't crash, it loses compilation links and doesn't stop warning me about class not found. I have to clean and recompile all projects.
I uninstalled it waiting for another solution or a better version.

A: If it works for you then keep using it :)  I have had odd cursor problems that I don't have when doing straight java.  Usually closing the editor window and reopening solves the problem.

A: I've tried interop (one project with mixed Java and Scala) and I was having problems so I abandoned it.  I really, really want this work... Anyway, I think my problems due to the fact that I was trying to build an RCP plugin versus a simple headless Java application.  The Scala Nature seemed to not invoke the Java compiler in every case.  I'd see a bunch of red lights that weren't real, because my problems view didn't show anything and the .class files were correct.
I'm really looking forward to the IDE with the 2.8 release.

A: I'm using Scala-IDE version 2.0.0-v2_09, Eclipse Indigo, Scala 2.9.1.
Sometime when I use auto completion such as:
//expected BufferedInputStream
BufferedInpu

Then I hit Ctrl-Space, select java.io.BufferedInputStream, then my import section loses some lines, and:
object PingPong extends Application {
  ...

turns into:
object PingPong
  ...

I have found my solution to avoid that is type full name of BufferedInputStream, then Ctrl-Shift-O  :-)
Or sometime it warns me these:
Multiple markers at this line
        - object io is not a member of package
        main.scala.pingpong.zip.java
        //repeats 15 times

with my imports:
import java.util.zip.ZipOutputStream
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.io.File
import java.io.ByteArrayOutputStream

I used to raise a terminal, code in Eclipse, then switch to terminal:
sbt compile
sbt run

:-)
Eclipse seems does not support for selecting builder if you have multiple ones. It always chooses the first one listed.


text:
Q: Area under navbar in Bootstrap I keep failing to make proper use of a navbar.
In my base.html I have this code fragment in the body section.
(or should the navbar be in the head?!)

                          Company

Strategies

Data

Views

            {% block content %}

            {% endblock %}

I then use
{% extends "base.html" %}
{% block content %}

         HELLO WORLD

{% endblock %}

However, the HELLO WORLD is hidden below the navbar. How can I block the area occupied by the navbar?
Many thanks
Thomas

A: Add
padding-top: 70px;

to your body. It's right there in the documents:

The fixed navbar will overlay your other content, unless you add padding to the top of the body. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.