text:
Q: How to make tableview delegates disappear behind margins / headers? After adding a custom header to a tableview in qml, I need to make the delegate items in the table disappear as they scroll up to the bottom of the header.
With the header in place, I've also added a topMargin to the tableview so that the header is above the delegates when the table is first drawn. When the table is scrolled, the delegate items scroll behind and above the header before they disappear.
I've tried adjusting the visible and opacity parameters of the delegate based on their position relative to the header, but it appears there is no signal triggering the position values to be re-evaluated. They continue to scroll up past the header without disappearing.
Therefore, I've also tried to use the onMovementEnded function within TableView to force the values to refresh when the table stops scrolling. However, it is not picking up the id of the delegate.
QML
TableView with header definition
TableView {
    id: xyztable
    columnWidthProvider: function (column) { return width / columns; }
    rowHeightProvider: function (column) { return 20; }
    topMargin: columnsHeader.height + 20
    Layout.rowSpan: 4
    Layout.fillHeight: true

    model: XYZTableModel
    width: 350
    boundsMovement: Flickable.StopAtBounds
    boundsBehavior: Flickable.DragOverBounds
    opacity: Math.max(0.5, 1.0 - Math.abs(verticalOvershoot) / height)

    delegate: CustomComp.XYZTableDelegate {
        id: localdelegate
        implicitWidth: parent.width / xyztable.columns
        implicitHeight: 20
    }

    Rectangle { // mask the headers
        id: columnsHeader
        z: 2
        color: "#222222"
        y: xyztable.contentY - 20
        x: xyztable.contentX
        width: xyztable.width
        height: 30
    }

    Row { // create header content
        id: columnsHeaderContent
        y: xyztable.contentY
        z: 3
        Repeater {
            model: xyztable.columns > 0 ? xyztable.columns : 1
            Label {
                width: xyztable.columnWidthProvider(modelData)
                height: xyztable.rowHeightProvider(modelData) * 2
                text: XYZTableModel.headerData(modelData, Qt.Horizontal)
                color: 'white'
                font.pixelSize: 15
                padding: 10
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter

                background: Rectangle { color: "#333333" }
            }
        }
    }

    ScrollIndicator.horizontal: ScrollIndicator { }
    ScrollIndicator.vertical: ScrollIndicator { }
}

Adjust visible within delegate
delegate: CustomComp.XYZTableDelegate {
    id: localdelegate
    implicitWidth: parent.width / xyztable.columns
    implicitHeight: 20
    visible: localdelegate.mapToItem(columnsHeader, 0, y).y < columnsHeader.height ? false : true
}

Adjust visible onMovementEnded
onMovementEnded: {
    localdelegate.visible = localdelegate.mapToItem(columnsHeader, 0, localdelegate.y).y < columnsHeader.height ? false : true
}

I expected that the delegates would disappear after they passed the bottom of the header during scrolling. However, they still scrolled up past the header. While adjusting the visible parameter within delegate, I did see the table get shifted downwards by about 6 delegate heights when the table was scrolled back to its original position.

A: After an extensive effort, I still hadn't found a way to turn the visibility of the table delegates to false as they moved past the bottom of the header. The closest I got was adjusting their values within the TabelView onMovementEnded handler by looping through the children of the TableView.contentItem.children. However, the visible parameter would only be changed when the table stopped moving.
Instead, I moved away from trying to manipulate the delegates, and simply began adjusting the header position. I moved the header a negative y value from the tableView.contentY location. Then I adjusted the topMargin value accordingly. This results in a header shifted far enough beyond the top of the flickable content that the content does not breech the top of the header when scrolling.
import QtQuick 2.12
import QtQuick.Controls 2.12

TableView {
    id: tableView

    property var yposition: 20

    columnWidthProvider: function (column) { return width / columns; }
    rowHeightProvider: function (column) { return 20; }
    topMargin: columnsHeaderContent.height - yposition

    boundsMovement: Flickable.StopAtBounds
    boundsBehavior: Flickable.DragOverBounds
    opacity: Math.max(0.5, 1.0 - Math.abs(verticalOvershoot) / height)

    Row { // create header content
        id: columnsHeaderContent
        y: tableView.contentY - tableView.yposition
        z: 2
        height: tableView.rowHeightProvider(modelData) * 2
        Repeater {
            model: tableView.columns > 0 ? tableView.columns : 1
            Rectangle {
                width: tableView.columnWidthProvider(modelData)
                height: tableView.rowHeightProvider(modelData) * 2
                Label {
                    id: columnsHeaderLabel
                    z: 1
                    width: tableView.columnWidthProvider(modelData)
                    height: tableView.rowHeightProvider(modelData) * 2
                    text: tableView.model.headerData(modelData, Qt.Horizontal)
                    color: 'white'
                    font.pixelSize: 15
                    padding: 10
                    verticalAlignment: Text.AlignVCenter
                    horizontalAlignment: Text.AlignHCenter

                    background: Rectangle { color: "#2A2C35" }
                }

                Rectangle {
                    color: "#000000"
                    y: tableView.rowHeightProvider(modelData) * 2 - 5
                    z: 2
                    height: 5
                    width: parent.width
                }
            }
        }
    }

    ScrollIndicator.horizontal: ScrollIndicator { }
    ScrollIndicator.vertical: ScrollIndicator { }
}


text:
Q: TextView wont show Html I created an activity where I have there a TextView to display Terms and Conditions.
In order to do so, I write in Html.
For example I tried this:
<string name="Terms_Title">

2. Use License

Permission is granted to temporarily download one copy of Apps per device for personal, non-commercial transitory viewing only. This is the grant of a license, not a transfer of title, and under this license you may not:

modify or copy the materials;

use the materials for any commercial purpose, or for any public display (commercial or non-commercial);

attempt to decompile or reverse engineer any software contained in Apps;

remove any copyright or other proprietary notations from the materials; or

transfer the materials to another person or "mirror" the materials on any other server.

This license shall automatically terminate if you violate any of these restrictions and may be terminated by Apps Team at any time. Upon terminating your viewing of these materials or upon the termination of this license, you must destroy any downloaded materials in your possession whether in electronic or printed format.

</string>

and the result is:

I tried also to use:
tv_Terms = findViewById( R.id.tv_Terms );
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    tv_Terms.setText( Html.fromHtml(getString( R.string.Terms_Title ), Html.FROM_HTML_MODE_COMPACT));
} else {
    tv_Terms.setText(Html.fromHtml(getString( R.string.Terms_Title )));
}

But it just doesnt work.
Any Ideas?

A: TextView is not a HTML browser. Also Html class docs clearly state that magic won't happen either:

This class processes HTML strings into displayable styled text. Not all HTML tags are supported.

If you need richer HTML support use WebView instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex for Input Validation in PHP I need a Regex to accept the input only following possible cases like
1.It start with characters only [a-zA-Z]
2.It may contains numbers but it may not repeated 3 or moretimes.
Example:
akjsjdfljsfjl133113 Valid
123123sfsf        not valid
asfsdf1111asdf      notvalid
adf111              not valid
I have tried this code
$input_line="sfjs123232";
preg_match("/^[a-zA-Z](\d)\1{2,}/", $input_line, $output_array);

A: You can use a Negative Lookahead here.
^[a-zA-Z]+(?:(?!.*(\d)\1{2,}).)*$

See Live demo
Regular expression
^                the beginning of the string
[a-zA-Z]+        any character of: 'a' to 'z', 'A' to 'Z' (1 or more times)
(?:              group, but do not capture (0 or more times)
 (?!             look ahead to see if there is not:
  .*             any character except \n (0 or more times)
  (              group and capture to \1:
   \d            digits (0-9)
  )              end of \1
   \1{2,}        what was matched by capture \1 (at least 2 times)
  )              end of look-ahead
  .              any character except \n
 )*              end of grouping
$                before an optional \n, and the end of the string


text:
Q: what does the following tag mean [cc lang="php"] I have been trying to learn php streams and I've come across this sentence which looks like it is doing the job of the php opening tag, could you please explain me what it is, or provide me with documentation, here is the code:
 [cc lang="php"]$opts = array(
     'http' => array(
     'method' => "GET",
     'header' => "Accept-language: en\r\n" .
     "Cookie: foo=bar\r\n"
   )
 );

A: This is not a PHP code, it's just an example with syntax highlighting for a WordPress blog, so you can add some nice colored Code Snippets in different (not only PHP) languages to your blog page. Thats's code coloring (syntax highlight) from WordPress or a WordPress plugin
Example:
[cc lang="php"]
  some php code
[/cc]

Here is a link with more information about it.
If you want to make your code highlighting work, you have to add the closing tag [/cc]
[cc lang="php"]
$opts = array(
     'http' => array(
     'method' => "GET",
     'header' => "Accept-language: en\r\n" .
     "Cookie: foo=bar\r\n"
   )
 );
[/cc]


text:
Q: ¿Cómo genero un LOGIN automatico? Quiero que la procedure me cree un usuario a partir del dni y una contraseña (con la primera letra del nombre y el tipo(que es tipo integer asi que 0,1,2).
Me da un error de SQL statement ignored y "TIPO" identificador no válido.
CREATE OR REPLACE PACKAGE BODY Proyecto1718 IS
              PROCEDURE generarLogin (v_dni IN VARCHAR , v_nombre IN VARCHAR, v_tipo IN VARCHAR) AS
                usuario VARCHAR(15);
                pass VARCHAR(15);
              BEGIN
                usuario := LOWER(v_dni);
                pass := LOWER(substr(v_nombre, 1, 1) || v_tipo);
                 INSERT INTO login (usuario, contraseña, tipo) VALUES (usuario, pass, v_tipo);
              EXCEPTION
                WHEN OTHERS THEN
                  RAISE_APPLICATION_ERROR (-20100, 'ERROR INESPERADO AL GENERAR EL LOGIN - USUARIO/CONTRASEÑA: '|| SQLERRM);
              END generarLogin;
            END Proyecto1718;

//TABLA DE LOGIN
CREATE TABLE Login (
  id_login INTEGER
    GENERATED ALWAYS AS IDENTITY
                      MINVALUE 1
                      MAXVALUE 999999
                      INCREMENT BY 1
                      START WITH 1
                      NOORDER NOCYCLE NOT NULL
                      ENABLE
           CONSTRAINT id_lo_pk PRIMARY KEY,
  usuario VARCHAR(15) NOT NULL,
  contraseña VARCHAR(15) NOT NULL,
  id_persona INTEGER NOT NULL,

  CONSTRAINT id_per_fk FOREIGN KEY (id_persona) REFERENCES Persona (id_persona));

A: Te comento lo que he visto:

*

*No veo que exista en la tabla el campo 'tipo'. Es obvio que si el campo no existe no lo puedas guardar. Crea el campo primero o quítalo del insert si no lo quieres guardar.

*¿Tienes triggers que afecten a esta tabla?
2.1. Si, tengo triggers: ¿El trigger rellena el campo id_persona? Si no es el caso, debes añadir a tu insert dicho campo, ya que lo tienes declarado como NOT NULL.
2.2. No, no tengo triggers: Tienes dos opciones; crear un trigger para que lo rellene o, como he indicado en el apartado 2.1, añadir al insert el campo id_persona.

*Esto no es un error, es un consejo. Dentro de la medida de lo posible, intenta siempre declarar los campos del tipo de la tabla. Por ejemplo, el parámetro de entrada v_dni lo declaras como tipo VARCHAR. Si en lugar de eso lo declaras de tipo login.usuario también se declarará como un VARCHAR, pero si cambias el tipo de campo a VARCHAR(50), no tendrás que modificar tu procedimiento porque ya toma directamente el tipo del campo de la tabla. Sería de la siguiente manera:

PROCEDURE generarLogin (v_dni IN login.usuario%TYPE, ...

Y lo mismo con la variable usuario

usuarion login.usuario%TYPE;

En principio con estos cambios debería funcionar. Pruébalo y comenta a ver que tal.


text:
Q: Finding points equidistant from the corners of a convex polygon in plane Let $Z_1, Z_2,......,Z_n$ be the no corners of convex polygon in the argand  plane. We may assume $Z_k=(x_k,y_k), k=1,2,3,..,n$ .Is it possible to find the points inside the polygon which are equidistant from the corners?  I remain obliged for any help .

A: In general no. Such a point would be the circumcentre of every triangle with vertices among the $Z_j$s. In general these circumcentres won't be the same. There are special cases (rectangles, regular polygons etc.) where they will be the same, though.

A: Take the circumcenter $C$ of the triangle $\triangle Z_1Z_2Z_3$. It either is equidistant from all corners or it isn't. If it is, then the set of all points equidistant from all corners is $\{C\}$; otherwise, it is the empty set.


text:
Q: I want to apply different item alignment in flex box This is my current code.

.d-flex {
  display:flex;
}

.flex-column {
  flex-direction: column;
}

.align-items-center {
  align-items: center;
}

centered content1

centered content2

I want to be this content to be left-aligned

centered content3

...

I can resolve this by adding a custom class to the desired div but I want to resolve this by only flex operation.
This means I want to resolve this by only using Bootstrap flex classes.
Is this possible?
Or are there any other easy solutions?

A:

.d-flex {
  display:flex;
}

.flex-column {
  flex-direction: column;
}

.align-items-center {
  align-items: center;
}

centered content1

centered content2

I want to be this content to be left-aligned

centered content3

...


text:
Q: Sql Server String Comparision Is there any information as to how SQL Server compares strings and handles searching in them (like statments)?  I am trying to find out if there is a way to determine how efficient it is to store information as a large string and use sql server to do a bunch of comparisons on rows to determine which match.  I know this is potentially going to be slow (the each string of information would be 2400 characters long), but I need something doucmenting how the string is compared, so I can show the efficency (or inefficency) of it.

A:
each string of information would be 2400 characters long

Exactly 2400?  So you've got fixed-width fields in there?  Save your time and just split it into separate columns.  You'll thank yourself later.
If you must have data, set up a test db and try it both ways.  Then at least you'll have data that's specific to your system.

A: searching in them will be slow because you won't be able to create an index since an index can't be over 900 bytes long/wide
I would do what Joel Coehoorn suggests and split it up into columns
you also might want to split it up in more tables because you can only store 3 rows pr page with 2400 chars per row

A: There are full text search indexes that you can apply to sql server, which are often used for things like search engines. The full text indexes typically allow for boolean logic operators for the search.

A: Just additional information to the already mentioned. If you need to filter the large string with like, indices are also not used (except the wildcard % is only at the end of the search string). So it's best to avoid like and make the part you need to filter for available in an own field.

A: In the MSDN Article about Full-Text searches the following is called out regarding how the LIKE predicate uses character patterns.

Comparing LIKE to Full-Text Search
In contrast to full-text search, the LIKE Transact-SQL predicate works
  on character patterns only. Also, you cannot use the LIKE predicate to
  query formatted binary data. Furthermore, a LIKE query against a large
  amount of unstructured text data is much slower than an equivalent
  full-text query against the same data. A LIKE query against millions
  of rows of text data can take minutes to return; whereas a full-text
  query can take only seconds or less against the same data, depending
  on the number of rows that are returned.


text:
Q: How to locate the real file with exception When my app is crashed, nestjs handled a exception, but i cannot get the real problem file
Exception Stack:
[Nest] 17946   - 4/18/2018, 5:00:56 PM   [ExceptionsHandler] duplicate key value violates unique constraint "uk_app_name"
QueryFailedError: duplicate key value violates unique constraint "uk_app_name"
    at new QueryFailedError (.../src/error/QueryFailedError.ts:7:9)
    at Query.<anonymous> (.../src/driver/postgres/PostgresQueryRunner.ts:216:26)
    at Query.handleError (.../node_modules/pg/lib/query.js:143:17)
    at Connection.connectedErrorHandler (.../node_modules/pg/lib/client.js:132:26)
    at Connection.emit (events.js:180:13)
    at Connection.emit (domain.js:422:20)
    at Socket.<anonymous> (.../node_modules/pg/lib/connection.js:117:12)
    at Socket.emit (events.js:180:13)
    at Socket.emit (domain.js:422:20)
    at addChunk (_stream_readable.js:274:12)

the ... is my work dir
how do i know which file the exception from

A: The exception is thrown in PostgresQueryRunner.js, which is, not your codebase.
Your app tried to insert a duplicate value in a table column indexed as unique, in your PgSQL database.


text:
Q: Django rest framework: checking IF employee.SSN exits then let employee complete the sign up the account First
I extend the User model and make it Custom for my needs and here is the model
class User(AbstractBaseUser, PermissionsMixin,TrackingModel):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Username and password are required. Other fields are optional.
    """
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(_('email address'),blank=False, unique=True,error_messages={'unique':'A user with that email already exists.'})
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    objects = MyUserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    @property
    def token(self):
        return ''

Second
I have another Model Employee which has a one-to-one relation with User_Model.
class Employee(models.Model):
    gender = (('m','male'),('f','female'),('n','notset'),)
    ssn =models.CharField(max_length=14,validators=[MinLengthValidator(limit_value=14)],unique=True,null=True,)
    fname = models.CharField(max_length=200,null=True,blank=True)
    lname = models.CharField(max_length=200,null=True,blank=True)
    six = models.CharField(max_length=1,choices=gender,default='n')
    img =  models.ImageField(upload_to='employee/',null=True,blank=True)
    user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True)

    def __str__(self):
        return self.fname

What I need:

*

*the admin Add just the Employee SSN

*then when employee go to registration form, it ask him to verify SSN

*if alraedy SSN added by admin

*then let him complete employee_info(fname,lname,img,six) and user_info(username,email,password)

*else send message "ask admin to add you" (admin just add the SSN)

*Finally, the employee login with normal Email,password to the whole system

Do I need Two tokens?

*

*One for Complete signup after verifying Employee.SSN

*another to log in to the system

This is my first Time Working with API.

A: You can check via Employee.objects.filter(SSN=your_ssn).exists() to see if SSN exists or not.


text:
Q: Shared variables in ASP.NET I'm Confused? I'm a little confused... Im having trouble with my web application. Im building a system that generates quotes for customers. The customer requests a quote then multiple generated quotes can be sent out to them based on the original request.
In my .vb file I have:
Partial Class NewQuote
Private Shared GeneratedQuoteIDArray As New ArrayList

this GeneratedQuoteIDArray is then accessed and built up from several Protected Sub's.
I'm having difficulty in multi user environment. If someone is working on the same page the GeneratedQuoteIDArray is holding both users values :S.
Please help... I'm sure im just doing something stupid!

A: Shared means that it's a static value which is attached to the definition of the class itself, not to any particular instance of it.  So there's only one within the context of the application.  That's why other code paths would change the same value and over-write each other's values.
It sounds like you're looking for an instance value, not a static value.  Like this:
Private GeneratedQuoteIDArray As New ArrayList

That way it'll be attached to any new instance of the class and private only to that instance.  So separate requests with separate instances will have separate values.
You can read more about Shared members here, as well as many other places.  When researching this topic, the keywords you're looking for are "static vs. instance" in terms of variables, functions, etc.  You'll likely find a lot of C-style code explaining it, but you can think of it the same way in VB.  VB just calls it Shared instead of static.

A: Keep per-user data somewhere either in Session or in Cookie.


text:
Q: Hawaii and article "the" I thought names of archipelagos are always used with article the. Like in the example:

Germans love to take beach holidays in countries like the Maldives,
  the Bahamas and the Dominican Republic.

However I encountered the example where the rule seems to be ignored:

When I went to Hawaii, my favorite island was Kauai.

Apparently I don't know how to use the article with names of chain of islands. So I would like you to teach me.
P.S. At first I thought maybe Hawaii is not considered an archipelago because it might be a part of some bigger island chain but wikipedia actually states that it is an archipelago in its own right: https://en.wikipedia.org/wiki/Archipelago

A: Archipelago names that are plural are preceded by "the" (e.g. the Maldives, the Philippines), while names that are singular are not (e.g. Samoa, Hawaii).
A good list of commonly accepted countries preceded by "the" can be found here.
"The" is also generally used in the formal names of countries. For example, the formal name of China is "the People's Republic of China". The formal name of Samoa is "the Independent State of Samoa".

A: Be careful of anything that says always or never regarding use of articles, or pretty much anything about English. That said,   one says the Hawaiian Islands.
Hawaii
is the name of one of the islands in the island chain. It is also the name of the state.  Some people  also use it as a nickname for the island chain.

A: The Hawaiian Islands are generally refered to as Hawaii because together, the make up the State of Hawaii. Hawaii is also the largest and most visited of the islands, so people could often be referring to the specific island where the most likely stayed on their trip for example.
As for the archipelago rule, there is no such thing. Using the article "the" before a group of islands is only used to describe the group as a whole, where as if you were to only say "Hawaiian islands" you could be reffering to any number of them. Because Hawaii (the state) is a region that encompasses all and only all of the islands, it works.


text:
Q: Animation flickering in ANDROID I am trying to implement something relatively simple in ADNROID. I have a bunch of Drawables stored in a list. I want to create an effect where the drawables are displayed on top of each other, one by one, using a fade-in effect.
I have had partial success with the code below. It actually works flawlessly on my phone (Nexus S), but it shows flickering on my tablet (ASUS TF101). This is probably due to the fact that the tablet has a faster CPU.
Here is my setup: I have stored all the Drawables in the drawables list. I have also defined two images in my layout, one on top of the other: imageViewForeground and imageViewBackground.
The idea is to set the background image first, then start an animation where the foreground image starts from alpha-0 and goes to alpha-1. Then replace the background with the new foreground image, choose a new foreground (i.e. the next drawable) and loop forever.
The counter object is a simple wrapper for an int counter.
Here is my code:
final Animation fadeInAnimation = new AlphaAnimation(0f, 1f);
fadeInAnimation.setDuration(2000);
fadeInAnimation.setStartOffset(3000);
fadeInAnimation.setFillBefore(false);
fadeInAnimation.setFillAfter(true);
fadeInAnimation.setRepeatCount(Animation.INFINITE);
fadeInAnimation.setRepeatMode(Animation.RESTART);
fadeInAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {
        imageViewForeground.setImageDrawable(drawables.get(counter.value()));
        Log.d(TAG, "onAnimationStart");
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        Log.d(TAG, "onAnimationEnd");
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        imageViewBackground.setImageDrawable(drawables.get(counter.value()));
        counter.increase();
        // the problem appears in this line,
        // where the foreground becomes visible for a very small period,
        // causing the flickering
        imageViewForeground.setImageDrawable(drawables.get(counter.value()));
    }
});

imageViewForeground.startAnimation(fadeInAnimation);

Any ideas how I can overcome this flickering problem?


text:
Q: Mysql Date fomat I have a date format coming from CSV file. The format looks like "2013/01/01 9:47 PM". I want to save that information into timestamp. How can I achieve that using MySQL query.

A: Try with
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
UPDATE field SET new_date = UNIX_TIMESTAMP(old_date)

A: mysql> SELECT UNIX_TIMESTAMP('2013/01/01 9:47 PM');

Here is the usefull link http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_unix-timestamp

A: in insert use this as value for desired column:
 UNIX_TIMESTAMP(STR_TO_DATE('2013/01/01 9:47 PM'))

A: I think this will help You,please go through http://blogs.msdn.com/b/ssma/archive/2011/06/15/converting-mysql-str-to-date-function.aspx

A: SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')

SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

A: //In PHP
$date = new DateTime('2013/01/01 9:47 PM');
echo $date2 = $date->format('Y-m-d H:i:s');

//output
2013-01-01 21:47:00

A: I got my answer
"select str_to_date('2013/01/01 9:47 PM','%Y/%m/%d %h:%i %p')"  :)


text:
Q: CSS Absolute Positioning and Z-index on top With the following simplified code,

$("[data-position]").each(function() {
  $(this).css({
    position: 'absolute',
    left: $(this).data('position')[0] + '%',
    top: $(this).data('position')[1] + '%',
  })
});
ul         {position: relative;
            width: 15em;height: 15em;
            background: #0af;
            list-style: none}
strong,em  {padding: .5em}
strong     {background: #000; color: #fff;z-index:50}
em         {display: none;background: #fff;z-index:-1}
li:hover em{display: block}

    A
    This is an ay

    B
    This is a bee

    C
    This is a see

The :hover-displayed element gets hidden by following siblings.
I tried to look at many similar questions and answers on this website but could not come up with an interesting answer. Changing the z-index or opacity levels do not work.
What could bring a hover-displayed element to the very top of z-index, whatever the position of siblings in the dom?

A: Go through the link to get the solution
em {
    background: #fff none repeat scroll 0 0;
    display: none;
    position: relative;
    z-index: 1000;
}

A: You need to add  z-index:1;position:relative in em class.

$("[data-position]").each(function() {
  $(this).css({
    position: 'absolute',
    left: $(this).data('position')[0] + '%',
    top: $(this).data('position')[1] + '%',
  })
});
ul         {position: relative;
            width: 15em;height: 15em;
            background: #0af;
            list-style: none}
strong,em  {padding: .5em}
strong     {background: #000; color: #fff;z-index:50}
em         {display: none;background: #fff;z-index:1;position:relative}
li:hover em{display: block}

    A
    This is an ay

    B
    This is a bee

    C
    This is a see


text:
Q: Fixed Point: Finding rate of convergence I have $g(x) =  \sqrt{1+\log(x)}$, I want to find the rate of convergence using fixed point iteration. I have confirmed that this is linearly convergent, because the absolute value of its derivative is less than $1$, but I want to know how fast it converges to $1$ (which is our fixed point).
How can I find the rate of convergence for : $x_{i+1} = \sqrt{1+\log(x_i)}$?
I have tried squaring both sides but wasn't able to weasel out a relationship between $x_{i+1}$ and $x_i$.

A: If you are near a root $r$ of $x-g(x)=0$ then let $x_n=r+\epsilon_n$. The linear approximation of the next iterate is
$$x_{n+1}=r+\epsilon_{n+1}=g(x_n)=g(r+\epsilon_n)\approx g(r)+\epsilon_ng^{\prime}(r)=r+\epsilon_ng^{\prime}(r)$$
So the error $\epsilon$ just gets multiplied by $g^{\prime}(r)$ at each iteration with the result that
$$\epsilon_n\approx\epsilon_0\left(g^{\prime}(r)\right)^n$$
Near the fixed point $r\approx0.450763652$,
$$g^{\prime}(r)=\frac1{2r\sqrt{1+\ln r}}=\frac1{2r^2}=2.460776817>1$$
so we won't converge there. Near $r=1$, $g^{\prime}(r)=\frac12$ so $\epsilon_n\approx\frac{\epsilon_0}{2^n}$ provided our initial aproximation was close enough to $1$.


text:
Q: Mongo locale variant meaning Some mongoDB locales have variants: for instance Catalan has variant search and Spanish has variants search and traditional. What do those variants mean and what effect do they have on string comparisons? MongoDB documentation specifies which variants are available for each supported language (see this page from their maunal) but it does not specify what do they mean.

A: The collation data comes from CLDR - Unicode Common Locale Data Repository.
Downloading the common archive and looking for the ca locale (common/collation/ca.xml), it has the following notes. Standard variant:
    <!-- standard collation &L<<ŀ=l·<<<Ŀ=L· is equivalent to root collation order
        (except root uses prefix rules for the middle dot, rather than contractions)
        references="Enciclopèdia Catalana: Diccionari de la llengua catalana ISBN 84-85194-46-2" -->

Search variant:
            # Below are the rules specific to ca.
            # Per Apple language group, these are modified from standard rules below
            # to make L primary-different from L-dot for search.


text:
Q: Magento product not appearing in front end (via rapidflow) I loaded some new products via Rapid flow and its shown at back end but it doesn't appear at front end. The product's
1. quantity is greater than zero,
2. It is set as In Stock
3. Enabled
4. Assigned Category
5. Assigned to website
All these done via import, after clearing cache and reindexing the product doesn't show up in front end.
  But when I modify any of the parameters at product edit page it appears on front end after Reindexing. It seems like a cache problem, but I have tried refreshing the cache. Appreciate any help.


text:
Q: Centering images in a div I am trying to the images in this gallery to auto center themselves and no matter what I do they refuse to go to the center. Yes I understand  should not be used anymore but it still should work. Please help
HTML

                    <?php
                        $directory = 'images/gallery';
                        $files = scandir($directory);
                        $file_length = sizeof($files);
                        $to = 16;
                        $start = 2;
                        if($to > $file_length) $to = $file_length;
                        for($i=$start; $i <= $start-1+$to; $i++)
                        {
                            echo "

";
                        }
                    ?>

CSS
#gallery_gallery
{
position: absolute;
top: 75px;
left: 80px;
width: 825px;
height: 960px;
}
#imageList
{
background-color: yellow;
width: 825px;
text-align: center;
}
.galleryImage
{
width: 180px;
height: 180px;
float: left;
overflow: hidden;
}
.galleryImage img
{
min-width: 100%;
min-height: 100%;
padding: 10px;
}
.galleryImage img:hover
{
cursor: pointer;
}

RESULT
http://sonny.hostingsiteforfree.com/gallery.html

A: I see the CSS is not following standards.
The ImageWrapper galleryImage has overflow:hidden with the image galleryImage img has padding:10px which cause everything to go unstable here.
I have created a fiddle here you may check the changes...
CSS:
#gallery_gallery {
    position: absolute;
    top: 75px;
    left: 80px;
    width: 825px;
    height: 960px;
    text-align:center;
    background:#777;
}
#imageList {
    background-color: yellow;
    width: 825px;
    text-align: center;
    margin-left:10px;
}
.galleryImage {
    width: 180px;
    height: 180px;
    float: left;
    overflow: hidden;
    margin:10px 10px;
}

.galleryImage img {
    min-width: 100%;
    min-height: 100%;

}
.galleryImage img:hover {
    cursor: pointer;
}

Also, we need to close the img tag in PHP code. using this self closing of tag />
This causes your image style not work properly.
 echo "

";

Check the fiddle its working fine.. :)

A: Just add text-align: center; to #imageList. Here's a demo: http://jsfiddle.net/VLJYq/

A: Its all because of the float style you are using, if you  remove the div with class 'galleryImg', it will work properly.
echo "";

try this one.

A: Just add:
width: 731px;/* change from 825px */
display: inline-block;//new added

to #imageList
Note: I have tested this.

A: *

*Remove your css

*Remove "center" tag from #gallery_gallery that you have written.

*Apply Below CSS.
 .pageWrap { margin: auto; width: 1000px;}

 #main_content_gallery {background: url("../images/gallery_bg.jpg") no-repeat scroll 0 0 rgba(0, 0, 0, 0);height: 1722px;padding: 72px;}

 .main_content {clear: both;width: 100%;}

 #gallery_gallery {clear: both;margin: 0 61px;padding: 0;width: 100%;}

 #imageList {background-color: yellow;clear: both;float: none;text-align: center;width: 80%;}

 .galleryImage {float: left;height: 180px;overflow: hidden;width: 180px;}

 .galleryImage img {min-height: 100%;min-width: 100%;padding: 10px;}

 #imageList {text-align: center;}

 #mainmenu {left: 1px;position: relative;width: 800px;}

 #mainmenu, #mainmenu ul {list-style: none outside none;margin: 0;padding: 0;}

 .pageWrap {margin: auto; width: 1000px;}

 #mainmenu a {color: black;float: left;font-family: 'Coda',cursive;font-size: 20px;padding: 0 30px 12px;text-decoration: none;text-shadow: 0 1px 0 #000;}

 #floatBox {background-color: rgba(0, 0, 0, 0.5);display: none;height: 100%;left: 0;position: fixed;top: 0;width: 100%;}

 #float_image { height: 600px;}

 #float_tools {margin: auto;opacity: 0.3;transition: opacity 0.5s ease-out 0s;width: 50px;}

 #floatimg {border: 10px solid white;border-radius: 5px;float: none;height: 550px;}

Let me know if it doesn't works.

A: You should changes height and width of ".galleryImage" css class, like this:
.galleryImage {
    float: left;
    height: 243px;   /* changed from 180*/
    overflow: hidden;
    width: 205px;   /* changed from 180*/
}

I have tested this on your link, It works well.

A: Try use the margin
margin:0 auto;

A: Just rewrite this style
 .galleryImage {
width: 180px;
height: 180px;
display: inline-block;
overflow: hidden;
}


text:
Q: Get string between strings in c# I am trying to get string between same strings:
The texts starts here ** Get This String ** Some other text ongoing here.....

I am wondering how to get the string between stars. Should I should use some regex or other functions?

A: You can try Split:
  string source =
    "The texts starts here** Get This String **Some other text ongoing here.....";

  // 3: we need 3 chunks and we'll take the middle (1) one
  string result = source.Split(new string[] { "**" }, 3, StringSplitOptions.None)[1];

A: You can use IndexOf to do the same without regular expressions.
This one will return the first occurence of string between two "**" with trimed whitespaces. It also has checks of non-existence of a string which matches this condition.
public string FindTextBetween(string text, string left, string right)
{
    // TODO: Validate input arguments

    int beginIndex = text.IndexOf(left); // find occurence of left delimiter
    if (beginIndex == -1)
        return string.Empty; // or throw exception?

    beginIndex += left.Length;

    int endIndex = text.IndexOf(right, beginIndex); // find occurence of right delimiter
    if (endIndex == -1)
        return string.Empty; // or throw exception?

    return text.Substring(beginIndex, endIndex - beginIndex).Trim();
}

string str = "The texts starts here ** Get This String ** Some other text ongoing here.....";
string result = FindTextBetween(str, "**", "**");

I usually prefer to not use regex whenever possible.

A: If you want to use regex, this could do:
.*\*\*(.*)\*\*.*

The first and only capture has the text between stars.
Another option would be using IndexOf to find the position of the first star, check if the following character is a star too and then repeat that for the second set. Substring the part between those indexes.

A: If you can have multiple pieces of text to find in one string, you can use following regex:
\*\*(.*?)\*\*

Sample code:
string data = "The texts starts here ** Get This String ** Some other text ongoing here..... ** Some more text to find** ...";
Regex regex = new Regex(@"\*\*(.*?)\*\*");
MatchCollection matches = regex.Matches(data);

foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[1].Value);
}

A: You could use split but this would only work if there is 1 occurrence of the word.
Example:
string output = "";
string input = "The texts starts here **Get This String **Some other text ongoing here..";
var splits = input.Split( new string[] { "**", "**" }, StringSplitOptions.None );
//Check if the index is available
//if there are no '**' in the string the [1] index will fail
if ( splits.Length >= 2 )
    output = splits[1];

Console.Write( output );
Console.ReadKey();

A: You can use SubString for this:
String str="The texts starts here ** Get This String ** Some other text ongoing here";

s=s.SubString(s.IndexOf("**"+2));
s=s.SubString(0,s.IndexOf("**"));


text:
Q: How do I share internet with my Windows 7 laptop such that DHCP is off? I basically want my Windows 7 Laptop to function as a switch. (like a router when DHCP is off).
Instead of getting 192.x.x.x addresses, I want public IP address assigned to everyone who connects to my Windows 7 created network, which is this case is 137.x.x.x
So, how do I do that?
I've done this with my router. Lets say for example your router has an IP of 12.34.56.0 then with DHCP disabled, all computers that connect to the router get IPs in the range of 12.34.56.(1-255)..
Disabling DHCP on a router acts a splitter of sorts for the port that the router is plugged in to.  When a computer requests an IP address, the request goes past the router to the next level up (for most cases, that is the ISP (In my case, it's a school)).
I want DHCP disabled because my school tracks bandwidth via an IP / MAC address combination, so with DHCP disabled, when people connect to my computer (whenever this question gets answered) they will be using their bandwidth, and not mine (because they will have their own IP assigned by the school (ISP for non-school situations) )

A: Sounds like you want your computer to act as a bridge. Instead of using Windows' Internet Connection Sharing, which it sounds like you're using, you can use Windows' Network Bridge instead.
Go to your Network Connections window, select both connections you want (aka wired and wireless) using the control + click to select more than one, and right click and choose Bridge Connections. You may need to turn off ICS first.
Here's more information.

A: I don't think its possible to assign 1 static ip to many computers on your network and expect them to connect to the internet. That's why you have NAT, to translate it to private ip's.
If you have to connect multiple computers to your network to access they internet, they have to be assigned private ip addresses (the 192.x.x.x kind) either manually or by using DHCP,but it seems that you want to turn off DHCP.
Why don't you want to use DHCP, what do you want to achieve here? Is you objective here just to share your internet connection? What is your current networking layout i.e. how do you connect to the internet? (directly to a modem or via switch > router > modem or via router > modem)
Please do correct me if I have failed to grasp your question.

A: A router never acts like a switch.  They are two different devices, working on two different layers of the OSI model.
My guess, you mean one of those cable/dsl home routers.  Those are actually a router and a switch combined.

*

*The router portion of the device takes packets from one network (usually 192.168.XX.XX) and routes them to the other network (usually the public internet)

-The switch portion takes one network interface from the router, and allows you to plug multiple devices into the same network interface.
The router ends up giving the IPs to the devices on the switch using DHCP.  In the event DHCP is turned off, then a system administrator is required to put an IP address into each machine within the range that the router is assigned to handle (it is still the same IP range as if DHCP were turned on)
From my understanding, it looks like you are trying to do one of two scenarios, depending on your school's connection:
1.) School provides wireless only: You are receiving the wireless signal, and pushing it out to each of your devices that do not have wireless capability
-- Maybe you can look for a device, such as a wireless router, that you can configure to be a repeater, with a wired switch hanging off of it? [Bridging]
-- Configure your laptop to do network bridging
(http://forums.cnet.com/5208-19411_102-0.html?threadID=326988)
2.) School provides a wired connection, but there is only one port in the room, and you have more than one device
-- Buy a switch.  They're 20$


text:
Q: Ionic : Data is not getting fetched after initial load in Android works fine in browser I'm developing booking app using ionic 5.
Issue is happening only in android devices (ios no idea)
When user comes for fist time and booked and navigates to booking history, data is displayed.
Again user books another item, now when he visits booking history latest entry is not displaying but in browser view it is working fine.
How to fix this issue ? please guide.
Booking History Component
  ngOnInit () {
    this.loaderService.showLoader();
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.getUserData(user.uid);
      }
    })
  }

  getUserData (uid) {
    firebase.database().ref('users/' + uid).once("value", snap => {
      let data = snap.val();
      let bookings = [];

      for (let key of Object.keys(data.bookings)) {
        let booking = data.bookings[key];
        booking.bookedDate = new Date(booking.bookedDate).toDateString();
        bookings.push(booking);
      }
      this.bookingHistory = bookings;
      this.loaderService.hideLoader();
      console.log(this.bookingHistory);
    })
  }

A: Sounds like an life cycle problem, your view is not being destroy and it only fetch the data from the first initialization on the ngOnInit. Try calling your data on the ionViewDidEnter event like so:
 ionViewDidEnter(){
      this.loaderService.showLoader();
      firebase.auth().onAuthStateChanged(user => {
        if (user) {
          this.getUserData(user.uid);
        }
      });
   }

You can check more about life cycle from the official docs Here


text:
Q: Click button in WebBrowser control vb.net I am trying to click the button highlighted in picture below. The code is from a web page:

I'm not to sure, but I believe the button is within an iFrame.
I have tried:
Dim wrapClick As HtmlElement = Contact.WebBrowser1.Document.GetElementById("Btn_WrapUp")
wrapClick.InvokeMember("Click")

And:
Dim elPoint As New Point(704, 340)
Dim wrapClick As HtmlElement = Contact.WebBrowser1.Document.GetElementFromPoint(elPoint)
wrapClick.InvokeMember("onClick")

And:
Contact.WebBrowser1.Document.GetElementById("Btn_WrapUp").InvokeMember("Click")

In all of the above, I have tried 'onClick' and 'Click'.
WebBrowser1 is on a different form.
Thanks!

A: Click button in WebBrowser control - working example:
Main file with frame - x.html:
<html>
<body>
<iframe width="400" height="300" src="y.html" id="frame1"> </iframe>
</body>
</html>

File placed in frame - y.html - with submit button:
<html>
<body>
<form action="...some_action...">
<input type="submit" id="btn"> Submit!
</form>
</body>
</html>

Button on VB form with OnClick event:
Dim Frame1 As HtmlWindow = WebBrowser1.Document.Window.Frames("frame1")
Frame1.Document.GetElementById("btn").InvokeMember("click")

VB2010Ex & .NET Framework 4 Client Profile.
I have tried code with action that load other site. Site was loaded in iframe.
Finally success :-)


text:
Q: Difference between 'echo' and 'echo -e' What is the difference between echo and echo -e?
And which quotes ("" or '') should be used with the echo command? i.e: echo "Print statement" or echo 'Print statement'?
Also, what are the available options that can be used along with echo?

A: In most of the SHELL echo cant take escape sequence ( \n \t ).
Where as echo -e can
echo -e " This is \n an \t example"
Single quote and double quote are mostly for handling the interpolation issues. You may find more details here,  Why is echo ignoring my quote characters?

A: echo by itself displays a line of text. It will take any thing within the following "..." two quotation marks, literally, and just print out as it is. However with echo -e you're making echo to enable interpret backslash escapes. So with this in mind here are some examples
INPUT: echo "abc\n def \nghi"
OUTPUT:abc\n def \nghi

INPUT: echo -e "abc\n def \nghi"
OUTPUT:abc
 def
ghi
Note: \n is new line, ie a carriage return. If you want to know what other sequences are recognized by echo -e type in man echo to your terminal.


text: Q: how to downgrade mono? i've been trying to modify the repo for it, but all i managed to get was an HTTP 404 Error. can someone tell me how to downgrade mono using repos or from annother way? thanks in advance


text:
Q: Settings wont launch Ubuntu 16.04 GNOME I have ubuntu Gnome installed on my laptop, and the settings application wont launch. It makes the animation and briefly shows at the top taskbar, but then goes away. I installed vanilla ubuntu then installed gnome desktop, so when I log into the default ubuntu desktop with unity, it works fine. Tweak tool also works fine as well.
Typing unity-control-center in terminal spits out this command below, and brings up settings but the only setting there is language.
ethan@ethan-macbook-ubuntu:~$ unity-control-center
/usr/lib/x86_64-linux-gnu/libnm-gtk.so.0: invalid ELF header
Failed to load module: /usr/lib/x86_64-linux-gnu/unity-control-center-   1/panels/libnetwork.so

Anyone know whats wrong here? thanks!

A: This error indicates that there is something wrong with the ELF, that is to say the header of the /usr/lib/x86_64-linux-gnu/libnm-gtk.so.0 binary file you have installed one possible reason for this could be that the file is corrupt. Since this file is installed by the libnm-gtk0 package you could try the following command to reinstall it in case it is corrupted.
sudo apt-get install --reinstall libnm-gtk0

The other likely candidate for this error would be if you have somehow installed amd64 packages on a 32 bit (i386) version of ubuntu since the 32 bit kernel will not recognise the ELF64 (64 bit binary) as being a valid ELF header which would produce this error also perhaps if the above doesn't fix the problem you should add the output of the following command to your question:
uname -a

That will print out some information about your kernel and platform that could help diagnose the issue further.


text:
Q: Wearable app does not install from mobile apk With the following Gradle files of my three modules (common, mobile, and wear), I was wondering why my wearable app doesn't install on the wearable device when I run the mobile app with both the wear virtual emulator and my mobile device running and connected (through USB and the Android wear app), and signed both apks through the mobile module (currently in the mobile directory):
Common module:
apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

Mobile module:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "dpark.gameoflife"
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    signingConfigs {
        debug {
            storeFile file("C:\\Users\\Dave\\AndroidStudioProjects\\KEY_STORE\\Game_of_Life.jks")
            storePassword "***"
            keyAlias "game_of_life"
            keyPassword "***"
        }
        release {
            storeFile file("C:\\Users\\Dave\\AndroidStudioProjects\\KEY_STORE\\Game_of_Life.jks")
            storePassword "***"
            keyAlias "game_of_life"
            keyPassword "***"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    wearApp project(':wear')
    compile project(':common')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.google.android.gms:play-services-wearable:8.4.0'
}

Wear module:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "dpark.gameoflife"
        minSdkVersion 22
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    signingConfigs {
        debug {
            storeFile file("C:\\Users\\Dave\\AndroidStudioProjects\\KEY_STORE\\Game_of_Life.jks")
            storePassword "***"
            keyAlias "game_of_life"
            keyPassword "***"
        }
        release {
            storeFile file("C:\\Users\\Dave\\AndroidStudioProjects\\KEY_STORE\\Game_of_Life.jks")
            storePassword "***"
            keyAlias "game_of_life"
            keyPassword "***"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.support:wearable:1.3.0'
    compile 'com.google.android.gms:play-services-wearable:8.4.0'
    compile project(':common')
}

Common manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="dpark.common" >
</manifest>

Mobile manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="dpark.gameoflife" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar" >
        <activity
            android:name=".MainActivity">
        </activity>
        <activity
            android:name=".WelcomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Wear manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="dpark.gameoflife" >

    <uses-feature android:name="android.hardware.type.watch" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
        </activity>
        <activity
            android:name=".WelcomeActivity"
            android:theme="@android:style/Theme.DeviceDefault" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

... While the app properly installs on my mobile device, I only get a notification (at most when my sample app is simply supposed to display a GridView) on my wear virtual emulator as follows:

Thanks!
EDIT AS OF 4/4:
-Here's what I get on my logcat:
04-04 09:39:27.462 15810-15810/dpark.gameoflife I/art: Late-enabling -Xcheck:jni
04-04 09:39:27.462 15810-15810/dpark.gameoflife I/art: VMHOOK: rlim_cur : 0 pid:15810
04-04 09:39:27.543 15810-15810/dpark.gameoflife W/System: ClassLoader referenced unknown path: /data/app/dpark.gameoflife-1/lib/arm
04-04 09:39:27.570 15810-15810/dpark.gameoflife I/GMPM: App measurement is starting up, version: 8487
04-04 09:39:27.571 15810-15810/dpark.gameoflife I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
04-04 09:39:27.580 15810-15810/dpark.gameoflife E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
04-04 09:39:27.580 15810-15810/dpark.gameoflife E/GMPM: Scheduler not set. Not logging error/warn.
04-04 09:39:27.644 15810-15831/dpark.gameoflife E/GMPM: Uploading is not possible. App measurement disabled
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3__release_AU (I3fa967cfef)
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: OpenGL ES Shader Compiler Version: E031.28.00.02
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: Build Date: 09/29/15 Tue
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: Local Branch: mybranch14683032
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: Remote Branch: quic/master
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: Local Patches: NONE
04-04 09:39:27.763 15810-15847/dpark.gameoflife I/Adreno-EGL: Reconstruct Branch: NOTHING
04-04 09:39:37.863 15810-15831/dpark.gameoflife I/GMPM: Tag Manager is not found and thus will not be used
04-04 09:43:06.197 15810-15847/dpark.gameoflife E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb9d385f0

... Am I missing something either in my Manifest or Gradle files as shown above in this post?

A: First impressions
Could be many things wrong here. On first sight the gradle configurations seem fine having a wear app reference, matching version name and numbers, application Id and package names. The manifests don't show permissions that could be missing. No special flavors.
What you really need to do -> get LOGS
In order to resolve this issue you need to collect logs. I see you have logcat output but that is really just from your app. You need to filter on android wear package installer specific stuff with a filter set on WearablePkgInstaller.
Also from the logging on your handheld device you will only see an instruction to trigger the installation. That should show every time you reinstall your app or trigger app sync from the wear OS app.
11-07 14:58:53.127 3330-8739/? I/WearablePkgInstaller: Setting DataItem to install wearable apps for com.spotify.music

The really valuable logging however is on the watch. So make sure to get logging from the wearable device. There you will get information, including the reason why, on the failed installation.
Some watches have a USB connection for debugging. Others require some extra steps to enable debugging over bluetooth. First step is to enable developer options and debugging by tapping the build number several times, similar to how it's done on the handheld.
The logging on the wearable can be filtered on that same WearablePkgInstaller filter or you could use your own package Id to filter on. The logging can be very clear (like mismatching google play services or missing permissions) or rather cryptical with a returnCode.
In case of the returnCode you'll have to check in source code of Android what that code stands for and based on the javadoc you can start searching more specifically.
Some more things you could check
Wearable projects are only included in release builds. Also the latest Android studio builds have a flag set (FLAG_TEST_ONLY) that would result in a failure with returnCode -15 upon installation. Check that the handheld app has the proper runtime permissions enabled (that should be clear from error logging also).
Even build tools for optimalisation could remove the wear project from the app. And then there is the option that either wearable or handheld doesn't have the latest Google Play Services. Make sure to also check the accepted answer on this SO question for options.


text:
Q: Linux users permissions I have to do the following as homework (on Fedora):

*

*Make 3 groups S,F,A

*add some users to the groups

*Make a file for each group which only the group members can use.

I logged as root and make in desktop a mkdir S F A and with chmod I give wrx in folder and with chgrp give the group A in dir A , but if I log in with a user from group A I cannot see the dir A in desktop, what i doing wrong?
Also, if I have a folder which can only be accessed by members of its group, can I create a subfolder in it and give access to the subfolder to users who are not in the parent folder's group?

A: The Desktop in Gnome (which I assume you are using) is a subdirectory of the user's $HOME, specifically $HOME/Desktop. So, if you log in as root and create a file or folder on root's Desktop, other users will not see it on their desktop. Also, root's $HOME is not accessible to normal users by default.
Instead of creating the directory in root's Desktop, create it in, for example, user A's Desktop.

Now, once you have the folders set up, if you want to give access to a subfolder to users who are not in the parent folders group, you will need to allow execution (not read or write) of the parent folder. The only way to access a subfolder is by having execution rights on ts parent. For example, run these commands as root:

*

*Create a folder and give rwx rights to the owner and members of its group, and only x permissions to everyone else:
mkdir /foo
chmod 771 /foo/

*Create a subdirectory of /foo that will be freely accessible to everyone and create a test file in it:
mkdir /foo/bar
chmod 777 /foo/bar/
touch /foo/bar/file.txt
chmod 766 /foo/bar/file.txt

This is what we have created so far:
# ls -l / | grep foo
drwxrwx--x   3 root root  4096 Apr 16 14:31 foo
# ls -l /foo
drwxr--r-- 2 root root 4096 Apr 16 14:31 bar
# ls -l /foo/bar
-rwxrw-rw- 1 root root 0 Apr 16 14:47 file.txt

So, if I now log in with a user not in root's group, I will not be able to read or write to /foo but I will be able to read and write to /foo/bar:
$ whoami
terdon
$ groups
users
$ ls /foo
ls: cannot open directory /foo/: Permission denied
$ ls /foo/bar
file.txt

So, to give any kind (read,write or execute) access to a subdirectory, you need to at least have execution rights on the parent folder.


text:
Q: How can I toggle/animate a  by hovering on a  S So. I have an  object. If i hover it i want to toggle an animation or just a css change of the div underneath.
I only want to use HTML & CSS no Javascript or something.
You can find the structure in the "code" section.
Thank you for your help :)

   stuff

A: You can use the adjacent sibling selector (note that the div must immediately follow the a in this case):

a:hover + div { background: blue } /* this is all that really matters */
HOVER ME

I AM A DIV

If there's another element between the a and the div, but they're still siblings, you need to use ~ instead of +.

A: First of all, you need to add a closing tag for your anchor element. After that, you can set the innermost div to animate when you hover on the anchor tag by doing:
    a:hover div{
      //Animation code here
    }


text:
Q: Python subprocess module I am making a GUI aplplication in Python that requires to run a cmd prompt command.
e. g.:
import subprocess
subprocess.Popen("arp -a > arptable.txt",stdin=PIPE, stdout=PIPE,shell=Ture)

Now, after running this command, I see a small splash of cmd screen, and a text file containing the arp table is generated. In my application, I don't want this black screen to splash, so that the user doesn't know there's a cmd prompt involved in the appplication.
How can I do this?

A: You don't need shell=True:
import os
from subprocess import PIPE, STDOUT, check_call

with open("arptable.txt", "rb") as file, open(os.devnull, "r+b") as devnull:
    check_call(["arp", "-a"], stdin=devnull, stdout=file, stderr=STDOUT)

A: On Windows you need to pass a STARTUPINFO class to the startupinfo argument of subprocess.Popen to make that happen. To make that portable:
import subprocess
import os

si = None
if os.name == 'nt':
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen("arp -a > arptable.txt",stdin=PIPE, stdout=PIPE, startupinfo=si)


text:
Q: replacing values in pandas df column with values from another of same row if condition is met I've got a df that I'm trying to clean. In instances where the value in col1 is = 0 I want to replace the 0 with the corresponding value from col2. What's the easiest way to do this?
edit: I got it nevermind..

A: One way is to use:
df['col1'] = df['col1'].replace(0, np.nan).fillna(df['col2'])

Another way with mask:
df['col1'] = df['col1'].mask(df['col1'] == 0, other=df['col2'])

Or the opposite with where:
df['col1'] = df['col1'].where(df['col1'] != 0, other=df['col2'])

And with loc:
df.loc[df['col1'].eq(0), 'col1'] = df['col2']


text:
Q: Android Bluetooth Development - connecting to an UNPAIRED device First off, I AM able to programmatically connect to a device via bluetooth if I have manually paired it beforehand. However, I haven't found a (user-friendly) way to connect with unpaired devices (that are discoverable, obviously), even using the unchanged sample Android Bluetooth code.
I would like to pop up the pairing dialog box that requests the user to input a passkey for the device. What happens with my code, and the sample Android Bluetooth code, is that making a socket with a discoverable bluetooth device
device.createRfcommSocketToServiceRecord(MY_UUID);

will add a notification to the notification bar at the top of the screen; however, it is pretty unlikely that the user will even notice a new notification (I know I didn't).
How would I pop up that pairing dialog box, prompting the user to enter the passkey - or better yet, supply a passkey for a particularly device automatically?

A: You can use BlueCove library to do that. However, it may be a bit heavier than you'd want as it requires a native component but in return gives you real access to Bluetooth on your phone.
Tim: I can see how a rogue app could abuse this mechanism but there are devices out there which don't support traditional PIN-based authentication method at all (for example the WiiMote).

A: I've seen a few threads on this but haven't really found a good
answer.
I am connecting my nexus 1 to a bluetooth spp server device to read
and write data.
After some experimentation I have found the following

*

*If I offload the establishment of the connection from the UI thread
(which I would consider a good idea) the pairing dialog (enter pin) is
not displayed - rather a notification item appears which the user must
click to pair the devices.

*If I establish the connection from within the UI thread then the
paring dialog will come to the foreground but obviously there is a
small ugly UI pause while waiting for this.
In either case the request to establish the connection is timing out
before the user (me) can enter the pin with an IOException Service
discovery failed.
My ideal would be that the pairing dialog comes to the front (without
have to block my UI thread) and that the connection attempt would not
time out while waiting on pairing entry.
Has anyone else come up with a way to make this work?


text:
Q: cassandra read query time analysis We are using cassandra-3.0.15. A few of the read queries takes longer time(>500ms). Based on the query tracing it seems the co-ordinator node takes a longer time than expected especially while starting to process the request. What could be the reason for that? How to solve this issue?
Have attached the query trace for one of the such requests below. It can be seen that the first activity "Executing single-partition query on facility_configuration" takes around 1.4sec. The rest of the activities are pretty fast.
activity                                                                  | source         | source_elapsed | thread
---------------------------------------------------------------------------+----------------+----------------+-------------------------------------------

   Executing single-partition query on facility_configuration | node1 |        1466289 |                       SharedPool-Worker-6

   Acquiring sstable references                               | node1 |        1466298 |                       SharedPool-Worker-6

   Key cache hit for sstable 6                                | node1 |        1466314 |                       SharedPool-Worker-6

   Skipped 0/1 non-slice-intersecting sstables, included 0 due to tombstones | node1 |        1466330 |                       SharedPool-Worker-6

   Merging data from memtables and 1 sstables                 | node1 |        1466341 |                       SharedPool-Worker-6

   Read 1 live and 0 tombstone cells                          | node1 |        1466450 |                       SharedPool-Worker-6

   reading digest from /node2                                 | node1 |        1466466 |                       SharedPool-Worker-6

   Sending READ message to /node2                             | node1 |        1467388 |  MessagingService-Outgoing-/node2

   READ message received from /node1                          | node2 |              1 | MessagingService-Incoming-/node1

   Executing single-partition query on facility_configuration | node2 |            536 |                       SharedPool-Worker-3

   Acquiring sstable references                               | node2 |            546 |                       SharedPool-Worker-3

   Key cache hit for sstable 6                                | node2 |            562 |                       SharedPool-Worker-3

   Skipped 0/1 non-slice-intersecting sstables, included 0 due to tombstones | node2 |            575 |                       SharedPool-Worker-3

   Merging data from memtables and 1 sstables                 | node2 |            586 |                       SharedPool-Worker-3

   Read 1 live and 0 tombstone cells                          | node2 |            642 |                       SharedPool-Worker-3

   Read 1 live and 0 tombstone cells                          | node2 |            807 |                       SharedPool-Worker-3

   Enqueuing response to /node1                               | node2 |            819 |                       SharedPool-Worker-3

   Sending REQUEST_RESPONSE message to /node1                 | node2 |            845 | MessagingService-Outgoing-/node1

   REQUEST_RESPONSE message received from /node2              | node1 |        1470583 |  MessagingService-Incoming-/node2

   Processing response from /node2                            | node1 |        1470665 |                      SharedPool-Worker-15

session_id                           | client       | command | coordinator    | duration | parameters                                                                                | request                     | started_at
--------------------------------------+--------------+---------+----------------+----------+--------------------------------------------------------------------------------------------+-----------------------------+--------------------------

ddef2100-eb53-11e9-86ed-9d59234ed651 | clientNode |   QUERY | node1 |  1470765 | {'consistency_level': 'QUORUM', 'page_size': '5000', 'serial_consistency_level': 'SERIAL'} | Execute CQL3 prepared query | 2019-10-10 11:48:24+0000

facility_configuration histograms
Percentile  SSTables     Write Latency      Read Latency    Partition Size        Cell Count
                           (micros)          (micros)           (bytes)
50%             1.00              0.00            182.79               124                 5
75%             1.00              0.00            263.21               258                 7
95%             2.00              0.00            545.79              1597                14
98%             2.00              0.00            943.13              1597                14
99%             2.00              0.00           1358.10              1597                14
Min             0.00              0.00             51.01                87                 5
Max             2.00              0.00           1955.67              1597                14

tablestats
 Read Count: 68390050
 Read Latency: 0.08643708858233032 ms.
 Write Count: 11
 Write Latency: 0.09781818181818182 ms.
 Pending Flushes: 0
     Table: facility_configuration
     SSTable count: 2
     Space used (live): 12241
     Space used (total): 12241
     Space used by snapshots (total): 0
     Off heap memory used (total): 103
     SSTable Compression Ratio: 0.5963017053887002
     Number of partitions (estimate): 7
     Memtable cell count: 0
     Memtable data size: 0
     Memtable off heap memory used: 0
     Memtable switch count: 4
     Local read count: 68390066
     Local read latency: 0.195 ms
     Local write count: 11
     Local write latency: NaN ms
     Pending flushes: 0
     Bloom filter false positives: 0
     Bloom filter false ratio: 0.00000
     Bloom filter space used: 40
     Bloom filter off heap memory used: 24
     Index summary off heap memory used: 55
     Compression metadata off heap memory used: 24
     Compacted partition minimum bytes: 87
     Compacted partition maximum bytes: 1597
     Compacted partition mean bytes: 420
     Average live cells per slice (last five minutes): 1.0
     Maximum live cells per slice (last five minutes): 1
     Average tombstones per slice (last five minutes): 1.0
     Maximum tombstones per slice (last five minutes): 1


text:
Q: Dynamically Change Range in Excel Chart Without VBA? I'm charting values and I need to change the start and stop of the range dynamically. The chart is plotting from a sheet that has data for 5 forecast days. Each line in the chart represents a forecast day. Every day new data is added to the sheet, so there are more entries for each forecast day. Here is an example:
=SERIES("Day 4",sheet!$B$2:$B$49,sheet!$F$147:$F$193,5)
I need Excel to find the start and stop row numbers for each forecast day and change them every time there is new data. So the range for forecast day 4 $F$147:$F$193 will change to $F$148:$F$194, etc.
Is it possible to do this in a formula? I really don't want to mess with VBA if I can avoid it.

A: If you have a defined starting date, like "01/01/2017" for example, you could use "TODAY()" to count the number of days and increment based on that number.
For example:
=DAYS(TODAY(),DATE(2017,1,1))

returns 263 today, and 264 tomorrow. You could add/subtract this number to change the values of your series ranges each day; e.g. ($F$ &  =DAYS(TODAY(),DATE(2017,1,1)) - 116 & ":$F$ & =DAYS(TODAY(),DATE(2017,1,1)) - 70) would give you the desired outcome.
Edit:
Because you apparently can't define chart series using formulas, create an intermediate data range outside of your list/table of data (you could even use named ranges without a cell reference - doesn't matter). This range should be the same size as the data range you would like to display on the chart. Then make your dynamic range references to your data to all the cells within this range; e.g. =F &  =DAYS(TODAY(),DATE(2017,1,1)) - 116 or whatever the formula needs to be, but do this for all the cells referenced. Then make your chart series reference to those cells that contain the dynamic formulas.


text:
Q: mockito how to verify using methodname and reflection I have a spy or a mock of an object and I wants to verify that a method has been call
problem, I receive methodname at execution Time not compilation time
I would like to do something like:
  SimpleObj mockObject= Mockito.mock(SimpleObj.class);
  Class myClass = SimpleObj.class;
  Method meth = myClass.getMethod("getGuid");

  Mockito.verify(meth.invoke(mockObject));

I have made a kind of workaround using
MockingDetails mockingDetails = Mockito.mockingDetails(mockObject);

Collection<Invocation> invocations = mockingDetails.getInvocations();

List<String> methodsCalled = new ArrayList<>();
for (Invocation anInvocation : invocations) {
  methodsCalled.add(anInvocation.getMethod().getName());
}
assertTrue(methodsCalled.contains("getGuid");

Problem it works until I use PowerMockito :
  for standard method it works but if the method is final, the method is not present in mockingDetails.getInvocations()
 (but even if not present in mockingDetails.getInvocations()
the real verify(mock).getGuid() works in a good way
So if you have any idea/advice it would be glad
Regards

A: This works for me using regular Mockito (I use this to verify that the hidden method "refresh()" in android.bluetooth.BluetoothGatt is invoked:
private void assertMethodInvoked(@NonNull Object object,
                                 @NonNull String methodName,
                                 @NonNull VerificationMode verificationMode) throws Exception {
    final Method method = object.getClass().getDeclaredMethod(methodName);
    final Object verify = verify(object, verificationMode);
    method.invoke(verify);
}

A: I actually made this work using reflection... I could not use the matchers but I've got the original parameters. My test verifies that an intermediate proxy and data convertion process invokes the real implementation:
private void assertMethodExecuted(String testName, Object ...params) throws Exception {
    assertManagerMethodExecuted(getMethodName(testName), params);
}

private void assertManagerMethodExecuted(String methodName, Object[] params) throws Exception {
    MiGRPCManagerImpl manager = Whitebox.getInternalState(server, MiGRPCManagerImpl.class);
    Method method = Arrays.stream(manager.getClass().getMethods())
        .filter(each -> each.getName().equals(methodName))
        .findFirst()
        .orElse(null);
    MiGRPCManagerImpl verify = Mockito.verify(manager, new VerificationMode() {

        @Override
        public void verify(VerificationData data) {
            assertEquals(1, data.getAllInvocations().size());
            data.getAllInvocations().get(0).getMethod().equals(method);
        }

        @Override
        public VerificationMode description(String description) {
            return this;
        }
    });

    if (params.length == 0) {
        method.invoke(verify);
    } else if (params.length == 1) {
        method.invoke(verify, params[0]);
    } else {
        method.invoke(verify, params);
    }

}

private String getMethodName(String testName) {
    return testName.substring(testName.indexOf("_") + 1, testName.length());
}

and a test goes like this:
@Test
public void test_disconnectFromGui() throws SecurityException, Exception {
    String ip = factory.newInstance(String.class);
    String userName = factory.newInstance(String.class);
    fixture.disconnectFromGui(userName, ip );
    assertMethodExecuted(new Object() {}.getClass().getEnclosingMethod().getName(), userName, ip );
}


text:
Q: Closed-form solution to a recurrence of all previous terms I am looking for a method/formula to solve recurrence relations of this form:
$$ U_{n+1}= \sum_{r=0}^{n} a_{r}U_{r} \ with \ U_0=x  $$
Where the coefficients are in terms of r. This is the only case I could work out:
$$ U_{n+1}= \sum_{r=0}^{n} U_r \ with \ U_0 =x \implies U_n = 2^nx$$
Any suggestions would be great (even saying that this is not worth the effort).

A: Writing out the first few terms, it seems there's a product relation for the $U$'s in terms of the $a$'s:
$$U_{n+1}=a_0x\prod_{i=1}^n(1+a_i) .$$
I'm sure a quick induction will confirm this.


text:
Q: how to add bookmarklet in IE 11? I can't figure out the way to manually add a bookmarklet, there is no edit option for url.
I can save javascript bookmarklet embedded in webpages though.
Anyone know is it possible?

A: Yea I think the only way is to put your bookmarklet into a webpage and save from there. It's not possible to do it in IE.


text:
Q: Prevent IntelliJ from removing newlines around single statement methods? Sometimes IntelliJ will take single statement methods and put them on the same line, as seen here:

If I click either bracket it will turn back into:

This question isn't a debate for which of the two is better - I want to know how to turn this off. I combed through IntelliJ preferences and couldn't seem to find anything, and searching both here and Google didn't bring up what I wanted.

A: I think these options are responsible for this:

A: If you're talking about code reformatting putting the extra newlines into your code, then it's the "Simple methods in one line" option you want to check in Editor/Code Style/Scala/Wrapping and Braces:


text:
Q: stack overflow after increasing stack reserve I have an assignment where I need to basically fill up main memory with allocated arrays in C. I am using VS2010 and kept on receiving stack overflow errors. Increasing the stack reserve past its default 1 MB helped, however now the array size I am working with is even larger and it seems no matter how much I increase the reserve, it now continually gives me a stack overflow error.
any help would be appreciated.
-thanks

A: You're probably allocating your arrays on the stack. That's why you're getting stack overflows since your stack is never gonna be as large as your entire main memory.
You need to use malloc() to create arrays on the heap. That will allow you to use up all the main memory.
In other words, you can't do this:
int array[1000000];

That will certainly blow your stack. You need to do this:
int *array = malloc(1000000 * sizeof(int));

and you need to eventually free it like this:
free(array);

Otherwise you will get a memory leak.


text:
Q: Secure client not using highest TLS version I'm updating an old .Net project, it targets .Net Framework 4.8.
The problem is that I'm using HttpClient to POST some data to an endpoint, using code similar to that below (editted for readability)
var jsonString = JsonConvert.SerializeObject(myData, jsonSettings);
var _client = new HttpClient();
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
var response = _client.PostAsync(endpoint, content).Result;

The problem is that it throws a "The request was aborted: Could not create SSL/TLS secure channel." exception. Using Wireshark I can see the connection reaches the correct endpoint, and the remote endpoint returns a Fatal response to the client handshake, but my client is trying to use TLS1.0. I'm using System.Net.Http v4.3.4, and setting SecurityProtocolType.Tls13 seems to make no difference if added or removed (as .Net 4.8 probably doesnt need it).
How do I make my project use Tls1.3 ?
I have another project that calls the same endpoint, and that works OK, but I cant see a difference between them.

A: OK, totally my fault. My customers endpoint isnt using Tls1.3 !!
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

This fixed it. Sorry, thanks for looking.


text:
Q: Why does this keep returning the last value of the dictionary? So i'm practicing my  nested dictionary skills with this data:
content = {'results':
    [
        {'_class': 'question',
    'course': {'_class': 'course',
        'title': 'Angular 7 (formerly Angular 2) - The Complete Guide',
        'url': '/the-complete-guide-to-angular-2/'},
    'replies': [{'_class': 'answer',
        'user': {'_class': 'user',
         'display_name': 'Maximilian'}}]},

        {'_class': 'question',
    'course': {'_class': 'course',
        'title': 'RUSTCRACEON',
        'url': '/the-holy-rust-book/'},
    'replies': [{'_class': 'answer',
        'user': {'_class': 'user',
         'display_name': 'Ella'}}]},

        {'_class': 'question',
    'course': {'_class': 'course',
        'title': 'PHP ULTIMATE WEB GUIDE',
        'url': '/php-to-the-world/'},
    'replies': [{'_class': 'answer',
        'user': {'_class': 'user',
         'display_name': 'Rick_Sanchez'}}]},

        {'_class': 'question',
    'course': {'_class': 'course',
        'title': 'Javascript - The Complete Guide',
        'url': '/javascript291/'},
    'replies': [{'_class': 'answer',
        'user': {'_class': 'user',
         'display_name': 'Morty'}}]}
]}

I'm able to access the value in the results key using this and all is good:
question_access = content['results']

If I want to loop through the dictionaries inside the results key I use this:
for question_data in question_access:
    print(question_data)

Which gives me this.. all is good:
{'_class': 'question', 'course': {'_class': 'course', 'title': 'Angular 7 (formerly Angular 2) - The Complete Guide', 'url': '/the-complete-guide-to-angular-2/'}, 'replies': [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Maximilian'}}]}
{'_class': 'question', 'course': {'_class': 'course', 'title': 'RUSTCRACEON', 'url': '/the-holy-rust-book/'}, 'replies': [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Ella'}}]}
{'_class': 'question', 'course': {'_class': 'course', 'title': 'PHP ULTIMATE WEB GUIDE', 'url': '/php-to-the-world/'}, 'replies': [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Rick_Sanchez'}}]}
{'_class': 'question', 'course': {'_class': 'course', 'title': 'Javascript - The Complete Guide', 'url': '/javascript291/'}, 'replies': [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Morty'}}]}

Problem
But now my problem is.. if I want to access the replies key in the question_data key, I keep getting the last replies value and not all of the values.
i.e:
replies_access = question_data['replies']

returns:
[{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Morty'}}]

Shouldn't replies_access = question_data['replies'] return all of the values that have the replies key and not only the last value? Or am i doing something wrong?

A: One question_data is one element only from the values, so accessing ['replies'] gives you one for sure, and if you keep saving it in the same variable, at the end, only the last one remain
You may use a list to collect the replies during the loop
replies = []
for question_data in question_access:
    replies_access = question_data['replies']
    replies.append(replies_access)

print(replies)

[[{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Maximilian'}}],
 [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Ella'}}],
 [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Rick_Sanchez'}}],
 [{'_class': 'answer', 'user': {'_class': 'user', 'display_name': 'Morty'}}]]

A: replies_access = question_data['replies'] will assign the value of the current question_data to replies_access. Since you're in a for loop, you keep assigning the next replies value to replies_access. Therefore in the last iteration you assign the last replies object and that's what you get when you print. Instead, you can make a list comprehension or use append.
replies_access = list()
for question_data in question_access:
    replies_access.append(question_data['replies'])

or
replies_access = [ question_data['replies'] for question_data in question_access]


text:
Q: Cómo sumar elementos de una columna incluida en una cosulta JSON_ARRAYAGG(JSON_OBJECT()) en MySql Estimada comunidad, necesito generar una consulta a una tabla , donde el resultado sea la suma de las mediciones del mismo mes en el mismo año. Como necesito que la respuesta sea graficada, lo más lógico es hacer una consulta del tipo JSON_ARRAYAGG con el fin de obtener los valores en un json.
La tabla es algo como esto (ejemplo simplificado)

La consulta que tengo hasta ahora, es la siguiente:
SELECT YEAR(hora_medicion) AS anio,JSON_ARRAYAGG(JSON_OBJECT( 'mes', MONTH(hora_medicion), 'metros', fondo_medido))AS datos  FROM grafico GROUP BY anio

Y la respuesta que obtengo es casi lo que necesito:

Es "casi lo que necesito", porque el mes 1 del 2021 tiene dos mediciones y se deberían sumar quedando algo como esto:
2021  [{"mes": 1, "metros": "300"},  {"mes": 2 "metros": "300"},...
2022  [{"mes": 1, "metros": "600"}, {"mes": 2, "metros": "800"},...
No me ha sido posible incluir un sum(metros) dentro del JSON_ARRAYAGG por que mysql no entendería cuando sumar y todos los intentos que he realizado han sido infructuosos. He intentado parametrizando "metros" y haciendo el select sum(metros) afuera del JSON_ARRAYAGG pero tampoco he podido. Obviamente estoy haciendo algo mal.
Agradezco de antemano vuestra ayuda.
Saludos!


text:
Q: Drupal WYSIWG bar not showing for populated fields When I edit a page, the body WYSIWYG field shows as a textarea with the HTML content inside. This only happens for pages with content in that field, else a WYSIWYG field with no content is shown successfully. Hitting 'Edit summary', which is also empty, does show the WYSIWYG options.

The text format is set to Full HTML, so that it shows correctly on the front end.

I do have a warning and a couple of errors:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

jquery-1.8.3.min.js - Failed to load resource: the server responded with a status of 404 ()

I recently moved this Drupal site from AWS to a simple WHM / Cpanel server, but I don't know what's different. I am not overly familiar with Drupal. The ckeditor plugin seems to be installed.
I have tried lowering the jQuery version, flushing the cache etc. Litespeed cache is running, but not when logged in.

Drupal: 7.56
CKEditor: 4.4.5.1

Update: By removing the async from the ajax call, I removed the warning. But any simple ajax call I make, with no data etc. to a completely new function that only echo's out some text still returns a 404.
Update 2: I can remove the AJAX XSS check and the WYSIWYG shows, but I think the issues is wider, in that all AJAX across the site seems to be broken. Paginated links don't work across the site.


text:
Q: How do I use jest to make sure I am only using two arguments? I'm challenging myself to create my own tests for problems in freeCodeCamp. Currently stuck on the second requirement for 'Subtract One Number from Another with JavaScript'. Here are the requirements.
var difference = 45 - 0;

//The variable difference should be equal to 12.

 //You should only subtract one number from 45.

How could I write my own test to make sure I am only using two arguments?
(freeCodeCamp problem can be found here:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript)

A: If you were testing this as part of an application, you wouldn't necessarily be testing the expression itself but rather some function that contains this expression. To organize that code example in a testable way, you could write a function like this:

function getDifference(numberToSubtract) {
  const difference = 45 - numberToSubtract;

  return difference;
}

Then you could use Jest to assert the return value is 12 and that you've only used a single argument like this:
expect(getDifference(33)).toBe(12);


text:
Q: Databricks: Adding path to table from csv In databricks I have several CSV files that I need to load. I would like to add a column to my table with the file path, but I can't seem to find that option
My data is structured with
FileStore/subfolders/DATE01/filenameA.csv
FileStore/subfolders/DATE01/filenameB.csv
FileStore/subfolders/DATE02/filenameA.csv
FileStore/subfolders/DATE02/filenameB.csv

I'm using this SQL function in databricks, as this can loop through all the dates and add all filenameA into clevertablenameA, and all filenameB into clevertablenameB etc.
DROP view  IF EXISTS clevertablenameA;
create temporary view clevertablenameA
USING csv
OPTIONS (path "dbfs:/FileStore/subfolders/*/filenameA.csv", header = true)

My desired outcome is something like this
col1 | col2|....| path
data | data|....| dbfs:/FileStore/subfolders/DATE02/filenameA.csv
data | data|....| dbfs:/FileStore/subfolders/DATE02/filenameA.csv
data | data|....| dbfs:/FileStore/subfolders/DATE02/filenameA.csv

Is there a clever option, or should I load my data another way?

A: The function input_file_name() could be used to retrieve the file name while reading.
SELECT *, input_file_name() as path FROM clevertablenameA

Note that this does not add a column to the view and merely returns the name of the file being read.
Refer to below link for more information.
https://learn.microsoft.com/en-us/azure/databricks/spark/latest/spark-sql/language-manual/functions/input_file_name
Alternatively you could try reading the files in a pyspark/scala cell and add the file name using the same function using the .withColumn("path", input_file_name()) function and then create the view on top of it.


text:
Q: Hide/Show table columns dynamicly with JavaScript I have a button, when I press it, I must show a hidden column I have in my table. But my problem is that I only show one row.
KIT

                    KIT
                    Material
                    Info

                    <?php
                        $rol = mysql_query("SELECT * from pg  WHERE pg.dataset = 2 ");
                            if (mysql_num_rows($rol) != 0) {
                                while($item = mysql_fetch_array($rol)) {

                                    $id = $item['id'];
                                    $info = $item['info'];
                                    $code = $item['lote_code'];
                    ?>

             <tr id="infodata_<?=$id;?>">

                            <input id="check_<?=$id;?>" type="checkbox">
                            <label for="check_<?=$id;?>">

                    <?php echo $info;?>

                    <?php echo $code;?>

        <? }} ?>

My Javascript has this code:
function call()
{
    document.getElementById('kit_head').style.display = 'block';
    document.getElementById('line').style.display = 'block';
}

What may I do it to show all of the rows that my database has inside?

A: You are using an ID for the cell line.
getElementById - as the name implies - will return a single element, this will always be true because IDs are intended for single use. So your code:
document.getElementById('line').style.display = 'block';
Is getting the first matching element and setting the style attribute as defined.
Instead you should use a class which is intended to be the designation of many related elements or elements sharing common rules.
Then you can get all matching elements, loop over them and set the desired style attribute.
The DOM API exposes lots of methods for retrieving elements by their class name, you should consult the list of browser versions you intend to support and pick an appropriate technique from those available.
Edit:
As a sidenote, KennyDope is correct in saying that best practice is generally to toggle classes in order to manipulate styles. It's much easier to keep track of and modify classes than it is inline styles.

A: Best practice is to toggle classes instead of inline styles.
Your code will then something like this:

        Toggle field
        Toggle field
        Other field

<button id="btn_callkit">toggle</button>

A: id property must be unique on the page.
Conversely, class property is, as the name suggests, a class of objects, and multiple objects can share the same class.
So if you want to show/hide a column, the specific  in each row must be assgined the same class, which then will be manipulated by Javascript, using getElementByClassName.
NB, getElementByClassName returns an array of objects, and you have to walk the array to change the display style in each.


text:
Q: YouTube Live Streaming API How to set custom thumbnails to Live Broadcast Object I am creating YouTube live broadcasts using YouTube live streaming API (by using PHP API client library) everything is working fine my question is can we also set thumbnails to that broadcast object using API so that on events page or watch page it shows our custom image right now its shows channel default image? If yes then please let us know how we can achieve that.
I have noted we can change thumbnail through website but i want to change it using PHP API client.
Thanks,
Faraz


text:
Q: jQuery make an image greyscale James here. I've looked at over 50 tutorials, but I cannot seem to find an easy compact jQuery greyscale tutorial. Every single script I've tried just will not work on the site i am trying to enable this on. If anyone could assist me in my journey to have a script that makes images WITHOUT A HEIGHT, but a width of 500px greyscale on page load but change to color on hover, it would be awesome. I believe this script would use HTML5 Canvas.
Page I'd like to do this on: http://jamestestblog.tumblr.com/

A: There's a library for this called Hoverizr you should look at.

Hoverizr takes advantage of the <canvas> element's image proccessing
  capabilities. What this means is that Hoverizr gets info on each
  separate pixel of the image and proccesses it acoordingly.
Then, depending on whether you wanted the manipulated image to be
  above or below the original, on mouse over the top element fades out
  to reveal the element below.

Code looks like:
$('#imageid').hoverizr({effect:"grayscale"});

A: For security reasons, javascript and a canvas element won't be able to modify an image obtained from another domain.
See details at: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements

A: If you want to do something like that with javascript you have to use a canvas. jQuery on its own can't do this. There are alternatives however. The most simple is to use a sprite or two different images superposed and animate | hide | show.
If there are lots of images then another option is to use something like the gd library in php on the backend. You could then load them dynamically with ajax from a simple php file.