text:
Q: Problem with Write Custom Function in reportViewer repot I want to use of a custom function in  reportviewer's expression report .
I wrote this function in code tab section in report's property.
I want to use  of this function in my feild's expression but when i write "Code" and put after that "." , intellisense in report's expression  does not show me my function.
   Public Function FarsiNumber(ByVal str As String) As String
         Dim s As String = ""
         Dim ch() As Char = str.ToCharArray
            For Each c In ch
                If IsNumeric(c) Then
                  s += CChar(ChrW(1728 + CInt(AscW(c))))
                Else
                    s += c.ToString
                End If
              Next
         Return s
  End Function

any body can show me an example.
thanks

A: The Intellisense doesn't catch my custom functions either. But you can still use them.
In your case, you can use Code.FarsiNumber() in your expressions in your report


text:
Q: Using Radialbar QML Port with PyQt5 I am wanting to use a "Radialbar" widget for an aesthetic purposes in a GUI I am creating. Currently, I am trying to use a port found at the following location:
http://pyjuice.com/porting-radialbar-cqt-pyqt/
My question is, how do I actually go about using this in the GUI I have already built? I currently use Qt Designer to create the ui file that I use for the GUI, and then import to PtQt5 using:
    uic.loadUi("name.ui")

Is there a way to include this widget into my existing GUI? I am pretty new at this, and do not understand how I should go about using the port from the link above.

A: There are several options:
1. convert to QWidget
The simplest option for you is to convert the QQuickPaintedItem to QWidget and thus you avoid learning to use QML which is not a simple task for a beginner.
For this, some changes must be made:

*

*use the update() method in the setters:
@SOME_PROPERTY.setter
def SOME_PROPERTY(self, type):
    ...
    self.SOME_PROPERTYChanged.emit()
    self.update() # <----

*change the paint() method to paintEvent() and create the QPainter since paintEvent() does not provide any.
def paintEvent(self, event):
    painter = QtGui.QPainter(self)
    painter.save()
    ...

*Finally, QWidget does not have the setWidth() or setHeight() method, you must use the resize() method.

Using all the above you must create a .py file called radialbar.py.
radialbar.py
from PyQt5 import QtCore, QtGui, QtWidgets

class RadialBar(QtWidgets.QWidget):
    class DialType():
        FullDial = 0
        MinToMax = 1
        NoDial = 2

    sizeChanged = QtCore.pyqtSignal()
    startAngleChanged = QtCore.pyqtSignal()
    spanAngleChanged = QtCore.pyqtSignal()
    minValueChanged = QtCore.pyqtSignal()
    maxValueChanged = QtCore.pyqtSignal()
    valueChanged = QtCore.pyqtSignal()
    dialWidthChanged = QtCore.pyqtSignal()
    backgroundColorChanged = QtCore.pyqtSignal()
    foregroundColorChanged = QtCore.pyqtSignal()
    progressColorChanged = QtCore.pyqtSignal()
    textColorChanged = QtCore.pyqtSignal()
    suffixTextChanged = QtCore.pyqtSignal()
    showTextChanged = QtCore.pyqtSignal()
    penStyleChanged = QtCore.pyqtSignal()
    dialTypeChanged = QtCore.pyqtSignal()
    textFontChanged = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(RadialBar, self).__init__(parent)

        self.resize(200, 200)
        # self.setSmooth(True)
        # self.setAntialiasing(True)

        self._Size = 200
        self._StartAngle = 40
        self._SpanAngle = 280
        self._MinValue = 0
        self._MaxValue = 100
        self._Value = 50
        self._DialWidth = 15
        self._BackgroundColor = QtCore.Qt.transparent
        self._DialColor = QtGui.QColor(80,80,80)
        self._ProgressColor = QtGui.QColor(135,26,5)
        self._TextColor = QtGui.QColor(0, 0, 0)
        self._SuffixText = ""
        self._ShowText = True
        self._PenStyle = QtCore.Qt.FlatCap
        self._DialType = RadialBar.DialType.MinToMax
        self._TextFont = QtGui.QFont()

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.save()
        r = min(self.width(), self.height())
        rect = QtCore.QRectF(0, 0, r, r) #self.boundingRect()
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        pen = painter.pen()
        pen.setCapStyle(self._PenStyle)

        startAngle = -90 - self._StartAngle
        if RadialBar.DialType.FullDial != self._DialType:
            spanAngle = 0 - self._SpanAngle
        else:
            spanAngle = -360

        #Draw outer dial
        painter.save()
        pen.setWidth(self._DialWidth)
        pen.setColor(self._DialColor)
        painter.setPen(pen)
        offset = self._DialWidth / 2
        if self._DialType == RadialBar.DialType.MinToMax:
            painter.drawArc(rect.adjusted(offset, offset, -offset, -offset), startAngle * 16, spanAngle * 16)
        elif self._DialType == RadialBar.DialType.FullDial:
            painter.drawArc(rect.adjusted(offset, offset, -offset, -offset), -90 * 16, -360 * 16)
        else:
            pass
            #do not draw dial

        painter.restore()

        #Draw background
        painter.save()
        painter.setBrush(self._BackgroundColor)
        painter.setPen(self._BackgroundColor)
        inner = offset * 2
        painter.drawEllipse(rect.adjusted(inner, inner, -inner, -inner))
        painter.restore()

        #Draw progress text with suffix
        painter.save()
        painter.setFont(self._TextFont)
        pen.setColor(self._TextColor)
        painter.setPen(pen)
        if self._ShowText:
            painter.drawText(rect.adjusted(offset, offset, -offset, -offset), QtCore.Qt.AlignCenter,str(self._Value) + self._SuffixText)
        else:
            painter.drawText(rect.adjusted(offset, offset, -offset, -offset), QtCore.Qt.AlignCenter, self._SuffixText)
        painter.restore()

        #Draw progress bar
        painter.save()
        pen.setWidth(self._DialWidth)
        pen.setColor(self._ProgressColor)
        valueAngle = float(float(self._Value - self._MinValue)/float(self._MaxValue - self._MinValue)) * float(spanAngle)  #Map value to angle range
        painter.setPen(pen)
        painter.drawArc(rect.adjusted(offset, offset, -offset, -offset), startAngle * 16, valueAngle * 16)
        painter.restore()

    @QtCore.pyqtProperty(str, notify=sizeChanged)
    def size(self):
        return self._Size

    @size.setter
    def size(self, size):
        if self._Size == size:
            return
        self._Size = size
        self.sizeChanged.emit()
        self.update()

    @QtCore.pyqtProperty(int, notify=startAngleChanged)
    def startAngle(self):
        return self._StartAngle

    @startAngle.setter
    def startAngle(self, angle):
        if self._StartAngle == angle:
            return
        self._StartAngle = angle
        self.startAngleChanged.emit()
        self.update()

    @QtCore.pyqtProperty(int, notify=spanAngleChanged)
    def spanAngle(self):
        return self._SpanAngle

    @spanAngle.setter
    def spanAngle(self, angle):
        if self._SpanAngle == angle:
            return
        self._SpanAngle = angle
        self.spanAngleChanged.emit()
        self.update()

    @QtCore.pyqtProperty(int, notify=minValueChanged)
    def minValue(self):
        return self._MinValue

    @minValue.setter
    def minValue(self, value):
        if self._MinValue == value:
            return
        self._MinValue = value
        self.minValueChanged.emit()
        self.update()

    @QtCore.pyqtProperty(int, notify=maxValueChanged)
    def maxValue(self):
        return self._MaxValue

    @maxValue.setter
    def maxValue(self, value):
        if self._MaxValue == value:
            return
        self._MaxValue = value
        self.maxValueChanged.emit()
        self.update()

    @QtCore.pyqtProperty(float, notify=valueChanged)
    def value(self):
        return self._Value

    @value.setter
    def value(self, value):
        if self._Value == value:
            return
        self._Value = value
        self.valueChanged.emit()
        self.update()

    @QtCore.pyqtProperty(int, notify=dialWidthChanged)
    def dialWidth(self):
        return self._DialWidth

    @dialWidth.setter
    def dialWidth(self, width):
        if self._DialWidth == width:
            return
        self._DialWidth = width
        self.dialWidthChanged.emit()
        self.update()

    @QtCore.pyqtProperty(QtGui.QColor, notify=backgroundColorChanged)
    def backgroundColor(self):
        return self._BackgroundColor

    @backgroundColor.setter
    def backgroundColor(self, color):
        if self._BackgroundColor == color:
            return
        self._BackgroundColor = color
        self.backgroundColorChanged.emit()
        self.update()

    @QtCore.pyqtProperty(QtGui.QColor, notify=foregroundColorChanged)
    def foregroundColor(self):
        return self._ForegrounColor

    @foregroundColor.setter
    def foregroundColor(self, color):
        if self._DialColor == color:
            return
        self._DialColor = color
        self.foregroundColorChanged.emit()
        self.update()

    @QtCore.pyqtProperty(QtGui.QColor, notify=progressColorChanged)
    def progressColor(self):
        return self._ProgressColor

    @progressColor.setter
    def progressColor(self, color):
        if self._ProgressColor == color:
            return
        self._ProgressColor = color
        self.progressColorChanged.emit()
        self.update()

    @QtCore.pyqtProperty(QtGui.QColor, notify=textColorChanged)
    def textColor(self):
        return self._TextColor

    @textColor.setter
    def textColor(self, color):
        if self._TextColor == color:
            return
        self._TextColor = color
        self.textColorChanged.emit()
        self.update()

    @QtCore.pyqtProperty(str, notify=suffixTextChanged)
    def suffixText(self):
        return self._SuffixText

    @suffixText.setter
    def suffixText(self, text):
        if self._SuffixText == text:
            return
        self._SuffixText = text
        self.suffixTextChanged.emit()
        self.update()

    @QtCore.pyqtProperty(str, notify=showTextChanged)
    def showText(self):
        return self._ShowText

    @showText.setter
    def showText(self, show):
        if self._ShowText == show:
            return
        self._ShowText = show
        self.update()

    @QtCore.pyqtProperty(QtCore.Qt.PenCapStyle, notify=penStyleChanged)
    def penStyle(self):
        return self._PenStyle

    @penStyle.setter
    def penStyle(self, style):
        if self._PenStyle == style:
            return
        self._PenStyle = style
        self.penStyleChanged.emit()
        self.update()

    @QtCore.pyqtProperty(int, notify=dialTypeChanged)
    def dialType(self):
        return self._DialType

    @dialType.setter
    def dialType(self, type):
        if self._DialType == type:
            return
        self._DialType = type
        self.dialTypeChanged.emit()
        self.update()

    @QtCore.pyqtProperty(QtGui.QFont, notify=textFontChanged)
    def textFont(self):
        return self._TextFont

    @textFont.setter
    def textFont(self, font):
        if self._TextFont == font:
            return
        self._TextFont = font
        self.textFontChanged.emit()
        self.update()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = RadialBar()
    w.backgroundColor = QtGui.QColor("#1dc58f")
    w.foregroundColor = QtGui.QColor("#191a2f")
    w.dialWidth = 10
    w.spanAngle = 70
    w.textColor = QtGui.QColor("#FFFFFF")
    w.penStyle = QtCore.Qt.RoundCap
    w.dialType = RadialBar.DialType.FullDial
    w.suffixText = "%"
    timeline = QtCore.QTimeLine(10000, w)
    timeline.setFrameRange(0, 100)
    timeline.frameChanged.connect(lambda val: setattr(w, "value", val))
    timeline.start()
    w.show()
    sys.exit(app.exec_())

And if you want to use it within Qt Designer there are 2 options: create a plugin that for a beginner can be heavy and unnecessary, or promote it, this second method is the one I am going to propose.
For this in your design you must add a Widget:

Then you right click on the part of the window where the widget is and click on "Promote to ..", and in the dialogue place RadialBar as I show below:

then press the Add button, then the Promote button.
with the above the generated .ui is:
name.ui:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <widget class="QLineEdit" name="lineEdit"/>
     </item>
     <item>
      <widget class="QPushButton" name="pushButton">
       <property name="text">
        <string>PushButton</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
   <item>
    <widget class="RadialBar" name="widget" native="true"/>
   </item>
  </layout>
 </widget>
 <customwidgets>
  <customwidget>
   <class>RadialBar</class>
   <extends>QWidget</extends>
   <header>radialbar.h</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

Finally, you use your .ui file:
main.py
from PyQt5 import QtCore, QtGui, QtWidgets, uic

class Widget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        uic.loadUi("name.ui", self)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

The structure you must have is the following:
├── main.py
├── name.ui
└── radialbar.py

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# to MySqlDB update I'm currently working on a little example for a friend to record employers working time. Therefore I want to update the record of a MySQL database.
The connection to the DB is already done and is working on the test, however, I do not manage (and yes I googled a lot) to actually get the values changing in the DB. This is my current attempt to give out the current time for when employers start working:
void main(string[] args)
{
    // Die Verbindung zur DB entnehmen.
    MySqlConnection conn = DBUtils.GetDBConnection();
    conn.Open();
    try
    {
        // Der Befehl UPDATE.
        string sql = "UPDATE user SET lastlogin = lastlogin WHERE user username = srademacher";

        MySqlCommand cmd = new MySqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = sql;

        MySqlParameter lastlogin = new MySqlParameter("@lastlogin", SqlDbType.DateTime);
        lastlogin.Value = DateTime.Now;
        cmd.Parameters.Add(lastlogin);

        // Command durchführen
        int rowCount = cmd.ExecuteNonQuery();

    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + e);
    }
    finally
    {
        conn.Close();
        conn.Dispose();
        conn = null;
    }

    Console.Read();
    MessageBox.Show("Die Arbeit wurde um " + DateTime.Now + " aufgenommen");
}

I guess you could call me a noob at scripting but I would be happy to get some advice to become better :-) thank you for your ideas.
Edit: I do not have any problems launching the application the code accords to, just the DateTime Value in DB does not change

A: Your update statement has incorrect syntax, WHERE user username = srademacher. Then you add MySqlParameter but not using that in sql.
Change sql to
string sql = "UPDATE user SET lastlogin = @lastlogin WHERE username = @username";

and  add
 MySqlParameter username = new MySqlParameter("@username", SqlDbType.NVarChar);
 username.Value = "srademacher";
 cmd.Parameters.Add(username);


text:
Q: Google autocomplete split into separate fields Hi I have 3 different inputs (city, street and street_number). For example my country is 'Polska' and city 'Warszawa' so I need display only street from this city. How to do that?
var input = document.getElementById('inputid');

var param = {
    componentRestrictions: {country: 'PL'},
};

autocomplete = new google.maps.places.Autocomplete(input, param);
geocoder = new google.maps.Geocoder();

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    if(place.address_components) {
        console.log(place.address_components);
    }
});

A: This one is pretty simple. If you are using a sample code from Google Place Autocomplete Address Form, all you need to do is remove unnecessary input fields and just leave the fields that you wanted to populate - e.g: street_number and route. You also need to remove unnecessary properties and just leave street_number and route from componentForm object. Like this:
var componentForm = {
 street_number: 'short_name',
 route: 'long_name'
};

Additional options like 'componentRestrictions' in Autocomplete object's second argument (options). It should look something like this:
autocomplete = new google.maps.places.Autocomplete(
   (document.getElementById('autocomplete')),
     {
       types: ['geocode'],
       componentRestrictions : {
        country: 'PL',
       }
     }
);

For more details about component filtering you can check this link.
Please also note this:

The selection of specific address components in this example is based on a typical address format. You may need to select different components to align with the postal address formats of different countries.

To learn more, please follow this link.
Here's a live demo:

      var placeSearch, autocomplete;
      var componentForm = {
        street_number: 'short_name',
        route: 'long_name'
      };

      function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
            {
              types: ['geocode'],
              componentRestrictions : {
                 country: 'PL',
              }
            }
        );

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);
      }

      function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        for (var component in componentForm) {
          document.getElementById(component).value = '';
          document.getElementById(component).disabled = false;
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
      }

      // Bias the autocomplete object to the user's geographical location,
      // as supplied by the browser's 'navigator.geolocation' object.
      function geolocate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
      }

      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>

        Street address
        <input class="field" id="street_number"
              disabled="true"></input>
        <input class="field" id="route"
              disabled="true"></input>

Hope it helps!


text:
Q: WebStorm type checking React props using type definition I'm using WebStorm 2018.3.4 and am trying to figure out how to do type checking on a React component's props. Specifically, if a prop is marked as a string but I give it a number I want WebStorm to show an error. I've created a type definition file (as described here). Here's what the file looks like:
MyComponent.d.ts
import * as React from 'react';

export interface MyComponentProps {
  /** this is the component's title */
  title: string;

  /** this is a short description of the component */
  description?: string;
}

declare class MyComponent extends React.Component<MyComponentProps, {}> {
  render(): JSX.Element;
}

export default MyComponent;

App.jsx
class App extends React.Component {
  render() {
    return (
      <MyComponent title={7} />
    );
  }
}

I was hoping WebStorm would underline title={7} telling me that 7 is the wrong type. If I Ctrl+Q on the prop it definitely tells me the type is string and it gives me the documentation from the .d.ts file. Is there a setting I need to enable? Or does WebStorm not support this? Or is my problem that my app is using JSX rather than TypeScript? Any help would be appreciated.

A: You can install prop-types
Then you can write your component like this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class App extends Component {
    static propTypes = {
        userId: PropTypes.string.isRequired,
        someObject: PropTypes.object.isRequired,
        someFunction: PropTypes.func.isRequired,
    };

    render() {
       ....
    }
}


text:
Q: how to implement code for display the text line by line by using animations? How to implement a code and xml by using animations to displaying the text line by line it means in the first line " well come to world page" in the second line "how are you friend" and in the third line "Have a nice day".

A: I think this will help you
 In your xml file write this property


text:
Q: My cookies are not being transmitted when using webtest.TestApp I am confused as to how to pass cookies in a request using python webtest.
I have the following test:
def test_commenting_and_voting(self):
    https = {'wsgi.url_scheme': 'https'}
    users = []
    for user in USERS:
      resp_post = self.testapp.post_json('/user', user)
      users.append(resp_post.json.get('id'))

    self.testapp.post_json('/login/%s' % users[0],
                           {'password' : USERS[0]['password']},
                           extra_environ=https)
    print "testapp's view of the cookiejar"
    print self.testapp.cookies
    print "END"
    resp_post = self.testapp.post_json('/comment', {'value': ""})

and the following handler:
class CommentHandler(webapp2.RequestHandler):

    def get(self, id=None):
        get_from_urlsafe(self, id)

    @ndb.transactional
    def post(self, id=None):
        assert False, self.request.cookies

I am raising an error from the handler function in order to see the cookies. It appears that the cookies, although in the cookiejar within the webtest.TestApp side of things, are not being transmitted when making the wsgi request. So how do I get the cookies to transmit?
Using scent:
test_commenting_and_voting (test_models.test_Models) ...
testapp's view of the cookiejar
{'secret': '58bd5cfd36e6f805de645e00f8bea9d70ae5398ff0606b7fde829e6732394bb7', 'session': 'agx0ZXN0YmVkLXRlc3RyIgsSD1VzZXJFbnRpdHlHcm91cBgBDAsSB1Nlc3Npb24YCww'}
END
WARNING:root:suspended generator transaction(context.py:941) raised AssertionError(<RequestCookies (dict-like) with values {}>)
ERROR:root:<RequestCookies (dict-like) with values {}>
Traceback (most recent call last):
  File "/home/stephen/bin/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  ... I removed some of the stacktrace here ....
  File "/home/stephen/work/seocomments/src/python/main.py", line 127, in post
    assert False, self.request.cookies
AssertionError: <RequestCookies (dict-like) with values {}>
----------------------------------------------------------------------
Ran 6 tests in 0.371s

FAILED (errors=1)
Failed - Back to work!

A: Nevermind. The reason I wasn't seeing the cookies was that the cookies were being set as secure cookies, which means they only exist when using a secure connection. My test was using a insecure connection.
To make this work, change the request to the following:
self.testapp.post_json('/comment',
                       {'value': ""},
                       extra_environ={'wsgi.url_scheme': 'https'})


text:
Q: Can't pass String via Extra on an Android grid view I have a gridView and I want to pass an Extra via an intent.
It usually works, but not here:
gv.setOnItemClickListener(new OnItemClickListener() {
                      public void onItemClick(AdapterView<?> parent, View v,
                                              int position, long id) {
                        String prompt = (String)parent.getItemAtPosition(position);
                        Intent intent = new Intent(BookletsGridActivity.this, PdfReader.class);
                        intent.putExtra("pdfurl", prompt);
                        System.out.println("prompt --->" + prompt);
                       overridePendingTransition(R.anim.animationin, R.anim.animationout);
                         startActivity(intent);
                      }
                    });

I have no idea why it is not working: I check prompt value and it's the right one.

A: Ok I close this one. Thanks for help. I did some mistakes with the data I wanted to send. Extras are not guilty! ^^

A: use following one
    BookletsGridActivity.class
 Intent intent = new Intent(BookletsGridActivity.this, PdfReader.class);
    intent.putExtra("pdfurl", prompt);
    System.out.println("prompt --->" + prompt);
    overridePendingTransition(R.anim.animationin, R.anim.animationout);
    startActivity(intent);

PdfReader.class
Intent intent = getIntent();
String value = intent.getStringExtra("pdfurl", "");


text:
Q: Sequelize findAll where many to many criteria I have 2 models User and Item with many to many relation, here is the definitions:
User = sequelize.define('User', {
    name: {type: Sequelize.STRING}
  })
Item = sequelize.define('Item', {
        name: {
          type: Sequelize.STRING,
          allowNull: false
        }
      }
User.belongsToMany(models.Item, {
     as: 'items',
     through: 'UserItem'
})
Item.belongsToMany(models.User, {
     as: 'owners',
     through: 'UserItem'
})

And my request is :
Item.findAll({
    include: [{
      model: User,
      through: {
        where: {id: 2}
      }
    }]
  }).then(items => {
    log.debug(items)
  }).catch(err => {
    log.error(err)
  })

Then I have : Error: User is not associated to Item!
I also try this :
Item.findAll({
    where: {'owners.id': 2},
    include: Item.assocations.owners
  }).then(items => {
    debug(items)
  }).catch(err => {
    log.error(err)
  })

But now I have Error: SQLITE_ERROR: no such column: Item.owners.id
Any ideas ?

A: Here is my working solution :
'use strict'
const Sequelize = require('Sequelize')

const sequelize = new Sequelize({
  host: 'localhost',
  dialect: 'sqlite',
  // SQLite only
  storage: 'database.sqlite'
})

const User = sequelize.define('user', {
  name: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true // Model tableName will be the same as the model name
})

const Item = sequelize.define('item', {
  name: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true // Model tableName will be the same as the model name
})

const UserItem = sequelize.define('useritem', {})

User.belongsToMany(Item, {
  as: 'items',
  through: 'useritem'
})
Item.belongsToMany(User, {
  as: 'owners',
  through: 'useritem'
})

Promise.all([
  User.sync({force: true}),
  Item.sync({force: true}),
  UserItem.sync({force: true})])
  .then(() => {
  return Promise.all([
    User.create({name: 'test'}),
    User.create({name: 'admin'}),
    Item.create({name: 'item1'}),
    Item.create({name: 'item2'})])
    .then(results => {
      return results[2].addOwner(results[0])
    }).then(() => {
      return Item.findAll({
        include: {model: User, as: 'owners', where:{
          'id': 1
        }}
      }).then(items => {
        console.log(items)
      })
})
}).catch(err => console.log(err))

as need to be on include clause and where should be added on include too


text:
Q: Rails Polymorphic Associations Total newbie to Rails and programming in general, so please forgive me if the answer to my question seems glaringly obvious. I've been doing a lot of reading including the ROR guides but can't seem to find a scenario specific to the following situation:
I have three models scaffolded under one User model, and am trying to link them like so:
class User < ActiveRecord::Base
   has_many :malls, :dependent => :destroy
end

class Mall < ActiveRecord::Base
   belongs_to :user
   has_many :stores, :dependent => :destroy
   has_many :cakes, :as => :cake_poly, :dependent => :destroy
end

class Store < ActiveRecord::Base
   belongs_to :mall
   has_many :cakes, :as => :cake_poly, :dependent => :destroy
end

class Cakes < ActiveRecord::Base
   belongs_to :cake_poly, :polymorphic => true
end

Will this work? If it does, is there a better way to implement this? If not, how else can I implement the associations?
The idea is that each User may have many malls, each Mall may have many stores, and both malls and stores may have many cakes.

A: A key question for your design is the intent - what do you want to achieve?
You should not use the polymorphic relationship if you simply like to aggregate cakes available in the mall's shops for the mall model. You can use the following relationship to achieve such a design:
class Mall < ActiveRecord::Base
  has_many :stores
  has_many :cakes, :through => :stores
end

The polymorphic approach is a perfect choice if the two sets (cakes in the mall, cakes in the mall's stores) don't correlate.


text:
Q: Como ocultar div com cookies após uma segunda visita do usuário Olá amigos já procurei muito e não achei como fazer eu agradeço pela ajuda desde já.
Quero ocultar uma div com cookies após uma segunda visita do usuário
Segue meu código:

jQuery(document).mousemove(function(e){
    if( document.activeElement && document.activeElement.tagName == 'IFRAME' ){
 jQuery.post(window.location.href, {click: 1});
 document.getElementById('mime').remove();
    }
});

jQuery(document).bind("contextmenu",function(e){jQuery("#mime").remove();});
    document.onkeypress = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            jQuery("#mime").hide();

            return false;
        }
    }
    document.onmousedown = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            jQuery("#mime").hide();

            return false;
        }
    }
document.onkeydown = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            jQuery("#mime").hide();

            return false;
        }
    }
<div id="mime" style="position:absolute; z-index:99999999999999; opacity:0.0; filter: alpha(opacity=0) ">
<script type='text/javascript'>
habilita=true;
if(document.all){}
          else document.captureEvents(Event.MOUSEMOVE);document.onmousemove=mouse;function mouse(e)
          {if(navigator.appName="Netscape"){xcurs=e.pageX;ycurs=e.pageY;}else{xcurs=event.clientX;ycurs=event.clientY;}
         if(habilita){ document.getElementById("mime").style.left=(xcurs-230)+"px";document.getElementById("mime").style.top=(ycurs-150)+"px";}}
</script>

</div>

A: É necessário setar o cookie na primeira visita do usuário, podendo ser feito por jquery dessa forma:
// O parâmetro de expiração é setado em dias, e ele não é obrigatório.
$.cookie("visited", 1, { expires: 5 } );

Nas próximas vezes que ele acessar seu site, é necessário verificar se o cookie existe na máquina do usuário para então esconder a div, com jquery:
if($.cookie("visited")) {
    $("div#mime").hide();
}


text:
Q: Is developing a BlackBerry app similar to Android? I'm almost done building my first android app and I was looking at making a version for Blackberry. Now since Blackberry native language is Java like Android, is easier to make a blackberry version of your android app from your android code? Is there a way to port it? (Not using the runtime software. More like porting the code to blackberry os standards) Will there be code that is reusable? I'm going to download the SDK soon and read their apis and stuff later but before I did that I just wanted to know about the similarities between developing an android app and a blackberry one.

A: I also came from Android development, and now I'm learning Cascades for BB10. I don't know anything about BB7 though.
If you want to make an Android port you have Repackaging tools

*

*Eclipse and Android studio Plug-in: this will add a few things to eclipse, and it's similar to Android launch. I suggest you use this if you port.

*Online Packager: no longer available. Please use command line tools

*Command-line Tools: self explanatory. Download here (check website if dead link!)
While porting Android app is easier, we're usually not too happy with them. Native apps look a lot better and work faster! Then again, we prefer a port then no app. I have 3200 downloads on Google Play and 2200 on BlackBerry World on a port (it's longer on google!), and I am considering rewriting it in Cascades.
If you want to write FOR BB10.. a few options here:

*

*Native/Cascades: good looking, fast and reliable. You can either make design in QML or C++ (Qt), or both at the same time. Small things are normally written in QML, since it supports Javascript, heavy duty is in c++ (Qt).

*HTML5: self explanatory

*Native/Core: C/C++

*Adobe AIR - Discontinued as of 10.3.1

You can't make Java apps for BB10. It will take some time to get used to BB10 way of working but it's worth it. I prefer Cascades over Android for design making, since those XML layouts have a mind of its own.
Edit: links fixed on 17.1.2014

A: Porting apps from the Native NDK in Android over to BlackBerry is relatively simple. You can either port it directly into Eclipse or you can use runtime tools. Check out the following link with a plethora of tools to use:
https://developer.blackberry.com/android/tools/

A: Blackberry uses c++/qt in its current version (10)
http://developer.blackberry.com/native/documentation/bb10/getting_started.html
but it can sideload android apps (emulate them) so it might just simply work
http://crackberry.com/how-run-almost-any-android-233-app-blackberry-10
For older versions of blackberry OS (6 and 7), check out the links provided in the other answers and also this question:
Is it possible to convert android app to blackberry app?

A: For BlackBerry10 you only need to convert it
But for Older BlackBerry OS, the java os7,  you need to rewrite code, because different with Android

A:
Using the packager
Before you begin: Follow these steps to install the Android SDK and SDK platform 4.2.2 APIs. Note that you don't need to install Eclipse or the BlackBerry Plug-in for Android Development to use the online packager.
To repackage an app using the BlackBerry Packager is as simple as completing the following steps:
1.Set the permissions to allow your browser to run the packager applet.
2.Run the compatibility test to determine whether your app is likely to run on a BlackBerry device.
3.BlackBerry ID token and configure your computer
4.Package and sign your app.
Get started with the online packager http://developer.blackberry.com/android/bpaa


text:
Q: Creating a loop of if statments if explication == "y":
    print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
    " objective is to guess it, if you type a number lower than the generated number i'll tell you" +
    " and the same will happen if you type a bigger number and there's a score if you guess wrong" +
    " it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
if explication == "n":
    print("Great then we'll go straight to having fun!")

if explication != "n" and explication != "y":
    explication = input("please choose y or n: ")

So i started learning python and i wanted to do a simple fun program, and here i wanted to ask the user if he needed explication of the game  that was simple to do, but i also wanted to make him choose another time if he miss clicked or he just wanted to type other things so i made the 3rd if statement, i also wanted it to repeat so if he keeps typing things other than y and n the program will always send "please choose y or n" until he he types either y or n is there a way to do this?

A: explication = None

# keep asking until we get "y" or "n"
while explication not in ["y", "n"]:
    # retrieve input
    explication = input("please choose y or n: ")

    # check whether it's y or n
    if explication == "y":
        print("The game is very simple...")
    elif explication == "n":
        print("Great then we'll go straight to having fun!")

    # if the input is neither y nor n, the program ends up here
    # and loops again

Alternative:
# keep looping unconditionally
while True:
    # retrieve input
    explication = input("please choose y or n: ")

    if explication == "y":
        # print and break
        print("The game is very simple...")
        break  # <- this gets us out of the while loop
    elif explication == "n":
        print("Great then we'll go straight to having fun!")
        break

A: Here is a simple way to write the code
explication = None
while(explication != "n" and explication != "y"):
    explication = input("please choose y or n: ")
    if explication == "y":
        print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
        " objective is to guess it, if you type a number lower than the generated number i'll tell you" +
        " and the same will happen if you type a bigger number and there's a score if you guess wrong" +
        " it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
        break
    if explication == "n":
        print("Great then we'll go straight to having fun!")
        break

#Code to start the game after this comment

Explanation
We set explication to None as the explication variable has to be initialized first.
The while loop runs while the input is not y or n. If it is y, we explain the game and then leave the loop using break. If it is n, we skip the explication and break from the loop. After you break from the loop you can put the code for the game!


text:
Q: Export CSV list with all specific files in directory - with their "path" I am currently running the following script:
Get-ChildItem $dir1 -recurse -include *ending.csv |
  Sort-Object fullname |
  Select $CurrentDate,Path,FullName,Name,CreationTime,Length,Chosen |
  Export-Csv -Delimiter ';' -Force -NoTypeInformation $dir2

$dir1 and $dir2 are the source / destination paths.
Now the script just creates a CSV file that lists all files that have an ending according to what I specified along with some other parameters of the files.
I'd also like to have a column that contains the "path without the file" for the file. So basically the FullName without Name of the file.
Is there such a cmdlet / command?

A: You're looking for the Directory property:
Get-ChildItem $dir1 -recurse -include *ending.csv |
  Sort-Object fullname |
  Select $CurrentDate,Directory,FullName,Name,CreationTime,Length,Chosen |
  Export-Csv -Delimiter ';' -Force -NoTypeInformation $dir2


text:
Q: webbrowser control login problem with password I am using webbrowser control for automate login in https://www.itslb.com/tms/ website i have written code also but password input box doesnt hold any value username hold so could anyone tell me why happen this
my code like below
Dim frmform As HtmlElement = WebBrowser1.Document.Forms("aspnetForm")
frmform.All("ctl00_lnkLogin").InvokeMember("Click")

frmform.All("ctl00_txtUserName").SetAttribute("value", sUserID)
frmform.All("ctl00_txtPassword").SetAttribute("value", sPWD)
frmform.GetElementsByTagName("select")(0).Document.GetElementsByTagName("option")(1).SetAttribute("selected", "true")

'frmform.All("ctl00$cboTerminal").InvokeMember("SelectedIndexChanged")
'frmform.GetElementsByTagName("select")(0).Document.GetElementsByTagName("option")(1).SetAttribute("selected", "true")
frmform.All("ctl00_btnLogin").Enabled = True
frmform.All("ctl00_btnLogin").InvokeMember("Submit")

Thanks in advance

A: I have used InnerText successfully for login boxes before(that is what you would use in a regular COM method, anyway):
I am guessing that sPWD is a var for your password, and that "ctl00_txtPassword" is the id for your password box.
whatbrowser.Document.GetElementById("ctl00_txtPassword").InnerText = sPWD

You might also try this:
frmform.Document.GetElementById("ctl00_txtPassword").SetAttribute("value", sPWD)


text:
Q: Usefulness of std::make_unique and std::make_shared in C++1z With C++17 we get template type deduction for class templates. So a lot of make functions could become obsolete.
How about make_unique and make_shared ?
So we can write
unique_ptr myPtr(new MyType());
// vs
auto myPtr = make_unique<MyType>();

so can we forget about those functions?

A: You forgot about one of the most important reasons we got make_unique. Consider the difference between these two function calls:
some_function(make_unique<T>(), std::vector<U>{1, 2, 3});
some_function(unique_ptr(new T()), std::vector<U>{1, 2, 3});

One of these functions has a subtle error in it. Can you guess what it is?
If the vector constructor throws, then something really bad can happen. Because of C++ function argument expression evaluation rules, it's possible that the order of evaluation can be new T() followed by std::vector<U>{1, 2, 3} followed by unique_ptr<T>'s constructor. If the vector throws, then the newed pointer is never freed.
That's bad. And that's about 90% of the reason why we have make_unique at all.
Now having said that, C++17 also makes a change about the evaluation of function argument expressions that makes this point obsolete. C++17's rules guarantee that there can be no overlap between the different expressions that initialize arguments. That is, each argument's initializer expression completes in full before another one can begin. C++17 doesn't guarantee the order of the argument expressions, but there cannot be interleaving between subexpressions.
In the above code, the evaluation order may be vector first, or new T() first. But if it evaluates new T() first, it must evaluate unique_ptr<T>() before evaluating the vector constructor.
So in C++17, both of these are safe. So while template argument deduction does not obsolete make_unique, C++17 as a whole does.
Of course, there's always an issue of standard compliance. A compiler might implement constructor argument deduction before implementing expression evaluation ordering rules. And there's no way to make your code break if expression evaluation ordering isn't there (not unless you're relying on the feature test macros, which some compilers don't support).
So just to be safe, I'd suggest sticking with make_unique in such circumstances.
And lastly, there's the special feature of make/allocate_shared: the ability to allocate the control block and the object in the same storage. This is not an unimportant feature of shared_ptr, and it cannot be replicated with template new.
So you should keep using make_shared where possible.

A: Neither unique_ptr nor shared_ptr are constructible without explicitly providing the type, due to the inability to distinguish between T* and T[]. Writing unique_ptr{new int} is ill-formed.
Additionally, std::make_shared does more than just construct a std::shared_ptr for you without you having to type new. It also allocates both the object and the control structure in a single allocation, which saves you both an allocation and gives you locality for when you have to change the reference count.


text:
Q: After submit nothing happens I'm building a forum with Laravel. After clicking the submit button to create a new thread nothing happens, the user is not redirected and the thread doesn't appear in the database.
Here's my controller:
public function store(ThreadValidation $rules, $request)
{
    $thread = Thread::create([
        'user_id' => auth()->id(),
        'channel_id' => request('channel_id'),
        'title' => request('title'),
        'body' => request('body'),
    ]);

    return redirect($thread->path());
}

Model:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    protected $guarded = [];
    protected $fillable = ['title', 'body', 'user_id', 'channel_id'];

    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function replies()
    {
        return $this->hasMany(Reply::class);
    }

    public function addReply($reply)
    {
        $this->replies()->create($reply);
    }

    public function path()
    {
        return "/threads/{$this->channel->slug}/{$this->id}";
    }

    public function channel()
    {
       return $this->belongsTo(Channel::class, 'channel_id');
    }
}

Routes:
Route::get('/', function () {
        return view('welcome');
});

Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('threads', 'ThreadsController@index');
Route::get('threads/create', 'ThreadsController@create');
Route::get('threads/{channel}/{thread}', 'ThreadsController@show');
Route::post('/threads', 'ThreadsController@store');
Route::get('threads/{channel}', 'ThreadsController@index');
Route::post('threads/{channel}/{thread}/replies', 'RepliesController@store');

Blade:

Create a New Thread

                  <form method="POST" action="/threads">
                    @csrf

                      Add a title
                      <input type="text" class="form-control" name="title" id="title">

                      <textarea name="body" id="body" class="form-control" rows="8"></textarea>

                    <button type="submit" class="btn btn-primary">Publish</button>
                  </form>

I would really appreciate if you could tell me what is wrong, because my test actually passes.
/**
 * @test
 */
public function an_authenticated_user_can_create_forum_threads()
{
    $this->withExceptionHandling()
        ->signIn();

    $thread = create('App\Models\Thread');
    $this->post('/threads', $thread->toArray());

    $this->get($thread->path())
        ->assertSee($thread->title)
        ->assertSee($thread->body);
}

Update: Form Request:
public function rules()
{
    return [
        'title' => 'required',
        'body' => 'required',
        'channel_id' => 'required||exists:channels, id',
    ];
}

A: Your post request does not contain a channel_id, thus this validation will fail: 'channel_id' => request('channel_id') and that is why your request will not be handled correctly.
You will have to add an input field which contains this variable, or remove it from the validation. In the order requests this will work because the url sometimes contains the id, but since this url is /threads it obviously does not contain this variable.
If you can not or do not want to force this variable you can remove the validation rule and provide a default value if the request variable is not present (however I would advice against this since it is better to require this variable if you need it anywhere else since this spares you the hassle of more checks if it is set). In order to do this you can use the Null coalescing operator, like this:
$thread = Thread::create(
    [
    'user_id' => auth()->id(),
    'channel_id' => request('channel_id') ?? "Default value",
    'title' => request('title'),
    'body' => request('body'),
    ]
);

I hope this helps you


text:
Q: How to get previous stored from an an object in redux I'm working on an application which uses react for the front-end and redux for state management.
In this application I have a reducer, which stores the current state of the user's presence. So whether the user is online or offline. I'm getting the current state of the user's presence using the useSelector hook.
My question however is how to get previous value stored in the userStatus object.
reducer.js
import * as actionTypes from "../actions/types";
import { combineReducers } from "redux";
const initialState = {

  userStatus: { value: "unavailable", label: "Offline" },
};
const user_reducer = (state = initialState, action) => {
  switch (action.type) {

    case actionTypes.SET_USER_STATUS:
      return {
        ...state,
        userStatus: action.payload,
      };

    default: {
      return state;
    }
  }
};

const rootReducer = combineReducers({
  user: user_reducer,

});
export default rootReducer;

//getting user current presence
const userPresence = useSelector((state) => state.user.userStatus);

example:
current State `userStatus: { value: "unavailable", label: "Offline" }`
previous state userStatus: { value: "available", label: "Online" }

How can i get this previous state

A: After updating the state in redux, use useEffect on change of that redux state and save that state in some local state. In this case whenever redux state updates you'll have that previous state stored in local
function Component(props){
  const userPresence = useSelector((state) => state.user.userStatus);
const [userLocal, setUserLocal] = useState(null)

  useEffect(()=>{
// here you have access to previous state(userLocal) and current
// state(userPresence)
   setUserLocal(userPresence)
},userPresence)
}


text:
Q: decode json response to get json parameter value Here is my json response:
stdClass Object ( [is_claimed] => [rating] => 4 [mobile_url] => http://m.yelp.com/biz/the-waterboy-sacramento [rating_img_url] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/c2f3dd9799a5/ico/stars/v1/stars_4.png [review_count] => 455 [name] => The Waterboy [snippet_image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [rating_img_url_small] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/f62a5be2f902/ico/stars/v1/stars_small_4.png [url] => http://www.yelp.com/biz/the-waterboy-sacramento [menu_date_updated] => 1387494198 [reviews] => Array ( [0] => stdClass Object ( [rating] => 5 [excerpt] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [time_created] => 1395158338 [rating_image_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png [rating_image_small_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png [user] => stdClass Object ( [image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [id] => H0qUqWctz5Ms6qdeaIvjFw [name] => Lori T. ) [rating_image_large_url] => http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png [id] => bZznirkpADmW3Qcpc5u_VA ) ) [phone] => 9164989891 [snippet_text] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [image_url] => http://s3-media1.ak.yelpcdn.com/bphoto/9e5sodvvP3p6_53wOqVTcg/ms.jpg [categories] => Array ( [0] => Array ( [0] => French [1] => french ) [1] => Array ( [0] => Italian [1] => italian ) ) [display_phone] => +1-916-498-9891 [rating_img_url_large] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png [menu_provider] => single_platform [id] => the-waterboy-sacramento [is_closed] => [location] => stdClass Object ( [city] => Sacramento [display_address] => Array ( [0] => 2000 Capitol Ave [1] => Midtown [2] => Sacramento, CA 95811 ) [neighborhoods] => Array ( [0] => Midtown ) [postal_code] => 95811 [country_code] => US [address] => Array ( [0] => 2000 Capitol Ave ) [state_code] => CA ) )

which I get using:
$response = json_decode($data);
print_r($response);
echo $response["rating"]; //Why this does not give json response value?

A: Pass true into the second parameter of json_decode to return an array (which is how you're trying to access it):
$response = json_decode($data, true); // associative array returned
print_r($response);
echo $response["rating"]; // 4

Manual
Otherwise, access the rating as a property of the object that you've got:
$response = json_decode($data);
echo $response->rating; // 4


text:
Q: Is there a Scala function of type `Nothing => A`? Or how to construct one? Through Curry-Howard isomorphism Scala's Unit corresponds to logical true and Nothing to logical false. The fact that logical true is implied by anything is witnessed by a simple function that just discards the argument:
def toUnit[A](x: A): Unit = { }

Is there a function that witnesses the fact that logical false implies anything, that is a function of type Nothing => A? Or is there an idiomatic way how to construct one?
One can always do something like
def fromNothing[A](n: Nothing): A = throw new RuntimeException();

but this is just ugly - it doesn't use the fact that Nothing has no values. There should be a way how to do it without exceptions.

A: You may do that
def emptyFunction[A]: Nothing => A = {n => n}

or
def emptyFunction[A](n: Nothing): A = n


text:
Q: Can I stuff all things in my Object ? In Javascript? I am writing something like this :
Object.prototype.xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : \
                       new ActiveXObject("Microsoft.XMLHTTP");

Then, if I do something like var something = new function(){},  something.xhr.open();. Well, this works. Likewise, I wish I could stuff all the common things in Object, and use them with any object created in the code. I wish to keep availability of the functionality with any object.
My doubt here is will there be memory overhead like all things created for every object created or will there be one copy of all things and they will be used only when they are called by some object ?


text:
Q: How to get WMS URL from a map embedded in a webpage? Objective
I am trying to download the images (or the vector files if possible) from a map embedded in the following webpage https://www4.sii.cl/mapasui/internet/#/contenido/index.html

Context
To see the layers you need to click Catálogo Mapas  and then chose Region, City and layer, for example "XVIII DIRECCION REGIONAL DE ARICA Y PARINACOTA"->"ARICA"->"Predios".
Inspecting the webpage I realized it uses a WMS request, for example: "https://www4.sii.cl/mapasui/services/ui/wmsProxyService/call?service=WMS&request=GetMap&layers=sii:BR_CART_ARICA_WMS&styles=PREDIOS_WMS_V0&format=image/png&transparent=true&version=1.1.1&comuna=1101&eac=0&eacano=0&height=256&width=256&srs=EPSG:3857&bbox=-7825622.9558363445,-2093457.3306744064,-7825317.2023204,-209351.5825612664"
My first attempt was trying to connect to the WMS from QGIS, but I couldn't figure out the correct URL (there is no documentation either). Secondly, I tried to change the parameters of the request, but the image doesn't show when anything is changed.
Question
Any ideas of how to download this layers?
I think the easiest way would be to infer the WMS URL but maybe there are other options.

A: The URL to append request parameters is just:
https://www4.sii.cl/mapasui/services/ui/wmsProxyService/call?

Normally, you would expect a GetCapabilities request to work
like:
https://www4.sii.cl/mapasui/services/ui/wmsProxyService/call?service=WMS&requst=GetCapabilities&

or for specific versions like:
https://www4.sii.cl/mapasui/services/ui/wmsProxyService/call?service=WMS&requst=GetCapabilities&version=1.1.1

but neither of these work, so it may be that the service provider has switched these responses off; possibly they weren't intending anybody else to use the service in their own software clients.  Clients like QGIS need a working GetCapabilities response to know what they can offer to the user; so I think it's unlikely you'll find anything to work with QGIS.
The service is working though to give images, your example request gives:

So possibly you can hand crank some requests for your needs by changing the image size (height=256&width=256&) and bounding box (bbox=-7825622.9558363445,-2093457.3306744064,-7825317.2023204,-209351.5825612664&)
like (bbox=-7825317.2023204,-2093457.3306744064,-7825011.448804455,-209351.5825612664):

A: Try with https://www.npmjs.com/package/wms-downloader with following parameters:
https://www4.sii.cl/mapasui/services/ui/wmsProxyService/call
{
"service":"WMS",
"request":"GetMap",
"layers":"sii",
"styles":"",
"format":"image%2Fpng",
"transparent":"true",
"version":"1.1.0",
"name":"Cadastre",
"height":"256",
"width":"256",
"srs":"EPSG%3A3857"
}


text:
Q: Logic for Moving the columns I have a table as below:

0

1

2

3

4

5

I want to move my rows up and down and I created a function as below
function moveColumn(i){

let next = parseInt(i) + 1;

$('#row' + parseInt(i)).insertAfter($('#row' + next));

}
but the logic doesn't work because if you work with ids and move a column down, then can't click again because now 0 is under 1.(for example)
what would be good logic to move my columns?
is there a way to tell one row to inserAfter the next row using jquery?
UPDATE
Looking for something like
    $('#row' + parseInt(i)).insertAfter($('tr:eq(next)'));

A: Use index and jQuery's .eq() to target elements, and .insertBefore() to move elements.

const moveChild = (from, to, $par) => {
  const $ch = $par.children();
  $ch.eq(from).insertBefore($ch.eq(to));
};

const $par = $("table tbody");
moveChild(4, 0, $par); // move index 4 to index 0
moveChild(3, 1, $par); // and then move index 3 to index 1

0

1

2

3

4

5


text:
Q: Attempting to modify CSV value based on the input received Below is an example of the code, essentially I am taking input received and attempting to modify an existing CSV value. The problem is the code runs and produces the "print" output as expected, but the values are not being modified to "True" or "False" based on the if and else statements:
def test():
    sn_cmn = pd.read_csv('cmn_location.csv')
    wan = re.findall(r'Tunnel12', str(router_output)) or re.findall(r'Tunnel13', str(router_output))
    hostname = re.search(r'...-....-R.', str(router_output))
    hostname_string = str(hostname)
    site_code = hostname_string[-13:-10]

    if wan == ['Tunnel12'] or wan == ['Tunnel13']:
        answer = 'Yes'
        if answer == 'Yes':
            for site in sn_cmn.u_site_code:
                sn_cmn.loc[sn_cmn['u_site_code'] == site_code, 'u_iwan_3'] = 'TRUE'

    else:
        for site in sn_cmn.u_site_code:
            sn_cmn.loc[sn_cmn['u_site_code'] == site_code, 'u_iwan_3'] = 'FALSE'

    sn_cmn.to_csv('new_cmn_location.csv')


text:
Q: How to add lock by id in python There is a function to get the object by the key, the objects is stored in a dict, if key does not exist, then initialize the object according to the key, then put the key and object to the dict, and return the object , How to ensure in the python multi-thread environment The initialization operation is not repeated when it does not exist, and does not block access to other keys.

A: locks with similar to any other programming languages.
from threading import Lock, Thread
lock = Lock()
g = 0

def add_one():
   global g
   lock.acquire()
   g += 1
   lock.release()


text:
Q: iOS: one itemSpace of uicollectionView is 1px but another is 2px, I want the two all 1px? I have a collectionView, in 1 and 2 section I want every itemSpace and lineSpace to be 1px, but the second itemSpace is always 2 px, this is screenshot, I have set collectionView's backgroundColor red, it looks more clearly.
this is screenshot

I set the minimumLineSpacing, minimumInteritemSpacing and itemSize like this:
 - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
        {
            float sortaPixel = 1.0/[UIScreen mainScreen].scale;

            NSLog(@"minimumLineSpacing%f", sortaPixel);

            return sortaPixel;
        }

        - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
        {
            float sortaPixel = 1.0/[UIScreen mainScreen].scale;

            NSLog(@"minimumInteritemSpacing%f", sortaPixel);

            return sortaPixel;
        }

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        if(ISBIND){
            return CGSizeMake(SCREEN_WIDTH, finalTopheight);
        }
        return CGSizeMake(SCREEN_WIDTH, defaultTopheight);
    }

    //This is the calculation process
    float sortaPixel = 1.0/[UIScreen mainScreen].scale;

    NSLog(@"sizeForItem%f", sortaPixel);

    CGFloat itemW = (self.collectionView.frame.size.width - sortaPixel * 2)/3.0;

    CGFloat itemH = 106;

    return CGSizeMake(itemW, itemH);
}

anyone can help me, give me some ideas, I am very grateful.

A:
A combination of having to describe the problem here and a bit of
  subsequent thought caused me to realize that although
  minimumInteritemSpacing is a CGFloat it doesn't make sense to pass it
  fractional values and its behaviour when you do so is undefined.
This is because, on devices where there's a 1:1 point to pixel ratio,
  there is no such thing as half a pixel. It just so happened that in
  some cases it behaved as I expected and thus blinded me to the real
  (and rather obvious) problem.

Hopefully reading this can help others quickly realize the mistake.
See the post to know Float and CGFloat,
Changing an Int to a CGFloat in Swift to return heightForRowAtIndexPath tableview function

A: // AdselecterNamed top border in a view
+ (void)addTopBorderWithColor:(UIView *)view color:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    border.frame = CGRectMake(0, 0, view.frame.size.width, borderWidth);
    border.tag = 1000;
    [view addSubview:border];
}

// Add bottom border in a view
+ (void)addBottomBorderWithColor:(UIView *)view color:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    border.frame = CGRectMake(0, view.frame.size.height - borderWidth, view.frame.size.width, borderWidth);
    border.tag = 1001;
    [view addSubview:border];
}

// Add left border in a view
+ (void)addLeftBorderWithColor:(UIView *)view color:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    border.frame = CGRectMake(0, 0, borderWidth, view.frame.size.height);
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
    border.tag = 1002;
    [view addSubview:border];
}

// Add right border in a view
+ (void)addRightBorderWithColor:(UIView *)view color:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
    border.frame = CGRectMake(view.frame.size.width - borderWidth, 0, borderWidth, view.frame.size.height);
    border.tag = 1003;
    [view addSubview:border];
}


text:
Q: Not getting data in post form i've been trying to get the data in a form with the POST method, but i don't get any, i've been reading a book to learn about expressjs.. this is my form:
<form method="post">

        Username

            <input type="text" class="form-control" id="usernameInput" name="username" placeholder="Enter username">

        Password

            <input type="password" class="form-control" id="passwordInput" name="password" placeholder="Enter password">

                    <input type="checkbox"> Remember me

    <button type="submit" class="btn btn-default">Log in</button>
</form>

and this is my node code.
/*
Chat application for @node.js
express version.
*/

//Load modules.
var express = require('express'),
    http = require('http'),
    socket = require('socket.io'),
    swig = require('swig'),
    fs = require('fs');

//Load config.
console.log('Loading configuration.');
var config = fs.readFileSync('config.json');
var config = JSON.parse(config);
var port = config.port;
var views = config.views;
console.log('Configuration loaded.');

//Initiate express module in app.
var app = express();

//Global vars
var Title = "Node.js Chat";
var result = '';

app.engine('html', swig.renderFile);

//Set view engine.
app.set('view engine', 'html');

//Set the directory for views.
app.set('views', __dirname + '/views');

swig.setDefaults(
{
    cache: false
});

app.get('/', function(request, response)
{
    console.log('GET OK');
    response.render('index',
    {
        'Title': Title,
        'result': result,
    });
});

app.post('/', function(request, response)
{
    console.log('POST OK');
    console.log(request.body);

    response.render('index',
    {
        'Title': Title,
        'result': 'Post detected.',
    });
});

//logger.
app.use(function(request, response, next)
{
    console.log('%s %s', request.method, request.url);

    var file = request.url.slice(1 + request.url.indexOf('/'));

    app.get(request.url, function(request, response)
    {
        response.render(file,
        {
            //Var to be named in the render : value;
            'Title': Title,
            'result': result,
        });
    });

    next();
});

//Set directory for static files (css, js, img)
app.use(express.static(__dirname + '/public'));

//Run the app.
http.createServer(app).listen(port, function()
{
    console.log('Server listening to ' + port);
});

i get "undefined" in request.body, which i dont know why i get this error, i've tried with other methods like request.param, or request.query, but they get nothing, i've made sure the post is detected and its why it sends the message that's being detected, but i want to get the data in the form..

A: You need the now-separate body-parser middleware. Run npm install body-parser or add body-parser to your package.json and npm install it.
Add var bodyParser = require('body-parser'); to your module-loading, then after instantiating your app, add the middleware with app.use(bodyParser());. That will populate req.body for the form.

A: add in app.js:
app.use(express.bodyParser());

As the comment indicated, it depends on the express version.
It works with 3.x as stated above.
For 4.0, you must manually include these frameworks that were previously included. See the note from vision media (overview tab):
https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x
These are NOT included to allow independent updates


text:
Q: Maybe need something other than onClick here a snippet from one of the layouts in my ViewPager.
<android.support.design.widget.TextInputLayout
        android:layout_width="286dp"
        android:layout_height="wrap_content"
        android:id="@+id/textInputLayout2"
        android:layout_marginTop="15dp"
        android:weightSum="1">

        <EditText
            android:id="@+id/email"
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:singleLine="true"
            android:textColor="@android:color/white"/>

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="286dp"
        android:layout_height="wrap_content"
        android:id="@+id/textInputLayout"
        android:layout_marginTop="15dp"
        android:weightSum="1">

        <EditText
            android:id="@+id/password"
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:singleLine="true"
            android:textColor="@android:color/white"
            android:onClick="layoutBuilt"/>

    </android.support.design.widget.TextInputLayout>

And here is the layoutBuild void:
public void layoutBuilt(View view) {
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        inputPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //ACTION DONE
                }
                return false;
            }
        });
}

So my Problem is, that the User must click two times at the Done Button, that it works.
NOTE: It works when I click on the passowordEditText manually and than click Done. When I am clicking on the EmailEditText type in my Email and click Next the passowordEditText will be automatically selected. And when I type in password and click Done. That doesnt work.
Why and how to fix it?
Thanks in advance.

A: Set the android:imeOptions to both of your `EditText.
<android.support.design.widget.TextInputLayout
    android:layout_width="286dp"
    android:layout_height="wrap_content"
    android:id="@+id/textInputLayout2"
    android:layout_marginTop="15dp"
    android:weightSum="1">

    <EditText
        android:id="@+id/email"
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:singleLine="true"
        android:imeOptions="actionNext"
        android:textColor="@android:color/white"/>

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:layout_width="286dp"
    android:layout_height="wrap_content"
    android:id="@+id/textInputLayout"
    android:layout_marginTop="15dp"
    android:weightSum="1">

    <EditText
        android:id="@+id/password"
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:imeOptions="actionDone"
        android:singleLine="true"
        android:textColor="@android:color/white"
        android:onClick="layoutBuilt"/>

</android.support.design.widget.TextInputLayout>

A: So I solved the Problem by myself.
But thanks to @ADM . The onClick won't be called first when the View gets called by Android himself. So I call the layoutBuilt from the ViewPageAdapter in instantiateItem where the new layout already is created.
But thanks for all.


text:
Q: Ms EXCEL: Copy contents of Clicked/Active Cell to another Cell This seems rather an easy task, but somehow nothing has worked since I have tried several solutions to now...
I want something, supposing we have this sheet:

When a Cell is Clicked randomly, the value/contents of that text should be shown in the Orange Box.

That's the first and most important part.

The second thing to happen is:
if possible, all other Cells that contain the same value should be highlighted/shaded with an Green Background (See image)

I have tried:
https://www.ablebits.com/office-addins-blog/2015/02/10/excel-indirect-function/
http://www.contextures.com/xlFunctions05.html
https://support.office.com/en-us/article/Hide-or-display-cell-values-c94b3493-7762-4a53-8461-fb5cd9f05c33
https://support.office.com/en-us/article/CELL-function-51bd39a5-f338-4dbe-a33f-955d67c2b2cf
Thank you in advance.

EDIT 1: PS: Preferably a Non-VB solution. However, if a VB solution would be all there is, then your VB suggestions would be highly appreciated

A: Most of this is answered here so it just needs editing a bit
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
     'Put in your actual range and the cell where you the text to be shown
        If Not Intersect(Target, Range("B5:D17")) Is Nothing Then
            Selection.Copy Destination:=Range("E2")
        End If
    End If
End Sub

and the colouring can just be done with a conditional formatting rule
=B5=$E$2

assuming that the values start in B5 and the text to be displayed is in E2.
If you only want to copy the value and not the formatting to E2, replace
Selection.Copy Destination:=Range("E2")

with
Range("E2").Value = Selection.Value

A:     Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Task1: Show your active cell contents in cell E2
    actval = ActiveCell.Value
    actaddr = ActiveCell.Address
    Range("E2") = actval

    'Task2: Turn all cells green, matching with active cell value, except host cell

    'first set entire background white
    Range("B5:F18").Interior.Color = vbWhite

    'second set all matching cells green
    For Each c In Range("B5:F18")
    If c.Address <> actaddr Then
    If c = actval Then
    Range(c.Address).Interior.Color = vbGreen
    End If
    End If
    Next c
    End Sub


text:
Q: How to checkout latest stable Boost (not development or bleeding edge)? According to Boost Subversion Repository, I can checkout Boost's bleeding edge development with svn co  http://svn.boost.org/svn/boost/trunk boost-trunk.
I'm interested in checking out the latest stable version because I need bcp (bcp is not part of the Boost downloads). I believe the latest version of Boost is Version 1.55.0, but there's no "XXX_1_55" in trunk, tags or branches in the repository (where XXX would presumably be something, like "release").
How do I checkout the latest stable Boost?
Thanks in advance.

A: It seems that the releases are found under tags/releases not trunk.  You could do svn list http://svn.boost.org/svn/boost/tags/release to verify the release you are interested is there.
This is described at Development and Release Practices, where it indicates the URLs for final releases are in the form http://svn.boost.org/svn/boost/tags/releases/xxx, where xxx is a revision like 1_54_0.
The checkout command would be similar to:
$ svn co http://svn.boost.org/svn/boost/tags/release/Boost_1_55_0


text:
Q: Resources inside root Java Dynamic web doesn't load ,JS Css While i'm tring yo include js file it's not working fine
<script type="text/javascript" src="js/bootstrap.js"></script>

I've tried also
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.1.1.min.js"></script>

you can check the project structure as below pic
And i have customized my view resolver to be, Does it will affect the path of resources !!
public class JstlView extends InternalResourceView{
@Override
 protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

 // Expose the model object as request attributes.
 exposeModelAsRequestAttributes(model,request);

 // Determine the path for the request dispatcher.
 String dispatcherPath = prepareForRendering(request, response);

 // set original view being asked for as a request parameter
 request.setAttribute("partial", dispatcherPath.substring(dispatcherPath.indexOf("Tasker/",1) + 1));

// force everything to be template.jsp
 RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/template.jsp");
 requestDispatcher.include(request, response);

 }

Thanks alot ..

A: It's just shot in the dark but did you try also:
<script type="text/javascript" src="/js/bootstrap.js"></script>


text:
Q: Hot to setup Azure Functions with custom Application Insight(Instrumentation key)? For an Azure Function(AF) one can select Application Insights (AI) in Azure Portal. All information put into ILogger in .Net application will be sent to this AI. But in my case AF and AI are running under different accounts. Is there any way to specify a sink for Ilogger using just the Instrumentation key?
I could directly use TelemetryClient from AI libraries, but I am not sure if all information will be sent before AF shuts down, and calling Flush at the end of each function seems wrong.
Edit: Different accounts means, different Active directories.

A: You can directly add the application insights via Application Settings.

*

*Nav to azure portal -> your function app -> Configuration -> Application Settings.

*Then add these 2 settings:
Key name: APPINSIGHTS_INSTRUMENTATIONKEY, and the value is the instrumentation key like xx22-xxdsds333.
key name: APPLICATIONINSIGHTS_CONNECTION_STRING, and the value is InstrumentationKey=the instrumentation key.
Then click the Save button.
The screenshot is as below:

*At last, you can use ILogger to write messages to application insights.


text:
Q: Object variables: Pointers vs References - what's common in languages? I've learned programming in Java at university. The book I read, explained the concept of pointers being used for object variables. Later I checked the actual concepts of pointers & references in C++.
I know these aren't 100% applicable to other high level / scripting languages, but there are recurring patterns that are similar.
When I started learning new languages, I noticed that most of them rely on the concept of storing some sort of object identifier inside a variable. When using an accessing-operator on the object-variable, it will read it, identify the object based on the identifier and access its content. I'd say this comes pretty close to the basic idea of a pointer.
I've confirmed that behavior for PHP and JS.
Example for PHP:
https://www.php.net/manual/en/language.oop5.references.php

When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

However, I often see people mixing up the terms reference and pointer. This started confusing me a little.
Personally, I think pointers are a more elegant way to store objects.
I'd like to know if pointers are actually a common case as object-variable or if references are just as common. Do pointers have notable advantages over references?
It's hard to tell which general concept is being used, because from a programmers perspective, the internals are often abstracted away. But I'd like to have a rough understanding of what's happening under the hood. Not in all detail, but conceptually.

A: At the CPU level, there are pointers (and nothing else except the registers). Therefore, all so called low-level languages must have some pointer mechanism because that's how the internals work. Every variable, function, etc is a pointer at the assembly level.
At the language level however, it's a different story if and how pointers and references are used. If they are implemented in similar way, that's up to the implementation. At the language level, they are different. So you need to learn both. It's not only the concept of a pointer or a reference also, it's the whole process of memory management, variable visibility and lifetime etc.
Suggestion: Start cleanly with a good C++ book and don't take assumptions on anything. Java's memory management is quite different from C++ and C++ 11 and later memory management is also different than earlier versions.


text:
Q: Force exit code zero for windows command line commands How can I force the exit code to be zero for a windows cmd command without changing the way it behaves
The linux equivalent of what is mean is
netstat -an | grep 12035 || true

Something I tried is
C:\>netstat -ano | find "25000" | exit 0

Though it forces exit code 0, it does not show the desired output when successful
Eg:
C:\>netstat -ano | find "25000"
TCP    0.0.0.0:25000          0.0.0.0:0              LISTENING       4832

C:\>netstat -ano | find "25000" | exit 0

Any idea if there is a way?

A: netstat -an | find "25000" || ver>nul

If the find command raises errorlevel, execute a command that resets it., in this case the ver command is used and its output discarded


text:
Q: Pass by value vs pass by reference in java Ok so if primitive data types in java are passed into methods, they are treated as pass by value. And if object data types are passed into methods, they are treated as pass by reference right? So in this code:
//Class 1
public void passByValue(int x){
    x = 0;
}

public void passByReference(Integer y){
    y= 40;
}

//MainClass(contains main method)

    int primitiveType = 50;
    Integer wholeInteger = 100;
    Class1 a = new Class1();

    a.passByValue(primitiveType);
    a.passByReference(wholeInteger);

    System.out.println(primitiveType);
    System.out.println(wholeInteger);

This should result in primitiveType being equal to 50(variable hasnt changed). I understand that, however the Integer object is also not changed... So how does this work? Thanks!

A: Object references are passed by value too. It is the reference that is passed and not the object. You confuse pass-by-reference of the object with pass-by-value of the reference.
In A x = new A() the symbol x is a reference to an object of type A.
If x is a reference and f(A a) { a = null; } is a method then f(x) will not set x to null. Hence, the reference was passed by value.
The reason behind this (and your confusion) is that - to some extend - the phrase "the object is passed by..." is already wrong. Because correctly we have to say "the object reference is passed by...". If A is a class then A a; means that a is a reference to an object of class A. If that is clear, it becomes clear why we have a pass-by-value.

A: First of all there is no pass by reference in java when you pass an object then it's also pass by value...
secondly, like String class , the wrapper class Integer is also immutable...
when you write Integer y= 40 ; then new Object new Integer(40); is being created by autoboxing feature java supports ..
That's why .... there is no change in value of wholeInteger you passed..


text:
Q: PHP DOMnode. How to check if it's pair or not? I have some tags in XML document:
      <kat1>42</kat1>
      <kat2/>
      <kat3/>

and if DOMNode $myNode is "kat2"
$myNode->nodeValue

returns zero instead of null. How to check if it is not paired tag and return NULL if true, else value.
Demo

A: <tag /> is the exact same thing as <tag></tag> so, all you have to do is check whether or not it's empty. If it's empty it wil be printed as a single tag, if it's not empty it will be be printed with both opening and closing tags.


text:
Q: Removing empty nodes from an XML document created by a .builder template I have a problem like What's the cleanest way to ignore empty nodes with Nokogiri::XML::Builder , except that my XML document is generated by a .builder template file using the builder gem.
I'm generating an XML document using the builder gem (and tilt) and I want to get rid of empty nodes.
The answer suggesting just iterating through each attribute and deciding whether to serialise each attribute or not isn't very suitable to my application, because there's quite a lot of logic involved in building the XML document.
The answer suggesting the use of Nokogiri::XML::Node#traverse doesn't look bad, but I suspect this approach isn't supported by the builder gem. The documentation for builder says

An Builder::XmlTree class to generate XML tree (i.e. DOM-like)
  structures is also planned, but not yet implemented. Also, the events
  builder is currently lagging the markup builder in features.

(I'm not sure if the quoted section is equivalent to Nokogiri::XML::Node#traverse, but it does at the least suggest that there's some functionality not available in Builder)
Also, searching for some sort of remove method doesn't get a match in the git repository.
The builder gem, as of 2017, is largely abandoned. The master branch last had a commit in June 2013, and there's only been a handful of commits in forks since then. Tilt's mention of maintenance only refers to the maintenance of integration between tilt and builder.
Are there any gems that support the .builder format other than the builder gem?
Do I have any alternatives other than adding a lot of if title or if feed conditionals to the .builder file, or once I've created the XML, feeding it through an unrelated XML parser?


text:
Q: getting TypeError: el is null .../ext/ext-all-debug-w-comments.js Line 44393 when loading grid a second time I'm using a panel called "content panel" in the center of a border layout of my viewport.
I swap content in and out as needed by click handlers against the menu buttons. The second time I swap in this grid it gives this error. This is the only grid that does it in the app and the only grid that has a paging bar. I know the error has something to do with the paging bar being rendered. What am I missing?
controller (changes is the button that's failing):
Ext.define('DDI.controller.DDI', {
extend : 'Ext.app.Controller',

views : [ 'panel.BannerPanel', 'panel.ContentPanel', 'panel.NavPanel', 'panel.FooterPanel', 'Welcome' ],

init : function() {

this.control({
    'navpanel button[text=Home]' : {
    click : function() {
        var cp = Ext.getCmp('contentpanel');
        cp.removeAll();
        cp.add({
        xtype : 'welcomepanel'
        });
    }
    },
                    ...
    'navpanel button[text=Changes]' : {
    click : function() {
        var cp = Ext.getCmp('contentpanel');
        var height = Ext.getBody().getViewSize().height - 100;
      //  cp.removeDockedComponent(cp.getDockedComponent(0));
        cp.removeAll(false);
        cp.add({
        xtype : 'changesummaryview',
        height : height
        });
        cp.doLayout();
    }
    },
                     ....

The grid panel is defined as such:
var changeStore = Ext.create('DDI.changetracker.store.Change');
Ext.define('DDI.changetracker.view.ChangeSummaryView', {
extend : 'Ext.grid.Panel',
alias : 'widget.changesummaryview',
id : 'changesummaryview',
title : 'All Change Summary',
scroll : 'both',
store : changeStore,
tbar : [
      'Open Change Summary View',
      '-',
      {text : 'New Change'
      }, {
     xtype : 'button',
     text : 'Print'
      },
      '->',
      {xtype : 'exporterbutton'
      }
],
bbar : Ext.create('Ext.PagingToolbar', {
store : changeStore,
displayInfo : true
}),

listeners : {
'render' : function(grid) {
    grid.view.tip = Ext.create('Ext.tip.ToolTip', {
    target : grid.getEl(),
    showDelay : 2000,
    // Each grid row causes its own seperate show and hide.
    delegate : ".x-grid-cell",
    items : [], // add items later based on the record
    // Render immediately so that tip.body can be referenced prior
    // to the first show.
    listeners : {
        // Change content dynamically depending on which element
        // triggered the show.
        beforeshow : function updateTipBody(tip) {
        var rec = grid.view.getRecord(
                        Ext.get(tip.triggerElement).findParentNode('.x-grid-row'));
        grid.fireEvent('rowhover', tip, rec);
        return true;
        }
    }
    });
}
},
columns : [
    {
    header : 'ticket',
    dataIndex : 'ticket',
    filter : {
        type : 'string'
    },
    flex : 1,
    editor : 'textfield'
    },
    {
    header : 'account_name',
    dataIndex : 'account_name',
    flex : 1,
    editor : {
        xtype : 'customercombo',
        fieldLabel : ''
    }
    },
    {
    header : 'employee_1',
    dataIndex : 'employee_1',
    flex : 1,
    editor : {
        xtype : 'personelcombo',
        fieldLabel : '',
        valueField : 'name'
    }
    },
    {
    header : 'dns_team_approved',
    dataIndex : 'dns_team_approved',
    filter : {
        type : 'string'
    },
    flex : 1,
    editor : {
        xtype : 'dnsapprovecombo',
        fieldLabel : ''
    }
    },
    {
    header : 'approval_status',
    dataIndex : 'approval_status',
    flex : 1,
    editor : {
        xtype : 'approvalstatuscombo',
        fieldLabel : ''
    }
    },
    {
    header : 'status',
    dataIndex : 'status',
    flex : 1,
    filter : {
        type : 'list',
        options : [ [ '%', 'All' ], [ 'OPEN', 'OPEN' ], [ 'HOLD', 'HOLD' ], [ 'CLOSED', 'CLOSED' ],
            [ 'CANCELED', 'CANCELED' ] ],
        value : '%',
        active : true,
        single : true
    },
    editor : {
        xtype : 'statuscombo',
        fieldLabel : '',
        store : 'Status'
    }
    }, {
    header : 'open_date',
    dataIndex : 'open_date',
    flex : 1,
    editor : 'textfield'
    }, {
    header : 'next_check',
    dataIndex : 'next_check',
    flex : 1,
    editor : 'textfield',
    renderer:function(value, metadata, record, rowIndex, colIndex, store){
        a=value.split(" ");
        d=a[0].split("-");
        t=a[1].split(":");
        dateValue=new Date(d[0],d[1]-1,d[2],t[0],t[1],t[2]);
        today=new Date();
       if (dateValue <= today){
        return ''+value+'';
        }
       return value;

    }
    }, {
    header : 'start_time',
    dataIndex : 'start_time',
    flex : 1,
    editor : 'textfield',
    renderer:function(value, metadata, record, rowIndex, colIndex, store){
        a=value.split(" ");
        d=a[0].split("-");
        t=a[1].split(":");
        dateValue=new Date(d[0],d[1]-1,d[2],t[0],t[1],t[2]);
        today=new Date();
       if (dateValue <= today){
        return ''+value+'';
        }
       return value;

    }
    }, {
    header : 'end_date',
    dataIndex : 'end_date',
    flex : 1,
    editor : 'textfield'
    }, {
    header : 'is_expedited',
    dataIndex : 'is_expedited',
    flex : 1,
    editor : 'textfield'
    } ],
features : [ {
ftype : 'filters',
encode : false,
local : false
} ],
plugins : [ {
ptype : 'cellediting',
clicksToEdit : 2,
pluginId : 'cellediting'
} ]


text:
Q: Terrain streaming in unity 3d I am making an open world game and i want to know if there is a way of doing terrain streaming ( loading the terrain into mamory only if the player is close to it ) without using the LoadLevelAdditiveAsync function . i am using free version so this function is not available to me .

A: Don't forget as long as your terrain patches together nicely, you can always Instantiate terrain prefabs at run time.
Depending on how proficient you are at it, you can also procedurally create terrain at run time as well.

A: You can do it, and there are different ways to do it. I figure the easiest way to do it (but definitely not the most memory friendly) would be to define your entire level in one scene with multiple small terrains, using the TerrainStitcher tool to deal with seams. Then you could parent all objects under each terrain to a single transform, and use Instantiate to create/destroy them at runtime (in another scene). There are tools that take this approach a bit further, like this one.
But remember that in general big terrains in Unity aren't memory friendly and will reduce your performance. When using an endless terrain, where you don't care about defining the terrain before runtime you can reuse a few terrain objects and simply reposition them, but if you're designing them first, there isn't too much you can do other than lowering terrain settings like Pixel Error, and limiting details and grass.


text:
Q: Create trigger to run procedure to check limits So what im trying to do is to check if variables are within range. Basically i have sensors that measure something (measure_Variable) so for exaple sensorID:1 is measuring temperature, sensorID:2 is measuring humidity etc.
I have another table for records where sensors post data.
I have one more table which is measure_type. Over there are stored the limits. What i want to do is to check the value of the record, and if its within the limits then update table validity column record_validity with 1. Else update with 0.
I've created a procedure which kinda works but I cannot pass the value to the other table called validity.
SELECT recordId,value,measure_variable,limit_min,limit_max FROM records,sensors,measure_type WHERE records.value BETWEEN measure_type.limit_min AND measure_type.limit_max GROUP BY(records.recordId)
Any ideas would be highly appreciated!
DB_Schema_Picture


text:
Q: How to capture who ran the pipeline in Azure DevOps How to capture who ran the build pipeline in Azure DevOps as a variable?
Is there any predefined variable to capture that?

A: From the docs:
Build.QueuedBy - See "How are the identity variables set?".
Note: This value can contain whitespace or other invalid label characters. In these cases, the label format will fail.
Build.QueuedById - See "How are the identity variables set?".

A: Yes, its called: "Build.QueuedBy"
https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables


text:
Q: Google App Script arrays I'm working on Google Script and I'm testing different ways to create two dimensions arrays.
I have created an array like this:
  var codes = new Array(6);
  for (var i = 0; i < 6; i++) {
  codes[i] = new Array(4);
  }
  codes[0][0]="x";
  codes[0][1]="x";
  codes[0][2]="x";
  codes[0][3]="x";
  codes[1][0]="x";
  codes[1][1]="x";
  codes[1][2]="x";
  codes[1][3]="x";
  codes[2][0]="x";
  codes[2][1]="x";
  codes[2][2]="x";
  codes[2][3]="x";
  codes[3][0]="x";
  codes[3][1]="x";
  codes[3][2]="x";
  codes[3][3]="x";
  codes[4][0]="x";
  codes[4][1]="x";
  codes[4][2]="x";
  codes[4][3]="x";
  codes[5][0]="x";
  codes[5][1]="x";
  codes[5][2]="x";
  codes[5][3]="x";

And it is working fine.
I read following links here, here and here.
But when I do it like this:
var codes = new Array(6);
  for (var i = 0; i < 6; i++) {
  codes[i] = new Array(4);
  }
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];

It didn't work, so I tried like this:
var codes = new Array([["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"]]);

it didn't work either.
When the code don't work, I get no error, just no display of the values.
What am I doing wrong? It looks to be the same code and the two not working ways are recommended in many documentations.

A: W3schools says that there is no need to use new Array().
For simplicity, readability and execution speed, use literal method ex:
var animals = ["cat", "rabbit"];
Reason why your code was not working is that you're equaling codes inside the loop and after end of loop scope 'codes' is getting only the last set array. Instead you should push those arrays to codes.

var codes = [];
for (var i = 0; i < 6; i++) {
  codes.push([i]);
}
console.log(codes)
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];

A: Better yet, two for loops to create the double array:
var codes = [], // Initiate as array, in Javascript this is actually fastre than using new (I don't know any cases you should use new)
    rows = 6,
    columns = 6;

for (var i = 0; i < rows; i++){
    codes.push([]); // Initiate
    for (var j = 0; j < columns; j++){
        codes[i][j] = 'x';
    }
}

Other idea, pre-initiate an array with the correct columns then copy:
var arrTemp = [],
    codes = [],
    rows = 6,
    columns = 6;

for (var j = 0; j < columns; j++)
    arrTemp[i] = 'x';

for (var i = 0; i < rows; i++)
    codes.push( arrTemp.slice(0) ); // If you just push the array without slice it will make a reference to it, not copy

Other way to pre-initiate the array with 'x's:
arrTemp = Array.apply(null, Array(columns)).map(function () {return 'x'});