text:
Q: Why can't a Jedi or Sith control something sliced with a lightsaber? In a number of lightsaber duels between Jedi and Sith, we see one duelist, usually a Sith, use the Force to toss objects at their opponent.  The opponent ducks or dodges the object, or slices it in two with a light saber.  And once the object is sliced with a saber, both halves fall to the floor or ground.
So if something is on a trajectory where it would hit one's opponent, and it's sliced, why is it none of the Sith or Jedi who use this technique can't keep at least one half of this object going so it hits their opponent, in spite of the light saber slicing?

A: The Jedi/Sith do not control the trajectory of the objects because it requires immense concentration to do so, allowing the opponent to stage an attack or make good his escape. Merely using the force to hurl it is less precise, but can be effective if you have several objects (at least one out of many might hit) or if you have a large object (larger area for the opponent to avoid).
Two particular scenes come to mind that conveys how much concentration it takes:

*

*(Episode 2: AotC) When Yoda and Dooku fight, Dooku very easily uses the force to dent the structure, causing it to fall towards Obi-wan and Anakin due to gravity. It requires a focussed effort from Yoda to control the object and move it away from the two. He couldn't just risk blasting it with force to push it because the trajectory in this case is unpredictable and could've ended up hurting either one of them. Needless to say, Dooku used this misdirection to escape.

*(Episode 3: RotS) When Yoda and Sidious duel, Sidious hurls several pods in the Senate assembly at Yoda. After avoiding a few, Yoda stops one mid air and concentrates on spinning it and hurls it back at Sidious, which was pretty effective in throwing him off balance. Perhaps the reason why Sidious didn't do anything was because he couldn't see Yoda behind the pod, and he probably wasn't paying too much attention, instead enjoying his little melee and the chaos.

Under normal circumstances, it's much easier to throw something at someone with reasonable aim and leave them to defend while you plan your next move, rather than controlling the object carefully and precisely.

A: Two main reasons are likely (aside from "They just didn't think it through and it makes for a nice plot/scene device with good visual", of course):

*

*Force push/force throw is mainly used to accelerate an object. Presumably you don't keep pushing it once you launched it a short distance. Whereas the slicer probably employs force push to slow down the object when near them and/or to impart momentum to two halves to split up to miss them.

*As Monkeygirl noted, changing the object by slicing it may disrupt control over the original object even if the push/throw was continuously being applied. This actually helps explain the effect better, but this approach contradicts physics more than the first one (forward-moving momentum should have prevented "falling to the ground immediately" part).

A: In Phantom Menace we see Qui-Gon and Obi-Wan face off against Maul. They immediately lose their outer cloaks and default to just their tunics.
Similarly, in Attack of the Clones, as the arena fight starts we see Mace Windu sneak up on Dooku and Fett and, as the fight turns to him, shed his cloak and fight in tunic.
As most others have said large cloaks are more fitting to the Jedi/Sith lifestyle, as they're the stereotypical "monk"/evil"monk garb that Jedi, then Sith, were designed wearing. Realistically a cloak is a useful outfit for a minimalist culture like the Jedi, or for a sneaky culture like the Sith; it's effectively one size fits all, keeps you warm in cold environments and can be opened in hot ones, or not worn. It helps hide you from prying eyes, meaning that the weird monk-looking guy isn't the centre of attention.
Also, even if you consider a typical lightsaber fight, a billowing cloak might be used to confuse an attacker. Remember that most force-wielders use the force to bolster their own strength and reflexes, so a "heavy" cloak probably doesn't bother them in the least, and can possibly be used as a visual hindrance against attackers e.g. billowing it in their eyes, making their target appear larger, etc.

A: The lightsaber itself is a focal point for channeling force energies.  When the blade slices through the force thrown object the force energy used for the throw is channeled into the lightsaber much the way Yoda channels away Dooku's force lightening.  Then the Jedi can redirect that energy into altering the path of the thrown object.  In TESB Luke has not learned to channel away energy effectively yet so when he slices the objects thrown by Vader he is not able to fully deaden and redirect the objects.  The effect is actually described quite regularly throughout the Extended universe of novels.


text:
Q: WP Shortcode get_template_directory_uri() Всем привет! Ребята, возможно есть какой-то стандартный shortcode в WP с помощью которого можно было бы узнать путь к теме?
Или таковых нету? :)

A: В Wordpress есть функция get_template_directory() которая указывает путь к теме.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linking user accounts to primary key values in Oracle Apex Im brand new to Apex and fairly new to SQL. I made a database that has teachers and students. I want to make an oracle apex application such that when teachers make a new course students can sign up to it. However, since there are many teachers how do i make a form in Apex so that it knows what teacher i am referring to? I wouldnt expect teachers to have to enter their teacher_id (primary key) but dont know what to do.
I made a sequence and trigger so that when a teacher makes a new course listing, a new row goes to the database. What i am stuck on is how apex can identify which teacher is posting that. I have tried to make different users as well but have no idea how to link a teacher user account on apex to a teacher_id (primary key) value in my database so that whenever a specific teacher logs into the apex application, the database knows their teacher_id and uses that automatically whenever a teacher_id is required.
Any form of guidance will be helpful (even a link to a useful youtube video that addresses my problem - I have searched to no avail thus far).
Thanks.

A: A simple option would be to identify teachers (and students) by their usernames (they use to log in into your Apex application). In Apex, it is then referenced as :APP_USER variable. As there can't be duplicates (obviously), it will be unique so there won't be any confusion.
So, alter the users table and - along with their ID (which you already have) - add the USERNAME column (or APP_USER, or whatever you want to name it).

A: Based on the information that you have provided, I gather that you have got the tables for the teacher in place. Also, I understand that this table has a primary key of teacher_id.
Now in the course creation form, you can have a field that is mapped to this primary_key column. For display purposes, you can make this field resolve the teacher name (instead of the teacher_id) value. You can achieve this by associating the field with a List of Values (either via a Shared Component).
There are multiple configuration options to achieve this. Here is a link to help you get started on this.
Oracle Apex - LoVs
Once, you have the field render user-friendly data, if you would like it to be auto-populated based on the logged in user, you can take the approach that @Littlefoot has suggested above and link the :APP_USER with the teacher_id and use that to set the default value into this field.


text:
Q: Как с Recovery определить версию Android? Моя задача: проверить версию установленного Android из Recovery. Делаю это так:
android_version == file_getprop("/system/system/build.prop", "ro.build.version.sdk");

Но в Recovery я получаю значение именно самого Recovery (а не установленной системы, устройство system-as-root). А как проверить-то версию Android? Т е, ro.build.version.sdk у меня 29, но получаю 25, как будто из Recovery.


text:
Q: UnicodeDecodeError: 'utf8' codec can't decode byte Пишу спам-бота для Skype, и при отсылке сообщения с русскими символами у меня вылезает ошибка: UnicodeDecodeError: 'utf8' codec can't decode byte 0xf4 in position 0: invalid continuation byte
Привожу мой код:
import Skype4Py, urllib
skype = Skype4Py.Skype()
skype.Attach()
message = raw_input("Введите сообщение для рассылки:")
for f in skype.Friends:
    skype.SendMessage(f.Handle, message)

A: Для русских букв
message = unicode(message, 'cp1251')


text:
Q: Page Transform for view pager is working unexpectedly Here is the code I used to achieve depth transformation from left side of the view pager. But the click of left fragment is working even if it is not selected.
@Override
public void transformPage(View view, float position) {

    if (position < -1) {
        view.setAlpha(0);
    } else if (position <= 0) {
        view.setAlpha(1 + position);
        view.setTranslationX(view.getWidth() * -position);
        view.setTranslationZ(-1);
        view.setScaleX(1);
        view.setScaleY(1);
    } else if (position <= 1) {
        view.setAlpha(1);
        view.setScaleX(1);
        view.setScaleY(1);
        view.setTranslationZ(1);
    } else {
        view.setAlpha(1);
    }

}

A: My problem resolved by sending false instead of true in the method.
viewpager.setPageTransformer(false, new DepthPageTransformer());


text:
Q: Terminal in broken state (invisible text / no echo) after exit() during input() / raw_input() I've been writing a small utility application using Python 3 (the below testcase also works in Python 2, however) and PyQt 4 that uses the code module to spawn a REPL prompt allowing interaction with a Qt window.
Unfortunately I've hit a problem I've been unable to solve: When I exit() the app while code is inside input() (known as raw_input() in Python 2.x), my Linux terminal subsequently no longer echoes typed characters. I.e. the terminal appears to be left in a broken state, presumably due to some escape sequence issued by input().
I've tried a variety of approaches to fix this, from using the curses module and other means to reset the terminal prior to running exit, to trying to emulate the stdin stream to exit by actually handing exit() to input() (unfornunately code.InteractiveConsole.push() does not work that way, as one might think it would), to trying to write my own non-blocking input() using threading, but I've been unable to pull together something working.
Here, here, here and here are discussions of similar problems.
Finally, here is a reduced testcase to demonstrate the problem:
#!/usr/bin/env python3

import code
import sys
from PyQt4.QtGui import QApplication, QWidget

app = QApplication(sys.argv)

app.lastWindowClosed.connect(exit)

widget = QWidget()
widget.show()

code.interact()

For those unfamiliar with (Py)Qt, this will open a blank window, and when it is closed, the connection from app's lastWindowClosed signal will cause a call to the built-in exit() function to happen. This occurs while the code module is executing a call to input() to read from sys.stdin. And here, when I close the window, typing into the terminal afterwards doesn't show any of the types characters.
I'm mainly using Python 3, and the actual app uses Python 3-specific code, but I've tried the testcase in Python 2.7 as well and it shows the same problem.

A: Try os.system('stty sane'). The stty sane is supposed to reset echo, and some other things apparently.

A: The answer from Quentin Engles worked for me too but as a Python neophyte I didn't understand where the stty sane was supposed to go. After some hunting and head scratching I figured out that exit was a reference to the exit() method so I created exiting() and passed a reference to it:
#!/usr/bin/env python3

import code
import sys
from PyQt4.QtGui import QApplication, QWidget

def exiting():
    os.system('stty sane')
    exit()

app = QApplication(sys.argv)

app.lastWindowClosed.connect(exiting)

widget = QWidget()
widget.show()

code.interact()

A: This is no real solution to the problem, but
if you type "reset" in the terminal after you've closed the app, it goes back to normal.
I had similar issues once when developing a c application that didn't close a pipe correctly.
Maybe something similar is happening here aswell.

A: I've run in to the same problem using the curses module. Using the other answer on this page, I've sidestepped the problem with import os at the beginning of the program, and then ending the program with os.system('reset').


text:
Q: Same list in two different containers Can we display a single list in two different columns i.e. two different containers Or a single div but different columns?

HTML

CSS

javascript

jquery

I want the above to appear as:
HTML javascript
CSS  jquery
Also the elements in first column may vary and if the elements decrease the elements from the second column must occupy the entire space.

A: No you can not (edit: cut the list off in the middle as in your suggested HTML). What you can do is create two separate lists, but if what you're after is for the list to appear as:
1. HTML 2. javascript 3. CSS 4. jquery

I fail to understand why you simply don't just put the items in that order and display the lis as 'inline`?
If in fact you want the list to appear as:
1. HTML 3. JavaScript
2. CSS 4. jQuery

And the order of the items is "1. HTML, 2. CSS, 3. JavaScript, 4. jQuery" you will need to use column-count: 2 on the ul. This will place the list items in columns where the first two items will be in the left column, and the last two items in the right column. column-count only works in modern browsers so for the rest you'll need to use float or inline-block which will make the list appear as:
1. HTML 2. CSS
3. JavaScipt 4. jQuery


text:
Q: Google Play Console API Issue: My clients need to access app information, such as installs, uninstalls, and respond app user comments.
They access the Google Play Console to manage the information above, but are computer laymen, and with access to the Google Play Console they can run undesirable settings or even remove the app from the Google Play Console.
Solution: Create a web portal for them to view only specific information (Installations, Uninstallations and responding to end user comments from the app).
Doubt: What API will the portal that I'm going to develop need to consume to display the information (Installs, Uninstallations and answer End User Comments)?
Annex draft of the project.

A: Why don't you just use user permissions in the Play console to prevent them from doing anything undesirable? You can give users read only access, and even per-app access.
Then you don't have to write any code at all.

A: As i understand it, your portal will mainly need two things :

*

*The reviews sent by users via Google Play Store

*The Google Play Console reports
Then, you will have to do the job yourself, create some kind of blog where end-users can posts reviews, and other users can comment it. You will also need to retrieve the reviews posted via Google Play Store, and use this data to automatically post a new review on your portal. The Reply to Reviews API can help you to retrieve such reviews, in a formated output (Json).
The install and uninstall are available thanks to Google Play Console reports, stored in a private Google Cloud Storage bucket. There are a few ways to download these reports, but i guess you want get them programmatically in order to automate the process. You will need gsutil to achieve this task. I understood gsutil gives you CSV files, witch can be parsed pretty easily, in order to isolate ans send the informations you need to your portal.


text:
Q: selecting from multiple tables in SQL without a join Complete SQL novice, trying to make sense of the following TPC-H query:
select
        l_orderkey,
        sum(l_extendedprice * (1 - l_discount)) as revenue,
        o_orderdate,
        o_shippriority
from
        customer,
        orders,
        lineitem
where
        c_mktsegment = ':1'
        and c_custkey = o_custkey
        and l_orderkey = o_orderkey
        and o_orderdate < date ':2'
        and l_shipdate > date ':2'
group by
        l_orderkey,
        o_orderdate,
        o_shippriority
order by
        revenue desc,
        o_orderdate;
:n 10

I was under the impression that you can only select from different tables after a join. However I don't see any joins here. Is it implicit?

A: The comma is archaic syntax for the CROSS JOIN.  It is essentially the same thing as a Cartesian product (although the scoping rules in the FROM clause are a bit different).
The filter conditions in the WHERE clause happen to turn this Cartesian product into an inner join, but that is a function of the filtering after the FROM clasue.
You should just forget that you every learned that this syntax works.  Use explicit JOIN syntax, even for CROSS JOIN.  JOIN has been part of SQL syntax -- literally -- for decades and it was added for very good reasons.


text:
Q: How to speed up calculating geometry area of 2D boundary arrays? Background
I have four 2D arrays: lon_centers, lat_centers, lon_bnds, and lat_bnds. bnds means the boundary of each pixel and centers stands for the center of pixels.
Data overview
import numpy as np
import matplotlib.pyplot as plt

lon_bnds = np.array([[-77.9645  , -77.56074 , -77.162025, -76.76827 , -76.37937 ],
                    [-77.88815 , -77.48613 , -77.08915 , -76.69711 , -76.30993 ],
                    [-77.811676, -77.41139 , -77.01614 , -76.62582 , -76.24034 ],
                    [-77.73638 , -77.337814, -76.944275, -76.55565 , -76.17186 ],
                    [-77.66197 , -77.265114, -76.87326 , -76.48632 , -76.1042  ]])

lat_bnds = np.array([[-77.34674 , -77.35804 , -77.36858 , -77.378395, -77.38752 ],
                    [-77.28847 , -77.299614, -77.31001 , -77.31969 , -77.328674],
                    [-77.23022 , -77.24122 , -77.25147 , -77.26101 , -77.26986 ],
                    [-77.17193 , -77.182785, -77.192894, -77.20229 , -77.211006],
                    [-77.11363 , -77.12434 , -77.13431 , -77.14357 , -77.15215 ]])

lon_centers = np.array([[-77.72404 , -77.323685, -76.92833 , -76.53787 ],
                        [-77.64892 , -77.2503  , -76.85666 , -76.46791 ],
                        [-77.57335 , -77.17646 , -76.78454 , -76.3975  ],
                        [-77.499626, -77.10444 , -76.71421 , -76.32886 ]])

lat_centers = np.array([[-77.32333 , -77.334175, -77.344284, -77.353676],
                        [-77.264946, -77.27564 , -77.28561 , -77.29487 ],
                        [-77.20665 , -77.21719 , -77.22702 , -77.23614 ],
                        [-77.14826 , -77.15867 , -77.16835 , -77.17734 ]])

plt.scatter(lon_bnds, lat_bnds, label='corner')
plt.scatter(lon_centers, lat_centers, marker='x', c='r', label='center')
plt.legend()

Goal
The goal is to calculate the area (m2) of each pixel, which means area has the same shape as lon_centers and lat_centers.
I found this useful question for calculating the area of one geo-polygon. However, it needs inputs in order and loop of the 2D arrays.
Attempt
from pyproj import Geod

geod = Geod(ellps="WGS84")

areas = []

for x in range(lon_bnds.shape[0]-1):
    for y in range(lon_bnds.shape[1]-1):
        lons = lon_bnds[x:x+2, y:y+2].ravel()
        lats = lat_bnds[x:x+2, y:y+2].ravel()
        lons[-2], lons[-1] = lons[-1], lons[-2]
        lats[-2], lats[-1] = lats[-1], lats[-2]

        poly_area, poly_perimeter = geod.polygon_area_perimeter(lons, lats)
        areas.append(poly_area)

areas = np.asarray(areas).reshape(lon_centers.shape)

The for loop is too slow if there're more pixels. Is it possible to speed it up?

A: Here's something you can consider when you are doing multiple for loops onto arrays.
# Without caching
def function1():
    geod = Geod(ellps="WGS84")

    areas = []

    for x in range(lon_bnds.shape[0]-1):
        for y in range(lon_bnds.shape[1]-1):
            lons = lon_bnds[x:x+2, y:y+2].ravel()
            lats = lat_bnds[x:x+2, y:y+2].ravel()
            lons[-2], lons[-1] = lons[-1], lons[-2]
            lats[-2], lats[-1] = lats[-1], lats[-2]

            poly_area, poly_perimeter = geod.polygon_area_perimeter(lons, lats)
            areas.append(poly_area)
    return areas

# With caching
from functools import lru_cache

@lru_cache(maxsize=512)
def function2():
    geod = Geod(ellps="WGS84")

    areas = []

    for x in range(lon_bnds.shape[0]-1):
        for y in range(lon_bnds.shape[1]-1):
            lons = lon_bnds[x:x+2, y:y+2].ravel()
            lats = lat_bnds[x:x+2, y:y+2].ravel()
            lons[-2], lons[-1] = lons[-1], lons[-2]
            lats[-2], lats[-1] = lats[-1], lats[-2]

            poly_area, poly_perimeter = geod.polygon_area_perimeter(lons, lats)
            areas.append(poly_area)
    return areas

%timeit function1()
229 µs ± 10.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit function2()
84.3 ns ± 2.8 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

A: It's very convenient that you have the points arranged in a grid so you know how they match up. The general formula for the area of a planar quadrilateral given a list of points arranged in a counter-clockwise direction is:
A = 0.5 * ((x1 * y2 + x2 * y3 + x3 * y4 + x4 * y1) -
           (x2 * y1 + x3 * y2 + x4 * y3 + x1 * y4))

This won't do you much good if x and y are in degrees, but you can convert them to meters on a flat local approximation of the surface for a pretty good estimate. To do that, you need to know the local radius of the Earth, R. You can use the average radius of 6371km, or you can use R = sqrt((R1**2 * cos(lat))**2 + (R2**2 * sin(lat))**2) / ((R1 * cos(lat))**2 + (R2 * sin(lat))**2), with R1 = 6378.137km and R2 = 6356.752. Let's use the mean lat/lon of the data as the reference point:
R1 = 6378.137
R2 = 6356.752

lons = np.deg2rad(lon_bnds)
lats = np.deg2rad(lat_bnds)
R = np.sqrt(((R1**2 * np.cos(lats))**2 + (R2**2 * np.sin(lats))**2) / ((R1 * np.cos(lats))**2 + (R2 * np.sin(lats))**2))
lon_ref = np.mean(lons, axis=None)
lat_ref = np.mean(lats, axis=None)
x = R * (lons - lon_ref) * np.cos(lats)
y = R * (lats - lat_ref)

Here is a plot similar to your original, but converted to meters:
lon_c = np.deg2rad(lon_centers)
lat_c = np.deg2rad(lat_centers)
Rc = np.sqrt(((R1**2 * np.cos(lat_c))**2 + (R2**2 * np.sin(lat_c))**2) / ((R1 * np.cos(lat_c))**2 + (R2 * np.sin(lat_c))**2))
xc = Rc * (lon_c - lon_ref) * np.cos(lat_c)
yc = Rc * (lat_c - lat_ref)
plt.scatter(x, y)
plt.scatter(xc, yc, marker='x', c='r')

A = 0.5 * ((x[1:, :-1] * y[:-1, :-1] + x[1:, 1:] * y[1:, :-1] + x[:-1, 1:] * y[1:, 1:] + x[:-1, :-1] * y[:-1, 1:]) - (x[:-1, :-1] * y[1:, :-1] + x[1:, :-1] * y[1:, 1:] + x[1:, 1:] * y[:-1, 1:] + x[:-1, 1:] * y[:-1, :-1]))

The result is
array([[65.80938398, 64.91795373, 64.04493782, 63.19815103],
       [65.77719064, 64.87959934, 64.01155424, 63.16247495],
       [65.77861439, 64.87956589, 64.01289216, 63.16872493],
       [65.755155  , 64.85808632, 63.98664385, 63.14105705]])

Units are square kilometers.

For larger quadrangles, you may want to project each one individually about its center. In that case, you can do something like this:
def xy(s1, s2):
    x = R[s1, s2] * (lons[s1, s2] - lon_c) * np.cos(lats[s1, s2])
    y = R[s1, s2] * (lats[s1, s2] - lat_c)
    return x, y
x1, y1 = xy(slice(None, -1), slice(None, -1))
x2, y2 = xy(slice(None, -1), slice(1, None))
x3, y3 = xy(slice(1, None), slice(1, None))
x4, y4 = xy(slice(1, None), slice(None, -1))
A = 0.5 * ((x1 * y2 + x2 * y3 + x3 * y4 + x4 * y1) -
           (x2 * y1 + x3 * y2 + x4 * y3 + x1 * y4))

In this case, the result is similar:
array([[65.80950493, 64.9180908 , 64.04508934, 63.19831548],
       [65.77721436, 64.87964039, 64.01161095, 63.16254575],
       [65.77854026, 64.87951032, 64.01285345, 63.16870148],
       [65.75498209, 64.85793324, 63.98650883, 63.14093847]])

The areas computed this way are almost identical:
array([[65.80950493, 64.9180908 , 64.04508934, 63.19831548],
       [65.77721436, 64.87964039, 64.01161095, 63.16254575],
       [65.77854026, 64.87951032, 64.01285345, 63.16870148],
       [65.75498209, 64.85793324, 63.98650883, 63.14093847]])

The differences are just a few tens of square meters:
array([[-1.20941134e-04, -1.37064710e-04, -1.51528127e-04, -1.64456803e-04],
       [-2.37217200e-05, -4.10480434e-05, -5.67132960e-05, -7.08008247e-05],
       [ 7.41315753e-05,  5.55721762e-05,  3.87051454e-05,  2.34522307e-05],
       [ 1.72913145e-04,  1.53083044e-04,  1.35020126e-04,  1.18583183e-04]])


text:
Q: How can I save a record to mongoDB by skipping a field which is marked as required in the Mongoose schema in nodejs? I have a schema in which a field is marked as required,I have many records to insert to db but one record will not have the field which is marked as required, but I would like to insert that record also without entering data to the filed that is marked as required.  Is there any posiibilty that I can do insertion to db  in  such a way. How can I manage that record from giving the error field required.
fi
e
ld2: {
          type: String,
          required: function() {
            if(this.field2) { return true }
            else return false
          }
        }
        //trying to insert the data from controller
        //some code..
        let jsonData ={field2 :"",field2 :'abcd'}
        var test = new SchemaTest()//creating schema instance
        for(var i in jsonData)
        //for below code for first iteration field2  have no data,
        //second have data
        test.field2 = jsonData.field2
        test.save((err,test)=> {})

A: The probable thing to do would be to remove the required field. If not all records will have the field filled then it should not be set as required.
You can otherwise use an if statement to set it to true if some other property turns to be true.

//Other code.
field1 :{
  type: Boolean,
  required: true
},
field2: {
  type: String,
  required: function() {
    if(this.field1) { return true }
    else return false
  }
}
// Rest of code


text:
Q: What the option full is doing on [full]{textcomp}? Looking over the package textcomp source code, I cannot find any option declared with the name full. Why and what is this full doing?
http://www.cs.cmu.edu/afs/cs/misc/tex/common/teTeX-1.0/lib/texmf/tex/latex/base/textcomp.sty

A: It is described in The LaTeX 2ε Sources documentation:

The textcomp package
(…)
  The options for the package are the following:

*

*safe for unknown font families enables only symbols that are also in the ISO-Adobe character set; without "currency", which is often misused for the Euro. Older Type1 fonts from the non-TeX world provide only this subset.

*euro enables the "safe" symbols plus the \texteuro command. Most newer fonts
  provide this.

*full enables all TS1 commands; useful only with fonts like EC or CM bright.

*almostfull same as "\full", except that \textcircled and \t are not redefined from their defaults to avoid that commands like \copyright suddenly no
  longer work.

*force ignore all subset encoding definitions stored in the package itself or in the configuration file and always use the default subset as specified by one of the other options (seldom useful, only dangerous).


text:
Q: Prevent controller action from direct execution by user in Rails I have a situation where i need to prevent users from explicitly calling say /town/addBuilding. Town is my controller and addBuilding is the action that is executed.
Now, the thing is that this action should only be executed in my program's code and not by a user requesting to execute it. Moreover, this action is executed like a callback. In my application_controller, when some condition is met, the controller action is triggered and there is a redirection. In php, a simple guard like defining a guard and checking against it would be enough. Is there an equivalent thing in rails and if so, what is the best way to implement it ?
Thanx for reading and i appreciate your help :)
EDIT: I'm pasting some code to make it clearer, note that /town/addBuilding was an example, the controller names and actions below are differently named.
Now, that is the actual application controller code, it is part of a browser game that i'm coding.
def checkQuest
if TavernQuest.hasQuest(current_user)
  quest = TavernQuest.getQuest(current_user)
  if quest.end_time < Time.now # get quest info and check if the quest has been completed
    TavernQuest.deleteQuest(current_user)
    redirect_to :controller => 'tavern', :action => 'monsterAttack'
  end
end
end

The tavern controller action is just the plain code that i want to execute, but only if the redirection happens inside the application controller.

A: Put the addBuilding method under a line that starts with protected, as follows
protected
def addBuilding
   #your code
end

Enjoy!
EDIT: In addition to this you might also wanna use the before_filter in your controllers... I'll post the exact syntax soon.
 before_filter :addBuilding, :only => :method_name

method_name is the method from which :addBuilding can be accessed, no other method can access this method after adding in this line..
EDIT: Ok, so based on the info you provided, protected wont work since if we put your secret action under protected only the tavern controller will have access to it.
EDIT: Please consider using Sessions to check if the users have a valid session when they try to to execute the monsterAttack action..

A: It seems that you are trying to put logic into a controller which actually should belong in a model or a library.
Why do i say this: aside from the current_user and the redirect, all the code is more related to your model (where the knowledge should be) and not your controller. Your model knows when a user's quest is expired.
Example implementation:
class TavernQuest

  def self.user_quest_is_expired?(user)
    quest = getQuest(current_user)
    if quest && quest.end_time < Time.now
      TavernQuest.deleteQuest(current_user)
      true
    else
      false
    end
  end
end

and in your controller you just need to write
redirect_to :controller => 'tavern', :action => 'monsterAttack' if TavernQuest.user_quest_is_expired?(current_user)


text:
Q: VisualStudio - Deploy Error I'm having 2 errors when i try to deploy my code in my org:

Variable does not exist: PriceMargin__c[43:27]
Variable does not exist: Price__c[44:27]

The full code is here:
public with sharing class OrderItemHelper {
public OrderItemHelper() {}

public static void checkError(List<OrderItem> OrderItemList) {
    for (OrderItem orderItem : orderItemList) {
        if (orderItem.Quantity <= 0) {
            orderItem.addError(Label.OrderItemQuantityError);
        }
        else if (orderItem.UnitPrice <= 0) {
            orderItem.addError(Label.OrderItemPriceError);
        }
    }
}

public static void calcPrice(List<OrderItem> orderItemList) {
    Set<Id> orderIdSet = new Set<Id>();
    Set<Id> productIdSet = new Set<Id>();

    for (OrderItem orderItem : orderItemList) {
        orderIdSet.add(orderItem.OrderId);
        productIdSet.add(orderItem.Product2Id);
    }

    Map<Id, Order> orderMap = new Map<Id, Order>([
        SELECT Id, AccountId, Account.AccountGroup__c, DistributionCenter__c, DistributionCenter__r.State__c
        FROM Order
        WHERE Id IN: orderIdSet
    ]);

    Map<Id, Product2> productMap = new Map<Id, Product2>([
        SELECT Id, ProductHierarchy__c
        FROM Product2
        WHERE Id IN: productIdSet
    ]);

    // search margins
    Map<OrderItem, PriceMargin__c> orderItemToMargin = searchMargin(orderItemList, orderMap, productMap);

    for (OrderItem orderItem : orderItemToMargin.keySet()) {
        PriceMargin__c priceMargin = orderItemToMargin.get(orderItem);

        if (priceMargin != null) {
            orderItem.PriceMargin__c = PriceMargin.Id;
            orderItem.Price__c = orderItem.ListPrice - (orderItem.ListPrice * (priceMargin.Margin__c/100));
        }
    }
}

public static Map<OrderItem, PriceMargin__c> SearchMargin(List<OrderItem> orderItemList, Map<Id, Order> orderMap, Map<Id, Product2> ProductMap) {
    Set<Id> ProductIds      = new Set<Id>();
    Set<Id> hierarchyIds    = new Set<Id>();
    Set<Id> accountIds      = new Set<Id>();
    Set<Id> groupIds        = new Set<Id>();
    Set<Id> distributionIds = new Set<Id>();
    Set<Id> stateIds        = new Set<Id>();

    for (Order order : orderMap.values()) {
        accountIds.add(order.AccountId);
        groupIds.add(order.Account.AccountGroup__c);
        distributionids.add(order.DistributionCenter__c);
        stateIds.add(order.DistributionCenter__r.State__c);
    }

    for (Product2 product : productMap.values()) {
        ProductIds.add(product.Id);
        hierarchyIds.add(product.ProductHierarchy__c);
    }

    List<PriceMargin__c> priceMarginList = [
        SELECT Id, Product__c, ProductHierarchy__c, Account__c, AccountGroup__c, DistributionCenter__c, State__c, Margin__c, Score__c
        FROM PriceMargin__c
        WHERE (Product__c IN: productIds OR Product__c = null) AND
        (ProductHierarchy__c IN: hierarchyIds OR ProductHierarchy__c = null) AND
        (Account__c IN: accountIds OR Account__c = null) AND
        (AccountGroup__c IN: groupIds OR AccountGroup__c = null) AND
        (DistributionCenter__c IN: distributionIds OR DistributionCenter__c = null) AND
        (State__c IN: stateIds OR State__c = null)
        ORDER BY Score__c
    ];

    Map<OrderItem, PriceMargin__c> orderItemToMargin = new Map<OrderItem, PriceMargin__c>();

    for (OrderItem orderItem : orderItemList) {
        orderItemToMargin.put(orderItem, null);

        for (PriceMargin__c margin : priceMarginList) {
            if (matchMargin(margin, orderItem, orderMap, productMap)) {
                orderItemToMargin.put(orderItem, margin);
                break;
            }
        }
    }

    return orderItemToMargin;
}

public static Boolean matchMargin(PriceMargin__c margin, OrderItem orderItem, Map<Id, Order> orderMap, Map<Id, Product2> ProductMap) {
   return (String.isBlank(margin.Product__c) || margin.Product__c == orderItem.Product2Id) &&
   (String.isBlank(margin.ProductHierarchy__c) || margin.ProductHierarchy__c == productMap.get(orderItem.Product2Id).ProductHierarchy__c) &&
   (String.isBlank(margin.Account__c) || margin.Account__c == orderMap.get(orderItem.OrderId).AccountId) &&
   (String.isBlank(margin.AccountGroup__c) || margin.AccountGroup__c == orderMap.get(orderItem.OrderId).Account.AccountGroup__c) &&
   (String.isBlank(margin.DistributionCenter__c) || margin.DistributionCenter__c == orderMap.get(orderItem.OrderId).DistributionCenter__c) &&
   (String.isBlank(margin.State__c) || margin.State__c == orderMap.get(orderItem.OrderId).DistributionCenter__r.State__c);
}

}
What am i doing wrong here? Tried to search everywhere in the code, but couldn't find the problem :(


text:
Q: Laravel Spatie Media Library model_type doesn't have a default i'm having trouble setting up Laravel with the Spatie Media Library package.
Here is the error i'm getting:
SQLSTATE[HY000]: General error: 1364 Field 'model_type' doesn't have a default value (SQL: insert into `images` (`updated_at`, `created_at`) values (2018-04-05 10:38:39, 2018-04-05 10:38:39))

I'm running MySQL via Homebrew and deactivated the strict mode. Also i set the strict mode to false in config/database.php file.
Controller | ImageController.php
<?php

namespace App\Http\Controllers;

use App\Image;
use Illuminate\Http\Request;

class ImageController extends Controller
{

    public function addBackgroundImage(Request $request)
    {

     Image::create()
            ->addMediaFromRequest('background')
            ->toMediaCollection('backgrounds')
            ->save();

        return redirect('/settings')->with('success', 'Hintergrund Bild hinzugefügt');
    }

}

Model | Image.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;

class Image extends Model implements HasMedia
{
        use HasMediaTrait;

}

View | settings.blade.php
{!! Form::open(['action' => 'ImageController@addBackgroundImage', 'method' => 'POST', 'files' => true]) !!}

            Background
            {{Form::input('file', 'background')}}

            <input class="file-path validate" type="text">

    <button class="btn waves-effect waves-light" type="submit" >Speichern
        send
    </button>

{!! Form::close() !!}

Routes | web.php
Route::post('/settings', 'ImageController@addBackgroundImage')->name('background.store');

Migration
Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->morphs('model');
    $table->string('collection_name');
    $table->string('name');
    $table->string('file_name');
    $table->string('mime_type')->nullable();
    $table->string('disk');
    $table->unsignedInteger('size');
    $table->json('manipulations');
    $table->json('custom_properties');
    $table->json('responsive_images');
    $table->unsignedInteger('order_column')->nullable();
    $table->nullableTimestamps();
});

Setup

*

*laravel/framework: "5.6.*"

*spatie/laravel-medialibrary: "^7.0.0"

Thanks for any help!

A: One way is to set the protected $fillable property (array) on the Image model.


text:
Q: Import multiple CSV fields into one MySQL field I have a table like this
mytable(`id` int, 'number1' varchar(11), 'number2' varchar(1200))

Also I have cvs-like file
111111111,222222222,333333333,44444444,,,
222222222,333333333,
111111111,555555555,666666666,

They are separated by ","(or something else)
The csv have 100 colunms.
I would like to combine the second column to 100rd loumn into mysql "number2",
the first column into mysql "number1".
like this:
id number1    number 2
1  111111111  222222222,333333333,44444444
2  222222222  333333333
3  111111111  555555555,666666666

So can I use LOAD DATA INFILE to load the file into the table? How can I do this..? or have other method?
thanks.

A: Here is an option which creates a new column combining columns 2 through 100:
LOAD DATA INFILE 'input.csv'
INTO TABLE myTable
COLUMNS TERMINATED BY ','
IGNORE 1 LINES
(id, number1, number2, ..., number99)
SET newCol = CONCAT(NULLIF(number1, ''), NULLIF(number2, ''), ..., NULLIF(number99, ''));

Then, you can remove columns 2 through 100 from within MySQL:
ALTER TABLE myTable
DROP COLUMN number1,
DROP COLUMN number2,
...
DROP COLUMN number99

A: you can use the function file() to open the cvs file ;
use the function explode(',', $each_line) to seperate each line with ,,
I did not understand your demand clearly,I think simple code could like this:
$file_items = file('file.cvs');
foreach($file_items as $item) {
    $item_arr = explode(',', $item);
    // combine $item_arr[0]... $item_arr[99] ,you get $number1, $number2;
    $sql_insert = "INSERT INTO mytable (number1, number2) VALUES(number1, $number2)";
}


text:
Q: Use same DialogFragment to pass data back to Activity and fragment I want to be able to use the same Dialogfragment to pass data back an activity used to launch it. I also use a fragment to launch it. How to I implement a listener that will work with both a fragment and an activity?
Here is the code where I set up the interface in my DialogFragment:
public interface RiskListener {
     void riskAdded(Geometry envelope, Geometry point);
     void riskUpdated();
}

private RiskListener listener;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    listener = (RiskListener) getTargetFragment();
}

I am creating the DialogFragment in my fragment like so:
 FragmentManager fm = getFragmentManager();
 RiskDialogFragment riskDialogFragment = RiskDialogFragment.newInstance();
 if (!riskDialogFragment.isVisible()) {
     riskDialogFragment.setTargetFragment(context, 0);
     riskDialogFragment.show(fm, "RiskDialog");
}

How would I set up the DialogFragment to work with an Activity as well?

A: *

*Both your Activity and Fragment should implement RiskListener

*Within the activity, cast the fragment to RiskListener

*Within the fragment do the following: riskListener = (RiskListener) getActivity(); (the onAttach() method should be the best place to do it)

Note: My recommendation is to invest some time in learning some bits of MVVM and RxAndroid. It will help you solve problems like the one posted very easily and reliably. Here is one article but you can find a lot more on the web.


text:
Q: When i am defining array with the required values it's throwing error in shell script When i am defining array with the required values it's throwing  below error
db_backup_daily.sh: 103: /home/user/Desktop/db_backup_daily.sh: Syntax error: "(" unexpected (expecting "fi")

The code which I have provided is getting executed in online shell editor but the same thing when I am trying to execute from my terminal it throwing error
#!/bin/sh
year=$(date +"%Y")
month=$(date +"%B")
day=$(date +"%d")
db_backup=/home/user/Documents/db_backup
YEAR_DIR=/home/user/Documents/db_backup/$year
MONTH_DIR=/home/user/Documents/db_backup/$year/$month
DAY_DIR=/home/user/Documents/db_backup/$year/$month/$day

FILE_NAME_ARRAY=( USER_TABLE_FILE PMT_TABLE_FILE FBA_PO_TABLE_FILE VENDOR_SUPPLIER_TABLE_FILE )

LOG_FILE_NAME_ARRAY=(USER_TABLE_LOG_FILE PMT_TABLE_LOG_FILE FBA_PO_TABLE_LOG_FILE VENDOR_SUPPLIER_TABLE_LOG_FILE)

TABLES_NEED_To_BACKUP=(Add_task checklist_task_management)

echo 'code executed successfully'

above code should get executed from the terminal

A: #!/bin/sh means this script is meant to be run on the system's default POSIX shell, which is not always a link to bash/ksh, thus not guaranteed to support arrays. You need to change it to:
#!/bin/bash


text:
Q: cannot find protractor-result folder 'protractor-html-screenshot-reporter' I'm trying to generate reports in Protractor and i followed this tutorial to do that.
Here is my conf.js file.
var HtmlReporter = require('protractor-html-screenshot-reporter');
var reporter = new HtmlReporter({
    baseDirectory: 'D:/My Work/Protractor/Financial/protractor-result', // a location to store screen shots.
    docTitle: 'Protractor Demo Reporter',
    docName: 'protractor-demo-tests-report.html'
});

exports.config = {
  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['invoice.js'],
  capabilities: {
    browserName: 'chrome',
  },
  jasmineNodeOpts: {
    showColors: true, // Use colors in the command line report.
  },
  onPrepare: function() {
      jasmine.getEnv().addReporter(reporter);
  }
}

I tried run this using command protractor conf.js and there's no folder generated containing test results. If I use command, protractor specs\configurations.js following error occurs.
ERROR - failed loading configuration file specs/conf.js
C:\Users\Manuli\AppData\Roaming\npm\node_modules\protractor\lib\configParser.js:
204
    throw e;
    ^

Error: Cannot find module 'D:\My Work\Protractor\Financial\specs\conf.js'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at ConfigParser.addFileConfig (C:\Users\Manuli\AppData\Roaming\npm\node_modu
les\protractor\lib\configParser.js:195:22)
    at Object.init (C:\Users\Manuli\AppData\Roaming\npm\node_modules\protractor\
lib\launcher.js:103:18)
    at Object.<anonymous> (C:\Users\Manuli\AppData\Roaming\npm\node_modules\prot
ractor\lib\cli.js:140:23)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)

Why can't I  generate reports?
Thanks in advance. :)

A: I changesd my conf.js as this.
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');

var reporter = new HtmlScreenshotReporter({
  dest: 'D:/My Work/Protractor/Financial/screenshots',
  filename: 'my-report.html'
});

exports.config = {
framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['invoice.js'],
  capabilities: {
    browserName: 'chrome',
  },
 // Setup the report before any tests start
   beforeLaunch: function() {
      return new Promise(function(resolve){
        reporter.beforeLaunch(resolve);
      });
   },

   // Assign the test reporter to each running instance
   onPrepare: function() {
      jasmine.getEnv().addReporter(reporter);
   },

   // Close the report after all tests finish
   afterLaunch: function(exitCode) {
      return new Promise(function(resolve){
        reporter.afterLaunch(resolve.bind(this, exitCode));
      });
   }
}

Then I used npm install protractor-jasmine2-screenshot-reporter --save-dev command to install npm.
Working now. :)


text:
Q: Cannot get access to SQL Server database after first access I get the following error message when I attempt to connect to my database.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (.Net SqlClient Data Provider)

This is the 3rd time that I removed and reinstalled it. On the first successful login, it is fine. Second time, I make changes to the database and get errors about not being able to find the database. I close the program and upon reopening get this error message.
It is confusing but this is SQL Server Express even though it says SQL Server Management Studio 17 upon opening.
Any thoughts or ideas?

A: Make sure database or instance is not in single-user mode.
To change it on instance-level you have to modify the launch parameters of your instance into SQL Server Configuration Manager.
To change it on database-level you have to modify the SINGLE USER option :
Set database from SINGLE USER mode to MULTI USER


text:
Q: Spacing behavior changes with empheq If I replace an align* environment with the empheq environment (of align* flavor) the spacing behavior changes: With empheq the spacing depends on the amount of text in the last line of the previous paragraph, with align it does not (see mwe).
How can I make empheq behave just like align without messing around with the spacing manually? The reduced spacing may be a good thing for small equations (as in the mwe), but if I use empheq my equations are always large enough that I feel the extra space is a good thing..
\documentclass{article}
\usepackage{blindtext}
\usepackage{empheq}
\begin{document}

\blindtext
\begin{empheq}{align*}
f(x) = x^2 % less spacing than align
\end{empheq}

\blindtext Test test test test test test test.
\begin{empheq}{align*}
f(x) = x^2 % more text on last line of paragraph => same spacing as align
\end{empheq}

\blindtext
\begin{align*}
f(x) = x^2
\end{align*}

\blindtext
\end{document}

Edit. Just to be clear: It's not so much that I dislike the fact that the environment is sensitive to its surrounding, with a little more space I would even prefer this. But I use \[ .. \] or align* for my other equations and the inconsistent spacing is really noticeable and makes my other equations stand out.

A: You can patch \empheq to set the "short skips" equal to the non short ones:
\documentclass{article}
\usepackage{blindtext}
\usepackage{empheq}
\usepackage{xpatch}

\ExplSyntaxOn
\xpretocmd{\empheq}
  {\abovedisplayshortskip=\abovedisplayskip
   \belowdisplayshortskip=\belowdisplayskip}
  {}{}
\ExplSyntaxOff

\begin{document}

\blindtext
\begin{empheq}{align*}
f(x) = x^2 % less spacing than align
\end{empheq}

\blindtext
\begin{align*}
f(x) = x^2
\end{align*}

\blindtext
\end{document}


text:
Q: How to regular monitoring the url in sketchup ruby plugin? I try to regular monitoring the url in sketchup ruby plugin..
I search some code to do this function:
require 'ping'
def every_n_seconds(n)
    loop do
        before= Time.now
        yield
        interval=n-(Time.now-before)
        sleep(interval) if interval>0
    end
end
every_n_seconds(50) do
   pingresult=Ping.pingecho("www.google.com")
   puts pingresult
   if pingresult="true"
        puts "t"
    else
        puts "f!"
    end
end

but in first line, I get the error:

LoadError: C:/Program Files (x86)/SketchUp/SketchUp
  2013/Plugins/xxx.rb:3:in `require': no such file to load --
  ping

I want to find the ping class library  but I  find nothing..
so where I can find the ping class or
Has any other method to achieve that function?

A: What's wrong with just running ping yourself?
`ping -c 1 www.google.com`
if $?.exitstatus == 0
  puts "t"
else
  puts "f"
end

Or, even better:
def ping(url)
  `ping -c 4 #{url}`
  $?.exitstatus == 0
end

if ping("www.google.com")
  puts "t"
else
  puts "f"
end

Running on a separate thread:
def ping(url)
  `ping -c 4 #{url}`
  $?.exitstatus == 0
end

def every_n_seconds(n)
  loop do
    before= Time.now
    yield
    interval=n-(Time.now-before)
    sleep(interval) if interval>0
  end
end

ping_thread = Thread.new {
  every_n_seconds(50) do
    pingresult=ping("google.com")
    puts pingresult
    if pingresult
      puts "t"
    else
      puts "f!"
    end
  end
}

puts "Doing other things now..."

ping_thread.join()


text:
Q: Query individual values in a nested json record I have the following table in Aurora Postgres:
create table newtable(column1 jsonb);

insert into newtable(column1) values
('{"usertype":[{"type":"staff","status":"active","permissions": {"1": "add user","2": "add account"}}
             , {"type":"customer","status":"suspended"}
             , {"type":"corporate","status":"active"}]}');

I can get to a certain degree of data selection using the LATERAL query syntax. But I need help with querying one level deeper.
PLEASE Ignore: the additional rows selected as I tried a few formats.
SELECT json_line_item ->> 'type' as "type", json_line_item ->> 'status' as "status" , json_line_item->>'permissions'  "permissions"
FROM   newtable
,  LATERAL jsonb_array_elements(newtable.column1 -> 'usertype') json_line_item;

I want the permissions column as a list without any extra double quotes.
Another option is to get one single permissions by filtering (for eg: permissions[1] or permissions[2] etc.

A: List

I want the permissions column as a list without any extra double quotes.

Use jsonb_each_text() in another LATERAL subquery to extract (key and) object values, then concatenate the list with string_agg():
SELECT id
     , js_line_item ->> 'type'        AS type
     , js_line_item ->> 'status'      AS status
     , js_line_item ->> 'permissions' AS permissions
     , p.permission_list                                -- !
FROM   newtable n
LEFT   JOIN LATERAL jsonb_array_elements(n.column1 -> 'usertype') AS js_line_item ON true
CROSS  JOIN LATERAL (
   SELECT string_agg(value, ', ') AS permission_list
   FROM   jsonb_each_text(js_line_item -> 'permissions')
   ) p;

db<>fiddle here
Use LEFT JOIN LATERAL to retain all rows even without "usertype" data. I added an id to make that clearer. CROSS JOIN like before would eliminate such rows from the result.
The added table expression can be joined with a CROSS JOIN because a subquery with an aggregate function and no GROUP BY always returns a single aggregated row.
Single permissions

... get one single permissions by filtering (for eg: permissions[1] or permissions[2] etc.

SELECT id
     , js_line_item ->> 'type'   AS type
     , js_line_item ->> 'status' AS status
     , js_line_item -> 'permissions' ->> '1' AS permission_1  -- !
     , js_line_item #>> '{permissions, 2}'   AS permission_2  -- !
--   , js_line_item['permissions']['3']      AS permission_3  -- ! ① for pg 14
FROM   newtable n
LEFT   JOIN LATERAL jsonb_array_elements(n.column1 -> 'usertype') AS js_line_item ON true;

db<>fiddle here
In (current) Postgres 13 you cannot iterate through objects of a record with subscripts like permissions[1]. That only works for arrays.
I added two syntax variants for Postgres 13.
① The third syntax variant requires Postgres 14, using the new "jsonb subscripting".
Use quoted key names to extract values from objects, and ordinal integer positions (starting at 0) to extract elements from arrays.
3 in our example js_line_item['permissions']['3'] is a key name and has to be quoted.
The manual:

If a jsonb value is an array, numeric subscripts start at zero, and negative integers count backwards from the last element of the array. Slice expressions are not supported.


text:
Q: Is there any public base image with docker daemon i can use within a kfp comoonent? I would love to have a base image with docker daemon up and running so i will be able to build/pull/push containers within the code running on top of it
Specifically, i have a kfp component which i want to use this base image with as follows:
 @component(
    packages_to_install=["GitPython", "docker"],
    base_image="????????",
 )

  def do_docker_stuff_component(
     ...
  ):

    import docker

    client = docker.from_env()
....

Is there a base image i can use? How should i build one if it does not exit?
I tried to build one as follows:
(Dockerfile)
FROM cimg/python:3.9.9
USER root

RUN apt-get update && apt-get install -y \
curl

RUN apt install -y apt-transport-https ca-certificates curl software-properties-common
RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"
RUN apt install -y docker-ce

ENTRYPOINT ["dockerd", "-b", "none", "--experimental", "--iptables=0","-l", "info", "--rootless"]

but when running the kfp component using the image built from this Dockerfile as base image i get an error:

docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

This question details maybe too much, just a base image with a Docker Daemon might be enough, thanks


text:
Q: How to run a custom System.Attribute over an ashx file Normally, on a usual aspx file, I can use System.Attribute at the begining of the page, like:
    [AuthorizePage()]
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }

    public class AuthorizePage : System.Attribute
    {
         public AuthorizePage()
         {
            //do some stuff to authorize
         }
    }

And before the page initializes the Attribute's constructor runs and do some stuff to ensure a person is currently logged in, otherwise the attribute constructor Redirects user to a login page.
I wanted to do the same on a HttpHandler (ashx file), but the attribute never initializes when on a ashx page.
[AuthorizePage()]
public class AjaxHandler : MuCustomClassBase, IHttpHandler, IReadOnlySessionState
{
     //The interface implementations and some other custom private methods
}

I do an AJAX Call to this ashx page. Could this be the reason why the Attribute doesn't run? Or any other things I must know?
Eventually, I would be extremely happy to know How to run a Custom System.Attribute over an ashx file?

A: Assuming you are using ASP.Net authentication, you can just add the .ashx to the list of protected pages in web.config and IIS/ASP.Net will take care of the rest:
  <location path="AjaxRequests.ashx">
    <system.web>
      <authorization>
        <allow users="?" />
      </authorization>
    </system.web>
  </location>

If you are using a self-built authentication scheme, you could override OnProcessRequest and  perform the necessary authentication in that method, redirecting as needed.

A: Attributes don't do anything by themselves. You can pile 10 random attributes on a class and nothing will really happen. Attributes just provide metadata about the class/method/property.
There should be a piece of code that looks at the metadata and act on it. Since you seem to be using custom AuthorizePageAttribute such piece of code either don't run for handlers or does not expect class that is not derived from Page to have such attribute.
To fix an issue you need to find what handles you custom attribute and fix it. You may need to add similar code to your handlers directly.
The fact that your code in constructor of attribute does something useful for a page class on every request to that page sounds suspicious - I'd expect such attributes to be created once per type instance. Relying on non-trivial code in constructor of an attribute to run per-instance of the class seems dangerous to my.

A: Well first of all yes you are reinventing the ActionFilterAttribute in Asp.Net MVC. But, I have to ask if you really need to use attribute? I suggest you to use inheritance model. Let me simply explain; you might have a SecurePage : Page class that implements the security operations. You may then pass the security code that is related to the derived page.
And if you insist on using attributes, you should intersect the handler mechanism by writing a base factory handler that routes to the needed handler. This handler should behave like a mediator object.


text:
Q: When do I init the segue controller UIViewController:prepareForSegue:? There is a lot of code out there and it's really varied. Sometimes the segue controller is :init'd, and sometimes it's used as is. It's obviously set to an object before I :init it, but in some cases the controller does not work as expected. There doesn't seem to be any documentation on prepareForSegue that clears this up.
Also I might add that some developers even use a third option and simply redefine what segue they present.
What am I missing?
Example
UIImagePickerController for iPad requires :init (no photos are loaded into the picker), on the iPhone it works as expected.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // This line is required for iPad functionality.
    // UIImagePickerController *segueController = [((UIImagePickerController*)(segue.destinationViewController)) init];

    // This line is all that is required on iPhone/iPod
    UIImagePickerController *segueController = (UIImagePickerController*)segue.destinationViewController;

    segueController.delegate = self;
    segueController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}

Another SO Post: iOS7 Storyboard image picker not working :(
Edit
It appears as though there might be an issue with UIImagePickerController:initWithCoder, but I don't know how to verify that.

A: -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    UIImagePickerController *destinationController = (UIImagePickerController*)segue.destinationViewController;

    destinationController.delegate = self;
    destinationController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}

You don't [ alloc] init] a UIViewController.


text:
Q: Is it possible to vertically center a SPAN within a DIV? Here's what I got:

    Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet. Lorum ipsum delore sit amet.
    Goodbye

And the CSS:
/* slideshow */
.slideshow {
width:940px;
height:64px;
text-align:center;
background-image:url(../images/quotes.png);
position:relative;
}
.slideshow span {
display:block;
width:940px;
height:64px;
}

The s are currently centered horizontally, but they should also be centered vertically. Is this possible?
The whole idea is to have testimonials on top the background image (quotes on the left and right side), but it doesn't quite look right without being centered both horizontally and vertically.
I'm sure I could somewhat get the desired effect using padding, but since each testimonial will be a different length I don't think that'd be a good approach.

A: if you know that the content of your span will never exceed one line of text, just set
.slideshow span {
    line-height: 64px /* = the height of the containing div */
}

Or, if you know the height of the span:
.slideshow span {
    display: block;
    position: absolute;
    height: 64px;
    top: 50%;
    margin-top: -32px; /* = height/2 */
}

Last option would be to use a table formed by a single cell in place of the div, and use the vertical-align property.

A: CSS:

HTML:

    The Span

A: yes it is possible.
Use the CSS attribute vertical-align:middle.
If you want to align verticaly below or above the horizontal center position then Use like this :
vertical-align:5;

or
vertical-align:-5;


text:
Q: Does anyone know how to get rid of this space when i press enter after a title in Word? So Im doing an assignment for school, and i have the titles numbered and stuff.. and well, after i press enter after one of the headings it creates HUGE space between it and the heading under it, like it puts the rest of the text on the next page. i tried everything and cant change it. Any tips?

A: The spacing is set to a higher value than you like, either the "spacing before" for the Heading 1, or the "spacing after" for the Heading 1.1.
Select one of the headings by clicking on the left margin at the level of the heading. Once the heading is selected, right click on it and select Paragraph... a.
A window opens where you can define all kinds of parameters for that type of heading. Among those there is spacing before/after.
Experiment with those values, but check first where the problem is. It may also be that it is a sum of two values, a bit too much spacing after for Heading 1 combined with too much spacing before for Heading 1.1. I personally normally use only spacing after.
To my eye, the spacing in your example looks fine, by the way.

A: If the problem is the space between your title and your first heading, it is the space before or space after formatting of the two paragraphs.
If the problem is that your next paragraph is on the next page, that has to do with the paragraph formatting of the text on that page. Look for "Keep with Next" and "Keep Lines Together" formatting.


text:
Q: Source with range of years Some of my references are annual publications of which I'm using multiple editions. I cannot figure out, however, how to cite them with only 1 reference entry.
In the text it should look something like this:
(IEA 1996-2012)
And in the References:
IEA 1996-2012. Energy Balances of non-OECD Countries, Paris.
BibTex does not seem to accept year-ranges in the year field...
Any help is highly appreciated!

A: It seems that BiBLaTeX accepts date ranges in the date and, also, in the year fields (see section 2.3.8 of the manual; v2.6)
The range specification is 1988/1992

A: BibTeX does accept year ranges, but then you have to enclose them in curly brackets. Tested with
@misc{yearrange,
  author = {F. Bar},
  title = {Some title},
  year = {2011--2013},
}

and
\documentclass{article}
\begin{document}
\cite{yearrange}
\bibliographystyle{plain}
\bibliography{test}
\end{document}

The year range is uncommon, but allowed in general, so I would blame Mendeley for not supporting it. To quote btxdoc:

year field: The year of publication or, for an unpublished work, the
  year it was written. Generally it should consist of four numerals,
  such as 1984, although the standard styles can handle any year whose
  last four nonpunctuation characters are numerals, such as '(about
  1984)'.


text:
Q: fetch images using picasso in adapter from fragment I have a recycleview which fetches data from api with a custom adapter containing a textview and imageview and I implemented this in Activity and it works fine, but now I tried to use fragment instead of activity and every thing works fine except for the images that are not displayed after moving the code to fragment so this is my fragment:
public class TVFragment extends Fragment implements TVAdapter.TVAdapterOnClickHandler {

    TVAdapter mAdapter;

    RecyclerView mSportsList;

    String sortsports="sports.php";

    Context mContext ;

    public static TVFragment newInstance() {
        TVFragment fragment = new TVFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_tv, container, false);

        mSportsList = (RecyclerView) view.findViewById(R.id.rv_sports);

        mContext = getActivity();

        GridLayoutManager LayoutManagerSports = new GridLayoutManager(getActivity(), 3);
        mSportsList.setLayoutManager(LayoutManagerSports);
        mSportsList.setHasFixedSize(true);
        mAdapter = new TVAdapter(this, mContext);
        mSportsList.setAdapter(mAdapter);

        loadTVData(sortsports);
        return view;
    }

    private void loadTVData(String sortChannels) {
        showTVDataView();
        new FetchTVTask().execute(sortChannels);
    }

    @Override
    public void onClick(TVItem channel) {
        Context context = getActivity().getApplicationContext();
        Class destinationClass = TVChannel.class;
        Intent intentToStartDetailActivity = new Intent(context, destinationClass);
        intentToStartDetailActivity.putExtra("TVChannel", channel);
        startActivity(intentToStartDetailActivity);
    }

    private void showTVDataView() {
        mSportsList.setVisibility(View.VISIBLE);

    }

    public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected ArrayList<TVItem> doInBackground(String... params) {
            if (params.length == 0) {
                return null;
            }
            String sortChannels = params[0];
            URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);

            try {
                String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);

                ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(getContext(), jsonTVResponse);

                return simpleJsonTVData;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(ArrayList<TVItem> TVData) {
            if (TVData != null) {
                showTVDataView();
                mAdapter.setTVData(TVData);
            } else {
            }
        }
    }

}

then this is my adapter:
public class TVAdapter extends RecyclerView.Adapter<TVAdapter.RecyclerViewHolder> {

    ArrayList<TVItem> mChannelItems;
    private Context mContext;
    private final TVAdapter.TVAdapterOnClickHandler mClickHandler;

    public interface TVAdapterOnClickHandler {
        void onClick(TVItem channel);
    }

    public TVAdapter(TVAdapterOnClickHandler clickHandler, Context context) {
        this.mContext = context;
        mClickHandler = clickHandler;
    }

    class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public final TextView Cat;
        public final ImageView Image;

        public RecyclerViewHolder(View view) {
            super(view);
            Cat = (TextView)itemView.findViewById(R.id.channel_cat);
            Image = (ImageView) itemView.findViewById(R.id.channel_image);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int adapterPosition = getAdapterPosition();
            TVItem channel = mChannelItems.get(adapterPosition);
            mClickHandler.onClick(channel);
        }
    }

    @Override
    public TVAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        mContext = viewGroup.getContext();
        int layoutIdForListItem = R.layout.tv_list_item;
        LayoutInflater inflater = LayoutInflater.from(mContext);
        boolean shouldAttachToParentImmediately = false;

        View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
        return new TVAdapter.RecyclerViewHolder(view);

    }

    @Override
    public void onBindViewHolder(TVAdapter.RecyclerViewHolder holder, int position) {
        Picasso.with(mContext).load(mChannelItems.get(position).getFullImagePath()).resize(500,500).placeholder(R.drawable.placeholder).error(R.drawable.placeholder).into(holder.Image);
        holder.Cat.setText(String.valueOf(mChannelItems.get(position).getTitle()));
    }

    @Override
    public int getItemCount() {
        if (null == mChannelItems)
            return 0;
        else {
            return mChannelItems.size();
        }
    }

    public void setTVData(ArrayList<TVItem> TVData) {
        mChannelItems = TVData;
        notifyDataSetChanged();
    }

}

you can see these lines:
Picasso.with(mContext).load(mChannelItems.get(position).getFullImagePath()).resize(500,500).placeholder(R.drawable.placeholder).error(R.drawable.placeholder).into(holder.Image);

and:
holder.Cat.setText(String.valueOf(mChannelItems.get(position).getTitle()));
the cat still displayed well in textview but the images with picasso library not displayed anymore and I read a lot of solutions like pass the context from fragment to adapter but nothing work!
this is the debugging images:

A: viewgroup.getContext() Isn't the context needed, but the context from the fragment or an activity.
@Override
public TVAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    //mContext = viewGroup.getContext(); This should fix it. You already init mContext in the constructor.
    int layoutIdForListItem = R.layout.tv_list_item;
    LayoutInflater inflater = LayoutInflater.from(mContext);
    boolean shouldAttachToParentImmediately = false;

    View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
    return new TVAdapter.RecyclerViewHolder(view);

}

A: Why are you assigning value to mContext twice? Try removing mContext = viewGroup.getContext(); from code.


text:
Q: Convergence of a sequence of periodic functions Motivated by the homogenization theory which studies the effects of high-frequency oscillations in the coefficients upon solutions of PDE, I am thinking about the following question.
Let the periodic function$$\alpha(x+1)=\alpha(x),\quad\alpha(x)>0,\quad x\in{\bf R}$$
and the sequence $$\alpha_n=\alpha(nx)\quad n\in{\bf N}$$ Consider the Hilbert space $$H^1_0([0,1]):=\{u:[0,1]\to{\bf R}\,|\,u,u'\in L^2([0,1]), u(0)=u(1)=0\}.$$
Here is my question:

What kind of convergence can one
  expect for the sequence
  $(\alpha_n(x))_{n=1}^{\infty}$, and
  what is the corresponding limit?

Edit: According to Qiaochu's comment, I assume TWO different inner products here:
$$\langle u,v\rangle_1=\int_{0}^1uvdx$$
and
$$\langle u,v\rangle_2=\int_{0}^1uvdx+\int_{0}^1u'v'dx$$
For what topology can one expect the convergence of the above sequence?

Edit: If one defines
$$\hat{\alpha} = \frac{1}{\int_0^1\frac{1}{\alpha(x)}dx}$$ can one expect some relationship between $(\alpha_n)$ and $\hat{\alpha}$?

A: If $\alpha\in L_2([0,1])$ then sequence $\alpha_n(x)$ converges weakly to $\int_0^1 \alpha(x)\,dx\ $.

A: Let's first figure out what the limit would be.  There are essentially two types of convergence that we might care about:  convergence in $H_0^1\left( [0,1]\right)$ and convergence in $C\left( [0,1]\right)$.  I have ordered them from strongest to weakest.  (As the interval is not changing, from now on, I'll just write the first letter for these spaces).
If the sequence converges in $H_0^1$, then it is a bounded sequence in $H_0^1$.  Thus, by the Sobolev Embedding Theorem (see, e.g., Brezis, Functional Analysis, Sobolev Spaces, and Partial Differential Equations), pg. 212-213), there is a subsequecne $\alpha _{m_n}$ that converges in $C$.  You can use this argument to show that every subsequence of $\alpha _n$ has in turn a subsequence that converges in $C$, so that the original sequence converges in $C$.  Thus, convergence in $H_0^1$ is stronger than convergence in $C$, so we might as well only concern ourselves with convergence in $C$.
Now, suppose $\alpha _n$ converges in $C$.  For each rational $x\in [0,1]$, $n$ will eventually be large enough $nx\in \mathbb{Z}$, so that $\alpha _n(x)=\alpha (nx)=\alpha (0)=0$.  Thus, the limiting function must be $0$ on the rationals, and hence by continuity, must be identically $0$.  Thus, if $\alpha _n$ is to convergence in either $H_0^1$ or $C$, it must convergen to the function that is identically $0$.
This clearly implies that this sequence will not converge for a lot of $\alpha$.  For example, $\alpha (x)=\sin (\pi x)$.  This certainly does not converge to $0$, and as this is the only possibility, it must not converge at all.
I hope I didn't screw any of that up.  Please point out any mistakes I have made.  In any case, correct or not, I hope what I have said has been useful.
-Jonny Gleason

A: Why would you expect your functions to converge? Rescaling the physical coordinates is given by a inverse scaling in frequency space: $\alpha_n$ has the same $L^2$ as $\alpha$, but the $\dot{H}^1$ norm grows unboundedly. So you have no convergence in any sense related to $H^1_0$, and you get weak convergence in $L^2$ (since any bounded sequence in a Hilbert space has a weakly converging subsequence by Banach-Alaoglu).
Furthermore, unless $\alpha$ is constant, the weak convergence in $L^2$ cannot be upgraded to strong convergence, since for any fixed $n$, you have $$\lim_{m\to\infty} \|\alpha_m-\alpha_n\|_{L^2} = 2\|\alpha - \bar{\alpha}\|_{L^2}$$ where $\bar\alpha$ is the mean of $\alpha$, by Andrew's observation.

As a side remark, while what you wrote for the definition of $H^1_0$ is intuitively acceptable, it is not technically correct as the definition. (Note that $L^2$ "functions" are equivalent classes, and it doesn't really make sense to require that an $L^2$ function vanishes on a measure zero set.) $H^1_0$ is better defined as the the completion of $C^\infty_0$ under the $H^1$ norm.


text:
Q: ¿Cómo utilizar una biblioteca de jquery que está en node_modules en un componente de Angular? Tengo instalado el paquete de masonry y sus archivos están en node_modules/masonry_layout. También tengo instalado jQuery. Necesito utilizar Masonry en un componente.
En mi componente tengo lo siguiente:
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';window["$"] = $; window["jQuery"] = $;
@Component({
  selector: 'app-galeria',
  templateUrl: './galeria.component.html',
  styleUrls: ['./galeria.component.min.css']
})
export class GaleriaComponent implements OnInit {
  constructor() { }
  ngOnInit() {
    $(document).ready(function() {
      $('.grid').masonry({
        itemSelector: '.grid-item',
        columnWidth: '.grid-sizer',
        percentPosition: true
      });
    });
  }
}

He intentado importar Masonry al componente de las siguientes maneras:
import * as _ from 'masonry-layout';
import * from 'masonry-layout';
import 'node_modules/masonry-layout/dist/masonry.min.js';

También intenté guardar el masonry.min.js en mi directorio de assets y cargarlo directamente en index.html como un script cualquiera.
<script src="node_modules/masonry-layout/dist/masonry.min.js"></script>

Nada de esto ha funcionado. La consola me dice que la función masonry() no es una propiedad de jQuery.
¿Saben cómo cargar correctamente este tipo de archivos a los componentes?

A: Según la documentación de Masonry puedes usar el plugin sin jQuery lo primero que debes hacer es instalar masonry desde npm
npm install masonry-layout --save

y para usar el plugin solo necesitas hacer el import de esta manera
import  Masonry  from 'masonry-layout';

en el componente que desees usar, te pongo un ejemplo ya funcionando https://stackblitz.com/edit/angular-dz1sva

A: Lo que tienes que hacer es lo siguiente:
1. En tu archivo index.html debes tener declarado tu archivo jquery.min:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
2. Instalar con npm install masonry-layout --save
3. Abrir el archivo .angular-cli.json (se encuentra en la raiz de tu proyecto)
4. Ir a la parte "scripts"

"scripts": [
          "../node_modules/masonry-layout/dist/masonry.pkgd.min.js"
      ],

5. En tu componente debe quedar de la siguiente manera

import { Component, OnInit } from '@angular/core';
declare var $:any;
declare var Masonry: any;
@Component({
  selector: 'app-galeria',
  templateUrl: './galeria.component.html',
  styleUrls: ['./galeria.component.min.css']
})
export class GaleriaComponent implements OnInit {
  constructor() { }
  ngOnInit() {
    $(document).ready(function() {
      $('.grid').masonry({
        itemSelector: '.grid-item',
        columnWidth: '.grid-sizer',
        percentPosition: true
      });
    });

    // o puede hacerlo de esta manera
    /*
  var elem = document.querySelector('.grid');
  var msnry = new Masonry( elem, {
    // options
    itemSelector: '.grid-item',
    columnWidth: 200
  })
    */
  }
}

6. Si sigues con problemas, puedes revisar este repositorio de masonry compatible con angular, el github es: Click aquí


text:
Q: Change file permissions in mounted folder inside docker container on Windows Host Disclaimer/Edit 2
Some years later, for everyone reading this question - If you are on Windows and want to use docker with linux containers, I highly recommend not using docker for windows at all and instead starting the entire docker environment inside a VM altogether. This Ext3 NTFS issue will break your neck on so many different levels that installing docker-machine might not even be worth the effort.

Edit:
I am using docker-machine which starts a boot2docker instance inside a Virtualbox VM with a shared folder on /c/Users from which you can mount volumes into your containers. The permissions of said volumes are the ones the question is about. The VMs are stored under /c/Users/tom/.docker/
I chose to use the docker-machine Virtualbox workflow over Hyper-V because I need VBox in my daily workflow and running Hyper-V and Virtualbox together on one system is not possible due to incompabilities between different Hypervisors.
Original question
I am currently trying to set up PHPMyAdmin in a container on windows but I can't change the permissions of the config.inc.php file.
I found: Cannot call chown inside Docker container (Docker for Windows) and thought this might be somewhat related but it appears to apply only to MongoDB.
This is my docker-compose.yml
    version: "3"

    services:
      pma:
        image: (secrect company registry)/phpmyadmin
        ports:
          - 9090:80
        volumes:
          - /c/Users/tom/projects/myproject/data/var/www/public/config.inc.php:/var/www/public/config.inc.php

now, when I docker exec -it [container] bash and change in the mounted directory, I try to run chmod on the config.inc.php but for some reason, it fails silently.
root@22a4bag43245: ls -la config.inc.php
-rw------- 1 root root 0 Aug 11 15:11 config.inc.php
root@22a4bag43245: chmod 655 config.inc.php
root@22a4bag43245: ls -la config.inc.php
-rw------- 1 root root 0 Aug 11 15:11 config.inc.php

Considering the linked answer, I thought I could just move the volume out of my Userhome but then vbox doesn't mount the folder at all.
How do I change the file permissions of /var/www/public/config.inc.php persistently?

A: Try one of the following:

*

*If you can rebuild the image  image:  image: (secrect company registry)/docker-stretchimal-apache2-php7-pma then inside the docker file, add the following
USER root
RUN chmod 655 config.inc.php
Then you can rebuild the image and push it to the registry, and what you were doing should work. This should be your preferred solution, as you don't want to be manually changing the permissions everytime you start a new container

*Try to exec using the user root explicitly
docker exec -it -u root [container] bash

A: I had the same problem of not being able to change ownership even after using chown. And as I  researched, it was because of NTFS volumes being mounted inside ext filesystem. So I used another approach.
The volumes internal to docker are free from these problems. So you can mount your file on internal docker volume and then create a hard symlink to that file inside your local folder wherever you want:
sudo ln $(docker volume inspect --format '{{ .Mountpoint }}' <project_name>_<volume_name>) <absolute_path_of_destination>

This way you can have your files in desired place, inside docker and without any permission issues, and you will be able to modify the contents of file as in the normal volume mount due to hard symlink.
Here is a working implementation of this process which mounts and links a directory. In case you wanna know about the details, see possible fix section in issue.
EDIT
Steps to implement this approach:

*

*Mount the concerned file in internal docker-volume(also known as named volumes).

*Before making hardlink, make sure volumes and concerned file are present there. To ensure this, you should have run your container at least once before or if you want to automate this file creation, you can include a docker run which creates the required files and exits.
docker run --rm -itd \
-v "<Project_name>_<volume_name>:/absolute/path" \
<image> bash -c "touch /absolute/path/<my_file>"
This docker run will create volumes and required files. Here, container is my project name, by default, it is the name of the folder in which project is present and <volume_name> is the same as one which we want to use in our original container. <image> can be the same one which is already being used in your original containers.

*Create a hardlink in your OS to the actual file location on your system. You can find the file location using docker volume inspect --format '{{ .Mountpoint }}' <project_name>_<volume_name>/<my_file>. Linux users can use ln in terminal and windows users can use mklink in command prompt.

In step 3 we have not used /absolute/path since the <volume_name> refers to that location already, and we just need to refer to the file.


text:
Q: How to check if a SQLite database is an in-memory database or not I have an handler for a connection to an sqlite3 database. I would like to know if the database is an in-memory database or not.
Is there any API to do so?

A: At the C API layer you can use sqlite3_db_filename to get the filename. If it's NULL or empty you've got a temporary or in-memory database.

The sqlite3_db_filename(D,N) interface returns a pointer to a filename associated with database N of connection D. The main database file has the name "main". If there is no attached database N on the database connection D, or if database N is a temporary or in-memory database, then this function will return either a NULL pointer or an empty string.

Whatever client API library you're using likely acts the same: the filename will be empty.


text:
Q: How to activate conda environment in GitHub Actions? I am setting up continuous integration using GitHub Actions. One of the prerequisites (samtools) is most easily installed by conda. The standard way to use installed packages is to activate the corresponding conda environment. I am looking for a way to activate the conda environment. The common methods to activate it failed, see details below. My current workaround is to add to the PATH a hardcoded path to samtools, installed by conda. But this is not maintainable if the number of installed packages increases. It is also not the standard way to use packages installed with conda.
DETAILS:
.github/workflows/conda.yml
name: Conda
on: [push]

jobs:
  # label of the job
  tests:
    name: Tests
    # containers must run in Linux based operating systems
    runs-on: ubuntu-latest
    # Docker Hub image that `postgres-job` executes in
    container: node:latest
    # service containers to run with `postgres-job`
    steps:
      - uses: conda-incubator/setup-miniconda@v2
        with:
          miniconda-version: "latest"
          channels: bioconda, conda-forge, defaults
          use-only-tar-bz2: true  # IMPORTANT: This needs to be set for caching to work properly!
          auto-update-conda: true
          auto-activate-base: true
      - name: Install samtools
        run: |
            set -x

            echo "begin: PATH=$PATH;"

            conda create -y --name samtools samtools

            conda activate samtools || true
            echo "after conda activate samtools: PATH=$PATH;"
            which samtools || true

            $CONDA/bin/activate samtools || true
            echo "after CONDA/bin/activate samtools: PATH=$PATH;"
            which samtools || true

            export PATH="3/envs/samtools/bin:$PATH"
            echo "after export PATH=3/envs/samtools/bin:PATH: PATH=$PATH;"
            which samtools || true

Output:
Run set -x
begin: PATH=3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ echo begin: PATH=3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ conda create -y --name samtools samtools
Collecting package metadata (repodata.json): ...working... done
Solving environment: ...working... done
[...]

# To activate this environment, use
#
#     $ conda activate samtools
#
# To deactivate an active environment, use
#
#     $ conda deactivate
+ conda activate samtools
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run
    $ conda init <SHELL_NAME>
Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell
See 'conda init --help' for more information and options.
IMPORTANT: You may need to close and restart your shell after running 'conda init'.
+ true
after conda activate samtools: PATH=3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ echo after conda activate samtools: PATH=3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ which samtools
+ true
+ 3/bin/activate samtools
+ echo after CONDA/bin/activate samtools: PATH=3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ which samtools
after CONDA/bin/activate samtools: PATH=3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ true
after export PATH=3/envs/samtools/bin:PATH: PATH=3/envs/samtools/bin:3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ export PATH=3/envs/samtools/bin:3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+ echo after export PATH=3/envs/samtools/bin:PATH: PATH=3/envs/samtools/bin:3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
+ which samtools
3/envs/samtools/bin/samtools

A: Add this to not ignore bash profile files (fix from: https://github.com/marketplace/actions/setup-miniconda ):
    defaults:
      run:
        shell: bash -l {0}

Complete GitHub Action yml file, .github/workflows/conda.yml:
name: Conda
on: [push]

jobs:
  # label of the job
  tests:
    name: Tests
    # containers must run in Linux based operating systems
    runs-on: ubuntu-latest
    # Do not ignore bash profile files. From:
    # https://github.com/marketplace/actions/setup-miniconda
    defaults:
      run:
        shell: bash -l {0}
    # Docker Hub image that `postgres-job` executes in
    container: node:latest
    # service containers to run with `postgres-job`
    steps:
      - uses: conda-incubator/setup-miniconda@v2
        with:
          miniconda-version: "latest"
          channels: bioconda, conda-forge, defaults
          use-only-tar-bz2: true  # IMPORTANT: This needs to be set for caching to work properly!
          auto-update-conda: true
          auto-activate-base: true
      - name: Install samtools
        run: |
            echo "begin: PATH=$PATH;"

            conda create -y --name samtools samtools

            conda activate samtools || true
            echo "after conda activate samtools: PATH=$PATH;"
            which samtools || true
            # Use samtools here.

Output:
begin: PATH=/__w/ngs-aggregate_results/ngs-aggregate_results/3/envs/test/bin:/__w/ngs-aggregate_results/ngs-aggregate_results/3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
...
after conda activate samtools: PATH=/__w/ngs-aggregate_results/ngs-aggregate_results/3/envs/samtools/bin:/__w/ngs-aggregate_results/ngs-aggregate_results/3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;
/__w/ngs-aggregate_results/ngs-aggregate_results/3/envs/samtools/bin/samtools

A: Automatic Activation
The documentation also gives examples of automatic activation. Specifically, Example #3 demonstrates this with a couple key components:

*

*As noted in the IMPORTANT section of the documentation and in the other answer, the shell needs to use login mode, which can be set globally within a job, using

jobs:
  example-3:
    defaults:
      run:
        shell: bash -l {0}

*An environment definition is provided to setup-miniconda GHA. In the example it's etc/example-environment.yml, which defines the environment anaconda-client-env and this is set to activate using the activate-environment argument.

    steps:
      - uses: conda-incubator/setup-miniconda@v2
        with:
          activate-environment: anaconda-client-env
          environment-file: etc/example-environment.yml
          auto-activate-base: false
      - run: |
          conda info
          conda list

Samtools Example

I have a repository where I test environment definitions, so here's an explicit example for samtools. Note that I prefer Mamba, and also recommend capturing an explicit mamba env export to document the environment.
envs/so-samtools.yaml
name: so-samtools
channels:
  - conda-forge
  - bioconda
  - defaults
dependencies:
  - samtools

.github/workflows/so-samtools.yaml
name: so-samtools
on:
  push:
    paths:
      - 'envs/so-samtools.yaml'
      - '.github/workflows/so-samtools.yaml'

jobs:
  create-env:
    name: ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    defaults:
      run:
        shell: bash -l {0}

    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest]

    steps:
      - name: checkout repository
        uses: actions/checkout@v2

      - name: create environment with mamba
        uses: conda-incubator/setup-miniconda@v2
        with:
          mamba-version: "*"
          channels: conda-forge,bioconda,defaults
          auto-activate-base: false
          activate-environment: so-samtools
          environment-file: envs/so-samtools.yaml

      - name: check solution
        run: |
          mamba env export

      - name: test samtools
        run: |
          which samtools
          samtools help


text:
Q: Query by object's child collection item property on mongodb I am storing a collection of the following:
{
    "_id" : ObjectId("59ffdb0c70a6560df428aaa3"),
    "name" : "Contact Information",
    "description" : "Basic contact information about myself",
    "questions" : [
        {
            "caption" : "First Name",
            "value" : ""
        },
        {
            "caption" : "Last Name",
            "value" : ""
        },
        {
            "caption" : "Email",
            "value" : ""
        },
        {
            "caption" : "Date of bith (mm/dd/yyyy)",
            "value" : ""
        },
        {
            "caption" : "Street Address",
            "value" : ""
        },
        {
            "caption" : "Address Line 2",
            "value" : ""
        },
        {
            "caption" : "State",
            "value" : ""
        },
        {
            "caption" : null,
            "value" : null
        },
        {
            "caption" : "Postal Code",
            "value" : ""
        },
        {
            "caption" : "Country",
            "value" : ""
        }
    ]

I need to query based on the parent property "name" or by questions collection and property "caption"
So I have constructed the following query:
var result =(from Query in this.CoreService.QuestionCategoriesCollection().AsQueryable()
                            from Questions in Query.questions
                            where Questions.caption.ToLower().Contains(filter.ToLower())
                            select Query).ToList();

However, when the query runs I receive the following exception:

Exception has occurred: CLR/System.NotSupportedException An exception
  of type 'System.NotSupportedException' occurred in MongoDB.Driver.dll
  but was not handled in user code: '$project or $group does not support
  {document}.'    at
  MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.TranslateValue(Expression
  node)    at
  MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.TranslateMapping(ProjectionMapping
  mapping)    at
  MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateProjectValue(Expression
  selector)    at
  MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateSelectMany(SelectManyExpression
  node)    at
  MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateWhere(WhereExpression
  node)    at
  MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateSelect(SelectExpression
  node)    at
  MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslatePipeline(PipelineExpression
  node)    at
  MongoDB.Driver.Linq.Translators.QueryableTranslator.Translate(Expression
  node, IBsonSerializerRegistry serializerRegistry,
  ExpressionTranslationOptions translationOptions)    at
  MongoDB.Driver.Linq.MongoQueryProviderImpl1.GetExecutionModel(Expression
  expression)    at
  MongoDB.Driver.Linq.MongoQueryableImpl2.ToCursor(CancellationToken
  cancellationToken)    at
  MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1
  source, CancellationToken cancellationToken)    at
  projectname.Services.Questions.GetQuestions(String filter) in
  c:\developerment\project\project\Service\Questions.cs:line 24    at
  projectnameAPI.Controllers.QuestionsController.Get(String filter) in
  c:\developerment\project\project\Controllers\QuestionsController.cs:line
  31    at
  Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object
  target, Object[] parameters)    at
  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()

I don't know what other way to write the query using linq.

A: I ended up rewriting my query to this.
    var result =this.CoreService.QuestionCategoriesCollection().Find(c=>c.name.ToLower().Contains(filter.ToLower())
    || c.questions.Any(q=>q.caption.ToLower().Contains(filter.ToLower())));

A: A cleaner - but more raw - way.
Given the following collection schema example:
public class Parent
{
    public IEnumerable<Child> Children { get; set; }
}

public class Child
{
    public string Id { get; set; }
}

Get the parent by child id:
var dictionary = new Dictionary<string, object>
{
    "Children.Id" : "childId"
}
var data = this.ParentCollection().Find(new MongoDB.Driver.CommandDocument(dictionary));


text:
Q: Calling my JavaScript from Dart This should be simple, but I just can't seem to wrap my head around it.
So I have my dartFile.dart and then I have my javaScriptFile.js. How do I link these two so that I can call JavaScript functions declared in my javaScriptFile.js from my dartFile.dart?
I tried to follow the explanation provided in this post, but I guess it was too vague for me :/
Edit: Here's what I tried:
In my javaScriptFile.js, there is nothing but this simple function:
function myFunction() {
  return 4;
}

In my dartFile.dart, there is only this blob of code:
import 'package:js/js.dart' as js;

void main() {
  print(js.context.myFunction());
}

Following the instructions in the post I mentioned, I added dependencies for js in the pubspec.yaml file.
Basically I'm exactly where the asker of the original question was - I can call basic JavaScript functions like alert, but wehn I try to call my function declared in the javaScriptFile.js, I get a 'NoSuchMethodError'

A: You can just do it like this:

*

*Make sure you include JS before .dart files or make sure all JS files are loaded before running Scripts from Dart

*Contents of the dart file:

import 'dart:js';

void main() {
  var ret = context.callMethod('myFunction', ['a', 'b']);
  var inst = new JsObject(context['someClass'], ['instance']);
  print(inst);
}

*

*my JS File:

function myFunction() {
  console.log(arguments);
}

function someClass(a) {
  this.a = a;
}

This should give you output like
[object Arguments] // from console.log
[object Object]    // from print()

Regards,
Robert


text:
Q: Excel VBA: create macro that deletes a row that has a cell of equal value in two columns I normally code C but I'm being forced to use VBA and I've been tearing my hairout all day.
Scenario: Every day the engineer I work for gets hundreds of documents, he has a macro that unzips and lists the documents in an excel sheet. Column A is UniqueID, B is Zip File Name, C is File Name. Each Zip file has a cover letter which will have the same name as Zip File Name.This cover letter is useless and it needs to be deleted.
I need a macro that goes through and deletes an entire row when the row holds coverletter info. For example, if B4=C4 delete row 4 or if B5=C5, delete row 5 etc. Everything I try has returned error.
I have come up with this :
Sub DeleteDuplicateEntries()
    Dim Cell As Range, Cel As Range, N&
    Application.ScreenUpdating = False
    N = 0
    For Each Cell In Selection
         ' ignore empty cells
        If Cell <> Empty Then
            For Each Cel In Selection
                 'compare non-empty cel values
                 'and clear contents if duplicated value
                If Cel <> Empty And _
                Cel.Value = Cell.Value And _
                Cel.Address <> Cell.Address Then
                    Cel.ClearContents
                    N = N + 1
                End If
            Next Cel
        End If
    Next
    Application.ScreenUpdating = True
   End Sub

PROBLEM: It ends up delting every Zip File Name (other than the first one) but it doesn't delete the row :(

A: Try this small macro:
Sub rowKiller()
    Dim N As Long, i As Long
    N = Cells(Rows.Count, "B").End(xlUp).Row
    For i = N To 2 Step -1
        If Cells(i, "B").Value = Cells(i, "C").Value Then
            Cells(i, "B").EntireRow.Delete
        End If
    Next i
End Sub