text:
Q: Casting HashMap of subtypes to HashMap of supertypes I do have troubles manipulating hashmaps. My problem is quite simple, but I cannot make it work...
I have an interface named MultilineWritable. My classes that do need to be marshalled on flat files do implement this interface, which define a String toFlatFormat() function and its opposite init(String flatFormat).
Now imagine that the Contract class do implement MultilineWritable and is identified by integers while the Person class do also implement this interface but is identified by Strings.
My function to marshall the HashMaps of contracts and persons looks like :
public void marshall(HashMap<Object, MultilineWritable>){}

My problem is I cannot find a way to cast a HashMap<String, Person> to a HashMap<Object, MultilineWritable>, even if String extends Object and Person extends MultilineWritable. Same for the casting of a HashMap<Integer, Contract>... consequently I cannot call my generic function.
Thx for any help regarding this problem.

A: Assuming your marshall method only ever reads values, you should just change the declaration to:
public void marshall(HashMap<?, ? extends MultilineWritable> map)

The problem is that if the existing method call were allowed, it could try to put any MultilineWritable into the map - even if it was the wrong map type:
Map<String, Person> map = new HashMap<String, Person>();

// What would you want map.put("foo", new Contact()) to do inside marshall?
marshall(map);

EDIT: For more details about wildcards, see the Java Generics FAQ.

A: What you are trying to do is to pass a specific type into a generic type. You need to use java's generics feature. Generics offer compile time safety only, so while you are allowed to pass specific types into a function that takes genetic type, you are not allowed to modify the collection or the map.
So in short your anser is:
public void marshall(HashMap<? extends Object, ? extends MultilineWritable> map)

A: In Java Generics are not Covariant. So you cannot do following
    List<Integer> numList = new ArrayList<Integer>();
    List<Number> numList = new ArrayList<Number>();
    numList = numList; //Error
    numList = (List<Number>)intList; //error

Generics are used by the compiler to typsafety. The actual type information (of the collections i.e. this is List of Integers) etc is lost at runtime.


text:
Q: 301 redirect for all content - domain.org to domain.com After trying several solutions I just can't seem to get this to work.
I owned a .org and had urls like
http://mydomain.org/view/3242343
http://mydomain.org/login
http://mydomain.org/page/5
and I now have the .com and want all of them to be taken right to their .com equivalents:
http://mydomain.com/view/3242343
http://mydomain.com/login
http://mydomain.com/page/5
etc.
The rules I've tried so far seem to take any URL from .org and just send them to the root of mydomain.com.
What htaccess rule do I need?
Thanks,

A: Assuming it's an .htaccess in the DocumentRoot of the .org site (and not the .com site, which would need a RewriteCond to prevent a redirect loop):
RewriteRule ^(.*)$ http://mydomain.com/$1 [R=301]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript List clarification var list = {};
list[19] = 'kapooya';
list[20] = 'apples';
delete list[19];

Does
    list[19] == 'apples' or null?

A: var list = {};
list[19] = 'kapooya';
list[20] = 'apples';
delete list[19];

( var list[xx] would not work due to syntax error )
list[19] would be undefined.

A: Apart from the syntax error you get when using varbefore list[19] = 'kapooya', list[19] is undefined after the delete, not null.
Technically you are not creating a list but an object, or a map, or a hash, or a dictionary, however you wish to refer to it.
The correct syntax for working with lists, or in the case of javascript, Arrays, is var list= []; be aware that the delete operator doesn't work on array items.


text:
Q: Show that $f(A) = A^2$ is differentiable function mapping $\mathscr{M}_{n\times n}$ to $\mathscr{M}_{n\times n}$ Question: Show that $f(A) = A^2$ is differentiable function mapping $M_{n\times n}$ to $M_{n\times n}$
In a previous question we showed that for any $A,B \in \mathscr{M}_{n\times n}$ ,
$D_{B}(A) = AB + BA$
to show the proposed map is differentiable we would show
$\lim\limits_{\textbf{h} \to \textbf{0}} \frac{f(a + h) - f(a) - Df(a)h}{\|h\|} = 0$
and in my case specifically:
$\lim\limits_{\textbf{H} \to \textbf{0}} \frac{f(A + H) - f(A) - Df(A)H}{\|H\|} = 0$
Here I'm treating $H$ as the "displacement vector"
To get the total derivative I did the following:
$Df(A) = [AE_1 + E_1A, \dots, AE_{n^2} + E_{n^2}A]$, where the $E_i$ are the standard basis vectors for $M_{n\times n}$ space.
It was suggested to look at these maps through the lense of $\mathbb{R}^{n^2}$.
Doing that, each component of $Df(A) = [AE_1 + E_1A, \dots, AE_{n^2} + E_{n^2}A]$ will be a vector of length $n^2$ and now doing the correct multiplication against the matrix $H$, adapated into a vector of length $n^2$, I will end up with a vector of length $n^2$. None of this is a problem because putting it together with $f(A + H) - f(A)$, I will get a vector of length $n^2$ coming from
$f(A + H) - f(A) - Df(A)H$.
Doing all this I still don't see any way to get my difference quotient to go to $0$. I played with the individual components of my vectors but that was getting very messy and was not seeing any light at the end of the tunnel. Suggestions on how to proceed?


text:
Q: Logging into an RDS session from the command-line Is it possible to start an xfreerdp session into Microsoft windows from a command-line only install of Linux?
The command I use from a full blown Linux install is this:
$ sudo xfreerdp /v:farm.company.com /d:company.com \
    /u:oshiro /p:oshiro_password /g:rds.company.com

This command works fine. However, when I run the same command from a command-line install of Linux, I get the following error message:
Warning xf_GetWindowProperty (client /X11/xf_window.c:178): Property 340 does not exist

A: If you're just logged into a system that doesn't have a X desktop running then no you won't be able to make use of xfreerdp or any such application that requires the use of a GUI.
Remember that the X desktop is driving the videocard & monitor locally and is providing a basis (the X protocol) on which other graphical applications can also display GUIs through it as well. Without it any applications such as xfreerdp have no way to access the the display directly.
If you're familiar with the DOS/Windows model then think of trying to run a Windows application directly from DOS. This wouldn't be possible here either. There are libraries and services that Windows provides APIs to, which applications then utilize.
This is the tradeoff one makes when developing an application for a given environment vs. developing it as a standalone entity that can interact with a given system's hardware directly.


text:
Q: free( ptr ) error - invalid size I have a c program that seems to be performing ok unless I call free on the pointer.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    int i;
    gid_t *list;

    int num_groups = getgroups(0, NULL);

    list = malloc(num_groups * sizeof(list));

    if (getgroups(num_groups, list) != -1)
    {
        for (i = 0; i < num_groups; i++)
        {
            printf("%d ", *list++);
        }
    }
    free(list); // free(): invalid size: 0x0000000002448040 ***
    return 0;
}

I've seen lots of similar posts that refer to invalid next size, but not for invalid size.
I'm a newbie when it comes to c - so I can't work out what's going on.

A: You are changing list with your *list++ and therefore the free is invalid. You need to free the original pointer obtained from malloc.

As dasblinkenlight notes, you're not allocating memory the right way. I think you were going for this idiom, but forgot the *:
list = malloc(num_groups * sizeof *list);
                                  ^


text:
Q: How can i change the placeholder text color to white I am trying to figure out how to change the color of placeholder text for a search box to white, here is my css:

Heres the html:

A: You can use the ::placeholder pseudo class.

input {
  background-color: #907;
}

input::placeholder {
  color: #fff;
}
<input type="text" placeholder="Enter Description Here" />

However, it is not standardized, and may not work well across all browsers.
Add vendor prefixes for better support:

input {
  background-color: #907;
}

input::placeholder {
  color: #fff;
}

::-webkit-input-placeholder {  /* Chrome/Opera/Safari */
  color: #fff;
}
::-moz-placeholder {  /* Firefox 19+ */
  color: #fff;
}
:-moz-placeholder { /* Firefox 18- */
  color: #fff;
}
:-ms-input-placeholder {  /* Edge/IE 10+ */
  color: #fff;
}
<input type="text" placeholder="Desciption" />

Important:  Do not group these selectors, as explained in this post.


text:
Q: Multithread access to a LinkedList in .Net I need a linked list to be able to add items at both sides. The list will hold data to be shown in a trend viewer. As there is a huge amount of data I need to show data before its completely read so what I want to do is to read a block of data that I know has been already written and while I read that block have two threads filling the sides of the collection:

I thought on using LinkedList but it says that is does not support this scenario. Any ideas on something at the Framework that can help me or will I have to develop my custom list from scratch?
Thanks in advance.
EDIT: The main idea of the solution is to do it without locking anything because I'm reading a piece of the list that is not going to be changed while writing at other places. I mean, the read Thread will only read one chunk (from A to B) (a section that has been already written). When it finishes and other chunks have been completely written the reader will read those chunks while the writters write new data.
See the updated diagram:

A: If you are on .NET4 you can use two ConcurrentQueue. One for the left side and one for the right side.

A: You could use the linked list and just use normal .NET threading constructs like the lock keyword in order to protect access to the list.
Any custom list you developed would probably do something like that anyway.

A: I would recommend to consider an other approach with single data structure to persist incomming data, in this way you can keep order of incomming data messages.
For instance you can use blocking queue, in this SO post you can find nice example Creating a blocking Queue in .NET?.

A: Why not using LinkedList class.
The documentation says its not threadsafe so you have to synchronize access to the list for yourself, but you have to do this with any datastructure accessed by multiple threads.
Performance should be quiet good here is what msdn says about inserting nodes at any position:

LinkedList provides separate nodes of type LinkedListNode, so insertion and removal are O(1) operations.

You just have to lock read and insert operations with the lock construct.
EDIT
Ok, i think i understand what you want. You want a list like datastructure which is split into chunks of items. You want to independently write and read chunks of items without locking the whole list.
I suggest to use the LinkedList holding your chunks of data items.
The chunks themself can be represented as simple List or can be LinkedList instances as well.
You have to lock the access to the global LinkedList.
Now your writer threads fill one private List with n items a time. When finished the writer locks the LinkedList and adds his private list with dataitems to the LinkedList.
The reader thread locks the LinkedList reads one chunk and releases the lock. Now it can process n dataitems without locking them.

A: If I understand correctly you have a linked list to which you are adding data at the beginning and the end. You are never adding or removing from anywhere else. If this is the case you do not have to worry about threading since the other threads will never interfere.
Simply do something like this:
        //Everything between first and last is thread safe since
        //the other threads only add before and after.
        LinkedListNode<object> first = myList.First;
        LinkedListNode<object> current = first;
        LinkedListNode<object> last = myList.Last;
        bool done = false;

        if (current == null) return; //empty list
        do
        {
            //do stuff
            if (current == last) done = true;
            current = current.Next;
        } while (!done && current != null);

After you are done with this section you can do the same with two more sections from the new myList.First to first and from last to the new myList.Last.


text:
Q: Numerical Approximation - Finding roots Is someone able to assist me or atleast point me in the right direction of finding the roots of the below formula:
$$n^2−n+730\times\ln(0.5)=0$$
I have not done much numerical analysis/ approximation and am not sure how to go about this. If you are not willing to answer, please just point me in the right direction then.
I know what the roots should be, I am just not sure how to do this algebraically.

A: Is there any reason not to use the quadratic formula?https://en.wikipedia.org/wiki/Quadratic_formula with $a = 1, b = -1$ and $c = -730~\ln(2)$


text:
Q: getting compile-time date and time without macros using c++
I compile my code on an automated schedule and need to use the time at which the code was compiled in the code itself. Currently I'm just using the __DATE__, __TIME__ macros to get the compile- time date and time. However, this causes the binaries to change even if no changes have been made to the source (macros will inflate at compile time) which is not good (i don't want the setup to think that the binary changed if there have been no changes to the source).
Is it possible to get the compile-time without using any means that would cause the source to change?
Thanks

A: The standard __DATE__ and __TIME__ macros do what you observe, return a time dependent string.
It depends upon the system (and perhaps the compiler) and notably the build system (like GNU make for example).
A possible idea could be to link in a seperate timestamp file, something like (in make syntax)
timestamp.c:
        date +'const char timestamp[]="%c";' > $@

program: $(OBJECTS) timestamp.c
        $(LINKER.cc) $^ -o $@ $(LIBES)
        rm -f timestamp.c

The timestamp.owould then be regenerated and your programwould be relinked at every make (so the generated program will indeed change, but most of the code -thru $(OBJECTS) make variable- will stay unchanged).

Alternatively, you could e.g. log inside some database or textual log file the time of linking, e.g.
program: $(OBJECTS)
      $(LINKER.cc) $^ -o $@ $(LIBES)
      date +'$@ built at %c' >> /var/log/build.log

(you might use logger instead of date to get that logged in the syslog)
Then the generated program won't change, but you'll have logged somewhere a build timestamp. BTW you could log also some checksum (e.g. $(shell md5sum program) in make syntax) of your binary program.

A: If you use the compile-time IN YOUR binaries, then you will have the binary change.
There are several solutions, but I think the main point is that if you rebuild the binaries on a regular basis, it should really only be done if there are actually some changes (either to the build system or to the source code). So make it part of your build system to check if there are changes, and don't build anything if there isn't any changes. A simple way to do this is to check what the "latest version" in the version control system for the source code is. If the latest version is the same as the one used in the previous build, then nothing needs to be built. This will save you generating builds that are identical (apart from build time-stamp), and will resolve the issue of storgin __DATE__ and __TIME__ in the binary.

A: It's not clear to me what you want.  If it's the last modified
time of the file, getting it will depend on your system and
build system: something like -D $(shell ls -l
--time-style=long-iso $< | awk '{ print $7, $8 }') could be used
in the compiler invocation with GNU make under Linux, for
example.  But of course, it means that if an include file was
changed, but not the source, the time and date wouldn't reflect
it.


text:
Q: static vs inner class method - performance [java 8] Is there any difference between static method and normal method in class in performance in java 8?
class First {
    public static String methodStatic1() {
       //performance
    }
}

vs
class Second {
    public String method2() {
       //performance
    }
}

A: Addressing the performance aspect: it's cheaper not to have to create an instance of something pointlessly, but the difference is very likely to be completely irrelevant. Focusing on a clear design is much more likely to be important over time.
Utility methods are frequently static, and if all the methods within a class are static it may well be worth making the class final and including a private constructor to prevent instantation. Fundamentally, with utility classes which don't represent any real "thing" it doesn't make logical sense to construct an instance - so prevent it.
On the other hand, this does reduce flexibility: if any of these utility methods contain functionality which you may want to vary polymorphically (e.g. for testing purposes) then consider leaving them as instance methods - and try to extract some meaningful class name to represent the "thing" involved. (For example, a FooConverter makes sense to instantiate - a FooUtil doesn't.)


text:
Q: Cannot execute an indented line of code in a python function I am learning python and was trying my first dummy project. I wrote a function, in which a user can continue the code execution if s/he types one of the values from the list, or stop the code, if s/he types the other value from another list. Here is the function
myList=['','','','','','','','','',]
def continueGame():
    options  = True
    optionList1=['Yes', 'Y','y','yes','YES']
    optionList2=['No','no','n','NO']
    userChoice = ''
    while userChoice not in optionList1 and userChoice not in optionList2:
        userChoice = input("Want to continue the game ? (Y,N) :")
        if(userChoice not in optionList1 and userChoice not in optionList2):
            print("This is not the correct option. Please enter either Y or N.")
            userChoice = ''

    if(userChoice in optionList1):
        #myList=['','','','','','','','','',] ---------->Code 1
        options =  True
    else:
        options =  False

    if options ==  True:                         -------> Code 2
        myList=['','','','','','','','','',]      -------> Code 2
    return options

myList is a list defined as a global List, whose values change in other functions, not described here . I have tried two methods. Code 1  and Code 2 (in the code above). But none of them work. Even if the user hits Y or Yes, it does not execute either Code 1 or Code 2.
Can someone tell me where I am going wrong?

A: The variable myList inside the continueGame() function is only the same as the myList variable at the top if you specify that it should be. In particular, you should insert global myList like this:
def continueGame():
    global myList
<then the rest of your code>

That tells python that the myList variable inside the function isn't a new one, it's the one in the global scope.
Also, no need for that trailing comma in your lists.


text:
Q: Advice about what kind of data structure to use for quick search times C++ I am currently in the thinking process of the data structure I might use for a current project. I don't need to delete items as i am loading a database,using it, and then exiting the program. The only constraint concerns search time.(memory in a second time but mainly time).
Overview on what I intend to do.
I am parsing files and extracting informations that I use to create various object.
After reading the files and creating the objects,i have a set of multiple objects that have references to other one as string.
The goal here is to find which net goes from one domain to another
E.g : text input file :
module Blabla
netTomodule Foo
domain 1
..../*Other parameters of the module*/
end module

module Foo
netTomodule Blabla
netTomodule Foo2
domain 2
..../*Other parameters of the module*/
end module

module Foo2
netTomodule Foo
domain 2
..../*Other parameters of the module*/
end module

After reading this I get 3 module objects Foo Foo2 and Blabla and their attributes are as follow :
class Module{
private :
string name;
int domain;
netlist * mynetlist;
...
}

My opinion and the thing i want to get advice on :
After thinking about this, i think that my best shot is to :

*

*When reading the file and extracting info, i should create a linked list of Module.

*Then with the number of Module i have read, i create an array that is double the size of that.

*For each module, I use a hash function to hash the module name and put a pointer to this module at the given index in the array

*Now when i will want to find a module, i just have to compute the hash value and get the pointer at the given index(or increment if its not the good module because of a collision previously in the making of the array)

This is basically an implematation of a hashtable or atleast what i know of a hashtable from my clasess.
My question is Is this a good thought ? Is there a hashtable library i can use that does that ? (i have heard and look for unordered_map and map but i don't know if it fits my needs very well)
This is a huge text so i hope it is detailed enough, so thank you if you have the courage to read everything !

A: you can maintain a hashtable (string => pointer to object of type Module) instead of a link list.
Again inside the class Module, again maintain a hashmap or a map of string => pointer

A: Just use any hash table that comes with your standard library or from boost. Most will have the unordered_map (as specified by TR1 and proposed for C++0x) as does boost, but some will have a std::hash_map or stdext::hash_map with various implementation being slightly different, e.g. the original SGI vs. Microsoft.
You don't need to build a list, just put the objects directly in the hash table; it allows sequential iteration, though it will be in some fixed random order.

A: If you are interested in indirect relationships as well (Foo2->Foo->BlaBla) you essentially have a graph. In that case you could use Boost.Graph.


text:
Q: Terraform copies but (cloud-init) doesn't run user_data script on Bitnami EC2 instance I'm trying to have Terraform run my bash script after deploying my Bitnami EC2 instance (AMI: ami-0f185ef928bf37528). I can find the file at /var/lib/cloud/instance/scripts/part-001 but it isn't being run.
My desired script is a little more complicated but even this isn't being run:
#!/bin/sh
set -x
echo "Hello World.  The time is now $(date -R)!" | tee /root/output.txt
mkdir /opt/bitnami/projects
exit

main.tf contains
resource "aws_instance" "app_server" {
  ami             = "ami-0f185ef928bf37528"
  instance_type   = "t2.micro"
  key_name        = "app_server"
  security_groups = [aws_security_group.ec2_sg.name]
  user_data       = file("init.sh")
}

I'm not seeing any obvious issues or indicators in /var/log/cloud-init-output.log and /var/log/cloud-init.log

A: I tried to replicate your issue, but your code works perfectly:
      ___ _ _                   _
      | _ |_) |_ _ _  __ _ _ __ (_)
      | _ \ |  _| ' \/ _` | '  \| |
      |___/_|\__|_|_|\__,_|_|_|_|_|

  *** Welcome to the Node.js packaged by Bitnami 17.8.0-2                 ***
  *** Documentation:  https://docs.bitnami.com/aws/infrastructure/nodejs/ ***
  ***                 https://docs.bitnami.com/aws/                       ***
  *** Bitnami Forums: https://community.bitnami.com/                      ***
bitnami@ip-172-31-37-75:~$ sudo su -
root@ip-172-31-37-75:~# ls
output.txt
root@ip-172-31-37-75:~# cat output.txt
Hello World.  The time is now Sat, 02 Apr 2022 22:53:55 +0000!
root@ip-172-31-37-75:~# cd /opt/bitnami/
apache/       bncert/       common/       gonit/        node/         python/       scripts/      var/
apache2/      bndiagnostic/ git/          nami/         projects/     redis/        stats/
root@ip-172-31-37-75:~# cd /opt/bitnami/p
projects/ python/
root@ip-172-31-37-75:~# cd /opt/bitnami/p
projects/ python/
root@ip-172-31-37-75:~# cd /opt/bitnami/projects/

Thus its possible that your real code that you are using is different then in the question.


text:
Q: Kentico workflow Pre-Edit steps I would like to automatically send 2 emails when the page is created. Those pages are being created automatically after some user's action (filling the form).
It seems that Edit step is the initial step of Kentico workflow's but I haven't found such info in a documentation. In my example email is being sent after page changes status from edit to published. But nothing that is before Edit step seems to be working. Any ideas how to achieve that ? I mean I'd like to send email after page is created - before or on Edit step.
Sample workflow

A: Wojtek, I'm not aware of a way to begin a workflow before the Edit step.  Edit is a source step, so this is where your workflow is starting; I do not think your two previous actions ever execute.
In my opinion, your best bet is to either hook into Global events when you create the pages or send the emails in the code that creates the pages if possible (I'm not sure how you're doing that part).
Update: Looking at the Configuring workflows page on DevNet implies that workflow and versioning only begins once the document has been created and is in the edit stage.

A: You may just need to add additional steps, edit is the most basic one, usually you have them edit them as a step between "edit" and "published" that you need to approve.
If you want an email on creation or whenever someone touches a page, you can hook into the global events (such as the CMS.document create after our update before) and use the api to send out an email.
If you need some code sample just tell me.


text:
Q: How to get data from a web table using python? I am having trouble trying to get the data from this web table. I was wondering if anyone could shed some light on my situation, thanks!
HTML:

A: You want to use pandas.read_html() in order to collect an HTML table into a pandas DataFrame.
Usage:
>>> import pandas as pd
>>> pd.read_html(io)

Where from the docs:

io : str or file-like
  A URL, a file-like object, or a raw string containing HTML.

For example, see with this Wikipedia URL:
In [0]: url = "https://en.wikipedia.org/wiki/List_of_Olympic_records_in_swimming"

In [1]: pd.read_html(url)[0]
Out[1]:
                      Event       Time                                               Name               Nation                Games            Date      Ref
0            50 m freestyle      21.30                                        César Cielo         Brazil (BRA)         2008 Beijing  16 August 2008      [4]
1           100 m freestyle      47.05                                     Eamon Sullivan      Australia (AUS)         2008 Beijing  13 August 2008   [5][A]
2           200 m freestyle    1:42.96                                     Michael Phelps  United States (USA)         2008 Beijing  12 August 2008      [6]
3           400 m freestyle    3:40.14                                           Sun Yang          China (CHN)          2012 London    28 July 2012      [7]
4          1500 m freestyle  ♦14:31.02                                           Sun Yang          China (CHN)          2012 London   4 August 2012      [8]
5          100 m backstroke     ♦51.85                                        Ryan Murphy  United States (USA)  2016 Rio de Janeiro  13 August 2016   [9][B]
6          200 m backstroke    1:53.41                                        Tyler Clary  United States (USA)          2012 London   2 August 2012     [10]
7        100 m breaststroke      57.13                                         Adam Peaty  Great Britain (GBR)  2016 Rio de Janeiro   7 August 2016     [11]
8        200 m breaststroke    2:07.22                                     Ippei Watanabe          Japan (JPN)  2016 Rio de Janeiro   9 August 2016  [12][C]
9           100 m butterfly      50.39                                   Joseph Schooling      Singapore (SGP)  2016 Rio de Janeiro  12 August 2016     [13]
10          200 m butterfly    1:52.03                                     Michael Phelps  United States (USA)         2008 Beijing  13 August 2008     [14]
11  200 m individual medley    1:54.23                                     Michael Phelps  United States (USA)         2008 Beijing  15 August 2008     [15]
12  400 m individual medley   ♦4:03.84                                     Michael Phelps  United States (USA)         2008 Beijing  10 August 2008     [16]
13  4×100 m freestyle relay   ♦3:08.24  Michael Phelps (47.51)Garrett Weber-Gale (47.0...  United States (USA)         2008 Beijing  11 August 2008     [17]
14  4×200 m freestyle relay    6:58.56  Michael Phelps (1:43.31)Ryan Lochte (1:44.28)R...  United States (USA)         2008 Beijing  13 August 2008     [18]
15     4×100 m medley relay    3:27.95  Ryan Murphy (51.85)Cody Miller (59.03) Michael...  United States (USA)  2016 Rio de Jainero  13 August 2016     [19]


text:
Q: How to insert the contents of one list into another I am trying to combine the contents of two lists, in order to later perform processing on the entire data set.  I initially looked at the built in insert function, but it inserts as a list, rather than the contents of the list.
I can slice and append the lists, but is there a cleaner / more Pythonic way of doing what I want than this:
array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

array = array[:1] + addition + array[1:]

A: You can do the following using the slice syntax on the left hand side of an assignment:
>>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
>>> array[1:1] = ['quick', 'brown']
>>> array
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

That's about as Pythonic as it gets!

A: The extend method of list object does this, but at the end of the original list.
addition.extend(array)

A: insert(i,j), where i is the index and j is what you want to insert, does not add as a list. Instead it adds as a list item:
array = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
array.insert(1,'brown')

The new array would be:
array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

A: Leveraging the splat operator / list unpacking for lists you can do it using
array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

# like this
array2    = ['the', *addition, 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

# or like this
array = [ *array[:1], *addition, *array[1:]]

print(array)
print(array2)

to get
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

The operator got introduces with  PEP 448: Additional Unpacking Generalizations.


text:
Q: Exscript and Cisco I don't understand why 3 connections are created when connecting to the switch and I can close only 1, there is not a word about this in the documentation.
account = Account(USER, PASSWORD)
conn = SSH2()
conn.connect(IP)
conn.login(account)
conn.execute('terminal length 0')
conn.execute('show users')
print(conn.response)
conn.send('exit')
conn.close()

Print:
show users
    Line       User       Host(s)              Idle       Location
   1 vty 0     user       idle                 00:00:05 10.3.0.251
   2 vty 1     user       idle                 00:00:04 10.3.0.251
*  3 vty 2     user       idle                 00:00:00 10.3.0.251


text:
Q: issue with QScrollArea I am trying to add some check boxes in scroll area.but for me it is not working properly.i am new in python could anyone help?
import PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
from configparser import ConfigParser
import paramiko
import threading
import os

if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
class Ui_MainWindow(object):
    def __init__(self, parent=None):
        self.configur = ConfigParser()
        self.configur.read('ServerConfigurationDetails.ini')
        self.serverName=self.configur.sections()
        print(self.serverName)
        self.getComponents = self.configur.options("Component")
        self.sLen = len(self.serverName)
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setEnabled(True)
        MainWindow.resize(951, 634)
        font = QtGui.QFont()
        font.setPointSize(10)
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(150, 220, 91, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.comboBox_2 = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox_2.setGeometry(QtCore.QRect(250, 220, 231, 31))
        self.comboBox_2.setObjectName("comboBox_2")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(700, 40, 101, 31))
        self.pushButton.setObjectName("pushButton")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(140, 260, 681, 81))
        self.groupBox.setObjectName("groupBox")
        self.radioButton = QtWidgets.QRadioButton(self.groupBox)
        self.radioButton.setGeometry(QtCore.QRect(10, 30, 201, 20))
        self.radioButton.setObjectName("radioButton")
        self.radioButton_2 = QtWidgets.QRadioButton(self.groupBox)
        self.radioButton_2.setGeometry(QtCore.QRect(220, 30, 201, 20))
        self.radioButton_2.setObjectName("radioButton_2")
        self.checkBox = QtWidgets.QCheckBox(self.groupBox)
        self.checkBox.setEnabled(False)
        self.checkBox.setGeometry(QtCore.QRect(10, 50, 231, 31))
        self.checkBox.setChecked(True)
        self.checkBox.setObjectName("checkBox")
        self.radioButton_3 = QtWidgets.QRadioButton(self.groupBox)
        self.radioButton_3.setGeometry(QtCore.QRect(420, 30, 171, 20))
        self.radioButton_3.setObjectName("radioButton_3")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(280, 40, 411, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(130, 40, 131, 31))
        self.label_3.setObjectName("label_3")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(140, 125, 661, 21))
        self.label_5.setText("")
        self.label_5.setObjectName("label_5")
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(130, 110, 681, 101))
        self.scrollArea.setAccessibleDescription("")
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 679, 99))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")

        c=10
        n=0
        x = 10
        y = 10
        print(self.sLen)
        for i in range(self.sLen):
            if(n==4):
                n=0
                x=10
                y=y+20
            self.checkbox1 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
            self.checkbox1.setGeometry(QtCore.QRect(x+1, y+1, 161, 20))
            self.checkbox1.setText(self.serverName[i])
            self.checkbox1.setObjectName(self.serverName[i])
            print(x)
            print(n)
            n=n+1
            if(n==4):
                x=10
                y = y+20
            else:
                x= x+180

##        self.checkBox_2 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
##        self.checkBox_2.setGeometry(QtCore.QRect(10, 10, 161, 20))
##        self.checkBox_2.setObjectName("checkBox_2")
##        self.checkBox_3 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
##        self.checkBox_3.setGeometry(QtCore.QRect(180, 10, 131, 20))
##        self.checkBox_3.setObjectName("checkBox_3")
##        self.checkBox_4 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
##        self.checkBox_4.setGeometry(QtCore.QRect(350, 10, 151, 20))
##        self.checkBox_4.setObjectName("checkBox_4")
##        self.checkBox_5 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
##        self.checkBox_5.setGeometry(QtCore.QRect(530, 10, 141, 20))
##        self.checkBox_5.setObjectName("checkBox_5")
##        self.checkBox_6 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
##        self.checkBox_6.setGeometry(QtCore.QRect(10, 30, 161, 20))
##        self.checkBox_6.setObjectName("checkBox_6")
        self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.scrollArea_2 = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea_2.setGeometry(QtCore.QRect(140, 380, 681, 191))
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollArea_2.setObjectName("scrollArea_2")
        self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()
        self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 679, 189))
        self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(70, 340, 811, 20))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 951, 26))
        self.menubar.setObjectName("menubar")
        self.menuhelp = QtWidgets.QMenu(self.menubar)
        self.menuhelp.setObjectName("menuhelp")
        MainWindow.setMenuBar(self.menubar)
        self.actionAbout = QtWidgets.QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.menuhelp.addAction(self.actionAbout)
        self.menubar.addAction(self.menuhelp.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label_2.setText(_translate("MainWindow", "
Component
"))
        self.comboBox_2.setItemText(0, _translate("MainWindow", "eComm"))
        self.comboBox_2.setItemText(1, _translate("MainWindow", "workproc"))
        self.pushButton.setText(_translate("MainWindow", "Search"))
        self.groupBox.setTitle(_translate("MainWindow", "Other Details"))
        self.radioButton.setText(_translate("MainWindow", "Only Search in Archive"))
        self.radioButton_2.setText(_translate("MainWindow", "Also Search in Archive"))
        self.checkBox.setText(_translate("MainWindow", "Auto Download"))
        self.radioButton_3.setText(_translate("MainWindow", "Only Search in Log"))
        self.label_3.setText(_translate("MainWindow", "
Search String*
"))
##        self.checkBox_2.setText(_translate("MainWindow", "CheckBox"))
##        self.checkBox_3.setText(_translate("MainWindow", "CheckBox"))
##        self.checkBox_4.setText(_translate("MainWindow", "CheckBox"))
##        self.checkBox_5.setText(_translate("MainWindow", "CheckBox"))
##        self.checkBox_6.setText(_translate("MainWindow", "CheckBox"))
        self.menuhelp.setTitle(_translate("MainWindow", "Help"))
        self.actionAbout.setText(_translate("MainWindow", "About"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

as you can see the scroll area is not showing properly.i have some 20 servers to show.this server list is coming from ini file and i need to show the check boxes in that scroll area.

A: you need to use QLayout to arrange you widgets. check out
Qt Designer -> "Widget Box" docker -> "Layouts" section
For the scrollarea part:

*

*create scrollarea scroll_area = QScrollArea()

*create view widget you want to put inside scrollarea base_widget = QWidget()

*install view layout for view widget base_layout = QVBoxLayout(base_widget)

*install view widget into scrollarea scroll_area.setWidget(base_widget)

*fill in objects with view layout base_layout.addWidget(QLabel('foo')) base_layout.addWidget(QPushButton('bar')) base_layout.addLayout(my_sub_layout) etc.


text:
Q: How do I do multiple browser operations with c#? I am using c # selenium. However, I tried several browsers, but the computer is using too many CPUs. How does the back panel work in multiple browsers without CPU exhaustion?
Could you give a code sample?
public static IWebDriver[] twitter;

twitter = new IWebDriver[5];

            for (int i=0; i<5;i++)
            {
                twitter[i] = new ChromeDriver();
            }

            foreach (var drivers in twitter)
            {
                drivers.Navigate().GoToUrl("http://www.google.com.tr");
            }

these operations are very tedious. very tiring. and very complicated. I also do not know whether the series can be done? Is there an example that will save the CPU?

A: You could try out with multiple tabs as shown here: https://www.youtube.com/watch?v=pZdMsLKAjs4
Since this is not an answer, I wanted to add it as a comment, but I can't because of low rep. sorry for that.


text:
Q: lastpage.sty file not found, datime2.sty, indentfirst.sty, esint.sty not found
lastpage.sty file not found,  datime2.sty not found

*

*yesterday everything was working fine

*shut down macbook air

*reopened today and the files have shown an error

*the packages are installed

*i have reinstalled miktex and texmaker still the same error while compiling

*similarly esint.sty and indentfirst errors

*any help is welcome

A: Below one probable cause and the remedy.

*

*After fresh installation of texlive the directory 'lastpage' has been installed (I do not know why?) in '/usr/local/texlive/texmf-dist/tex/latex/'. Invocation of 'texhash', quite obviously has lead to no improvement.

*Next, I have copied the directory 'lastpage' from this location to correct location '/usr/share/texlive/texmf-dist/tex/latex/', using administrator privileges (sudo or su for Linux).

*Invocation of 'texhash' has completed the procedure.


text:
Q: Create new KO.observable array and populate it from an array object Is possible to create an ko.observable array and populate it using an array object?
My goal here is to create a ko.observable array with all the description/objects that are with the original array.
//Sample data the original data is coming from an socket query and being push on the array("people")
var people = [{
    name: "Contact 1",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "family"
  },
  {
    name: "Contact 2",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "friend"
  }
];.

var people = [{
    name: "Contact 1",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "family"
  },
  {
    name: "Contact 2",
    address: "1, a street, a town, a city, AB12 3CD",
    tel: "0123456789",
    email: "anemail@me.com",
    type: "friend"
  }
];

var quotesarray = function(items) {
  this.items = ko.observableArray(items);
  this.itemToAdd = ko.observable("");
  this.addItem = function() {
    if (this.itemToAdd() != "") {
      this.items.push(this.itemToAdd());
      this.itemToAdd("");
    }
  }.bind(this);
};
ko.applyBindings(new quotesarray(people));

console.log(people);

A: You just needed to make it items instead of quotesarray

var people = [
    { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
    { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend" }
];

var quotesarray = function(items){
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.addItem = function(){
        if (this.itemToAdd() != ""){
            this.items.push(this.itemToAdd());
            this.itemToAdd("");
        }
    }.bind(this);
};
ko.applyBindings(new quotesarray(people));

console.log(people);

name	address

A: You can create an observableArray to which the socket writes messages. You subscribe to the array to be automatically notified when the contents change (i.e. after every write by the socket).
In the subscribe callback you empty the array and add the items to your viewmodel's property.
If you expect to receive many rapidly succeeding messages, you can rateLimit the array to which you write to ensure you don't update the DOM too many times.
Here's an example. The explanations are in the code comments.

const UPDATE_EVERY_MS = 500;

// The observable array the socket writes to
const received = ko.observableArray([])
  // Use a rateLimit extension if you expect to
  // receive many updates from your socket
  .extend({ rateLimit: UPDATE_EVERY_MS });

// The observable array in your viewmodel
const rendered = ko.observableArray([]);

received.subscribe(items => {
  // Write "inbox" to viewmodel's list
  rendered(rendered().concat(items));

  // Clear received without triggering notification
  items.length = 0;
});

ko.applyBindings({ items: rendered });

// Mock a socket that writes to `received`
setInterval(() => received.push(Math.random()), 200);


text:
Q: items collection must be empty before using itemssource - datagrid wpf I keep getting this error when trying to explicitely define the datagrid columns.  If I comment out the 3 datagridtext columns, it works (but I want to hide some columns obviously).      In my code, all I am doing is setting the datacontext for DataGridLookupsTab..not messing with itemsource or anything in my code.  Any idea what I might be doing wrong here ?
Thanks !
<TabItem Header="Lookups" Height="23" VerticalAlignment="Top">
            <Grid x:Name="DataGridLookupsTab" Background="#FFE5E5E5" Margin="0,0,-1,-2" DataContext="Apps.OMS.Models.Lookups">
                <ComboBox x:Name="ComboBoxDistinctLookups" HorizontalAlignment="Left" Margin="128,14,0,0" VerticalAlignment="Top" Width="228" ItemsSource="{Binding Path=LookupTypeList}" SelectionChanged="ComboBoxDistinctLookups_SelectionChanged"/>
                <Label Content="Select Lookup Type" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" RenderTransformOrigin="1.105,4.731"/>
                <DataGrid x:Name="DataGridLookups" HorizontalAlignment="Left" Margin="10,41,0,0" VerticalAlignment="Top" Width="768" Height="327" ItemsSource="{Binding LookupRecords}" >
                    <DataGridTextColumn Binding="{Binding LookupType}" Header="Lookup Type" />
                    <DataGridTextColumn Binding="{Binding LookupValue}" Header="Lookup Value" />
                    <DataGridTextColumn Binding="{Binding LookupDescription}" Header="Lookup Description" />
                </DataGrid>
            </Grid>
        </TabItem>

A: Actually the problem ended up being my lack of the Datagrid.Columns tag.
Thanks

A: If you're setting the DataContext in your code (meaning your background code file), then DON'T set your datacontext in your XAML.  Instead, use ItemSource={Binding }.  See if that fixes your issue.


text:
Q: AWS VPC Endpoint for S3 with Terraform - Error: multiple VPC Endpoint Services matched I'm using aws_vpc_endpoint_service in Terraform (v0.11.14) to create an AWS VPC Endpoint for S3 on my AWS account and recently started facing the following error: Error: multiple VPC Endpoint Services matched; use additional constraints to reduce matches to a single VPC Endpoint Service
The same code was working fine before. What's the resolution?

A: I have found the solution.
Causes of the Issue:

*

*AWS has just released a new feature in S3 (PrivateLink) which means that multiple results are now being returned when searching for the S3 endpoint service. Reference: Amazon S3 now supports AWS PrivateLink

*Singular data sources in the Terraform AWS Provider (like aws_vpc_endpoint_service) return an error if multiple results are returned.

Solution if AWS Provider Version >= v3.10.0:

*

*Use the following in the Terraform template:

data "aws_vpc_endpoint_service" "s3" {
  service      = "s3"
  service_type = "Gateway"
}

Solution if AWS Provider Version < v3.10.0:
If you are unable to update to a recent version of the provider, as a temporary workaround you can also use com.amazonaws.REGION.s3 as an endpoint value in downstream configurations rather than using the datasource.

*

*Use the following in the Terraform template:

data "aws_region" "current" {}

resource "aws_vpc_endpoint" "s3" {
  vpc_id       = "${local.vpc_id}"
  service_name = "com.amazonaws.${data.aws_region.current.name}.s3"
}

That is all.
Previous code for reference that is not working anymore:
data "aws_vpc_endpoint_service" "s3" {
  service = "s3"
}

resource "aws_vpc_endpoint" "s3" {
  vpc_id       = "${local.vpc_id}"
  service_name = "${data.aws_vpc_endpoint_service.s3.service_name}"
}

A: For aws provider < v3.10.0 the problem could be solved using the filter configuration block in aws_vpc_endpoint_service
data "aws_vpc_endpoint_service" "s3" {
  service = "s3"
  filter {
    name   = "service-type"
    values = ["Gateway"]
  }
}

resource "aws_vpc_endpoint" "s3" {
  vpc_id       = "${aws_vpc.vpc.id}"
  service_name = "${data.aws_vpc_endpoint_service.s3.service_name}"
}

See also github issue page https://github.com/hashicorp/terraform-provider-aws/issues/17417


text:
Q: Add or Append section with rows on top of tableView data values Swift I have created a DataList in UITableView with sections and rows. Plus I have implemented delegate function for add & delete functions. Actually I need to add or append new section and row value which is selected. My first model is PickListData and then other sections values retrieving from Item -> pickList.
Model Hierarchy: PickListData -> let items: [Item]? -> var pickList: [SectionList]? -> textField
I implemented func didAddnewRow(_ sender: UIButton) but its adding row within the section and I need new section on top with name of Selected.

*

*Issue is how to put Section Selected and row which is selected from below sections.

Images attached current and actual I want to implement.

A: You forgot to add a new section before adding a row to that section. After inserting "Selected" section, the "A. Items" section will be moved down.
func numberOfSections(in tableView: UITableView) -> Int {
        return AppData?.pickList?.count ?? 0
    }

 func sectionIndexTitles(for tableView: UITableView) -> [String]? {

  return ["Selected", "A. Items"]
}

 func didAddnewRow(_ sender: UIButton) {
    if let cell = sender.superview?.superview as? DictionaryTableViewCell,
        let indexPath = self.tableView.indexPath(for: cell) {

        if let selectedItem = AppData?.pickList?[indexPath.section].items?[indexPath.row] {

            let insertIndexPath = IndexPath(item: AppData?.pickList?[0].items?.count ?? 0, section: 0)

    if !AppData?.pickList.contains(where: {$0.title == "Selected" }) {

   AppData?.pickList.append(SectionList(title: "Selected", items: selectedItem))

   tableView.insertSections(IndexSet([selectedItem]), with: .automatic)

    } else {

      AppData?.pickList?[0].items?.append(selectedItem)
  }

            cell.btnAdd.isHidden = true
            cell.btnDelete.isHidden = false
            tableView.beginUpdates()

            tableView.insertRows(at: [insertIndexPath], with: .automatic)
            tableView.endUpdates()

        }
    }
}


text:
Q: Double index Pandas shifting along one of the two index I have a dataframe like the following (double index dataframe):
index1      index2  close
......
2020-05-01  AAAA    11
2020-05-01  BBBB    21
2020-05-02  AAAA    12.5
2020-05-02  BBBB    22.5
2020-05-02  CCCC    32.5
2020-05-03  AAAA    13
2020-05-03  BBBB    23
2020-05-03  CCCC    33

I need to create a new column with the value of the close column shifted. But just shifting one of the two indexes (index1). Like the following:
index1      index2  close   close_shifted
......
2020-05-01  AAAA    11      12.5
2020-05-01  BBBB    21      22.5
2020-05-01  CCCC            32.5
2020-05-02  AAAA    12.5    13
2020-05-02  BBBB    22.5    23
2020-05-02  CCCC    32.5    33
2020-05-03  AAAA    13
2020-05-03  BBBB    23
2020-05-03  CCCC    33

Is that possible?
df['close'].shift(-3) is not the solution I need

A: df = pd.DataFrame({'index1':[1,1,2,2,2,3,3,3],'index2':['A','B','A','B','C','A','B','C'],
                   'close':[11,21,12.5,22.5,32.5,13,23,33]})
df.set_index(['index1','index2'], inplace=True)

df['shifted'] = df.groupby(level=1).shift(-1)
df

in your desired output I think CCCC at 2020-05-01 is a mistake (we don't have it in the original input df)


text:
Q: How can I import a package at any version greater than or equal to 1.0.0 in OSGi? I'm trying to import an OSGi package and any version greater than or equal to 1.0.0 is valid. Basically, I just want to ensure that I don't get any 0.x version, but other than those, any version  is acceptable. How can I allow all versions between 1.0.0 (inclusive) and infinity (unbounded).
I've tried the following:
com.mypackage.example;version="[1.0.0,)"
com.mypackage.example;version="[1,)"
com.mypackage.example;version="[1.0.0]"
com.mypackage.example;version="[1.0.0)"

I've also looked at this question: OSGI Valid Version Ranges. But it seems to be referencing a Java API rather than the MANIFEST.MF Import-Package header.

A: There is already an answer which explains how this can be done, but I feel duty bound to say that nobody should ever do this.
Placing upper bounds on a package import is an important part of API evolution and semantic versioning. If you claim to work with all future versions then you will eventually be broken by API changes.
Moving the version of an Export-Package from 1.x to 2.0 implies that a breaking change has been made. Methods that you rely on may no longer exist, or may behave differently. It is simply not safe to say that you will be compatible with all future versions of an API.
The correct version range to use when importing a version 1.0 API is "[1,2)" if you are a consumer or "[1,1.1)" if you are a provider.
Consumers are "typical users" of the API, for example if I write a Servlet I am a "consumer" of the Servlet API. Providers are people who provide the backing implementation for the API (e.g. TomCat). Note that this is not the same as saying that implementing an interface makes you a provider - consuming the Servlet API requires you to implement the Servlet interface.

A: To specify a version range of [1.0.0,infinity) for a package, just include the version number in the quotes:
com.mypackage.example;version="1.0.0"

This will allow any version greater than or equal to 1.0.0.
Since specifying a single version number implies an unbounded/infinite range, you may be wondering how you would import a specific version of a package (and no other versions). You can do that by specifying a range from a version to itself:
com.mypackage.example;version="[1.3.1,1.3.1]"

All this information comes from the Eclipse documentation on OSGi Concepts (specifically the Versioning section).


text:
Q: Горизонтальная линия рядом с картинкой Нужно сделать, как на картинке:

На всём сайте очень много горизонтальных линий (нарисована красным). Они должны быть по всей ширине блока. Но, если линия оказывается рядом с картинкой (с float:left/right), то линия должна по ширине доходить только до картинки (+ ее margin). А получается так, что линия растягивается на всю ширину и заходит под картинку. Линия сделана
-ом:
.line {
  height:1px;
  margin:22px 0 26px 0;
  background:#c7c7c7;
  border-bottom:1px solid #fff;
}

Если сделать
 вместо
, то линия ведёт себя нормально, но там другие проблемы, поэтому
 не подходит.
Скажите, можно ли так вообще сделать, и если можно то как?

A: Попробуйте оборачивать изображение в div с указанным цветом фона и паддингами равными необходимым отступам картинки.

*текст*

*текст*

*текст*

Должно помочь в условиях одноцветного фона.
A:

.line {
  height: 1px;
  margin: 10px 0 10px 0;
  background: #c7c7c7;
  border-bottom: 1px solid #fff;
  overflow: hidden;
}
img {
  float: left;
  margin-right: 5px;
}

b { animation: 1.5s infinite ease-in-out pulse; color: #b00; } @keyframes pulse { 50% { letter-spacing: 3px; } }

Достаточно добавить классу линии одно свойство:

.line {
  height: 1px;
  margin: 10px 0 10px 0;
  background: #c7c7c7;
  border-bottom: 1px solid #fff;
  overflow: hidden;
}

Вроде всё.


text:
Q: Tagging translated text correctly (tagging with lang="") A client has asked me to add some polish text to their website, not having much experience in this area, can anyone tell me which of the two 'lang' solutions below is correct (or offer an alternative):-
Tag everything:-

Najlepszy ruch jaki zrobisz!

Do przyszłych najemców:

Tutaj w SPS mamy bogate doświadczenie na rynku najmu i wyszukiwaniu domu, który będzie idealnym miejscem dla przyszłych lokatorów. Dla wielu może to być trudne i stresujące, dlatego my w SPS pomożemy Wam przejść przez pole minowe związane z najmem i uczynić ten proces  najprostszym i najszybszym jak to możliwe.

Jeśli szukasz nieruchomości obecnie lub w najbliższej przyszłości  prosimy o kontakt z naszym doświadczonym , przyjaznym i pomocnym personelem, a my  postaramy się pomóc  znaleźć Ci idealne miejsce, które jest właśnie dla Ciebie.

Więc aby w łatwy sposób wynająć zadzwoń już dziś.

Just tag the div

Najlepszy ruch jaki zrobisz!

Do przyszłych najemców:

Tutaj w SPS mamy bogate doświadczenie na rynku najmu i wyszukiwaniu domu, który będzie idealnym miejscem dla przyszłych lokatorów. Dla wielu może to być trudne i stresujące, dlatego my w SPS pomożemy Wam przejść przez pole minowe związane z najmem i uczynić ten proces  najprostszym i najszybszym jak to możliwe.

Jeśli szukasz nieruchomości obecnie lub w najbliższej przyszłości  prosimy o kontakt z naszym doświadczonym , przyjaznym i pomocnym personelem, a my  postaramy się pomóc  znaleźć Ci idealne miejsce, które jest właśnie dla Ciebie.

Więc aby w łatwy sposób wynająć zadzwoń już dziś.

A: The latter. You only need to indicate changes in language.
Otherwise you would end up with:

        <title lang="en-us"> A document written in American English </title>
…


text:
Q: Why does getWidth function return more value in JAVA? I expected output to be 120 and 220. But output now is 136 and 220.
Why?
import java.lang.*;
import java.awt.GraphicsConfiguration;
import javax.javax.swing.*;
import javax.swing.JFrame;

public class Main {
    static GraphicsConfiguration gc;
    public static void main(String[] args) {
        JFrame frame = new JFrame(gc);
        frame.setVisible(true);
        frame.setSize(120,220);
        System.out.println(frame.getWidth());
        System.out.println(frame.getHeight());
    }
}

A: From setSize(int width, int height)

The method changes the geometry-related data. Therefore, the native windowing system may ignore such requests, or it may modify the requested data, so that the Window object is placed and sized in a way that corresponds closely to the desktop settings.

But this is java 7, java 8 doc doesn't tall about this.

A: This is because of window decorations - minimize, maximize, close buttons.
I tested this on Windows 10 and created window cannot be resized to smaller size than 136 pixels.
As has been already pointed out, windowing system may change geometry as needed.
Here is screenshot from windows test:

Also if you turn off window decorations, window will have the specified size (120x220):
JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.setVisible(true);
frame.setSize(120, 220);
System.out.println(frame.getWidth() + " - " + frame.getHeight());

prints: 120 - 220
There could be also issue where minimum size is set, so setSize does not go below minimum size, but this is not the case.


text:
Q: php my admin my sql database and android studio failed to connect to local host This is the error I am getting and I am not sure why. This is the code I have for connecting to my local host. My IPv4 addresses is the ip address below for the base url. Is this correct? I really do not know what is causing this error. I have no errors in android studio and the apps run but crashes.
public class Common {

private static final String BASE_URL = "https://192.168.1.8";

public static CoffeeShopAPI getAPI()
{
    return RetrofitClient.getClient(BASE_URL).create(CoffeeShopAPI.class);
}

}
 019-11-02 13:17:01.706 4554-4554/? E/AndroidRuntime:     at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)

 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
 Caused by: java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 443) from /192.168.1.6 (port 59442) after 10000ms

 io.reactivex.exceptions.OnErrorNotImplementedException: failed to connect to /192.168.1.8 (port 443) from /192.168.1.6 (port 59442) after 10000ms


text:
Q: How do I know the size of the background image for variable-height content? I couldn't think of a good title, apologies.
I'm designing a personal website that has 4 sections inside a main. Inside each section is a title and a grid. The background of each section is a picture. I'm taking really large images and cropping them to the right aspect ratio, scaling them, and then assigning them to the appropriate section.
Currently, I'm designing for mobile but I'm sure the problem is ubiquitous across screen sizes. My problem is that when I set an images width and height, and then move to check on a different device (iPhone X to Pixel XL, for example), there is a space at the bottom of the section after the background image. This is because the image is too short.
I thought about making the image tall enough to accommodate the tallest device, but I ran into this problem: The content isn't always the tallest on the largest device. So I suppose this boils down to:
How do I know how large to make my images?

Do I have to look at the dimensions of the content on every device and pick the largest? There's gotta be a better way, right? The reason I don't want to just scale the image to 100% of the background is for fidelity (it makes a difference!).
Hope this is enough info, if it's not I'll be around. Thanks!
Edit for clarification:
Perhaps I wasn't clear. I'll be using media queries for the larger screen sizes, where I'll use larger images. Here's an example to clarify:
Suppose my first break-point is up to 568px. There are a range of devices under this value. However, just because they fall into the same break-point doesn't mean they have the same height and width.
Let's say device A has width 320px and height 600px, and device B has width 400px and height 650px. On device A, the first section of my website is 320px wide and 800px tall. On device B, the first section of my website is 400px wide and 750px tall.
I could make an image that is 400px wide and 800px tall, and this would satisfy the background conditions for both devices. However, I can't practically go through every device that exists to find the largest width for a particular section and the largest height for a particular section. I also can't be sure that my content won't change, in which case I would have to repeat the process.
Is there a way to do this without losing the quality of the image, without cutting out content, and with keeping reasonably the same padding and margins around elements? Or maybe I'm thinking about this the wrong way?
Hope that helps clarify it. Thanks for the answers I've already received!
Edit for solution:
Ended up setting the size of each section manually. Messes with my spacing a bit but now I know the height and width across all devices under my breakpoint, as it will be the same.

A: We can do this purely through CSS thanks to the background-size property now in CSS3. We'll use the html element (better than body as it's always at least the height of the browser window). We set a fixed and centered background on it, then adjust it's size using background-size set to the cover keyword.
html {
  background: url(XXX) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Note: Copy your URL into the XXX area, for example: images/bg.jpg. Then copy and paste the above into your CSS stylesheet.
Works in:
- Safari 3+
- Chrome Whatever+
- IE 9+
- Opera 10+
- Firefox 3.6+
Hope this helps.

A: You can accomplish this with @Media Queries in your CSS.
If its a larger screen--say a computer. You can have your normal CSS showing your background image. As the screen size changes, and you notice at a certain screen size (Like a phone screen) the image doesn't look right, you can add a media query to your CSS that looks something like this:
@media only screen and (max-width: 600px) {
  body {
    background-image: url("IMAGEURL.jpg");
  }
}

On devices that are equal to or smaller than the max-width of 600px the CSS will override your main CSS. This is how Responsive websites are built all the time. You can have as many Media queries as you would like. And there are other ways you can write the media queries. Hope this answers your question!
Check out this tutorial Found Here at W3schools.
https://www.w3schools.com/cssref/css3_pr_mediaquery.asp


text:
Q: "No rows could be found for LocalizedLabel with id  if LocalizedLabel were published" I am getting given below error while importing  Account entity  solution in online ms crm 2011.
"No rows could be found for LocalizedLabel with id  if LocalizedLabel were published"
Regards,
Ramakrishna M

A: Open SQL and run the next command
select * from LocalizedLabel where LocalizedLabelid = 'Guid'

if found the records run the next command:
delete LocalizedLabel Where LocalizedLabelid = 'Guid'

Try to import again and if failed change the command when the LocalizedLabelid from the excel file


text:
Q: How to reuse a serializer in Django (Python) I have a service in a Django app that I am building where I want to handle get and post requests. I though I should reuse a serializer I've built but in the examples I found, whenever someone wants to use a serializer they create a new object.
This is an implementation where the serializer class is called multiple times to create multiple instances, one each time a request arrives:
from django.http.response import JsonResponse
from django.http.request import RAISE_ERROR, HttpRequest
from rest_framework.parsers import JSONParser
from rest_framework import status
from models import Instrument
from serializers import InstrumentsSerializer

class InstrumentsService():

    def __init__(self):
        self.serializer: InstrumentsSerializer = None

    def get_instruments_by_type(self, instrument_type: str):
        if instrument_type is not None:
            instruments = Instrument.objects.all()
            instruments.filter(instrument_type__icontains=instrument_type)
            instruments_serializer = InstrumentsSerializer(instruments, many=True)
        else:
            raise ValueError("Value type None is not acceptable for 'instrument_type'")

        return instruments_serializer.data

    def add_instrument(self, instrument_data: Instrument):
        instrument_serializer = InstrumentsSerializer(data=instrument_data)

        if instrument_serializer.is_valid():
            instrument_serializer.save()

How can I use the same serializer and pass different data to it each time? Because in the example I presented, the data are being passed during initialization.

A: Why not use Python Class Objects?
class InstrumentsService():
    serializer = InstrumentsSerializer

    def __init__(self):
        pass

    def get_instruments_by_type(self, instrument_type: str):
        if instrument_type is not None:
            instruments = Instrument.objects.all()
            instruments.filter(instrument_type__icontains=instrument_type)
            instruments_serializer = InstrumentsService.serializer(instruments, many=True)


text:
Q: How to get a secret-key reCaptcha for Contact Form 7 To integrate reCAPTCHA with Contact Form 7, you need to enter 2 codes Site key and The secret key.
wordpress
Google gave only one key Id, where to get the second code?
secret-key

A: From the screenshot provided it looks like you tried creating a key with reCaptcha enterprise (the payed version of reCaptcha).
reCaptcha enterprise typically does not authenticate the same way the free version of reCaptcha.  Instead of a site key and a secret key, you usually get a site key and an authentication file.
Unless you have a business reason to use reCaptcha enterprise, I suggest you use the free version of reCaptcha, there you will get both a site key and a secret key: https://www.google.com/recaptcha/admin/create
You'll want to create a V3 reCaptcha if you want to use the secret score reCaptcha or V2 if you want to use the classic checkbox reCaptcha


text:
Q: Android appbar has actionbuttons' icons squeezed if inflated from Fragment (Issue on layouts?) After upgrading my compileSdkVersion, targetSdkVersion and Google support libraries the icons on appbar got squeezed on height.
Then before the upgrade of the dependencies all the icons where in the correct aspect (Squared), but after the upgrade of my project dependencies all the inflated icons on the appbar got squeezed on height. Bellow follows the difference between the upgrade.
I also notice that the squeeze only happens if the inflated button is inflated from a Fragment.
Screenshots:
Before upgrade the search icon is OK
After upgrade the search icon is squeezed on height
The Android Studio version is AS3 Cannary 8.
The upgrade on Gradle...

*

*Before upgrade (Icons with correct aspect)

app/build.gradle:
android {
    compileSdkVersion 25
    ...
    targetSdkVersion 25
    ....
}

ext.supportLibraryVersion = '25.4.0'
ext.playServicesLibraryVersion = '11.0.2'

dependencies {
    // Android Support
    implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
    implementation "com.android.support:design:$supportLibraryVersion"
    implementation "com.android.support:support-v4:$supportLibraryVersion"
    implementation "com.android.support:recyclerview-v7:$supportLibraryVersion"
    implementation "com.android.support:cardview-v7:$supportLibraryVersion"
    implementation 'com.android.support:multidex:1.0.1'
    implementation "com.google.android.gms:play-services-gcm:$playServicesLibraryVersion"
    implementation "com.google.firebase:firebase-appindexing:$playServicesLibraryVersion"
}

*

*After upgrade (Icons with wrong aspect)

app/build.gradle:
android {
    compileSdkVersion 26
    ...
    targetSdkVersion 26
    ....
}

ext.supportLibraryVersion = '26.0.0'
ext.playServicesLibraryVersion = '11.0.4'

dependencies {
    // Android Support
    implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
    implementation "com.android.support:design:$supportLibraryVersion"
    implementation "com.android.support:support-v4:$supportLibraryVersion"
    implementation "com.android.support:recyclerview-v7:$supportLibraryVersion"
    implementation "com.android.support:cardview-v7:$supportLibraryVersion"
    implementation 'com.android.support:multidex:1.0.2'
    implementation "com.google.android.gms:play-services-gcm:$playServicesLibraryVersion"
    implementation "com.google.firebase:firebase-appindexing:$playServicesLibraryVersion"
}

The layout inflated on the appbar:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.MainActivity">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/search"
        android:orderInCategory="125"
        android:title="@string/search"
        app:showAsAction="always" />
</menu>

The layout appbar that will be inflated:
<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways">
    </android.support.v7.widget.Toolbar>

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

The code to inflate the view above:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.search_menu, menu);
}

Any ideas about this issue? This is a bug or I miss something?


text:
Q: ¿Cómo puedo deshabilitar esas sugerencias de VS Code? Quiero deshabilitar esas sugerencias (que están en encerradas en rojo); ya deshabilité todas las extensiones, pero siguen apareciendo, es algo molesto ya que no me deja seleccionar lo que realmente necesito.

A: Amigo, no puedo comentar aun por mis puntos, pero te recomiendo visitar esta pagina: Configuración VSCode Intellisense. Ahi hay bastante informacion de la configuracion de Intellisense (que es el sistema de autocompletado) y de VSCode en general. Para aplicar cualquiera de esas opciones de configuracion te vas a tu archivo settings.json y ahi las agregas. En cuanto a tu problema con el autocompletado en si, solo sé que podés desactivar todas las opciones de un solo, pero no sé si te deja conservar solo una.


text:
Q: Mysql join query taking too much time even though indexes are implemented Hi I have a mysql query
SELECT
    `locationMapping`.`keyId` AS `caseId`,
        `locationMapping`.`id`
FROM
    `locationMapping`
INNER JOIN `locationSubtype` ON (`locationMapping`.`locationSubtypeId` = `locationSubtype`.`id`
    AND `locationMapping`.`locationTypeId` = `locationSubtype`.`locationTypeId`
    AND `locationMapping`.`govtId` = `locationSubtype`.`govtId`)
    AND ((`locationSubtype`.`govtId` = '90')
    AND (`locationMapping`.`keyTable` = 'xercase'))
WHERE
    locationMapping.govtId = 90

GROUP BY `keyId`

Taking 8 seconds to execute.
Create table command for locationMapping is:
    show create table locationMapping;
CREATE TABLE `locationMapping` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`govtId` int(11) NOT NULL DEFAULT '0',
`locationSubtypeId` int(11) NOT NULL DEFAULT '0',
`keyId` int(11) NOT NULL DEFAULT '0',
`keyTable` varchar(100) NOT NULL DEFAULT '',
`locationTypeId` int(11) DEFAULT '0',
`gisCode` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `locationmapping_instance` (`keyId`,`keyTable`),
KEY `locationmapping_subtype` (`locationSubtypeId`),
KEY `locationmapping_govtid` (`govtId`)
) ENGINE=InnoDB AUTO_INCREMENT=3994710 DEFAULT CHARSET=latin1

Create table command of locationSubType is
CREATE TABLE `locationSubtype` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`govtId` int(11) NOT NULL DEFAULT '0',
`locationTypeId` int(11) NOT NULL DEFAULT '0',
`name` varchar(100) DEFAULT NULL,
`description` varchar(100) DEFAULT NULL,
`code` varchar(30) DEFAULT NULL,
`gisCode` varchar(100) DEFAULT NULL,
`sortorder` smallint(6) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `locationsubtype_locationtype` (`locationTypeId`),
KEY `locationsubtype_govtid` (`govtId`),
KEY `locationsubtype_giscode` (`gisCode`)
) ENGINE=InnoDB AUTO_INCREMENT=4319 DEFAULT CHARSET=latin1

Explain statement for query is:
id,   select_type, table,             type,  possible_keys,                                                             key,                      key_len, ref,                              rows, Extra
'1',  'SIMPLE',    'locationSubtype', 'ref', 'PRIMARY,locationsubtype_locationtype,locationsubtype_govtid',             'locationsubtype_govtid', '4',     'const',                          '756', 'Using index condition; Using temporary; Using filesort'
'1', 'SIMPLE',     'locationMapping', 'ref', 'locationmapping_instance,locationmapping_subtype,locationmapping_govtid', 'locationmapping_subtype','4',     'comcate_dev6x.locationSubtype.id','333', 'Using where'

A: Try this rewrite:
SELECT  m.`keyId` AS `caseId`,
        m.`id`
    FROM  `locationMapping` AS m
    WHERE  m.`keyTable` = 'xercase'
      AND  m.govtId = 90
      AND  EXISTS (
        SELECT  *
            FROM  locationSubtype
            WHERE  m.`locationSubtypeId` = `id`
              AND  m.`locationTypeId` = `locationTypeId`
              AND  m.`govtId` = `govtId`
                  )
    GROUP BY  m.`keyId`

In many cases EXISTS() is faster than INNER JOIN.
This 'composite' index is important:
locationMapping: INDEX(govtId, keyTable)  -- in either order

The Optimizer is smart enough to notice the transitive nature of govtId=90, so I removed one mention of it.
More
AND   `locationMapping`.`govtId` = `locationSubtype`.`govtId`)
AND ((`locationSubtype`.`govtId` = '90')
...        locationMapping.govtId = 90

The optimizer, if given the first of those, plus either of the other two, will deduce the final one.  You have provided all 3, which is OK.  But it is 'overkill'.
The first line is important because it tells the optimizer how the two tables are related.


text:
Q: How to represent any integer value in a string? I am trying to determine if a sub-string exists within a text document of repetitive formatting. I am looping through specific keywords, and trying to identify another word after it. The two words are always separated by an integer, of varying value. I basically want a way to represent that integer in the sub-string as any integer value at all, if possible at all.
Something like this:
substr = keyword +' '+ integer +' '+ word
teststr = "one two three keyword 24 word four five"
if substr in teststr:
    print("substr exists in teststr")

Alternatively, I can do a loop and check around the iterator:
for el in teststr():
    checkstr = keyword +' '+ el.isdigit +' '+ word
    if checkstr in teststr:
        print("yes")

Just wondering if anyone knows an elegant solution at the top of their head.

A: You can use Regular Expressions to capture that pattern. Here is a quick implementation of what you are looking for:
import re

sample = "one two three keyword 24 word four five, another test is here pick 12 me"

# (\w+) is a group to include a word, followed by a number (\d+), then another word
pattern = r"(\w+).(\d+).(\w+)"
result = re.findall(pattern, sample)

if result:
   print('yes')


text:
Q: does clamav work on windows subsystem for linux? I scanned my pendrive using clamscan which has a virus but it is showing 0 infected file.

A: It does if the files you scan are windows files and your virus database is up to date and has the virus you know it has in its database.
ClamAV is also intended for scanning attachments in mails and therefor has a limit on the size of files it scans (by default 20Mb and if you provide the option  --max-filesize=n --max-scansize=n it will do larger files but there is a hard limit of 4G.
It will however not work on Linux files as the signatures it looks for are based on Windows and our system is fundamentally different. What is considered a virus signature in Windows is likely common coding practice in Linux resulting in 100% false positives.
If you have windows and a windows formatted pendrive scanning from windows would be the more logical way to go. It might even be more prudent to use a live session virus scanner as that would prevent your disks from running and actively fight your attempts to fix things.


text:
Q: Insert each data different rows PDO I have 10 inputs with the same name, and i'm trying to insert them in each rows
but i'm not sure how should i do that, i searched on google to see if there's any answers but failed.
i hope i explained clearly.
My codes are below:
TQ
I loop my inputs with PHP
for($x = 0; $x <= 10; $x++){
    print '

                <input class="form-mod" type="text" name="sn[]"/>
                <input class="form-mod" type="text" name="ename[]"/>
                <input class="form-mod" type="text" name="hrs[]"/>
                <input class="form-mod" type="text" name="sales[]"/>
                <input class="form-mod" type="text" name="wages[]"/>
                <input class="form-mod" type="text" name="inc[]"/>

    ';
}

PHP CODE
    if(isset($_POST['submited'])){
    $rows = array( array($_POST['pc'],$_POST['wn'],$_POST['from'],$_POST['to'],$_POST['sn'],$_POST['ename'],$_POST['hrs'],$_POST['sales'],$_POST['wages'],$_POST['inc'] )

 );

    $args = array_fill(0, count($rows[0]), '?');

    $query = "INSERT INTO wages (program_code,week_no,`from`,`to`,serial_no,name,hrs,sales,wages,incentive) VALUES (".implode(',', $args).")";
    $stmt = $dbo->prepare($query);

    foreach ($rows as $row)
    {
       $stmt->execute($row);
    }

    if(!$stmt->rowCount() >= '1'){
        print "unsuccessfully insert";
    }else{
        print "successfully inserted";
    }
}

UPDATED
i have revised the code that @Vitor Lima type. i remove this code ""implode(',', $row)"" and replace it with ?,?,?,? and it worked. but if i enter only 2 rows with values in the input page it will still insert the remaining 8 to the database, so 2 rows with values and 8 are empty. any idea how to overcome that
if(isset($_POST['submited'])){
    for($x = 0; $x < 10; $x++){
        $row = array($_POST['pc'], $_POST['wn'], $_POST['from'], $_POST['to'],
                     $_POST['sn'][$x], $_POST['ename'][$x], $_POST['hrs'][$x],
                     $_POST['sales'][$x], $_POST['wages'][$x], $_POST['inc'][$x]);

        $query = "INSERT INTO wages (program_code, week_no,`from`,`to`,serial_no,
               name,hrs,sales,wages,incentive) VALUES (?,?,?,?,?,?,?,?,?,?)";
        $stmt = $dbo->prepare($query);
        $stmt->execute($row);

        if(!$stmt->rowCount() >= '1'){
            print "unsuccessfully insert";
        }else{
            print "successfully inserted";
        }
    }
}

A: Look for your page: the input's names have [], it means they will be passed as an array to the server, so, for example, $_POST['sn'] will be an array with ten positions (you can use var_dump to certify...)
So, in your PHP script, you should make a loop, something like that
if(isset($_POST['submited'])){

    $stmt = $dbo->prepare(
        "INSERT INTO wages
         (program_code, week_no,`from`,`to`,serial_no, name, hrs, sales, wages, incentive)
         VALUES (?,?,?,?,?,?,?,?,?,?)"
        );

    for($x = 0; $x < 10; $x++){
        $row = array($_POST['pc'], $_POST['wn'], $_POST['from'], $_POST['to'],
                     $_POST['sn'][$x], $_POST['ename'][$x], $_POST['hrs'][$x],
                     $_POST['sales'][$x], $_POST['wages'][$x], $_POST['inc'][$x]);

        $stmt->execute($row);

        if(!$stmt->rowCount() >= '1'){
            print "unsuccessfully insert";
        }else{
            print "successfully inserted";
        }
    }
}


text:
Q: is my syntax wrong with throwing new error? My test is failing... not sure why I am new to Javascript and am currently being taught about classes and tests. My test is failing on a test for an error. My class code, test code and test results are below.
Sorry if I am missing something obvious I am very new and have been thrown right into it.
Class:
class Bag {
    constructor(weight) {
        if (!weight) throw new Error("bag must have a weight")
        this.weight = weight
    }
}

module.exports = Bag

Test Code:
const { TestScheduler } = require("jest")

const Bag = require("./bag")

describe("bag", () => {
    test("has a weight", () => {
        const bag = new Bag(13)
        expect(bag.weight).toBe(13)
    })
    test("bag must have a weight", () => {
        const bag = new Bag()
        expect(() => new Bag()).toThrowError("bag must have a weight")
    })
})

Test result:
Debugger attached.
 FAIL  ./airport.test.js
  bag
    ✓ has a weight (1 ms)
    ✕ bag must have a weight (1 ms)

  ● bag › bag must have a weight

    bag must have a weight

      2 |     constructor(weight) {
      3 |         if (!weight) {
    > 4 |             throw new Error("bag must have a weight")
        |                   ^
      5 |         }
      6 |         this.weight = weight
      7 |     }

      at new Bag (bag.js:4:19)
      at Object.<anonymous> (airport.test.js:11:21)

  console.log
    16

      at Object.<anonymous> (bag.js:11:9)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.166 s
Ran all test suites.
Waiting for the debugger to disconnect...
npm ERR! Test failed.  See above for more details.

A: In your second test, you get and error before the expect statement:
test("bag must have a weight", () => {
        const bag = new Bag() // here!
        expect(() => new Bag()).toThrowError("bag must have a weight")
    })

Just remove this line and the test should be fine.


text:
Q: Evaluating Conditions for Normal Family I am having troubles dealing with following problems:

*

*Suppose $\mathcal{F}$ is a collection of all holomorphic functions defined on a region $\Omega$ with values on the right half plane. If there exists a point $z_0 \in \Omega$ such that $f(z_0)=g(z_0)$ for all $f,g \in \mathcal{F}$, then $\mathcal{F}$ is a normal family.

*Let $\mathcal{F}$ be a collection of all holomorphic functions defined on a region $\Omega$ with values in $U_0=\mathbb{C} \backslash \{x+i0, 0 \leq x \leq 1\}$. If there exists a point $z_0 \in \Omega$ such that $f(z_0)=g(z_0)$ for all $f,g \in \mathcal{F}$, then $\mathcal{F}$ is a normal family.
A hint is to use the following version of the Montel Theorem:
Let $\mathcal{F}$ be a family of holomorphic functions on $\Omega$. If every function in $\mathcal{F}$ does not assume the same two values, then $\mathcal{F}$ is a normal family.
However, I don't see any conditions in the above two problems that can imply "If every function in $\mathcal{F}$ does not assume the same two values". Any clarifications or hints will be greatly appreciated!


text:
Q: Eclipse source attachment configuration path does not exist I just installed fresh Eclipse 2021-06 (4.20.0) on Kubuntu OS and jdk 11 via apt.
java -version:
openjdk version "11.0.11" 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.20.04)
OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.20.04, mixed mode, sharing)

Problem is when i try to open class/method declaration from jdk
in Eclipse i get message that source is not found.

Tried to locate src.zip file Eclipse - Source not found when trying to open declaration of random(), but when selecting it, Eclipse interestingly says that the file does not exist. I tought it might be permissions problem as it's path is /usr/lib/jvm/java-1.11.0-openjdk-amd64/lib/src.zip, but i copied that file to home and nothing changed.

Any guesses where problem might be?

A: First download java-17 from https://www.oracle.com/java/technologies/downloads/ then open eclipse marketplace and search for java-17 and download the java-17 plugin for eclipse. Then try opening classes in jdk. It should work.

A: I had JRE installed instead of JDK. Downloaded and installed AdoptOpenJDK 16 (JDK) switched to this in Eclipse and it just works now


text:
Q: image URL isn't working anymore I cannot seem to get the following code to work.  I am trying to make it so when you click on my image (img.banner in the following code) it navigates to a link.

A:
"how can I fix this so that when the image is clicked it follows the link?"

Surrounding the image in the anchor tag with the href attribute set should turn the actual image into a link.

Here is an example

A: If you want clicking on the image to result in following the link, the image must be placed inside the anchor ( tag)...


text:
Q: angularJS Custom directive functionality works using ng-click but not using ng-mouseOver Requirement goes like this :- I have left navigation panel which has to be in sync with the items added in the main active view by the user and has to display in tree structure. Basic idea is to provide context aware sub-view that change based on active view.
Custom directive used to display tree structure: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree/blob/master/src/abn_tree_directive.js
my HTML code: (using ng-click)

         S
         ection

         Section2

            <abn-tree tree-data="mainArrayObj"></abn-tree> // passing data to tree directive

         Section3

         Section4

JS implementation in my controller

$scope.panelExpand = false;  //setting default flag
$scope.panelCollapse = true; //setting default flag

$scope.expandPanel = function() {
 $scope.panelExpand = true;
 $scope.panelCollapse = false;
 $scope.mainArrayObj = []; // array that holds the data passed in html to custom directive
 initialJsonSeparator($scope.model.Data); // method used for iteration
};

$scope.collapsePanel = function() {
 $scope.panelExpand = false;
 $scope.panelCollapse = true;
};

my HTML code: (using ng-mouseover which is not working and displaying the data passed to navigation bar)

         S
         ection1

         Section2

            <abn-tree tree-data="mainArrayObj"></abn-tree> // array that holds the data passed in html to custom directive

          Section3

         Section4

js Implementation for the ng-mouseOver: (while debugging all the iteration and methods executed as expected)
$scope.hoverIn = function() {
 this.hoverEdit = true;
 $scope.mainArrayObj = []; // array that holds the data passed in html to custom directive
 initialJsonSeparator($scope.model.Data); //method used to iterate the data
};

$scope.hoverOut = function() {
 this.hoverEdit = false;
};

Any solution to this issue would be of gr8 help. If there is any other better approach other than the ng-mouseOver and ng-mouseLeave to implement hover, please do let me know.


text:
Q: How to store String Enums with Realm I can't save data as enum in Realm. When I track the state of a variable, and save, the old value remains, instead of the new one. What am I doing wrong?
I used a setter and a getter, but still the problem is not solved.
import RealmSwift

class Transaction: Object {

var accounting: Accounting = .income
@objc dynamic var amount = 0
@objc dynamic var date = ""
@objc dynamic var note = ""

private var privateCategory: String = Category.noCategories.rawValue
var category: Category {
    get { return Category(rawValue: privateCategory)! }
    set { privateCategory = newValue.rawValue }
  }
}

enum Category: String {
   case noCategories = "No сategories"
   case food = "Food"
   case cafesAndRestaurants = "Cafes And Restaurants"
   case manufacturedGoods = "Manufactured Goods"
   case forceMajeure = "Force Majeure"
   case entertainment = "Entertainment"
}

When I try to save a property, the Сategory is saved by default("No categories")
let transactionOne = Transaction()
    transactionOne.accounting = .consuption
    transactionOne.amount = 250
    transactionOne.category = .food

transaction   privateCategory String  "No categories"

A: As seen from all the examples in the Realm guide, string properties that you want to persist are marked with @objc dynamic. So you should mark privateCategory as @objc dynamic too:
@objc dynamic var privateCategory: String = Category.noCategories.rawValue


text:
Q: EXC_BAD_ACCESS in drawRect The code below "sometimes" causes a crash (EXC_BAD_ACCESS) when run on the device. Never on the simulator.
To reproduce it I keep overlaying a modal view controller over my table view controller. It usually happens when the modal view controller is dismissed.
Any ideas why this happens?
CGContextRef context = UIGraphicsGetCurrentContext();

//set the background of the cell
[self.backgroundColor set];
CGContextFillRect(context, rect);

// get cached image
UIImage *image = [[ImageUtil sharedInstance] getImageByRouteType:route.type];
CGSize imageSize = CGSizeMake(IMAGE_WIDTH, IMAGE_WIDTH);
// DEBUGGER STOPS ON THIS NEXT LINE, image object is fine though
[image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];

[...]

Thanks

A: If you use drawInRect in a multiple tread situation like NSOperationQueue, try use a lock to avoid "drawInRect" is called in more than one thread. I met a similar issue and solved it in this way.
@synchronized([UIImage class]){
    UIGraphicsBeginImageContext(newSize);
    CGRect rect = CGRectMake(0.0, 0.0, newSize.width, newSize.height);
    [self drawInRect: rect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

}


text:
Q: Integrating Salesforce with Informatica Cloud We are working on a POC on Salesforce-Informatica cloud REST API integration.
Please let me know the process/step by step information on how to integrate Salesforce with Informatica Cloud REST API, say push data from a .csv(or oracle) to Salesforce and pull(read) data from Salesforce to .csv.
Thanks a lot.

A: Here are the details:
Youtube : https://www.youtube.com/watch?v=Gx2KKdQBP98
Document : https://network.informatica.com/docs/DOC-15311
Thanks,
Vipul


text:
Q: Multiline pattern with one line of any content included I need to count the occurance of a multiline pattern of 3 lines in a htm file. The problem is that I have a fix content in line 1 and 3, however the content of line 2 is not fix, it can change (the file is a log). Here's an example of what I mean:
fix line 1
changing line 2
fix line 3

I have searched for solutions, but haven't found a 100% suitable one... pcregrep should work, but how do I include the changing line 2? So far I can only look for two fix lines. The code itself is the problem here, but the output is very easy to use for me.
pcregrep -Mc '^line1\n^line2\n^line3' file

Or should I use sed instead? The code works, but the output is complicated to use. How do I handle it to count the occurances of this multiline pattern? Because there has to be just one line between line 1 and 3, that's important.
sed -n '/^line1/,/^line3/=' file

I hope you can help me. Thank you very much!

A: You could use the below pcregrep command.
pcregrep -Mc '^line 1\n[^\n]*\nline 3' file

Example:
$ cat file
line 1
changing line 2
line 3
foo
bar
buz
line 1
changing line
line 3
foo
bar
buz
line 1
bar
line 3
$ pcregrep -Mc '^line 1\n[^\n]*\nline 3' file
3

A: idk what pcregrep is and I don't have it on any of the UNIX boxes I use but you could just use awk since it's available on all UNIX installations, e.g. run against @AvinashRaj's sample input file and using GNU awk for multi-char RS:
$ awk -v RS='^$' '{print gsub(/(^|\n)line 1\n[^\n]*\nline 3\n/,"")}' file
3

or with any awk:
$ awk '{rec=rec $0 RS} END{print gsub(/(^|\n)line 1\n[^\n]*\nline 3\n/,"",rec)}' file
3

I added anchoring to the front+back of the RE to make it impossible to produce false matches.

A: This might work for you (GNU sed & wc):
sed '1N;N;/fix line 1\n.*\nfix line 3/{x;s/^/\n/;x};$!D;x;s/.//p;d' file | wc -l

This creates a moving window of 3 lines throughout the file and appends a newline to the hold space when it encounters the desired pattern. At the end of the file the newlines are counted using wc (less the added newline that sed appends).
This solution will also cater for interleaved patterns as it specifically looks at all groups of 3 lines throughout the file.


text:
Q: Cargar archivos de una extensión concreta en un jComboBox Java Quiero insertar en items cada uno de los ficheros con una extensión concreta de un directorio determinado.
En mi caso, controlar los ficheros .txt de mi Escritorio y colocarlos en el Combobox.
Código:
package leertxts;

import java.io.File;
import java.io.FileInputStream;

public class MostrarTXTs extends javax.swing.JFrame {
    String ubicacion = "C:\\Users\\Nombre\\Desktop";
    File contenedor = new File(ubicacion);
    File[] registros = contenedor.listFiles();

    private void MostrarCombo() {
        for (int i = 0; i < registros.length; i++) {
            combobox.addItem(registros[i].getName().endsWith("txt"));
        }
    }

    public MostrarTXTs() {
        initComponents();
        MostrarCombo();
    }
}

¿Por qué no me aparecen los nombres en el combobox y sí me aparece true o false?

A: El problema radica en la forma como funciona el método endsWith. Este método retorna true si el sufijo txt se encuentra en la cadena, de lo contrario, devuelve false. Esa es la razón del porque en el combobox muestra valores booleanos.
Una posible solución es usar el método replaceFirst. Este método eliminará una parte especifica de la cadena, en la cual, retornará un nuevo objeto de tipo String con los cambios hecho.
Por ejemplo:
public class Program
{

    public static void main(String[] args)
    {
        String nameFile = "myFile.txt";
        String result = nameFile.replaceFirst(".txt", "");
        System.out.println("String: "+result + " , Length: "+ result.length());

    }
}

Salida por pantalla:
String: myFile, Length: 6

Entonces, el código del combobox quedaría así:
combobox.addItem(registros[i].getName().replaceFirst(".txt", ""));

De este modo, podrás obtener los nombres de cada archivo sin la extensión.