text:
Q: How to implement a selectable array struct in swift? I would like to implement an array struct which can mark a single element is able to be as selected. Thus, that element can be easily accessed.
I am creating a wrapper class around Array struct. Is there any good way to delegate Array methods to my SelectableArray's internal array?
Or is there other better way to do it?
class SelectableArray<Element: Comparable> {
    let array = Array<Element>()
    private var selectedIndex: Int? = .None

    var selectedElement: Element? {
        guard let index = selectedIndex else {
            return .None
        }
        return array[index]
    }

    func select(index: Int) {
        selectedIndex = array.indices.contains(index) ? index : .None
    }

    func select(element: Element) {
        selectedIndex = array.indexOf(element)
    }
}

A: Just create an append method for your wrapper class and change array to a var from a let:
class SelectableArray<Element: Comparable> {
    var array = Array<Element>()
    private var selectedIndex: Int? = .None

    // other functions...

    func append(element: Element) {
        self.array.append(element)
    }
}


text:
Q: How to pass value/variable from one function to another in django - views Not able to pass a variable from one function to another.
@api_view(['GET'])
def UserList(request):
    loc = User.objects.all()
    latest_id = User.objects.latest('userid').userid  #want to pass this variable into DetailList function
    serializer = UserSerializer(loc, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def DetailList(request):
    loc = Detail.objects.all()
    serializer = DetailSerializer(loc, many=True)
    return Response(serializer.data)

and finaly want to use that userid variable to add the data into Detail table.
class UserAPIView(APIView):
    def post(self, request ):
        userid = request.data.get('userid')
        name = request.data.get('name')
        age = request.data.get('age')
        gender = request.data.get('gender')
        address = request.data.get('address')
        phone = request.data.get('phone')
        user_serializer = UserSerializer(data={"name": name, "age": age, "gender": gender})
        detail_serializer = DetailSerializer(data={"userid": userid,"address": address, "phone": phone})
        if user_serializer.is_valid(raise_exception=True):
            user_serializer.save()
        if detail_serializer.is_valid(raise_exception=True):
            detail_serializer.save()
        return Response({'status': 'Success'})

not able to pass variable data through declaring global , as getting error Nulltype is not callable.

A: I don't know how to pass data from one view to another view, but I have an idea about the session, you can do same thing with session
#set session from view
request.session['session_name'] = session_value

#get session from another view
session_var = request.session.get('session_name')

A: Functions itself are stateles, in a meaning that each function have it's own context and context isn't shared between them. The only "bridge" you have, else then keep some data on frontend side, is to use DB or Django sessions as mentioned in previous answer. For the last one here's an example:
@api_view(['GET'])
def UserList(request):
    loc = User.objects.all()
    latest_id = User.objects.latest('userid').userid  #want to pass this variable into DetailList function
    request.session['latest_id'] = latest_id  # here you set session var
    serializer = UserSerializer(loc, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def DetailList(request):
    loc = Detail.objects.all()
    latest_id = request.session.get('latest_id')  # here you get session var
    serializer = DetailSerializer(loc, many=True)
    return Response(serializer.data)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL offset infinite rows I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's LIMIT requires a limit as well as an offset. Is there any way to do this?

A: Another approach would be to select an autoimcremented column and then filter it using HAVING.
SET @a := 0;
select @a:=@a + 1 AS counter, table.* FROM table
HAVING counter > 4

But I would probably stick with the high limit approach.

A: As others mentioned, from the MySQL manual. In order to achieve that, you can use the maximum value of an unsigned big int, that is this awful number (18446744073709551615). But to make it a little bit less messy you can the tilde "~" bitwise operator.
  LIMIT 95, ~0

it works as a bitwise negation. The result of "~0" is 18446744073709551615.

A: As you mentioned it LIMIT is required, so you need to use the biggest limit possible, which is 18446744073709551615 (maximum of unsigned BIGINT)
SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5

A: As noted in other answers, MySQL suggests using 18446744073709551615 as the number of records in the limit, but consider this: What would you do if you got 18,446,744,073,709,551,615 records back? In fact, what would you do if you got 1,000,000,000 records?
Maybe you do want more than one billion records, but my point is that there is some limit on the number you want, and it is less than 18 quintillion. For the sake of stability, optimization, and possibly usability, I would suggest putting some meaningful limit on the query. This would also reduce confusion for anyone who has never seen that magical looking number, and have the added benefit of communicating at least how many records you are willing to handle at once.
If you really must get all 18 quintillion records from your database, maybe what you really want is to grab them in increments of 100 million and loop 184 billion times.

A: From the MySQL Manual on LIMIT:

To retrieve all rows from a certain
  offset up to the end of the result
  set, you can use some large number for
  the second parameter. This statement
  retrieves all rows from the 96th row
  to the last:

SELECT * FROM tbl LIMIT 95, 18446744073709551615;

A: You can use a MySQL statement with LIMIT:
START TRANSACTION;
SET @my_offset = 5;
SET @rows = (SELECT COUNT(*) FROM my_table);
PREPARE statement FROM 'SELECT * FROM my_table LIMIT ? OFFSET ?';
EXECUTE statement USING @rows, @my_offset;
COMMIT;

Tested in MySQL 5.5.44. Thus, we can avoid the insertion of the number 18446744073709551615.
note: the transaction makes sure that the variable @rows is in agreement to the table considered in the execution of statement.

A: I ran into a very similar issue when practicing LC#1321, in which I have to select all the dates but the first 6 dates are skipped.
I achieved this in MySQL with the help of ROW_NUMBER() window function and subquery. For example, the following query returns all the results with the first five rows skipped:
SELECT
    fieldname1,
    fieldname2
FROM(
    SELECT
        *,
        ROW_NUMBER() OVER() row_num
    FROM
        mytable
) tmp
WHERE
    row_num > 5;

You may need to add some more logics in the subquery, especially in OVER() to fit your need. In addition, RANK()/DENSE_RANK() window functions may be used instead of ROW_NUMBER() depending on your real offset logic.
Reference:
MySQL 8.0 Reference Manual - ROW_NUMBER()

A: WHERE .... AND id > <YOUROFFSET>

id can be any autoincremented or unique numerical column you have...

A: Just today I was reading about the best way to get huge amounts of data (more than a million rows) from a mysql table. One way is, as suggested, using LIMIT x,y where x is the offset and y the last row you want returned. However, as I found out, it isn't the most efficient way to do so. If you have an autoincrement column, you can as easily use a SELECT statement with a WHERE clause saying from which record you'd like to start.
For example,
    SELECT * FROM table_name WHERE id > x;
It seems that mysql gets all results when you use LIMIT and then only shows you the records that fit in the offset: not the best for performance.
Source: Answer to this question MySQL Forums. Just take note, the question is about 6 years old.

A: I know that this is old but I didnt see a similar response so this is the solution I would use.
First, I would execute a count query on the table to see how many records exist.  This query is fast and normally the execution time is negligible.  Something like:
SELECT COUNT(*) FROM table_name;

Then I would build my query using the result I got from count as my limit (since that is the maximum number of rows the table could possibly return).  Something like:
SELECT * FROM table_name LIMIT count_result OFFSET desired_offset;

Or possibly something like:
SELECT * FROM table_name LIMIT desired_offset, count_result;

Of course, if necessary, you could subtract desired_offset from count_result to get an actual, accurate value to supply as the limit.  Passing the "18446744073709551610" value just doesnt make sense if I can actually determine an appropriate limit to provide.


text:
Q: Magento multi store multi currency i have 2 store, 1 for USD 2 for CAD
my first store working fine, my 2nd store shows product value CAD when i send in paypal that time CAD value convert in USD, can you suggest me how to slove it i need when paypal goes its show CAD.

A: The solution to this problem lies in this Magento thread; here's a summary for anyone struggling with this:

*

*You need to set-up multiple websites, one for each currency (not just store views, complete websites)

*Set 'Catalog Price Scope' to 'Website' in System > Configuration > Catalog

*Set the Base Currency of each website to its respective currency in System > Configuration > Currency Setup

*Set all your currency rates to '1.0' in System > Manage Currency Rates

*Now you can set your product prices per store when editing a product, voila!


text:
Q: How can one achieve generics in python? Something like Java or C++ offers I'm working with generics in python, and want to know if I can achieve generics in python as other languages. The syntax needs not to be same as other languages but if I can do something like

template<typename T>
class List {
public:
    T array[10];
};

int main() {
    List<int> list;
}

I tried the below code but I'm not sure how can I achieve the same as C++ or Java. Like, I shouldn't be allowed to add objects of any other type once I define the data type on initialization.

from typing import TypeVar, Generic, List

T = TypeVar('T')

class CircularQueue(Generic[T]):

    def __init__(self):
        self._front = 0
        self._rear = 0
        self._array = list()

    def mod(self, x): return (x+1) % (len(self._array)+1)

    @property
    def is_full(self):
        return self.mod(self._rear) == self.mod(self._front) + 1

    def insert(self, element: T):
        if not self.is_full:
            self._rear += 1
            self._array.append(element)

if __name__ == "__main__":
    # I want to Initialize the queue as cQueue = CircularQueue<int>()
    # Something that other compiled languauges offer
    # Is it possible to do so?
    # Or any other method so that I can restrict the type of objects.
    cQueue = CircularQueue()
    cQueue.insert(10)

    # Here I want to raise an error if I insert any other type of Object
    cQueue.insert('A')

A: Python does not have the notion of generics but one could say that every function is generic because parameters are not actually typed.  This is a duck typing approach where anything that walks like a duck and quacks like a duck it treated as a duck.  So, typically, "generic" functions would only check if the parameters or objects have the minimal set of required attributes and process the data accordingly.


text:
Q: `go`'s in stored procedures in Sybase 16 I have the following stored procedure in Sybase 16,
create or replace procedure ... as
...
drop table tempdb..koppelingen
go
declare
    vre_cursor cursor  for
...

Then I see: declare cursor must be the only statement in a query batch.
If I skip the go, I can create the stored procedure.
If I execute the code of the stored procedure by hand by selecting it and execute, I have to use the go.
So what happens in a stored procedure? Does it insert the go's by itself? But then I do not understand the error message of declare cursor above.

A: go is not an ASE command.
go is a client-side command that tells the client application (eg, isql) that a batch of SQL can now be sent to ASE. In the case of the create or replace procedure ... the go tells the client application (eg, isql) that you've completed the stored proc definition and it can now be submitted to ASE for parsing & compiling.
declare cursor must be in a batch of SQL by itself (ie, declare ...\ngo) if being run from a client application (eg, isql); when inside a stored proc the declare cursor command can be grouped with other follow-on commands (eg, open, fetch).


text:
Q: jQuery Table Columns / Rows Hide or Change color Right now I am playing with an idea where I want to change the color (maybe eventually remove/hide) a column or row of data right now my aim is the columns. So far I have it partly working but not entirely
with this:
$('#'+arry[0]+' tr td:eq('+arry[1]+')').css({"background-color":"FF0"});

I am able to effect the column but only one row, not all rows within that column, and it seems to be effecting the rows/columns within the "tbody" but not the "thead" or "tfoot" I need to effect all 3.
an example of the table I am working with looks like:

        First
        Second
        Third
        Fourth
        Fifth

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

I'm thinking my approach is to simple, so I need some ideas. This will ultimately be used with datatables from datatables.net but first I need to figure out this part.
****EDIT****
The arry variable is currently take from the rel attribute of something else arry[0] is the tables id.. and arry[1] is the position of the column in this case 0-4

A: I would use <colgroup> to color the columns as it would be quick and easy to manipulate.
http://www.w3schools.com/tags/tag_col.asp
An example, you could put:
<colgroup>
  <col style="background-color:FF0" />
  <col span="4" />
</colgroup>

and edit the entire colgroup with jquery or other means.

A: demo jsBin
var string= 'testerTable::2'; // your data // test with: 0,1,2,3,4
var arry= string.split('::'); // split to separate values

var $tr = $('#'+arry[0]+' tr');

$('#'+arry[0]+' th').eq(arry[1]).css({"background-color":"FF0"});

$tr.each(function(el){ // iterate through all 'tr' to find relative 'td' .eq()
  $(this).find('td').eq(arry[1]).css({"background-color":"FF0"});
});

A: You could just give each element in column 1 the class 'c1' and then do $('.c1').css...  This would save mucking about with th/tr/td distinctions. You'd do this for every column, of course.
And BTW, it's spelt 'array' :)


text:
Q: Method not found at runtime I have the following extension in my personal toolbox library:
public extension UIViewController {

    public func removeChildViewControllers() {
        for child in self.childViewControllers {
            child.willMove(toParentViewController: nil)
            child.view.removeFromSuperview()
           child.removeFromParentViewController()
        }
   }

    public func addChildViewController(_ controller: UIViewController, embedViewIn containerView: UIView) {
        controller.willMove(toParentViewController: self)
        addChildViewController(controller)
        containerView.addSubview(controller.view)
        controller.view.addCustomConstraints(CustomConstrains.FullSizeInSuperview)
        controller.didMove(toParentViewController: self)
    }
}

From my current app, I call as follows:
private func embedViewController(_ controller: UIViewController) {
    removeChildViewControllers()
    addChildViewController(controller, embedViewIn: containerView)
}

Everything is working as expected.
Now I add one more convenience Method removeChildViewController:
public extension UIViewController {

    public func removeChildViewControllers() {
        for child in self.childViewControllers {
            child.willMove(toParentViewController: nil)
            child.view.removeFromSuperview()
           child.removeFromParentViewController()
        }
   }

    public func addChildViewController(_ controller: UIViewController, embedViewIn containerView: UIView) {
        controller.willMove(toParentViewController: self)
        addChildViewController(controller)
        containerView.addSubview(controller.view)
        controller.view.addCustomConstraints(CustomConstrains.FullSizeInSuperview)
        controller.didMove(toParentViewController: self)
    }

    public func removeChildViewController(_ controller: UIViewController) {
        controller.willMove(toParentViewController: nil)
        controller.view.removeFromSuperview()
        controller.removeFromParentViewController()
    }
}

From now on, calling the code which has not been modified crashes at runtime EXC_BAD_ACCESS:
removeChildViewControllers()

To sum it up:
Calling removeChildViewControllers() crashes on runtime if the (unused) method removeChildViewController exists.
Calling removeChildViewControllers() does not crash on runtime if the  (unused) method removeChildViewController is commented.
Also, calling removeChildViewControllers() does not crash on runtime if the  (unused) method removeChildViewController is renamed to removeChildViewControllerr.

A: I'm going to guess that this is one of those situations where you are banging into a secret namespace conflict. There probably is a removeChildViewController method hidden in the Objective-C Cocoa world, and you have stumbled over it by duplicating its name. Thus, Objective-C Cocoa chokes at runtime, even though the official API has no problem with it and so there is no trouble getting Swift to compile your code. This sort of thing happens all the time, unfortunately.


text:
Q: SQL Connection String Format Error in Docker I am running a Docker container with a gMSA identity to connect to SQL Server via Windows Authentication. I confirmed the gMSA identity is working correctly within the container, however I'm receiving a SQL connection string format error:
"Format of the initialization string does not conform to specification starting at index 0."
My Dockerfile looks like this:
FROM microsoft/dotnet:2.2-runtime-nanoserver-sac2016
COPY . .
ENTRYPOINT ["dotnet", "Daemon.dll"]
CMD ["EventConfig:MqHostName=10.23.2.1", "ConnectionStrings:TestDb1=Data Source=10.23.2.1;Initial Catalog=Events;Integrated Security=true", "ConnectionStrings:TestDb2=Data Source=10.23.2.1;Initial Catalog=Notifications;Integrated Security=true", "ConnectionStrings:TestDb3=Data Source=10.23.2.1;Initial Catalog=TESTDB;Integrated Security=true"]

Running docker inspect on the container looks like the CMD parameters are parsed correctly, however I'm still receiving the error. The connection strings work without issue outside of Docker.
I've tried surrounding the connection strings by a backtick `, single quotes, double quotes, and slash . I've also tried passing in the strings as ENV variables instead of as CMD parameters. I've also tried adding a parser directive such as
# escape=`

to the top of my Dockerfile. Any help would be greatly appreciated.

A: For anyone who may have a similar issue, I determined how to escape the inner quotes using the \ character. The correctly formatted Dockerfile connection strings looks like this:
CMD ["EventConfig:MqHostName=10.23.2.1", "ConnectionStrings:TestDb1\"=Data Source=10.23.2.1;Initial Catalog=Events;Integrated Security=true\"", "ConnectionStrings:TestDb2=\"Data Source=10.23.2.1;Initial Catalog=Notifications;Integrated Security=true\"", "ConnectionStrings:TestDb3=\"Data Source=10.23.2.1;Initial Catalog=TESTDB;Integrated Security=true\""]


text:
Q: Drawable vs Single reusable Bitmap better with memory? As I understand it (not that I'm correct) Drawables are generally correctly removed from memory when the application is finished with them. Bitmaps however need to be manually recycled, and sometimes even have a special class written to handle them properly. My question is, in regards to memory and leaks, is it more beneficial to simply stick with Drawables like such:
myView.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_image));
myView1.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_image1));
myView2.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_image2));

rather than something like so with Bitmaps:
Bitmap tmpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
myView.setImageBitmap(tmpBitmap);

tmpBitmap.recycle();
tmpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image1);
myView1.setImageBitmap(tmpBitmap);

tmpBitmap.recycle();
tmpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image2);
myView2.setImageBitmap(tmpBitmap);
tmpBitmap.recycle();

I've also read of course that you have to be careful about recycle() method on Bitmaps because they can be removed while still in use? It seems like these issues keep popping up in different forms, but I can't really get a straight answer from anyone on the matter. One person says to reuse a Bitmap and recycle after every use, and others say use Drawables and an unbindDrawables() method (this is what I've been using):
private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
        ((ViewGroup) view).removeAllViews();
    }
}

Any applicable insight would be much appreciated though. Thanks

A: Bitmaps do not need to be manually recycled. They are garbage collected just like Drawables and other objects. Similarly you don't need to unbind drawables, except in very specific situations. It seems that you read a lot of misleading information.
Recycling bitmaps and unbinding drawable can be useful in some situations (for instance if your app manipulate large amounts of bitmap data or if you store drawable in a static manner.)
The two examples you show at the beginning of your question are equivalent. If you load a drawable directly, bitmaps will be loaded on your behalf. If you load bitmaps manually and set them on an ImageView, they will be enclosed in drawables on your behalf.
Use the first solution since it's simpler and don't worry about unbinding and other memory management techniques until you actually need them.

A: I back Romain's proposal, but I'm not sure your question is addressing your actual problem. I don't know how you handle the references to your Views. Maybe you simply have memory leaks in your application? A lot of memory leaks in Android are related to Context. When a Drawable is attached to a View, the View is set as a callback on the Drawable.
TextView myView = new TextView(this);
myView.setBackgroundDrawable(getDrawable(R.drawable.my_bitmap));

In the code snippet above, this means the Drawable has a reference to the TextView which itself has a reference to the Activity (the Context) which in turns has references to pretty much anything depending on your code.
Without looking at more of your code I guess you're on the right track by setting the stored drawables' callbacks to null when an Activity is destroyed.


text:
Q: How can I kill a stuck LXC container? I have a new unprivileged LXC container that I just cannot seem to stop. lxc-stop -n dl hangs. lxc-stop -k --nolock -n dl hangs. lxc-ls hangs. lxc-attach -n dl hangs. Nothing works on this container.
I have restarted lcxfs. All that did was upset a privileged container. This is what the current processes for this container look like (from the host).
lxc-start,24434
  └─systemd,24446 --system --deserialize 9
      ├─agetty,25258 --noclear --keep-baud console 115200 38400 9600 vt220
      ├─agetty,25846 --noclear --keep-baud pts/1 115200 38400 9600 vt220
      ├─agetty,25878 --noclear --keep-baud pts/3 115200 38400 9600 vt220
      ├─agetty,25906 --noclear --keep-baud pts/2 115200 38400 9600 vt220
      ├─agetty,25934 --noclear --keep-baud pts/0 115200 38400 9600 vt220
      ├─rsyslogd,26016 -n
      │   ├─{rsyslogd},26043
      │   └─{rsyslogd},26044
      └─systemd-journal,25962

And the process states:
$ ps aux | grep -P '24434|24446|25258|25846|25878|25906|25934|25934|26016|26043|26044|25962'
oli      24434  0.0  0.0  43400  3552 ?        Ss   10:56   0:00 [lxc monitor] /home/oli/.local/share/lxc dl
100000   24446  0.0  0.1  36896  4972 ?        Ss   10:56   0:00 /lib/systemd/systemd --system --deserialize 9
100000   25258  0.0  0.0  15676  2504 pts/0    Ss+  10:56   0:00 /sbin/agetty --noclear --keep-baud console 115200 38400 9600 vt220
100000   25846  0.0  0.0  15676  2496 pts/1    Ss+  11:33   0:00 /sbin/agetty --noclear --keep-baud pts/1 115200 38400 9600 vt220
100000   25878  0.0  0.0  15676  2380 pts/3    Ss+  11:33   0:00 /sbin/agetty --noclear --keep-baud pts/3 115200 38400 9600 vt220
100000   25906  0.0  0.0  15676  2416 pts/2    Ss+  11:33   0:00 /sbin/agetty --noclear --keep-baud pts/2 115200 38400 9600 vt220
100000   25934  0.0  0.0  15676  2332 pts/0    Ss+  11:33   0:00 /sbin/agetty --noclear --keep-baud pts/0 115200 38400 9600 vt220
100000   25962  0.0  0.0  35256  3500 ?        Ss   11:33   0:00 /lib/systemd/systemd-journald
100104   26016  0.0  0.0 182640  3244 ?        Ssl  11:33   0:00 /usr/sbin/rsyslogd -n

A: Force killing the container's systemd process worked for me.
In your example,
kill -9 24446

A: I keep this command line around to quickly kill all processes with a very high UID (which are in my container):
ps -ef | grep "^100[0-9][0-9][0-9]" | tr -s " " | cut -f2 -d " " | xargs -I {} kill -9 {}

Then I can use lxc-start again.
I also found out that I have less problems with lxc-stop when I use lxc-start -d (in background mode) and then connect using lxc-attach or ssh.


text:
Q: Is there a way to open a file that is on a local network on a users computer from a link on a webpage? I am making a php page that will go on my companies corporate intranet, which will be hosted on a domain. We have files on a local network that are accessible through My Network Places. I would like to be able to make a link that acts as a shortcut to a file on the network, much like a shortcut you would have on your desktop, rather than have the link download it to the user's machine. The user would click the link and excel opens the document from its network location. Is this possible and if so how can I go about doing this?

A: yes, you will need the full path ( unc path)
get file ( right click 'save target as')


text:
Q: Module parameter permission I'm new to kernel programming. When I was going through module_param, I was confused by the permission value 0. It was explained that it won't get an entry in sysfs, while the others like S_IRUGO would get an entry. I couldn't understand the concept.
What does the perm value 0 indicate?
When do we need a sysfs entry? What is the need for that?
Kindly guide me. Thanks in advance.

A: You can module parameters in some ways to a kernel module. Assuming a kernel module foo with a parameter named bar:

*

*Using the kernel command line which can be provided in your bootloader configuration. To see the command line for the current boot, run cat /proc/cmdline. Example output: BOOT_IMAGE=/vmlinuz root=/dev/sda1 foo.bar=some-value

*While loading a kernel module using insmod or modprobe: modprobe foo bar=some-value.

*When a module is loaded, you can usually see find the parameter bar for module foo at /sys/module/foo/parameters/bar.

A permission value of 0 prevents the sysfs entry from being created (third bullet above). An example usage in the kernel code is to allow for enabling debug without exposing this parameter in sysfs.
An example of a readable/writable module parameter is acpi. It allows you to dynamically set the debugging information that should be generated. Available as acpi.debug_level for the kernel command line or as the /sys/module/acpi/parameters/debug_level sysfs entry.


text:
Q: Why this simple ArangoDB query sometimes takes very long time I am querying ArangoDb of about 500k document via arangojs.query() with this very simple query
"FOR c IN Entity FILTER c.id == 261764 RETURN c"

It is a node in node-link graph.
But sometimes, it took more than 10 seconds and in the log of arangodb also has warning about query taking too long.Lots of time it happens if new session is used on browser. Is it problem of arangodb or arangojs or my query itself is not optimized?
-------------------Edit----------------------
Added db.explain
Query string:
 FOR c IN Entity FILTER c.id == 211764 RETURN c

Execution plan:
 Id   NodeType                    Est.   Comment
  1   SingletonNode                  1   * ROOT
  2   EnumerateCollectionNode   140270     - FOR c IN Entity   /* full collection scan */
  3   CalculationNode           140270       - LET #1 = (c.`id` == 211764)   /* simple expression */   /* collections used: c : Entity */
  4   FilterNode                140270       - FILTER #1
  5   ReturnNode                140270       - RETURN c

Indexes used:
 none

Optimization rules applied:
 none

A: As your Explain shows, your query doesn't utilize indices, but does a full collection scan.
Depending on when it finds the match (at the start or the end of the collection) execution times may vary.
See the Indexing chapter for creating indices, and the AQL Execution and Performance chapter howto analyse the output of db._explain()


text:
Q: What are the requirements to enter Prifddinas? I've heard that the city in RuneScape will be for high-levelled players only. But I can't find the exact requirements needed to enter the city. What are they?

A: To enter Prifddinas(Elf City), there is only the quest requirement of finishing Plague's End.  Plague's End does have requirements in order to start it.
Quest requirements:
- Making History
    - The Restless Ghost
    - Priest in Peril
- Catapult Construction
- Within the Light
    - Mourning's Ends Part II
        - Mourning's Ends Part I
            - Big Chompy Bird Hunting
            - Sheep Herder
            - Roving Elves
                - Waterfall Quest
                - Regicide
                    - Underground Pass
                        - Biohazard
                            - Plague City

The level requirements for Plague's End are:
75 Construction
75 Dungeoneering
75 Agility
75 Crafting
75 Herblore
75 Mining
75 Prayer
75 Summoning

Once you have finished Plague's End you will have access to Prifddinas!  Just head to the gates in Tirannwn, and enjoy the beautiful city.
Plague's End Wiki Source

A: You need to complete Plague's end quest, which requires Within the light quest, Making history quest, Catapult construction quest and level 75 in 8 skills.
EDIT: The skills are construction, agility, crafting, herblore, mining, prayer and summoning

A: You need to have these 10 skills up to level 75 :

*

*Mining

*Summoning

*Herblore

*Agility

*Construction

*Dungeoneering

*Prayer

*Crafting

*Ranged

*Woodcutting
Plus the masses of quests that were already mentionned.
It may say different on the WIKI page but in Runescape if you check the Quest Journal for Plagues end it tells you, you need ranged and woodcutting as well.

A: On top of the listed requirements that people have already mentioned, you also need
70 Fletching as it is one of the requirements in the Within the Light quest - a pre-requisite for Plague's End.
https://runescape.wiki/w/Within_the_Light


text:
Q: .NET MAUI Adaptive triggers not firing I have a style setup in a new file that is being merged in App.xaml. In the view, Intellisense shows me the x:Key of the style I want to use but adaptive triggers do not fire. I tested it with a style that only contains a setter for changing the background color. This works fine. Just not the adaptive trigger.
I'm attempting to apply this style to the parent container(Grid) of all elements (Child of the <ContentPage>) but the problem persists even if using this style on inner controls. I tried changing the TargetType as well but even on other control types it does not work.
I even tried placing the style inside of the control and same view page but it's not working like that either. I don't know what I'm doing wrong.
Because this app will have many pages, I'd prefer to be able to use a separate file to contain the styles for a central place to make changes in the future.
Tested on Windows and also multiple Android Emulators.
Current values are for testing.
Style:
    <Style x:Key="MainGridStyle"
       TargetType="Grid">
    <Setter Property="VisualStateManager.VisualStateGroups">
        <VisualStateGroupList>
            <VisualStateGroup>
                <VisualState x:Name="Small">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="0"/>
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Property="WidthRequest" Value="200"/>
                    </VisualState.Setters>

                </VisualState>
                <VisualState x:Name="Medium">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="800"/>
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Property="WidthRequest" Value="500"/>
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateGroupList>

    </Setter>

</Style>

App.xaml
    <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
            <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
            <ResourceDictionary Source="Resources/Styles/CustomStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Control opening tag (I tried StaticResource too with the same result):
    <Grid
    Style="{DynamicResource MainGridStyle}">

EDIT:
I've narrowed down the problem to being with .Net 6. I tested the same code on .Net 7 and it works well there. Any idea how to fix this issue that I'm only experiencing with .Net 6?

A: This is related to the size of the MinWindowWidth value you set.
To get value of Grid.Window.Width:
<Grid Style="{DynamicResource MainGridStyle}
      "BackgroundColor="Gold"
      x:Name="grid">

Console.WriteLine(grid.Window.Width);

grid.Window.Width: 375.6521739130435
Then in CustomStyles.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<?xaml-comp compile="true" ?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <Style x:Key="MainGridStyle" TargetType="Grid">
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup>
                    <VisualState x:Name="Small">
                        <VisualState.StateTriggers>
                            <AdaptiveTrigger MinWindowWidth="0"/>
                        </VisualState.StateTriggers>
                        <VisualState.Setters>
                            <Setter Property="WidthRequest" Value="200"/>
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState x:Name="Medium">
                        <VisualState.StateTriggers>
                            <AdaptiveTrigger MinWindowWidth="376"/>
                        </VisualState.StateTriggers>
                        <VisualState.Setters>
                            <Setter Property="WidthRequest" Value="450"/>
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>
</ResourceDictionary>

Since 0 < grid.Window.Width < 376,  WidthRequest of Gird will be 200.
If:
             <VisualStateGroupList>
                <VisualStateGroup>
                    <VisualState x:Name="Small">
                        <VisualState.StateTriggers>
                            <AdaptiveTrigger MinWindowWidth="0"/>
                        </VisualState.StateTriggers>
                        ...
                    </VisualState>
                    <VisualState x:Name="Medium">
                        <VisualState.StateTriggers>
                            <AdaptiveTrigger MinWindowWidth="375"/>
                        </VisualState.StateTriggers>
                        ...
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>

375 < grid.Window.Width, so WidthRequest of Gird will be 450.

A: After a lot more testing, I was able to narrow down the problem to being related to .Net 6. I upgraded to .Net 7 and, using the same code, it works well.


text:
Q: Can I install a systemd file during distcheck using $dc_install_base? I have the following Autotools code for installing a systemd service file, which must be installed outside of $prefix to a directory given by a pkg-config variable:
(I know this is not proper, but I can't change the way systemd works.)
configure.ac
AC_ARG_WITH([systemdsystemunitdir],
    AS_HELP_STRING([--with-systemdsystemunitdir=DIR],
        [Directory for systemd service files]),
    [],
    [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)])
AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])

When you run make distcheck, your package gets installed into a temporary staging directory and then uninstalled. Since installing something outside of $prefix will break that, I must override the --with-systemdsystemunitdir configuration option for distcheck. I do it like so, since the location of the staging directory is available in the variable $dc_install_base. I can't pass an absolute path here, and $prefix or any other $prefix-derived variable such as $libdir will not be correct during the distcheck run itself.
Makefile.am
AM_DISTCHECK_CONFIGURE_FLAGS = \
    --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)

My question is twofold:

*

*This feature ($dc_install_base) doesn't seem to be documented anywhere. Is it officially supported or an implementation detail? Usually Automake-private variables have two consecutive underscores in them, I believe.

*Is there a better way to do what I'm trying to do? I know the Autotools way would be to set systemdsystemunitdir to a subdirectory of $prefix by default, and let the user or the distro override it. However, it's an important requirement to me that one should be able to extract the package from the tarball, run ./configure && make and sudo make install and have everything just work. If the systemd file were installed anywhere else besides the location given by pkg-config, it would not work, and what's more, fail silently.

A: A bit late but...
I had a similar problem with gobject-introspection and I (hopefully) resolved by adding a couple of configure options and something like:
AM_DISTCHECK_CONFIGURE_FLAGS= \
    --with-girdir='$$(datadir)/gir-1.0' \
    --with-typelibdir='$$(libdir)/girepository-1.0'

In your case I think the following should work:
AM_DISTCHECK_CONFIGURE_FLAGS = \
    --with-systemdsystemunitdir='$$(prefix)/$(systemdsystemunitdir)'

The trick is that you must protect $(prefix) against two expansions: the make expansion (hence the double $$) and the shell expansion performed during the configure call (hance the single quotes).


text:
Q: UITableView application crushes when scrolling way too down When I am scrolling my table way too down, application crushes. And I cannot find where the error in code is.
Here is my code:
NSMutableDictionary *tableDataDictionary;
NSInteger *rows_in_section;

-(void) initView
{
    if (!tableDataDictionary)
    {
        tableDataDictionary = [ [NSMutableDictionary alloc] init];
    }
    [self reloadTableData];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [mainTableView deselectRowAtIndexPath: [mainTableView indexPathForSelectedRow] animated:NO];

    [tableDataDictionary release];
    tableDataDictionary = nil;
    free(rows_in_section);
}

-(void) reloadTableData {
    [tableDataDictionary removeAllObjects];

    //Sections
    if (rows_in_section)
    {
        free(rows_in_section);
    }

    rows_in_section = (NSInteger*)calloc(25, sizeof(NSInteger));
    for (int i = 0; i <= 25; i++)
    {
        rows_in_section[i] = 0;
    }

    NSMutableArray *words_in_section = [ [NSMutableArray alloc] init];

    int cur_section = -1;

    while ( TRUE )
    {
        WordObject *tempWordObj = [ [WordsDatabase sharedWordsDatabase] getNextWordABC];
        if (!tempWordObj)
        {
            [tableDataDictionary setObject:words_in_section forKey:[NSNumber numberWithInt: cur_section] ];
            [tempWordObj release];

            [tableDataDictionary setObject:[words_in_section copy] forKey:[NSNumber numberWithInt: cur_section] ];
            [words_in_section removeAllObjects];

            break;
        }

        //First loop
        if (cur_section == -1) cur_section = toupper([ [tempWordObj word] characterAtIndex:0 ] ) - 'A';

        //If a has letter changed, assign the previous array to a dictionary
        if ( (toupper([ [tempWordObj word] characterAtIndex:0 ] ) - 'A') != cur_section )
        {
            [tableDataDictionary setObject:[words_in_section copy] forKey:[NSNumber numberWithInt: cur_section] ];
            [words_in_section removeAllObjects];
        }

        cur_section = toupper([ [tempWordObj word] characterAtIndex:0 ] ) - 'A';

        [words_in_section addObject:tempWordObj];

        [tempWordObj release];
        tempWordObj = nil;

        rows_in_section[cur_section]++;

    }

    [words_in_section release];

    [ [WordsDatabase sharedWordsDatabase] endGettingWordsABC];

    [mainTableView reloadData];
    [mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];

}

//
// Table handling
//

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 26;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return rows_in_section[section];
}

// Adding a section index here
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return ALPHA_ARRAY;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DebugLog(@"cellForRowAtIndexPath");
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    WordObject *tempWordObj = [ [tableDataDictionary objectForKey: [NSNumber numberWithInt:[indexPath section] ] ] objectAtIndex: [indexPath row] ];

    if (!tempWordObj)
    {
        DebugLog(@"!tempWordObj");
        return cell;
    }

    cell.text = [tempWordObj word];

    [tempWordObj release];

    return cell;
}

How can I solve this problem with scrolling down and why it occurs?
And if you will find any other disadvantages in my code, please tell me this.
Thank you in advance,
Ilya.

A: You do not need this line;
[tempWordObj release];

[NSDictionary objectForKey] returns an auto-released object, that is the object will be automatically released sometime after your function returns.


text:
Q: Poincare Map for $\dot{x}=-x(t)+\sin(t)$ Im looking at the equation $\dot{x}=-x(t)+\sin(t)$ and am trying to derive a formula form for the Poincare map corresponding to the Poincare section $\{(x,t):  t=2\pi\}$.  I know that if I solve my equation I get
$$x(t)=\frac{1}{2}(\sin(t)-\cos(t)+2c/e^t)$$
Next I know that $x(0)=x(2\pi)$ and so
$$x(t)=\frac{1}{2}(\sin(t)-\cos(t))$$
Thus the poincare map starts at $F(x_0)=x(2\pi)=-\frac{1}{2}$.  I'm not quit sure how to find the Poincare map, however.

A: You know $x(t)=\frac12(\sin(t)-\cos(t)+2Ce^{-t})$. If $x(0)=x_0$, we have $C-\frac{1}{2}=x_0$, and $C=x_0+\frac12$. Thus we have the flow $x(t,x_0)=\frac12\left(\sin(t)-\cos(t)+\left(2x_0+1\right)e^{-t}\right)$. The Poincare map is $$P(x_0)=x(2\pi,x_0)=-\frac{1}{2}+\left(x_0+\frac{1}{2}\right)e^{-2\pi}.$$
You can also see that $x_0=-1/2$ is a fixed point of the Poincare map, which confirms the periodic orbit you found.


text:
Q: How can I fetch data from a REST API where field names vary and how to type it in typescript? I've had trouble fetching an API because an object field name can vary from one object to another, as well as the number of children of this same object:
[
  {
    "name": {
      "common": "Finland",
      "official": "Republic of Finland",
      "nativeName": {
        "fin": {
          "official": "Suomen tasavalta",
          "common": "Suomi"
        },
        "swe": {
          "official": "Republiken Finland",
          "common": "Finland"
        }
      }
    }
  },
  {
    "name": {
      "common": "Guatemala",
      "official": "Republic of Guatemala",
      "nativeName": {
        "spa": {
          "official": "República de Guatemala",
          "common": "Guatemala"
        }
      }
    }
  }
]

Here nativeName's first child can be spa or fin depending on the object, and there can be one or two (and even more in other instances) children.
How can I get to the first nativeName's common value here ?
Also, how can I type this data in typescript ? So far, I left it as such :
type name = {
  name: {
    common: string,
    official: string,
    nativeName: {
      var1: {
        official: string,
        common: string
      },
      var2: {
        official: string,
        common: string
      }
    }
  }
}

Thanks in advance.
Edit:
I realize I have one last question:
"languages": {
      "spa": "Spanish"
    }

here spa varies as well as the number of entries in languages, how would I type that in typescript?

A: first question:
const nameObj =  {
    "name": {
      "common": "Finland",
      "official": "Republic of Finland",
      "nativeName": {
        "fin": {
          "official": "Suomen tasavalta",
          "common": "Suomi"
        },
        "swe": {
          "official": "Republiken Finland",
          "common": "Finland"
        }
      }
    }
  }

const firstCommon = Object.values(nameObj.name.nativeName)[0].common

second question:
type name = {
  name: {
    common: string,
    official: string,
    nativeName: {
      [key: string]: {
        official: string,
        common: string
      }
    }
  }
}


text:
Q: What's the use of & in Programming languages? I have seen the use of & in many programming language and since I love groovy a lot I tried the following code to find the use of & :
a = 1 ;
println a & 2

I'm getting the output as 0. When I change the values of a I get different answer's.
So any one can say whats the use of & in programming languages like Groovy in simple english, possibly with an simple example in any language?
Thanks in advance.

A: & is usually either bitwise-and (on integer arguments) or non-short-circuiting logical and (on boolean arguments).
bitwise-and returns a series of bits (usually represented as an int type) that have only the bits in common set
18          == 10010
6           == 00110
18 & 6 == 2 == 00010

This seems to be what is happening in your Groovy code.  1 & 2 == 0 since 1 and 2 share no bits in common.
Non-short-ciruiting logical and is similar to && but
if (f() && g())   // g is only called if f returns false
if (f() &  g())   // g is called even when f returns false

In languages that allow operator overloading, libraries sometimes overloaded & to do set intersection, or element-wise bit-intersection.

A: Searching "Groovy Operator" in Google, the first result yields: http://groovy.codehaus.org/Operators

In general all operators supported in Java are identical in Groovy.

Further in http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html:

bitwise AND   &

Searching for "Bitwise AND" in Google, the first result is: http://en.wikipedia.org/wiki/Bitwise_operation#AND

AND
A bitwise AND takes two binary representations of equal length and
  performs the logical AND operation on each pair of corresponding bits.
  For each pair, the result is 1 if the first bit is 1 AND the second
  bit is 1; otherwise, the result is 0. For example:
    0101 (decimal 5)
AND 0011 (decimal 3)
  = 0001 (decimal 1)

it takes less than 5 minute to work all that out.


text:
Q: How to display Products Images on Category Products How can I show products images on category products page?

A: Please refer to this link: http://inchoo.net/magento/show-product-thumbnail-in-grids/
There is one small change you will require to a file in above module or it may give you Image file was not found error.
Open app\code\local\Inchoo\Thumbnail\Block\Adminhtml\Template\Grid\Renderer\Image.php file and update render function with below code.
public function render(Varien_Object $row)
{
    try{
      $val = Mage::helper('catalog/image')->init($row, 'thumbnail')->resize(97);
    }
    catch(Exception $e) {
      $val = Mage::getDesign()->getSkinUrl('images/catalog/product/placeholder/image.jpg',array('_area'=>'frontend'));
    }
    $out = "<img src=". $val ." width='97px'/>";
    return $out;
}

Images will be displayed as per below screenshot.

To add edit link on grid, updated below file.
app\code\local\Inchoo\Thumbnail\Block\Adminhtml\Catalog\Category\Tab\Product.php
Add below code just before return parent::_prepareColumns();
$this->addColumn('action',
    array(
        'header'    => Mage::helper('catalog')->__('Action'),
        'width'     => '50px',
        'type'      => 'action',
        'getter'     => 'getId',
        'actions'   => array(
            array(
                'caption' => Mage::helper('catalog')->__('Edit'),
                'url'     => array(
                    'base'=>'adminhtml/catalog_product/edit',
                    'params'=>array('store'=>$this->getRequest()->getParam('store'))
                ),
                'field'   => 'id'
            )
        ),
        'filter'    => false,
        'sortable'  => false,
        'index'     => 'stores',
));


text:
Q: Redux Selectors - Filter and then sort using selectors In my Redux store I have a list of notes.
I wish to

*

*Filter out the notes that are created by me

*sort those notes by created date / title / etc.

I would like to separate logic for filtering and sorting into own functions to make the code more easy to maintain.
I have read the tutorial on redux-reselect and have come up with the below structure.
import { createSelector } from 'reselect';

const sortNotesBy = ({notes, sortBy}) => {
  return notes.sort((a, b) => {
    if (sortBy === TITLE) {
      //dueDate date - createdAt
      return a.dueDate > b.dueDate ? -1 : 1
    }
    else if (sortBy === CREATED_DATE) {
      //createdAt
      return a.createdAt > b.createdAt ? -1 : 1
    }
  })
}

const getMyNotes = ({notes, uid}) => {
  return notes.filter(note => note.author === uid)
}

const sortBy = props.sortBy // set by mapStateToProps
const uid = props.uid // set by mapStateToProps
const notesSelector = state => state.notes;

// Filter out my notes
export const myNotes = createSelector([notesSelector], notes => {
  return getMyNotes({notes, uid})
});

// Sort my notes
export const sortedNotes = createSelector([myNotes], notes => {
  return sortNotesBy({notes, sortBy})
});

Is the above approach of "stacking" selectors a good approach to accomplish code separation, or might there be any issues with this approach?
Kind regards /K

A: My initial code does not work fully - I cannot access sortBy and uid from variables. These values can however be read from store by stacking selectors.
const sortBy = props.sortBy // set by mapStateToProps
const uid = props.uid // set by mapStateToProps

The result would look something like
import { createSelector } from 'reselect';

// INPUT SELECTORS
const getFilters = state => (state.filters) ? state.filters : []
const getUser= state => (state.user) ? state.user : []
const getNotes = state => (state.notes) ? state.notes : []

// SELECTORS
//Get my sort preference
export const getMySortBy = createSelector(
  [getNotes, getFilters],
  (notes, filters) => {
    const openNoteId = filters?.id ?? ''
    const noteObj = notes.find((not)=>not.id === openNoteId )
    const mySortBy = notObj?.personalSortOrder ?? TITLE // Default to title sort
    return mySortBy
  }
)

//Get my uid
export const getMyUid = createSelector(
  [getUser],
  (user) => { return user?.uid ?? '' }
)

// Get my notes
export const getMyNotes = createSelector(
  [getMyUid, getNotes],
  (uid, notes) => {
    return notes.filter(note => note.author === uid)
  }
)

const sortNotesBy = ({notes, sortBy}) => {
  return notes.sort((a, b) => {
    if (sortBy === TITLE) {
      //dueDate date - createdAt
      return a.dueDate > b.dueDate ? -1 : 1
    }
    else if (sortBy === CREATED_DATE) {
      //createdAt
      return a.createdAt > b.createdAt ? -1 : 1
    }
  })
}

// Sort my notes
export const sortedNotes = createSelector(
  [getMyNotes, getMySortBy],
  (notes, sortBy) => {
    return sortNotesBy({notes, sortBy})
  }
);

I found that by using reselect and stacking selectors, my code is easier to follow and maintain, since each piece of logic can be tested and maintained separately.
Kind regards /K

A:     function sortObjectsByField(fieldAlias) {
    return function(a, b) {
        return a[fieldAlias] > b[fieldAlias] ? -1 : 1
    }
}
const FIELD_YOU_NEED = 'FIELD_YOU_NEED'
array.sort(sortObjectsByField(FIELD_YOU_NEED))

I am using this function for my purposes, so you can provide this function right into Array.sort and provide any field alias you need. In my opinion this is good for maintaining and also, you dont need to provide an array to your sorting fucntion.


text:
Q: Iteration over cursor with pymongo unreasonably slow Context
I have a mongo database that has one collection called documents. This collection has 436333 entries and I have to do some operations on each of them. My code is:
client = MongoClient()
db = client['database']
documents = db.documents.find()
bias = {
        'title': pd.DataFrame(index=POS_TAGS, dtype=np.int32),
        'abstract': pd.DataFrame(index=POS_TAGS, dtype=np.int32),
        'title_abstract': pd.DataFrame(index=POS_TAGS,     dtype=np.int32)}
for i, doc in enumerate(documents):
    pos_tags = doc['agg_pos_tagging']
    for k, v in pos_tags.items():
        if len(v) != 0:
            bias[k].loc[:, doc["id"]] = \
                pd.Series(_match_values(v), index=POS_TAGS)
        else:
            bias[k].loc[:, doc["id"]] = \
                pd.Series([0] * len(POS_TAGS), index=POS_TAGS)
    if i % 10000 == 0:
       logging.info("{0} docs added".format(i))

I have CentOS 6.7 and mongodb 2.6. I'm using python 3.4, pymongo 3.2.2 (with c extensions installed) and pandas 0.18.0. The program and the server are in the same machine. The collection is indexed over its id.
Problem
The problem is that the time it takes to pass for each chunck of 10000 entries increases with the amount of lines retrieved. This is the log:
2016-06-12 16:11:17,016 : INFO : 0 docs added
2016-06-12 16:13:45,553 : INFO : 10000 docs added
2016-06-12 16:17:47,117 : INFO : 20000 docs added
2016-06-12 16:23:14,786 : INFO : 30000 docs added
2016-06-12 16:29:40,412 : INFO : 40000 docs added
2016-06-12 16:38:11,807 : INFO : 50000 docs added
2016-06-12 16:50:38,987 : INFO : 60000 docs added
2016-06-12 17:04:19,188 : INFO : 70000 docs added
2016-06-12 17:18:21,669 : INFO : 80000 docs added
2016-06-12 17:34:18,687 : INFO : 90000 docs added
2016-06-12 17:53:11,497 : INFO : 100000 docs added
2016-06-12 18:18:57,503 : INFO : 110000 docs added
2016-06-12 18:51:33,503 : INFO : 120000 docs added
2016-06-12 19:24:47,799 : INFO : 130000 docs added
2016-06-12 19:57:40,690 : INFO : 140000 docs added
2016-06-12 20:31:44,103 : INFO : 150000 docs added
2016-06-12 21:10:24,900 : INFO : 160000 docs added
2016-06-12 22:02:46,849 : INFO : 170000 docs added
2016-06-12 22:57:50,108 : INFO : 180000 docs added
2016-06-12 23:55:52,541 : INFO : 190000 docs added
2016-06-13 00:56:43,676 : INFO : 200000 docs added
2016-06-13 02:07:39,460 : INFO : 210000 docs added
2016-06-13 03:22:43,074 : INFO : 220000 docs added
2016-06-13 04:40:00,819 : INFO : 230000 docs added
2016-06-13 06:05:09,572 : INFO : 240000 docs added
2016-06-13 07:27:09,148 : INFO : 250000 docs added
2016-06-13 08:58:45,093 : INFO : 260000 docs added
2016-06-13 10:13:26,832 : INFO : 270000 docs added
2016-06-13 11:30:29,821 : INFO : 280000 docs added
2016-06-13 12:53:54,008 : INFO : 290000 docs added
2016-06-13 14:20:45,617 : INFO : 300000 docs added
2016-06-13 16:01:00,446 : INFO : 310000 docs added
2016-06-13 17:40:26,558 : INFO : 320000 docs added
2016-06-13 19:30:14,056 : INFO : 330000 docs added
2016-06-13 21:19:33,698 : INFO : 340000 docs added
2016-06-13 23:10:49,665 : INFO : 350000 docs added

Adding the documents 340000 to 350000 takes almost two hours but adding the first 10000 takes only 2 minutes.
I don't think there is a problem with the calculations. They should take approximately the same amount of time for each chunck of 10000 items. I looked the log file of the database and it doesn't show all the getMore operations (I added all nreturns and it doesn't corresponds to the amount of documents retrieved), so I don't know if I should trust it.
I tried changing the cursor_type to EXHAUST but it didn't change the results.
What can I do to make it faster?
EDIT
I run the code without any calculation and so far I got this.
2016-06-14 15:43:19,263 : INFO : 0 docs added
2016-06-14 15:43:23,488 : INFO : 10000 docs added
2016-06-14 15:43:27,532 : INFO : 20000 docs added
2016-06-14 15:43:32,112 : INFO : 30000 docs added
2016-06-14 15:43:36,098 : INFO : 40000 docs added
2016-06-14 15:44:13,818 : INFO : 50000 docs added
2016-06-14 15:44:52,624 : INFO : 60000 docs added
2016-06-14 15:45:48,415 : INFO : 70000 docs added
2016-06-14 15:47:10,645 : INFO : 80000 docs added
2016-06-14 15:48:26,565 : INFO : 90000 docs added
2016-06-14 15:48:57,270 : INFO : 100000 docs added
2016-06-14 15:49:52,323 : INFO : 110000 docs added
2016-06-14 15:51:22,808 : INFO : 120000 docs added
2016-06-14 15:53:30,554 : INFO : 130000 docs added
2016-06-14 15:55:31,960 : INFO : 140000 docs added

There is still some lag that increases over time.


text:
Q: average of $\{n\alpha \}$, where $\alpha$ irrational Let $\alpha$ be an irrational number.
Let $\{x\}$ denote the fractional part of $x$.
Is it true that $\displaystyle\lim_{n\to\infty}\frac{\{\alpha \}+\{2\alpha \}+\{3\alpha \}+\cdots+\{n\alpha \}}{n}=\frac{1}{2}$.
How to prove it? Thank you.


text:
Q: Selection not proper after rowspan on PrimeNG Table I am facing a strange issue. I am not able to select the merged row using rowspan on table of PrimeNG. Can anyone help me to quick fix this ?
See Stackblitz


text:
Q: Checking for Char/Int Alright so I am doing an assignment and am getting frustrated. The assignment wants me to ask the user for a number then say if the number is even or odd, but if the user types "done" the program will exit.
So my question is how do you check the input for character/int at the same time, then decide which it is.
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
bool isEven(int userAnswer);
using namespace std;
int userAnswer;

int main()
{
    cout << "Which number would you like to check?" << endl;
    cin >> userAnswer;

    if (isEven(userAnswer) == false)
    {
        cout << userAnswer << " is a odd number." << endl;
    }
    else if (isEven(userAnswer) == true)
    {
        cout << userAnswer << " is a even number." << endl;
    }

    cin.get();
    cin.get();

    return 0;
}

bool isEven(int userAnswer)
{
    if (userAnswer % 2 == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

A: Read into a string (which works in both cases), then parse the string yourself.

A: Read into a std::string and exit if done is in the string. Otherwise convert to int and carry on as you are.  Hint: see std::stoi


text:
Q: How to remove quotes around a word within a long string using regex in C# I am new to C# regex. I have the following JSON string. I want to remove quotes around "true" or "false", whenever they occur, within this string so that these values become JSON boolean types instead of strings.
    "{"email":"johnq@gmail.com","firstName":"John","lastName":"Quinton","moreThanFiveYears":"false","member":"true","insertDate":"2019-04-14 17:28:40"}"

"{"email":"johnq@gmail.com","firstName":"John","lastName":"Quinton","moreThanFiveYears":false,"member":true,"insertDate":"2019-04-14 17:28:40"}"

The first string is the one I currently have. I want to change it to the second one. I know how to remove quotes from the start and end of a string, but not sure how to remove from words within a longer string and moreover the words in question (true/false) can occur at multiple times.

A: May be you get some idea from this.
(?<=false|true)"|"(?=true|false)

Demo: https://regexr.com/4c94f


text:
Q: std::errc ABI portability I've built this project from source.  I have a setup that hits this codepath:
if (err != std::errc::no_such_file_or_directory) {
    Ctx.Diags.diagnose(moduleID.second, diag::sema_opening_import,
                       moduleID.first, err.message());
  }

On my system (Debian Jessie), this condition evaluates to false.  Therefore we do not call Ctx.Diags.diagnose.
However, I took the binary I built and gave it to a friend who runs Ubuntu.  Under the exact same conditions on his system, the if statement evaluates to true, and err.message() is No such file or directory.
How is that possible?  I thought std::errc is supposed to be portable?  ENOENT is 2 on both systems, as required by POSIX.
I assume this has something to do with libstd on his system at runtime being different than it is on my system at buildtime, but I don't understand why, or how to build a portable version.

A: @T.C.'s hypothesis in the comments above is correct.
The ABI for C++11 features changed between the experimental C++0x support in GCC 4.9 and the finished C++11 support in GCC 5.x, so if your code uses C++11 you can't compile with GCC 4.9 and then use the libstdc++ from GCC 5.
This is PR 66438. I closed that as invalid, because mixing 4.9 and 5.x doesn't work for C++11 code.


text:
Q: Shared Preferences MODE_APPEND constant is not recognised I'm trying to append data on my already existing preferences, but it seems like the MODE_APPEND
constant is not recognised. Despite the error, the program can be executed, but the content of preferences is overwritten.

I've already searched for a solution but didn't find anything. What might be the problem?
Thank you.
EDIT
Expected Scenario:
After first program execution
array.add("ONE");array.add("TWO");array.add("THREE");
set=new HashSet<String>(array);
editor.putStringSet(key, set);
print(prefs);

Output

[ONE, TWO, THREE]

After second program execution
array.add("FOUR");array.add("FIVE");array.add("SIX");
set=new HashSet<String>(array);
editor.putStringSet(key, set);
print(prefs);

Output

[ONE, TWO, THREE, FOUR, FIVE, SIX]

A: Adding to the answer in relation to

The solution you provided does not append new values. It overwrites them

The following is a set of methods that can be used to append to an existing shared preferences set.
public void appendSharedPreference(SharedPreferences sharedPreferences,String key, Object o) {
    SharedPreferences.Editor e = sharedPreferences.edit();
    for (Map.Entry<String,?> entry: sharedPreferences.getAll().entrySet()) {
        sharedPrefPut(e,entry.getKey(),entry.getValue());
    }
    sharedPrefPut(e,key,o);
    e.commit();
}

public void sharedPrefPut(SharedPreferences.Editor e, String key, Object o) {
    if (o instanceof Boolean) e.putBoolean(key,(Boolean) o);
    if (o instanceof String) e.putString(key,(String) o);
    if (o instanceof Integer) e.putInt(key,(Integer) o);
    if (o instanceof Long) e.putLong(key,(Long) o);
    if (o instanceof Float) e.putFloat(key,(Float) o);
    if (o instanceof Set) e.putStringSet(key,(Set<String>) o);
}

An example of using this, within an Activity, is :-
    SharedPreferences.Editor e1 = this.getSharedPreferences("test",0).edit();
    e1.putInt("KEY1",100);
    e1.putString("KEY2","MYDATA");
    e1.commit();

    for (Map.Entry<String,?> e: this.getSharedPreferences("test",0).getAll().entrySet()) {
        Log.d("SPINITIAL","Key is " + e.getKey() + " Value is " + e.getValue());
    }

    appendSharedPreference(this.getSharedPreferences("test",0),"KEYAPPENDANOTHER","SomeOtherData");

    for (Map.Entry<String,?> e: this.getSharedPreferences("test",0).getAll().entrySet()) {
        Log.d("SPEND","Key is " + e.getKey() + " Value is " + e.getValue());
    }

The log produced from the above
Before

D/SPINITIAL: Key is KEY2 Value is MYDATA
D/SPINITIAL: Key is KEY1 Value is 100

After

D/SPEND: Key is KEY2 Value is MYDATA
D/SPEND: Key is KEY1 Value is 100
D/SPEND: Key is KEYAPPENDANOTHER Value is SomeOtherData

Of course, over use/abuse of SharedPreferences can have performance ramifications
Edit about Edit
A method (subtle change) can be used like
public void replaceSharedPreference(SharedPreferences sharedPreferences, String key, Object o) {
    SharedPreferences.Editor e = sharedPreferences.edit();
    for (Map.Entry<String, ?> entry: sharedPreferences.getAll().entrySet()) {
        if (entry.getKey().equals(key)) {
            sharedPrefPut(e,entry.getKey(),o);
        } else {
            sharedPrefPut(e,entry.getKey(),entry.getValue());
        }
    }
}

So instead of appending a new it will replace the existing. The object passed has to be built and for your requirement it needs the existing object to be extracted and appended to.
An example based upon your requirements could be :-
    ArrayList<String> array =  new ArrayList<>();
    array.add("ONE");array.add("TWO");array.add("THREE");
    HashSet<String> set = new HashSet<>(array);

    SharedPreferences.Editor e1 = this.getSharedPreferences("test",0).edit();
    e1.putInt("KEY1",100);
    e1.putString("KEY2","MYDATA");
    e1.putStringSet("KEY3",set);
    e1.commit();

    for (Map.Entry<String,?> e: this.getSharedPreferences("test",0).getAll().entrySet()) {
        Log.d("SPINITIAL","Key is " + e.getKey() + " Value is " + e.getValue());
    }

    //appendSharedPreference(this.getSharedPreferences("test",0),"KEYAPPENDANOTHER","SomeOtherData");
    ArrayList<String> appendset = new ArrayList<>();
    appendset.add("FOUR");
    appendset.add("FIVE");
    appendset.add("SIX");
    HashSet<String> oldset = null;
    if ((oldset  = (HashSet<String>) this.getSharedPreferences("test",0).getStringSet("KEY3",null)) != null) {
         oldset.addAll(appendset);
         replaceSharedPreference(this.getSharedPreferences("test",0),"KEY3",oldset);
     }

    for (Map.Entry<String,?> e: this.getSharedPreferences("test",0).getAll().entrySet()) {
        Log.d("SPEND","Key is " + e.getKey() + " Value is " + e.getValue());
    }

If order is an issue then please note

It makes no guarantees as to the iteration order of the set; in
  particular, it does not guarantee that the order will remain constant
  over time.
  Class HashSet


text:
Q: Spring Boot context initialization error when run application's main() method I'm trying out a Hystrix sample app and everything works fine if I run the application using maven command mvn spring-boot:run but if I try to run the application's main() method, there are bunch of errors and application context won't initialize.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hystrixCommandAspect' defined in class path resource [org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2c13da15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at me.lakmal.moviecatalogservice.MovieCatalogServiceApplication.main(MovieCatalogServiceApplication.java:14) ~[classes/:na]
Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2c13da15]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:232) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:210) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(InitDestroyAnnotationBeanPostProcessor.java:149) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:294) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:1093) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:568) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    ... 16 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/aspectj/lang/ProceedingJoinPoint
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method) ~[na:na]
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3166) ~[na:na]
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2309) ~[na:na]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    ... 23 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.ProceedingJoinPoint
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ~[na:na]
    ... 27 common frames omitted

I'm wondering what is the difference between running application's main() method and mvn spring-boot:run which could cause for this issue.


text:
Q: Invalid start byte when reading multiple files in Python My function reads multiple .sgm files. I get an error when reading the content from the file speficially at line contents = f.read()
def block_reader(path):
    filePaths = []
    for filename in os.listdir(path):
        if filename.endswith(".sgm"):
            filePaths.append(os.path.join(path, filename))
            continue
        else:
            continue

    for file in filePaths:
        with open(file, 'r') as f:
            print(f)
            contents = f.read()
            soup = BeautifulSoup(contents, "lxml")

    return ["test content"]

Error message
    Traceback (most recent call last):
  File "./block-1-reader.py", line 32, in <module>
    for reuters_file_content in solutions.block_reader(path):
  File "/home/ragith/Documents/A-School/Fall-2020/COMP_479/Assignment_1/solutions.py", line 29, in block_reader
    contents = f.read()
  File "/usr/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 1519554: invalid start byte

A: Try this: with open(path, 'rb') as f: That b in the mode specifier in the open() states that the file shall be treated as binary, so contents will remain a bytes. No decoding attempt will happen this way. More details at: this link


text:
Q: How to build a responsive CSS grid with square items to display images with multiple aspect ratios I'm trying to build this responsive grid for an image gallery.
I want the grid items to be square-shaped at all times (aspect ratio 1:1), even though the pictures are coming in all sorts of aspect-ratios.
I'll probably display any picture inside the square items, using object-fit: cover.
I'm trying to get a solution that works well across browsers. Nothing too hacky. It's seems like a simple task but so far I couldn't wrap my head around it.
See an example on the code snippet that I've made.
Note: Every image needs to have an icon on top of it, just like the example.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: 10px;
}

.gridItemContainer {
  position: relative;
}

.grid img {
  display: block;
  object-fit: cover;
  width: 100%;
}

.grid i {
  font-size: 120%;
  position: absolute;
  top: 10px;
  left: 10px;
}

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">

A: You can use padding-top: 100% to set the height of a grid item - this will make a square as padding in percentages is based on width in CSS.
Now make the image position: absolute so that it will be taken out of the flow and height will be fully dictated by padding-top set on the grid item (gridItemContainer) - see demo below:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: 10px;
}

.gridItemContainer {
  position: relative;
  padding-top: 100%; /* added */
  border: 1px solid;
  background: cadetblue;
}

.grid img {
  display: block;
  object-fit: cover;
  width: 100%;
  height: 100%; /* image fills the grid item */
  position: absolute; /* position absolutely */
  top: 0;
  left: 0;
}

.grid i {
  font-size: 120%;
  position: absolute;
  top: 10px;
  left: 10px;
}

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">


text:
Q: how to re-initialize a div position when filtered from N such div Below is small code.
X.html
<input type="text" id="search-criteria"/>
<input type="button" id="search" value="search"/>

Services

Branches

Firm Type

Designations

X.js
$('#search-criteria').keyup(function(){
    $('.misc').hide();
    var regex = new RegExp($('#search-criteria').val(), 'i');
    $('.misc').filter(function() {
       return regex.test($(this).text());
    }).show();
});

I tried with the code above and it is working,  But, The problem is that the position of the div is not refreshed, it must be initialized to start of page. There are many div with class misc. After searching the expected div, it
 is visible but remains at the same position. I want it's position to be re-initialized and when I clear the search input, all must be visible as they were.
Below is the supporting image,
NO SEARCH

AFTER SEARCH

EXPECTED OUTPUT

A: You are only hiding the divs inside your column layout, so the columns are still being displayed at their widths. You should hide the col-sm-3 divs to achieve what you need.

A: You need to hide the columns not the element inside the column. Just use parent() on the .misc elements. Like this:

$('#search-criteria').keyup(function(){
    var regex = new RegExp($('#search-criteria').val(), 'i');
    var elements$ = $('.misc').parent();
    elements$.hide().filter(function() {
       return regex.test($(this).text());
    }).show();
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<input type="text" id="search-criteria"/>
<input type="button" id="search" value="search"/>

Services

Branches

Firm Type

Designations

A: try change the structure like this

Services


text:
Q: Intersection of 3 circles which are on the same line - Trilateration I have faced a problem: I would like to compute the intersection of three circles. To the best of my knowledge, I should use the so called Trilateration. I have implemented it in c++. The article says that there are three limitation of this solution.

*

*all three centers are in the plane z = 0,

*the sphere center, P1, is at the origin,

*and the sphere center, P2, is on the x-axis

As for the first "criterion", I have nothing to do because all the three centers are in the plane z = 0 since I do not use Z coordinates.
After that I translated the points to the positions where the center of the first point (P1) is at the origin. After that, I rotated the P2 (and P3 as well) point to the position where the P2 is on the x-axis.
My problem is: When all the three center are on the X axis, I tried to compute the center of the intersection area(which is computed by using the algorithm of the wiki's article), but the calculation can not be done. On the other hand there is no limitation which says something like "the centers of the circles can not be on one line...
Let's see my problem visually, I just painted it:

As you can see, the three circle intersect each other on the same point at coordinates of (4,3). Therefore there is a solution for these points which are all on the same line (in this example, on the x axis).
The parameters of the circles are the following (x,y,radius):
P1: (0,0,5)
P2: (4,0,3)
P3: (8,0,5)

As I mentioned, I successfully implemented the algorithm of the Trilateration but it can not solve this example, the result is NaN (Not a Number). Of course I already tried this algorithm with another circles (which are not on the same line), and it works properly.
So I started debugging my implementation, and I have found where the problem might lie. My implementation is the following:
#include <iostream>
#include <fstream>
#include <sstream>
#include <math.h>
#include <vector>
std::ifstream infile("coordinateList.txt");
using namespace std;

std::vector<double> trilateration2D(double point1[], double point2[], double point3[], double r1, double r2, double r3) {
    std::vector<double> resultPose;
    //unit vector in a direction from point1 to point 2
    double p2p1Distance = pow(pow(point2[0]-point1[0],2) + pow(point2[1]-point1[1],2),0.5);
    double exx = (point2[0]-point1[0])/p2p1Distance;
    double exy = (point2[1]-point1[1])/p2p1Distance;

    //signed magnitude of the x component
    double ix = exx*(point3[0]-point1[0]);
    double iy = exy*(point3[1]-point1[1]);
    double i = ix+iy;
    //the unit vector in the y direction.
    double eyx = (point3[0]-point1[0]-ix*exx)/pow(pow(point3[0]-point1[0]-ix*exx,2) + pow(point3[1]-point1[1]-iy*exy,2),0.5);
    double eyy = (point3[1]-point1[1]-iy*exy)/pow(pow(point3[0]-point1[0]-ix*exx,2) + pow(point3[1]-point1[1]-iy*exy,2),0.5);
    //the signed magnitude of the y component
    double jx = eyx*(point3[0]-point1[0]);
    double jy = eyy*(point3[1]-point1[1]);
    double j = jx + jy;
    //coordinates
    double x = (pow(r1,2) - pow(r2,2) + pow(p2p1Distance,2))/ (2 * p2p1Distance);
    double y = (pow(r1,2) - pow(r3,2) + pow(i,2) + pow(j,2))/(2*j) - i*x/j;
    //result coordinates
    double finalX = point1[0]+ x*exx + y*eyx;
    double finalY = point1[1]+ x*exy + y*eyy;
    resultPose.push_back(finalX);
    resultPose.push_back(finalY);
    return resultPose;
}
int main(int argc, char* argv[]){
    std::vector<double> finalPose;
    double p1[] = {0,0};
    double p2[] = {4,0};
    double p3[] = {8,0};
    double r1,r2,r3;
    r1 = 5;
    r2 =3;
    r3 = 5;
    finalPose = trilateration2D(p1,p2,p3,r1,r2,r3);
    cout<<"X:::  "<<finalPose[0]<<endl;
    cout<<"Y:::  "<<finalPose[1]<<endl;

}

When the program calculates eyx and eyy there are zeros in the division, and needless to say, a division by zero is not "allowed".
The eyx and eyy are unit vectors in the y direction, but at such this locating of circles there is no unit vector in y direction.
My question is: Is there a 4th limitation to this algorithm? In my opinion it would be written to the article, so: Could you advise other solution for this problem, where the intersection can be calculated while all the points are on the same line?
Thanks in advance!


text:
Q: Возведение больших чисел в степень Задача состоит в том, чтобы возвести большое число n ( 0 <= n <= 10^50) в степень m ( 0 < m < 1000). Для этого, безусловно, использую длинную арифметику
typedef vector<long long> largen;

А также бинарное возведение в степень.
largen recbinpow(largen a, int n) {
    largen e;
    e.push_back(1);
    if (n == 0)
        return e;
    if (n % 2 == 1)
        return multiply(recbinpow(a, n - 1), a);
    else {
        largen b = recbinpow(a, n / 2);
        return multiply(b, b);
    }
}

Но это всё равно оказалось слишком медленно. Я выяснил, что если брать основание системы счисления побольше, например 10^9, то возведение в степень будет происходить гораздо быстрее.
const int base = 1000 * 1000 * 1000;

largen  multiply(largen a, largen b) {
    largen c(a.size() + b.size());
    for (size_t i = 0; i<a.size(); ++i)
        for (int j = 0, carry = 0; j < (int)b.size() || carry; ++j) {
            long long cur = c[i + j] + a[i] * 1ll *(j < (int)b.size() ? b[j] : 0) + carry;
            carry = (long long)(cur / base);
            c[i + j] = (long long)(cur % base);
        }
    while (c.size() > 1 && c.back() == 0)
        c.pop_back();
    return c;
}

Но, по непонятным мне причинам, программа работает некорректно на некоторых значениях, например 999 999 999.
Часы отладки ни к чему не привели. Помогите, пожалуйста, отыскать ошибку programme.

A: А вы не хотите учесть, что ваш вывод
for (int i = result.size() - 1; i >= 0; i--) {
    cout << result[i];
}

должен, вообще-то, выводить еще и ведущие нули (буде таковые имеются)?... Т.е. если ваш элемент вектора меньше того самого миллиарда, то он-то все равно должен выводиться в 9 знакомест?


text:
Q: Need to pass ArrayList from servlet class to js function I am doing pagination in my project. I have a ArrayList in servlet class which has 50 records. I need to show 10 records per page. I am able to get first 10 records in the jsp. However, when I click on the next button I want the records 11-20 from the same ArrayList. Hence I need to cache the ArrayList somewhere. I have tried a number of methods and ways to pass the ArrayList from jsp to js function and from servlet to js function but no luck. Can someone tell me how can I cache the ArrayList so that I can iterate it next time? Any link or help would be appreciated.

A: To pass ArrayList from Servlet to js function in JSP file you need to convert the ArrayList to JSON with Gson. Gson is an open source Java library to serialize and deserialize Java objects to (and from) JSON.
First you need to add gson jar to your project
download here
Then convert ArrayList to JSON.
String json = new Gson().toJson(yourArrayListName);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

And then you can use it in your ajax function in JSP.


text:
Q: Why is node.js not processing these both functions/methods asyncronousliy? Why is node not processing the following both functions/methods asyncronousliy?
function loop(y) {
    var x = 1;
    for (let index = 0; index < y; index++) {
        x = x + index;
    }
    console.log(x);
}

loop(3000000000);
console.log(1);

A: Generally a function is non-blocking when:

*

*current execution requests external service like I/O or networking requests etc.

*a function call is put on a timer to be executed at a later time.
but your function is not any of those.

A: You're not making any sort of asynchronous request in your current code. In node, code is generally executed in order unless specified otherwise.
Therefore, the loop finishes running first and then the last statement of your code is executed.


text:
Q: Python 3. Обозначение переменных внутри строк, которые хранятся, например в словаре или списке Я начал делать поддержку мультиязычности для свой программы, и возник вопрос хранения переменных внутри сообщений - строк.
При выводе строки происходит подстановка переменной, строки хранятся в словаре конкретного языка. То есть например у меня есть словарь, я вывожу строку по ключу, а в этой строке должны вызываться переменные которые я должен вывести, как бы вставить на нужные мне места внутри этой строки.
Надеюсь правильно и понятно описал суть вопроса. Переменная чаще всего приходит например из функции при ее вызове, и далее должна происходить подстановку в строку.
P.S. у меня в программе данные хранятся в JSON соответственно при выводе совершается encode JSON в Python данные.


text:
Q: Gnome and Cinnamon loads in fallback (classic) mode only So I have been using linux mint for a while now. A few months ago my Gnome shell crashed and I was unable to use the full 3d features and loaded into fallback mode only. From that day (around 2 months ago) I still have only fallback mode (both Gnome and cinnamon). I installed Linux mint maya, and Ubuntu 12.04 both as windows file and complete installation in an external hard drive. and for many times I sitll cannot fix this problem. ps I made sure to download all the drivers for my graphics card. what could the problem be?

A: I've got crash when using Rhythmbox, switched to amarok and everything is ok now. It may be application (not drivers) problem then.


text:
Q: Use Toad Data Point to graphicaly choose values for IN operator in where clause I'm trying to add static values into my IN operator.
Such as
Where Customers.Name in ('Jack', 'Jill')

But I'm only able to add one value for an = operator
Such as
Where Customers.Name = 'Jack'

I am able to type them into the Formula window
But, Is there a way to graphically choose values for the IN operator, rather than have to type them?

A: Yes.  Click the ellipsis button on the Where line of the field you want to query on.  Then pick In (instead of equals) and check the boxes in the drop down for the items you want.
(src: http://www.toadworld.com/products/toad-data-point/f/36/t/29888)


text:
Q: HTTP Digest Authentication - Share MD5 instance between multiple http requests I have my own HTTP request class  which I am using it as a client to send an HTTP requests to some remote servers.
I am implementing an HTTP digest authentication and using MD5 instance in order to preform the hash algorithm .
I would like to know what is the efficient way to store the MD5 instance ?
I thought about these options:

*

*Every request will hold a MD5 instance, so every time that request are being sent we will do : m_md5 = MD5.Create();
How expensive is the 'Create' process ?

*The MD5 instance will be static and will be store out of the request class and we will use the MD5.Create() just once and all the request instance will use the same MD5 instance.Note that a lot of threads are creating instances of the HTTP request class. Is it thread-safe ?

Thnaks.

A: As Oguz Ozgul Said the second optiond doesn't possible since MD5 doesn't thread-safeas we can see here:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe


text:
Q: Angular routing in ASP.NET MVC application I'm trying to read query parameters in my angular controller so I set up the route config
confirmedemailcontroller.js
var app = angular.module('confirmedemail', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
    // calls
    $routeProvider.when('/confirmedemail/:userid/:token', {
        templateUrl: 'templates/confirmedview.html',
                    controller: 'ConfirmedEmailController'
                });
    $locationProvider.html5Mode(true);
});

app.controller('ConfirmedEmailController', function ($scope, $http, $routeParams, $location) {
    // never calls
    // read params from $routeParams and send them then display the result...
    //...
});

ConfirmedEmail.cshtml
@{
    ViewBag.Title = "Confirm Email";
}

@ViewBag.Title.

            Thank you for confirming your email. Please @Html.ActionLink("Click here to Log in", "Login", "Home", routeValues: null, htmlAttributes: new { id = "loginLink" })

my root is http://localhost:25715/confirmedemail/111/222,
where 111 is userId and 222 is token which I want to read out inside controller
But controller never calls. What have I missed?
Updated
I have HomeController with working action
public ActionResult ConfirmedEmail(string userId = "", string code = "")
{
    ViewBag.Message = "Account confirmed";
    return View();
}

and in templates folder there's confirmedview.html

A: In RouteConfig.cs
  routes.MapRoute(
         name: "Confirm",
         url: "ConfirmedEmail/{userId}/{code}",
         defaults: new { controller = "Home", action = "ConfirmedEmail", userId = "", code = "" }
     );

in confirmedemailcontroller.js
var app = angular.module('confirmedemail', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.when('/ConfirmedEmail/:param1/:param2', {
        templateUrl: '/templates/confirmedview.html',
                    controller: 'ConfirmedEmailController'
                });
    $locationProvider.html5Mode({ requireBase: false, enabled: true });
});
app.controller('ConfirmedEmailController', function ($scope, $http, $routeParams) { ... });

And don't forget about case sensivity! If I call it like mysite.com/confirmedemail/111/222, it won't work


text:
Q: openssl returns Bad Magic Number In my Linux machine i have a binary AES encrypted file:
head -c 100 Leela_Turanga.plr
�|�XѨ��>��c��N�Ώڤ�LW�M��t�p5=c.4���ᑸ�#Owl����M�d��>�ٷa�L�r|��ć�ڐ,��:����#�����\

Also i know that the file has been encryped using the password:
h3y_gUyZ

I am able to decrypt this file using .NET's RijndaelManaged class in the following routine:
public static bool decryptFile(string inputFile, string outputFile)
    {
        string s = "h3y_gUyZ";
        UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
        byte[] bytes = unicodeEncoding.GetBytes(s);
        FileStream fileStream = new FileStream(inputFile, FileMode.Open);
        RijndaelManaged rijndaelManaged = new RijndaelManaged();
        CryptoStream cryptoStream = new CryptoStream(fileStream, rijndaelManaged.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
        FileStream fileStream2 = new FileStream(outputFile, FileMode.Create);
        try
        {
            int num;
            while ((num = cryptoStream.ReadByte()) != -1)
            {
            fileStream2.WriteByte((byte)num);
            }
            fileStream2.Close();
            cryptoStream.Close();
            fileStream.Close();
        }
        catch
        {
            fileStream2.Close();
            fileStream.Close();
            File.Delete(outputFile);
            return true;
        }
            return false;
    }

Since im on Linux I embedded this code in a c# program which i run with mono, after i compiled it with mcs.
mcs *.cs -out:mybinary.exe
mono mybinary.exe d Leela_Turanga.plr outputfile.dat

Where the d parameter executes the aforementioned function, Leela_Turanga.plr is the file to decrypt and outputfile.dat is the resulting decryped file.
This works fine: I can decrypt the file correctly, and i am able to say this because human readable text appears in the decrypted file.
Now i want to decrypt the same file with openssl.
First of all i need to get the algorithm parameters, and since the code above works, I modified it to give me these informations:

*

*Key Size

*AES operation mode (cbc, ecb, pcbc, cfb...)

*Padding (have no idea what that is)

by adding some code:
public static bool decryptFile(string inputFile, string outputFile)
    {
        string s = "h3y_gUyZ";
        UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
        byte[] bytes = unicodeEncoding.GetBytes(s);
        FileStream fileStream = new FileStream(inputFile, FileMode.Open);
        RijndaelManaged rijndaelManaged = new RijndaelManaged();
        CryptoStream cryptoStream = new CryptoStream(fileStream, rijndaelManaged.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
        FileStream fileStream2 = new FileStream(outputFile, FileMode.Create);

        //=======DEBUG INFO=======
        //PRINT ALGORITHM SETTINGS
        Console.WriteLine(rijndaelManaged.Mode);    //what AES mode are we using?
        Console.WriteLine(rijndaelManaged.KeySize); //what is the keysize?
        Console.WriteLine(rijndaelManaged.Padding); //what is the padding?
        //========================

        try
        {
            int num;
            while ((num = cryptoStream.ReadByte()) != -1)
            {
            fileStream2.WriteByte((byte)num);
            }
            fileStream2.Close();
            cryptoStream.Close();
            fileStream.Close();
        }
        catch
        {
            fileStream2.Close();
            fileStream.Close();
            File.Delete(outputFile);
            return true;
        }
            return false;
    }

What it comes out is that RijndaelManaged is working in CBC mode, with a 256 bit key and PKCS7 Padding (again no idea if that is important).
Now i can try using openssl to decrypt:
openssl enc -aes-256-cbc -d -in Leela_Turanga.plr -out out.bin

Then the password prompt appears, I enter the pass, and a "bad magic number" error is returned"
enter aes-256-cbc decryption password:
bad magic number

And i get no decrypted file.
Why does openssl say that? I have searched on the internet but I haven't found my answer.
Also:
Since in c# strings are encoded in UTF-16 (hence 16 bits in a char), and the key is "h3y_gUyZ" which are 8 chars, shouldn't the key be 16 x 8 = 128 bits wide? instead of the 256 rijndaelManaged.KeySize returns.

A:
Why does openssl say that?

OpenSSL uses it's own key derivation routine called EVP_BytesToKey, which takes a salt. This salt is prefixed with a 8 byte magic: Salted__ in ASCII encoding. Passwords should not be directly used as keys, so OpenSSL converts them to keys first.
You can instead provide a key using -K and then the hexadecimal representation of your string (read on for the encoding). You will also need to provide the IV (in your case the same bytes).

Since in C# strings are encoded in UTF-16 (hence 16 bits in a char), and the key is "h3y_gUyZ" which are 8 chars, shouldn't the key be 16 x 8 = 128 bits wide instead of the 256 rijndaelManaged.KeySize returns?

Yes, probably you asked the Rijndael class for the key size before initializing it with the key. And note that .NET uses UTF-16LE (little-endian) as the whole ecosystem is in (stupid) little-endian.

PKCS#7 is a standard that contains a padding scheme. It is both used by .NET and OpenSSL, so that's fine. It is required as ECB and CBC mode require the input size of the cipher is N times the block size of the cipher. So PKCS#7 adds 1 to 16 bytes (the block size of AES) valued \x01 to \x10. Unpadding removes these.