text:
Q: Regex to match two exact key=value's regardless of the order First, I know my question would be possibly duplicate of this one, but I need solution which must be correct in 100%. And I am not so good in regexes to achieve this :)
I have maaaaaaaaany requests with few params passed like ...&params=key1=value1|key2=value2|.... There may be few params and I don't know the order. What I need is to catch request that contains exact key1=myValue1 and key2=myValue2, but they can be like:

*

*key1=myValue1|key2=myValue2

*key2=myValue2|key1=myValue1

*key1=myValue1|key3=myValue3|key2=myValue2
or even more complicated. What is known:

*

*params is only part of the request, so it can be ?something=other&params=key1=value1|key2=value2 or ?params=key1=value1|key2=value2&something=other

*inside params parameter there are not white chars, only pair(s) of key=value's (separated with |)

To be clear: I know two pairs of key=value so regex is only for matching requests containing those 2 pairs. Requests could be ordered in different way. I don't have access to request itself, I only work on saved data (as string).
Language where regex will be used is PHP. But I don't have access to full code, because we declare regex in web application interface.
I think I need two positive lookaheads, like (?=[^\s]*(key1=myValue1)[^\s]*){1}(?=[^\s]*(key2=myValue2)[^\s]*){1} but I can't get it to work and clock is ticking...

A: Use two lookaheads:
^(?=.*\bkey1=myValue1\b)(?=.*\bkey2=myValue2\b)

The \b word boundary anchors make sure that only entire alphanumeric "words" are matched.

A: Here is an extremely fine-tailored regex for your specific problem.  See a live demo here.
(?:^\?|&)params=(?:|[^&]*\|)([^=]+)=([^|&]*)(?=[^&]*\|\1=\2(?:[|&]|$))
|               |           |       |          |    | |    |
|               |           |       |          |    | |    Ensure the value
|               |           |       |          |    | |    is followed by a
|               |           |       |          |    | |    '|' or '&' or the
|               |           |       |          |    | |    end-of-string so
|               |           |       |          |    | |    as not to match
|               |           |       |          |    | |    a substring.
|               |           |       |          |    | |
|               |           |       |          |    | Use backreferences to
|               |           |       |          |    | refer to the preceding
|               |           |       |          |    | key/value pair found.
|               |           |       |          |    |
|               |           |       |          |    Logically it must be
|               |           |       |          |    true that the second
|               |           |       |          |    pair follows a '|'.
|               |           |       |          |
|               |           |       |          Keep searching for the
|               |           |       |          duplicate key/value pair as
|               |           |       |          long as we don't hit a '&'.
|               |           |       |
|               |           |       Consider all characters valid for a
|               |           |       value until we hit a '|' or '&'.  Also,
|               |           |       allow empty values (*).
|               |           |
|               |           Consider all characters valid for a key until we
|               |           hit a '='.  Therefore, expect having an odd
|               |           number of key/value entities to cause a problem.
|               |
|               Start searching immediately following the "params=" or after
|               a string of non-'&' characters followed by a '|'.
|
Start at the beginning of the string with a '?', or somewhere (anywhere) in
the string with a '&'.

Its advantages over other solutions include being more rigorous about finding complete keys (as opposed to substrings) and of course, not needing to specify specific keys at all, by using backreferences.
Notes:

*

*The \r\ns in the demo are only for demoing purposes.

*It is not possible to capture within lookaround assertions; hence the first set is matched without a lookaround assertion.

*This regex does not guard against the possibility that a value1=key1 might coincidentally match a key1=value1.

A: Does this suit?
(key[\d]+=[^|]+)

Without knowing your language of choice, I can't provide a method of using it to extract groups..
This means the following:
Match "key" explicitly
Match any amount of numbers until you hit a non-number
Match "=" explicitly
Match any amount of characters that aren't a pipe "|"

This will match any amount key#=value pairs separated by pipe characters.
EDIT: In response to your comment:
([A-Za-z\d]+=[^|]+)

This means:
Match any amount of alphabetical characters or numbers
Match "=" explicitly
Match any character that is not a pipe character "|"

This will match any of the following:
key=value|myKey=MyValue|key2012=MyValue2012|country=usa|sex=female


text:
Q: I am having trouble understanding what is meant when the output of a matrix decoder is in the set of all real numbers I am going through the equations of a research paper that describes the restoration of old films and came across the following equation:
$$y_t=D(s_t\frown\bar{s_t})\in\mathbb{R}^{W \times H}.$$
The result is a single recovered image matrix where the D represents a decoder network who's input is a concatenation of two encoded hidden states. I am having difficulties understanding what is meant by the second part of the equation.
My first thought was that it is constricting the bounds of the result to fit within the height and width of the original image that is being recovered.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como saber se um objeto é um array em javascript (sem jquery)? Gostaria de saber como posso identificar que um objeto é ou não um array no Javascript.
Eu sei que no jQuery existe a função $.isArray. Porém gostaria de aprender a fazer isso sem o jQuery.
Tentei pelo typeof e não retornou o resultado esperado.
Exemplo:
typeof([]) // "object"

A: Pode tentar fazer assim:
Object.prototype.toString.call( list ) === '[object Array]' )

vai retornar True ou False

A: Outra forma:
[].constructor === Array

A: O método Array.isArray() retorna true se um objeto é uma array, e false se não é.
Exemplo: Array.isArray([]);
Fonte: http://phpdojo.com.br/javascript/arrays-e-objetos-em-javascript/

// Antipadrão
frutas = new Array('banana', 'laranja', 'uva');

// Padrão Literal
frutas = ['banana', 'laranja', 'uva'];

//Usando o operador typeof podemos verificar o tipo retornado para a variável, e //conforme disse anteriormente, em Javascript um array é um objeto. Veja abaixo:

alert(typeof frutas); // object

//E usando o método isArray podemos verificar se o objeto é um array:

alert(Array.isArray(frutas)); // true

O typeof é um Operador Unário do JavaScript. Trocando em miúdos, é um
  método nativo no JavaScript que retorna o tipo de um Operando.


text:
Q: Why isn't this background image being displayed when using a bootstrap template for it I have a asp.net application, where I wanted to use a premade bootstrap template for my frontend. I found this one.
The original site from the template looks really nice with a background like this:

I copied all the css into my css folder, and also took the html and cut some parts of it out such that I could just render my own content in it.
My _layout.cshtml that should be a scaffolding for other html files looks now like this:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Clean Blog - Start Bootstrap Theme</title>
        <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />

        <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css" />
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css" />

        <link href="css/styles.css" rel="stylesheet" />

                Start Bootstrap
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
                    Menu

                </button>

Home

About

Sample Post

Contact

Clean Blog

                            A Blog Theme by Start Bootstrap

            @RenderBody()

Copyright © Your Website 2021

As far as I understand, the central line for displaying the background image is this one:

Where we set the image as our background.
The problem is though, that the site I get, looks like this:

Instead of having the nice image as a background, I just get grey. I would like for the image to be displayed.
How do I get the image shown in the background, just like in the source i have linked?
EDIT:
I now looked in the dev tool, where I found it:

But clicking the image gets me This localhost page can't be found.
So it might look like the given path is bad. This is a little bit strange to me, since my IDE actually suggested the entire current path to me.
What should I do with my path such that the image can be found?

A: Is your mentioned path (../../wwwroot/assets/home-bg.jpg) correct? because image won't be rendered if path is incorrect, and the background color becomes grey because of the classname mentioned.

A: i after trying the path ../../wwwroot/assets/home-bg.jpg I then tried to assume that my application by default would be looking in the wwwroot directory. So I tried the path assets/home-bg.jpg.
My IDE (rider) shows red lines, and complains about it. But it works


text:
Q: python downloading data (urllib, urllib2) I have a link like this, direct to a mp3 file. So when I put it in my browser, basically asks me if I want to download the file, however when I do the same thing with python by the following code :
> data = urllib2.urlopen("http://www23.zippyshare.com/d/44123087/497548/Lil%20Wayne%20ft.%20Eminem%20-%20Drop%20The%20World.mp3".read())

I will redirected to another link like this. Therefore, instead of the MP3 data, I am getting the html code for

'http://www23.zippyshare.com/v/44123087/file.html'

any ideas ?
thanks

A: urllib2 handles redirection transparently. You might want to see what the server is actually doing when it is presenting such a redirection as well allowing you to download. You might want to subclass the redirect handler and see which property of the header is giving you the url and use urlretrieve to download that.
Setting the cookies, trying explicitly might be a good try as well.
import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.open('yourmp3filelink')

A: Your link redirects to an HTML webpage, most likely because your download request is timing out. That's often how these download websites work: you never get a static link to the download, only a temporarily assigned link.
My guess is that there's no way to get that static link using that website. You'd have to know where that file was actually coming from.
So no, nothing is wrong with your python code; just your sources.


text:
Q: Holder space in Partial Diferential Equation Let $u^{\epsilon}\in C^3(\Omega\times(0,T))$, $\tau>0$, $\beta\in(0,1)$ and  $\Omega'\subset\subset\Omega$. Suppose there is a constant $C$ such that:
$$
|u^{\epsilon}(x,t)-u^{\epsilon}(x,s)|\leq C|t-s|^{\frac{1}{1+\beta}}\ ,\ \forall x\in\Omega' , \forall t,s\in(\tau,T)
$$
and
$$
|\nabla u^{\epsilon}(x,t)-\nabla u^{\epsilon}(y,t)|\leq C|x-y|^{\frac{1-\beta}{1+\beta}}\ ,\ \forall x,y\in\Omega' , \forall t\in(\tau,T).
$$
where $C$ does not depend on $\epsilon$.
Show that there exists the limit  $\displaystyle\lim_{\epsilon\rightarrow0}u^{\epsilon}=u$ and that $u\in C^{\frac{1}{1+\beta}}$ and $u\in C^{1,\frac{1-\beta}{1+\beta}}$.
PS. I believe we must use compact immersion but found results to solve.


text:
Q: How to make only part of the text bold Can you tell me how I can make only part of the text bold:
TextArea dataPane = new TextArea();
        dataPane.appendText("Product Version: " + "1.0");
        dataPane.appendText("\nJava: " + "7");
        dataPane.appendText("\nRuntime: " + "7");
        dataPane.appendText("\nSystem: " + "Linux");
        dataPane.appendText("\nUser directory: " + "/home/dir");

I want to make only these strings bold: Product Version, Java, Runtime, System, User directory? What will be the easiest way to do this?
UPDATE
I also tested this code:
TextArea dataPane = new TextArea();
    dataPane.setPrefRowCount(10);
    Text wd = new Text("Version");
    wd.setFont(Font.font ("Verdana", FontWeight.BOLD, 20));

    dataPane.appendText(wd + "1.0");
    dataPane.appendText("\nJava: " + "7");
    dataPane.appendText("\nRuntime: " + "7");
    dataPane.appendText("\nSystem: " + "Linux");
    dataPane.appendText("\nUser directory: " + "/home/dir");

I get this: Text@149e84241.0
The text is not properly formatted.

A: You could use an editor pane with the content type set to html instead of a text area. I threw an editor pane into a scratch project really quick and just used the default variable names and object properties. Here's how I produced what I believe you're looking for:
jEditorPane1.setContentType("text/html"); //by default this is text/plain
//use margin-top and margin-bottom to prevent gaps between paragraphs
//or actually customize them to create space if you desire so
jEditorPane1.setText("
Product Version: 1.0
" +
    "
Java: 7
" +
    "
Runtime: 7
" +
    "
System: Linux
" +
    "
User directory: /home/dir
");


text:
Q: JSF command button redirect url does not open in the same frame I have a  in my form which redirects to another page in a 3rd party product.The action event of the button is given below:
 public void returnToTrackerSummary() throws IOException {
        StringBuilder trackerSummaryURL = new StringBuilder();
        trackerSummaryURL.append(PropsUtil.getProperty(PropsDef.a));

         FacesContext.getCurrentInstance().getExternalContext().redirect(trackerSummaryURL.toString());

    }

My issue is on clicking the button it goes to the new page but the header gets painted twice.Added the url of the redirect page is not updated. Though the latter is not a big issue,I really want the page to open in the same frame as in with one header.Any ideas?


text:
Q: Scan text function Windows Phone 8 I would like to know if it is possible to copy text from "Scan Text" Function Scan Text MSDN  and use in my app ?
On my app it will be button to move to scan text page and after when user has finished scanned it will be return to my app with text .
Is it possible to do this ?


text:
Q: Bind CAPS+hjkl to arrow keys; CAPS to ESC Currently running Antergos Linux. The set-up I would like to have is the following.

*

*Pressing and releasing CAPS sends ESC.

*The combinations of CAPS and any of CAPS+h, CAPS+j, CAPS+k, CAPS+l send Left, Down, Up, and Right respectively. Upon release of CAPS, ESC is not sent.
Of course, the goal here is to get some VIM-style bindings in programs which do not have them.
It seems that xcape would be useful here:
https://github.com/alols/xcape
But the examples do not get me quite as far as I would like.
Any help is appreciated.
EDIT: I came across a very useful answer here:
https://unix.stackexchange.com/a/163675/267068
Can anybody help me figure how to modify the procedure so that I get CAPS+hjkl as needed. Could I use Hyper_L, instead of the Super_L in that answer, and then map Hyper_L + hjkl to left, down, up, right?

A: I wanted to do the exact same thing, and after some search and experiment, finally got it working.
Solution 1
See solution 2 below, which is potentially better.

*

*Mapping Caps_lock + hjkl:
Follow this answer and add the config. You should add to the us file if you are using the US keyboard layout and skip the other keybindings that you're not interested in. Then run setxkbmap -layout us.

*Caps_lock as Esc:
Run xcape -e 'ISO_Level3_Shift=Escape'. You can add this line to your /etc/profile so you don't have to run it manually after reboot.
Solution 2 (probably better)
I was happy with solution 1, until I realized I couldn't use the key bindings in IntelliJ, which is a big bummer. Eventually I figured out that I could just use xmodmap and xcape to do the job, while still being able to use them in IntelliJ!

*

*Mapping Caps_lock + hjkl:
Create a file (say ~/.xmodmap) with the following content:
keycode 66 = Mode_switch
keysym h = h H Left
keysym l = l L Right
keysym k = k K Up
keysym j = j J Down
keysym u = u U Prior
keysym i = i I Home
keysym o = o O End
keysym p = p P Next

Feel free to skip the last 4 lines. I pasted them because they might be useful to you as well. In fact I'm really hoping to get the caps_lock enhancement working in Linux.
Then, run xmodmap ~/.xmodmap.

*Caps_lock as Esc:
Run xcape -e 'Mode_switch=Escape'.

*Optional:
To avoid manually applying the keybindings, put the above 2 commands into your /etc/profile.

A: I was having trouble getting this to work properly with /etc/profile, so expanding on the answer from @matrinica I was able to achieve success (on ubuntu/gnome) with the following method:
Step 0 : install xclip and xcape
sudo apt install xclip
sudo apt install xcape

Step 1 : create ~/.xmodmap
Copy the following text:
keycode 66 = Mode_switch
keysym h = h H Left
keysym l = l L Right
keysym k = k K Up
keysym j = j J Down

Create file with contents:
touch ~/.xmodmap
xclip -o > ~/.xmodmap

Step 2 : create script
Copy the following text:
xmodmap ~/.xmodmap
xcape -e 'Mode_switch=Escape'

Create file with contents:
touch ~/xmodmap.sh
xclip -o > ~/xmodmap.sh

Make file executable:
chmod +x ~/xmodmap.sh

Step 3 : create autostart entry
Copy the following text:
[Desktop Entry]
Type=Application
Exec=sh -c "$HOME/xmodmap.sh"
Hidden=false
X-GNOME-Autostart-enabled=true
Name=xmodmap
Comment=xmodmap script

Create file with contents:
touch ~/.config/autostart/xmodmap.deskop
xclip -o > ~/.config/autostart/xmodmap.deskop

Note:
This method does not work with Wayland and so is not futureproof. For Wayland compatible methods of achieving similar results please consult:
https://askubuntu.com/a/898462
https://wiki.archlinux.org/index.php/Keyboard_input
https://realh.co.uk/wp/linux-keymap-hacking/
If you are able to come up with a clean method which is Wayland compatible please post it here.

A: I use 3rd layer symbols and assign arrows to letters hjkl
Install gnome-tweaks tool
Inside gnome-tweaks go to Additional Layout Options and choose Caps Look as a key to choose the 3rd level.
Then open your terminal and go to /usr/share/X11/xkb/symbols/ There are all keyboard layouts store on your computer
Make a backup of your layout
cp us us_old
Modify file as root
sudo nano us
Third values in arrays are your keys:
key <AC01> {[a,A,Home]};
key <AC02> {[s,S,BackSpace]};
key <AC03> {[d,D,Delete]};
key <AC04> {[f,F,End]};
key <AC05> {[g,G]};
key <AC06> {[h,H,Left]};
key <AC07> {[j,J,Down]};
key <AC08> {[k,K,Up]};
key <AC09> {[l,L,Right]};


text:
Q: Use PHP to locate all elements with a class that starts with "enddate-"? Thanks in advance for accommodating my glaring PHP limitations.
Consider this HTML:

misc HTML content

  ...

blah blah blah

  ...

How can I use PHP to identify all elements in an HTML doc with a class that starts with "enddate-" ?
Why I'd like to know: I want to use PHP (bx it's server-side) to locate all such elements, as in both divs above; then grab (and validate) the implied date info, and, if today's date is after the end date, cause that element and its inner contents to NOT be displayed on the served web page (so, in the above, remove all evidence of the first div now but leave the second one visible until 2014).
I found some advice here on stackoverflow about using a PHP HTML parser to locate elements with a specific ID, as in:
$doc = new DOMDocument();
$doc->loadHTML($html);
$element = $doc->getElementById('ithis');
$element->parentNode->removeChild($element);
$html = $doc->saveHTML();

Can this be modified to look for "class that starts with 'enddate' "?

A: I think you could do this using XPath.
Something like this should work:
$xpath = new DOMXPath($domdocument);
$elements = $xpath->query("//*[contains(@class, 'enddate-')]");

(The xpath query is untested)


text:
Q: console music player - parallel computing I'm a beginner python programmer and for my own training, i created a simple (Console) music player.
So the point and my main problem is I put a timer on this player but at the end of the song
the timer still continues without conclusion.
import playsound
import threading
import time
import datetime
import sys

def player(x):
    input_name = x
    filename = f"{input_name}"
    print("Playing: " + filename)
    playsound.playsound(f'{filename}')
    return str("end")

def timer(x):
    localtime = 73800
    while x != "end":
        result = datetime.datetime.fromtimestamp(
            int(f"{localtime}")).strftime('%H:%M:%S')
        print(result, end="")
        print("\r", end="")
        time.sleep(1)
        localtime += 1

def main():

    input_name = input("Please enter a file name: ")
    res = ""

    while True:
        if res == "end":
            sys.exit(0)
        p1 = threading.Thread(target=timer, args=(f"{res}",))
        p1.start()

        res = player(input_name)
        print(res)

main()


text:
Q: Translate HmacSHA1 checksum generating method from Java to PHP I would like to translate the following Java method to PHP:
    private byte[] generateChecksum(byte[] inData){
        try{
            byte[] b_key = secretValue.getBytes("ISO-8859-1");

            SecretKeySpec sha1Key = new SecretKeySpec(b_key, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(sha1Key);

            byte[] sigBytes = mac.doFinal(inData);
            return sigBytes;

        }catch(Exception e){

            log.error("problem create hash: " + e);
            return null;
        }
    }

I came up with the following, but it doesn't seem to be producing the same results as the Java method:
private function generateChecksum ( $inData ) {

    try {

        $hash = hash_hmac( 'sha1', $inData, $this->secretValue, TRUE );

        return $this->getBytes( $hash );

    } catch (Exception $e) {

        return null;
    }

}

A: I resolved it. The issue was caused by passing the $inData to hash_hmac( ) as a byte array instead of a string.


text:
Q: 2d tile based game design, how do I draw a map with a viewport? I've been struggling with this for a while.
Presently, I have a grid of 100 by 100 tiles, which belong to a Map.
The Map implements IDrawable. I call Draw() and it draws itself at 0,0 which is fine.
However, I want to expand this to draw essentially a viewport. The player will be drawn on the screen in the middle, and thus I want to display say, 10 tiles in each direction (rather than the entire map).
I'm having trouble thinking up the architecture for this one. I'm in the mindset that things should draw themselves, ie I say player1.Draw() and it draws itself. This would have worked before, where it drew the player at x,y on the screen, but with a viewport it will no longer know where to draw itself.
So should the viewport be told to draw, and examine every object in the game and draw those which are visible? Should the map tiles be objects that are subjected to this? Or should the viewport intelligently draw the map by coupling both together?
I'd love to know how typical scrolling tile games accomplish this.
If it matters, I'm using XNA
Edit to add: Can you do graphics manipulation such as trying the HTML rendering approach, where you tell things to draw, and they return a graphic of themselves, and then the parent places the graphic in the correct location? I'm thinking, if I had 2 viewports side by side for splitscreen, how would I stop them drawing outside the edges?

A: Some basic ideas, not specifically for XNA:

*

*objects draw themselves to a "virtual screen" in world coordinates, they don't draw themselves to the screen directly

*drawable objects get a "graphics context" object which offers you a drawing API. The "graphics context" knows about the current viewport bounds and realizes the coordinate transformation from world coordinates to screen coordinates (for every drawing operations). The graphics context also does the direct drawing to the screen (or to a background screen buffer, if you need double buffering).

*when you have many objects outside the visible bounds of your viewport, then as a performance optimization, your drawing loop can make a before-hand bounds-check for your objects and test if they are completely outside the visible area. If so, there is no need to let them draw themselves.

A: Possible design:

*

*There's a 2D "world" that contains object instances.

*"Object instance" is a sprite reference + its coordinates in the world.

*When you draw scene, you request list of visible objects that exist in given 2D area, THEN you draw them.

With such design world can be very huge.

I'm in the mindset that things should draw themselves, ie I say player1.Draw() and it draws itself.

visible things should draw themselves. Objects outside of viewport are not visible.

, how would I stop them drawing outside the edges?

Not sure about XNA, but OpenGL has "scissors test"/"glViewport" and Direct3D 9 has "SetViewport" method that allows you to use part of the screen/window for rendering. There are also clipplanes and stencil buffer (using stencil for 2D clipping is overkill, though) You could also render to texture then render the texture. There are many ways to deal with this.

So should the viewport be told to draw, and examine every object in the game and draw those which are visible?

For a large world, you shouldn't examine every object, because it will be slow. You should be able to find visible object without testing every one of them. For that you'll need some kind of space partitioning - quad trees (because we are in 2D), k-d trees, etc. This way you should be able to handle few thousands (or even hundreds of thousands) of objects, as long as you don't see them all at once.

Should the map tiles be objects that are subjected to this?

If you keep drawing invisible things, FPS will drop.

and they return a graphic of themselves

For 2D game this may be very slow. Remember KISS principle.


text:
Q: No audio/images when deploying jar on another host The following Java code (stored in a Jar file) works on my computer, but when I deploy it to another computer I only see the text, but not the audio or images.
Any ideas?
import java.awt.Color;
import java.awt.Font;
import java.util.*;
import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;

public class SlotMachines
{
    public static void main (String[] args)
    {

        UIManager.put("OptionPane.background",new ColorUIResource(250,175,0));
        UIManager.put("Panel.background",new ColorUIResource(0,0,0));
        String ask;
        JLabel lbl = new JLabel("Input your cash?");
        lbl.setFont(new Font("Georgia", Font.BOLD, 16));
        lbl.setForeground(Color.WHITE);
        ask = JOptionPane.showInputDialog(null, lbl);
            double money = Double.parseDouble(ask);
        int again;
        int rerun = 1;
        Random generate = new Random();
        while (rerun == 1) //rerun while loop
        {
            JLabel pnl = new JLabel("Would you like to play Slots?");
            pnl.setFont(new Font("Georgia", Font.BOLD, 16));
            pnl.setForeground(Color.WHITE);
            again = JOptionPane.showConfirmDialog (null, pnl);

            int bet = 2;

            if (again == JOptionPane.NO_OPTION)
            {
            JLabel lab = new JLabel("Your cash stays at: " + money);
            lab.setFont(new Font("Georgia", Font.BOLD, 16));
            lab.setForeground(Color.WHITE);
            JOptionPane.showMessageDialog (null, lab);
            }

            while (again == JOptionPane.YES_OPTION)
            {
                File Winner = new File("jackpot.au");
                File Mega = new File("mega.au");
                File lose = new File("lose.au");
                if (money >= 2)
                {
                    money -= bet;
                    int[] arr = new int[3];
                    for (int i = 0; i < arr.length; i++)
                    {
                        ImageIcon icon = new ImageIcon("slotmachine.jpg");
                        arr[i] = generate.nextInt(10);
                        JLabel label = new JLabel("[" + arr[i] + "] ");
                        label.setFont(new Font("Impact", Font.BOLD, 125));
                        label.setForeground(Color.ORANGE);
                        JOptionPane.showMessageDialog (null, label, " ", JOptionPane.INFORMATION_MESSAGE, icon);

                    }
                    if (arr[0] == arr[1] && arr[1] == arr[2])
                    {

                        JLabel win = new JLabel("JACKPOT!!! BET X 5!");
                        win.setForeground(Color.CYAN);
                        PlaySound(Mega);
                        win.setFont(new Font("Arial", Font.BOLD, 140));
                        JOptionPane.showMessageDialog (null, win);
                        money += bet*5;
                    }
                    else
                    {
                        if (arr[0] == arr[1] || arr[0] == arr[2] || arr[1] == arr[2])
                    {
                            JLabel small = new JLabel("Rolling In cash! Doubles!");
                            small.setForeground(Color.magenta);
                            PlaySound(Winner);
                            small.setFont(new Font("Arial", Font.BOLD, 20));
                            JOptionPane.showMessageDialog (null, small);
                            money += bet*2;
                    }
                    }

                    JLabel cash = new JLabel("Your cash: $" + (int)money);
                    cash.setForeground(Color.GREEN);
                    cash.setFont(new Font("Georgia", Font.BOLD, 18));
                    JOptionPane.showMessageDialog (null, cash);

                    if (money >= 2)
                    {
                        JLabel big = new JLabel("Would you like to spin again?");
                        big.setForeground(Color.WHITE);
                        big.setFont(new Font("Georgia", Font.BOLD, 16));
                        again = JOptionPane.showConfirmDialog (null, big);

                        if (again != JOptionPane.YES_OPTION)
                    {
                            JLabel hell = new JLabel("You came out of hell with: $" + (int)money);
                            hell.setForeground(Color.RED);
                            hell.setFont(new Font("Georgia", Font.BOLD, 18));
                            JOptionPane.showMessageDialog (null, hell);
                            rerun = 0;
                    }
                    }

                    }
                    else
                    {
                        JLabel sorry = new JLabel("Sorry you can't afford to spin, your card is at: $" + money);
                        sorry.setForeground(Color.WHITE);
                        sorry.setFont(new Font("Georgia", Font.BOLD, 16));
                        PlaySound(lose);
                        JOptionPane.showMessageDialog (null, sorry);
                        again = JOptionPane.NO_OPTION;
                    }

            }
            rerun = 0;
        }
    }
    static void PlaySound(File Sound)
    {
        try{
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(Sound));
            clip.start();

        }catch(Exception e)
        {

        }
    }
}

A: Two probable causes:

*

*You forgot to take your assests with  you to another computer.

*You packaged assests into the jars, but you should be using ClassLoader.getResource() to retrieve them because they are on the classpath not in the working directory. Something like this:
public static void playSound(String pathToMusicOnClasspath) {
    try {
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(ClassLoader.getSystemResource(pathToMusicOnClasspath)));
        clip.start();
    } catch(Exception ignore) {}
}

call it like this:
playSound("jackpot.au");

This should be done to your ImageIcon, too.
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource("slotmachine.jpg"));


text:
Q: How Two different Maven Web project can share same EJB I have two different Maven-Based JSF Web Projects (Netbeans and Glassfish) one for admin users and the other one is for regular users. I wanted to keep them separate because it is simpler this way. Entity classes will be the same and I want these two war projects share these entity classes.
What is the best way of doing this? I don't want users and admins share the same UI because it gets too complicated I want to keep their user interfaces separate it is much easier and clear for me.
Thanks a lot

A: I would suggest that you split both your projects into at least 4 maven projects:

*

*common-ejb: maven project type 'EJB', keep all of your EJB/Entities there

*customer-web: maven project type 'WAR', keep all your UI for the regular users, with dependency on 'common-ejb'

*admin-web: maven project type 'WAR', keep all your UI for the admin users, with dependency on 'common-ejb'

*common-ear: maven project type 'EAR', that includes 'common-ejb' as EJB dependency, and contains the 2 web projects (WAR).

The EAR pom.xml could look like:
<groupId>com.example</groupId>
<artifactId>example-ear</artifactId>
<version>1.0</version>
<packaging>ear</packaging>

<dependencies>

  <dependency>
    <groupId>com.example</groupId>
    <artifactId>example-ejb</artifactId>
    <version>${project.parent.version}</version>
    <type>ejb</type>
  </dependency>

  <dependency>
    <groupId>com.example</groupId>
    <artifactId>customer-web</artifactId>
    <version>${project.parent.version}</version>
   <type>war</type>
  </dependency>
  <dependency>
    <groupId>com.example</groupId>
    <artifactId>admin-web</artifactId>
    <version>${project.parent.version}</version>
   <type>war</type>
  </dependency>
<dependencies>

and look at the maven-ear-plugin doc if you need some customization of context-root or library deployment.


text:
Q: Extracting values from JSON using JSONPath, excluding specific ones I've got a JSON like that:
[
{
"accID": "3asdasd321asdasdfsadf2",
"test": "one",
"isGood": "true",
},
{
"accID": "Not Found",
"test": "two",
"isGood": "true",
},
{
"accID": "1asdasd121asdasdfsadf5",
"test": "five",
"isGood": "false",
}
]

And I want to get all of the accID values, but excludeing 'Not Found' values, like an example:
[
"3asdasd321asdasdfsadf2",
"1asdasd121asdasdfsadf5"
]

I just can't figure out how to setup a filter.
.accID returns all of accID values in the needed format, but obviously 'Not Found' is included.
$.[?(@.accID != 'Not Found')] - this one returns the almost the same original JSON. 'Not Found' is excluded from that, but I need only accID's.
I thought that this filter should work $.accID[?(@.accID != 'Not Found')] , but it doesn't.
Could someone please tell me the correct filter to get values just like an example?

A: I found an answer:
$.[?(@.acc != 'Not Found')].acc

Thanks anyway.


text:
Q: Arrayindex out of bound in java I am not able to figure out that why i am getting the Array index out of bound exception in this code
class sample
{
  public static void main(String args[])
  {
    int a[]={1,2,3};
    int b[]=new int[10];
    for(int i=0;i<10;i++)
    {
      b[a[i]]=a[i]/*getting array out of bound exception*/
     }
  }
 }

A: Your loop has to rather be:
for(int i = 0; i < a.length; i++) {
   if (a[i] < b.length) {
       b[a[i]] = a[i];
   }
}

because you're copying the values of a into b, not vice versa.

A: a has a length of 3, so the only valid indices are 0,1 and 2.
Therefore a[i] is out of bounds when i > 2.

A: array a[] contains only 3 elements, but for loop iterates 10 times. so it raising ArrayIndexOutofBoundsException.
use : for(int i=0;i<3;i++) or for(int i=0;i


text:
Q: Count number of attributes with schematron i am trying to check the existence of an attribute with Schematron.
<Layout>
<Pages>
    <Page id="id-001" description="Database Sections">
    </Page>
</Pages>
<TreeViews>
    <TreeView id="id-001" description="">
    </TreeView>
</TreeViews>

If there is a "TreeView id" it must allready exist in a "Page id"
So i tried to count the "Page id´s" with the same name as my "Treeview id", they have to be >=1:
 <?xml version="1.0" encoding="UTF-8"?>
<sch:schema xmlns:sch="http://purl.oclc.org/dsdl/schematron"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            queryBinding="xslt2">

   <sch:pattern name="Vote Count">
      <sch:rule context="Layout/TreeViews/Treeview/@name">
         <sch:report test="count(Layout/Pages/Page[@id=current()]) >= 1">
             min. 1
        </sch:report>
      </sch:rule>
   </sch:pattern>
</sch:schema>

What am i doing wrong? Thanks for your hlep!

A: how about this rule:
<iso:pattern id="check IDs">
  <iso:rule context="TreeView">
    <iso:assert test="parent::*/parent::*/Pages/Page/@id = @id">
      TreeViews/TreeView/@id = <iso:value-of select="./@id" /> NOT FOUND in Pages
    </iso:assert>
  </iso:rule>
</iso:pattern>

Hope this helps.


text:
Q: Create Outlook task with Java I have a requirement to have a new task appear in a user's task list in Outlook. The catch is that the source of the task will be generated in a Java environment. Does anyone know how I can create an Outlook task using Java?
Thanks.

A: http://www.moyosoft.com/joc/

A: Use the new Exchange Web Services SDK - basically a SOAP web service you can call.
Creating a task, scroll down past the .net code for the xml that is sent to the server.


text:
Q: Eclipse Errors/Warnings ignore assert in unused variable analysis I have had 'hidden' bugs due to Eclipse not reporting 'unused' variables because they were used in an assertion (precondition), for example:
public void method(final String text, ...other parameters) {
  assert StringUtils.isNotBlank(text);
  ...
  // The text variable is never used in the method.
  // If Eclipse had reported the variable as 'unused' I would have noticed that something is wrong with the code.
  ...
}

I would like to tell Eclipse to ignore assertions when checking for unused variables. I doubt anyone would pass a parameter to only run an assertion on it...
Also let me know if FindBugs or another tool can do this.

A: Here is my own attempt at solving this with a 'brute' solution:

*

*Write a script that makes a copy of your source code and removes all
assertions from it

*Inspect that assert less copy as you would inspect the original

*Manually remove variables used only
in asserts from the original source code

Note that there is a similar problem with JavaDoc linked variables... if a variable is mentioned in the JavaDoc it will be considered as used (by Eclipse and maybe other IDE).


text:
Q: Store data into Array in For loop using JavaScript I have two grids that use some JS fuction to move items on one grid into another, thats works fine for me.
But my problem start when i need to get the modified grids and save data.
To do so im trying this. ( This is my function that move all the items to the other grid )
function AddAllItems() {
    MoveAllItems(articulosAvailable, articulosChoosen);
    UpdateButtonState();
}

var articulosEnGrilla = new Array;

function MoveAllItems(srcListBox, dstListBox) {
    srcListBox.BeginUpdate();
    var count = srcListBox.GetItemCount();
    for (var i = 0; i < count; i++) {
        var item = srcListBox.GetItem(i);
        dstListBox.AddItem(item.text, item.value);

        articulosEnGrilla[i] = [item.value];
        alert(articulosEnGrilla[i]);
    }
    srcListBox.EndUpdate();
    srcListBox.ClearItems();
}
function UpdateButtonState() {
    btnMoveAllItemsToRight.SetEnabled(articulosAvailable.GetItemCount() > 0);
    btnMoveAllItemsToLeft.SetEnabled(articulosChoosen.GetItemCount() > 0);
    btnMoveSelectedItemsToRight.SetEnabled(articulosAvailable.GetSelectedItems().length > 0);
    btnMoveSelectedItemsToLeft.SetEnabled(articulosChoosen.GetSelectedItems().length > 0);
}

So... what im doing wrong? When i send alert its says "undefined"
My bottom
<div class="col-md-4">
                       @Html.DevExpress().Button(settings =>
                       {
                           settings.Name = "btnMoveAllItemsToRight";
                           settings.Text = "Agregar todos >>";
                           settings.ClientSideEvents.Click = "function(s, e) { AddAllItems(); }";
                       }).GetHtml()
</div>


text:
Q: Big query analytical function not giving expected results I am trying to write a sql in bigquery and I have a requirement to filter records based on a group by column and another column in the table
what I mean is I want to check if the group by column(column name:mnt) has more than one row then I have to check if col2 (col name: zel)  value, then I have to apply a filter saying col2 ='X' and only pass that record else pass i.e dont filter the records if the col1 has only distinct one value per group
So I have written a sql to do this I have used row_number as well as rank , dense rank function but I noticed the value of rank and dense rank and row number functions return same value for a group
Please see the below code
#standardsql
with t1 as  (SELECT  mnt,
case when rank() over (partition by ltrim(rtrim(mnt)) order by
ltrim(rtrim(mnt)) asc) >1 then 'Y' else 'N' end
as flag,
rank() over (partition by mnt order by mnt) as rn,
dense_rank() over (partition by mnt order by mnt) as drn, FROM
projectname.datasetname.tablename1),
t2 as ( SELECT
        mnt,
        rel,
        lif,
        lts,
lokez FROM projectname.datasetname.tablename2
WHERE lts <> ""  AND  _PARTITIONTIME = TIMESTAMP(CURRENT_DATE()) ) ,
t3 as  (SELECT
       lif,
       lifn,
       lts,
       par FROM `projectname.datasetname.tablename3`)

    ,t4 as (SELECT rcv FROM `projectname.datasetname.tablename4` WHERE mes
    = 'PRO')
   select * from (
   SELECT t1.mnt as mnt,
          t1.flag,
          t1.rn,
          t1.drn
          t2.rel as zel,
          t2.lokez as ZLOEKZ,
          t4.rcv as Zrcv
           FROM t1 left join t2 on replace(t1.mnt, '00000000', '') =
    REPLACE(t2.mnt, '00000000', '') AND t1.lif = t2.lif and t2.lts <> ""
    and
    case when t1.flag = 'Y' and  t2.rel ='X' then 1
         when (t1.flag ='N' and t2.rel=t2.rel) or (t1.flag ='N' and t2.rel
    is null)  then 1
         when t1.flag = 'Y' and  t2.rel <>'X' then 2
         else 3
         end = 1
    left join t3  ON t1.lif = t3.lif  AND t2.lts = t3.lts AND
    t3.par = 'BA' left join t4 on t4.rcv = t3.lifn and  t2.lokez is null  )
    where     ZLOEKZ is null  order by mnt

As you can see I am using a case statement and even it seems to be not working fine. I am pasting the case condition below again
case when t1.flag = 'Y' and  t2.rel ='X' then 1
             when (t1.flag ='N' and t2.rel=t2.rel) or (t1.flag ='N' and
      t2.rel
        is null)  then 1
             when t1.flag = 'Y' and  t2.rel <>'X' then 2
             else 3
             end = 1

But the expected record count did not match so I added the above sql lines to see if my analytical functions were giving me result I wanted
rank() over (partition by mnt order by mnt) as rn,
dense_rank() over (partition by mnt order by mnt) as drn

strangely for same mnt number the rank , dense rank and row_number function are assigning the same value what am i doing wrong here.
mnt     flag    rn     drn     rel     lokez     rcv
100      N       1      1       X       abc       123
100      N       1      1      null     xyz       123
100      N       1      1      null     def       234

This is my output
I mean as per  my code for same mnt number I am seeing flag set to N instead of Y and for the rank and dense rank are giving me same number for all 3 mnt it is generating 1 instead of 123 (note for rank function I understand) but dense rank should not do that
I tried to convey the issue as efficiently as I could please let me know if there is any clarifications I can provide.
any help appreciated
thanks

A: SELECT * EXCEPT(ct) FROM (
  SELECT *, COUNT() OVER(PARTITION BY mnt) AS ct
) WHERE ct=1 or zel='X'

This is the code snippet for the problem you mentioned. Use this in your code according to the logic.


text:
Q: Reactive Native - custom iOS module with pod dependency I need to create react native ios module which intern uses cocopod.
I tried creating static library which had podfile and created workspace. In my main react project i have added my static library ,but i am unable to add those dependencies of pod in my main project . I am stuck here.
I am having two questions,

*

*What would be the best way to create react native modules (which doesnt have any UI components). Does it need to be static library or any other project template to be choose?

*If static library is the best option , then how do i have dependency with pods and integrate the module with main project?
Note : I tried creating module.podspec file and tried installing pod from main project. But i am unable to install my framework's dependency.
Pod installation goes like this.
MainReactProject -> MainReactProject.podfile (this refers) -> module.podspec(added as s.depandacy "somespec")->somespec.podspec.
During this execution,
I am getting error as unable to find specification for 'somespec


text:
Q: How to trigger a download prompt through post callback function simple question I guess, but can't figure it out... Here's the problem:
In the front end, I export some user-selected data to the server to dynamically create a file:
$("#export-button").click(function() {

$.post("'.$postUrl.'",{variable:exportSelection},
    function(data) {
        console.log(data);
    }
);});

Then, after I receive the data and create/save the file on the server, I am doing the following in php:
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;}

What am I supposed to do in the post callback function instead of printing on the console in order to get a download prompt?
UPDATE: OK - I just realised that my #export-button was an anchor tag with no href... Now when I point to the file on the server, the problem is that when I click, it follows the link prompts to save file etc., but it gets to the file BEFORE the "new" version is generated (so using the previous selection at each click)

A: OK - I figured it out. I just needed to disable the link from pointing anywhere and then do:
window.location = 'my_file_location.doc';
... inside the callback function


text:
Q: What would be the best/simplest solution to retrieve values from my database for comparison? - ASP.NET Core I'm currently stuck on accessing all of the 'UserName' values from my database.
I am doing this so I can compare the user input for a username to check if it has been used before (I don't want two instances of the same username). This is on a .cshtml.cs page.
I am already able to access the database through my program, as create commands have been tested and do work.
My program is on ASP.NET 6.0 Core Web App.
I am a student with basic knowledge on ASP.NET Core, and on how to solve this issue, therefore as much simplified explanation would be very appreciated.
Here is my code:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using AQA_A_Level_CS_NEA__Suvat_Solver_.Models;
using AQA_A_Level_CS_NEA__Suvat_Solver_.Data;

namespace AQA_A_Level_CS_NEA__Suvat_Solver_.Pages.UserLogin
{
[BindProperties(SupportsGet = true)]
public class RegisterPageModel : PageModel
{

    public new TempUserLoginModel TempUser { get; set; }
    public bool HasPassword { get; set; } = true;
    public bool HasUsername { get; set; } = true;
    public bool UniUsername { get; set; } = true;
    public bool RegisterApproved { get; set; } = false;
    public bool AQAPhys { get; set; } = false;
    public bool AQAMaths { get; set; } = false;
    public bool SubjectChosen { get; set; } = true;

    private readonly ApplicationDbContext _context;
    public RegisterPageModel(ApplicationDbContext context)
    {
        _context = context;
    }
    public List<User> UserList = new List<User>();

    public void OnGet()
    {

    }
    public IActionResult OnPost()
    {
        User User = new User();
        HasPassword = true;
        HasUsername = true;
        UniUsername = true;
        SubjectChosen = true;
        UserList = _context.User.ToList();

        if (!AQAMaths && !AQAPhys)
        {
            SubjectChosen = false;
        }
        if (string.IsNullOrWhiteSpace(TempUser.Password) || TempUser.Password.Length < 4)
        {
            HasPassword = false;
        }
        if (string.IsNullOrWhiteSpace(TempUser.Username) || TempUser.Username.Length < 4)
        {
            HasUsername = false;
        }
        if (TempUser.Username == //database UserName value here )
        {
            //Here would be where the Username is compared
            //UniUsername = false;
        }
        if (!HasPassword || !HasUsername || !UniUsername || !SubjectChosen)
        {
            return RedirectToPage("/UserLogin/RegisterPage", new { HasPassword, HasUsername, UniUsername, SubjectChosen });
        }
        else
        {
            RegisterApproved = true;
            User.UserName = TempUser.Username;
            User.UserPass = TempUser.Password;
            User.UserCorrectAnsw = 0;
            User.UserTotalAnsw = 0;
            _context.User.Add(User);
            _context.SaveChanges();
            return RedirectToPage("/UserLogin/LoginPage", new { RegisterApproved });
        }
    }
}
}

Many Thanks.

A: Probably the strongest method is to enforce the user name column to be unique at the database level using a Unique Constraint. That way if you try to add a user with a duplicate user name, the database will simply return an error.

This article shows how to create a Unique Constraint with Entity Framework

You can be sure that the database will not allow a user with a duplicate user name with this method. However, trying to add a duplicate user will create an error which you will have to either handle or prevent from occurring in the first place (which is what you are doing now)
So for the code you are using now, since you already have the users pulled from the database here:
UserList = _context.User.ToList();
We can use LINQ to check if any of the users Usernames in UserList matches the TempUser like this:
if (UserList.Any(x => x.Username == TempUser.Username))
{
    //Here would be where the Username is compared
    UniUsername = false;
}

Since you didn't share your User model, this assumes your User class has a property named Username.

Happy Coding


text:
Q: Lodash - method which return non-share elements from two arrays Helo guys, could you help with:
I need a method to lodash which return:
_.method( [1,2,3,4,5,6,7], [1,2,3] ) => [4,5,6,7]

In other words method which return non-share elements.
Best regards
Greg.

A: You could use _.difference.

Creates an array of array values not included in the other given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array.

var result = _.difference([1, 2, 3, 4, 5, 6, 7], [1, 2, 3]);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

A: I found:
For Objects it should be:
albumNotPhotos = _.differenceWith(this.albumNotPhotos, this.albumPhotos, _.isEqual);

Thanks and regards!@


text:
Q: When I replace the mac m2 chip, I can't use mysql2 and I get an error symbol not found in flat namespace (_mysql_affected_rows) Rails -> 7.0.3
MySQL -> 5.7.29
Ruby -> 3.1.1
Rvm -> 1.29.12
mysql2 -> 0.5
My project is trying to migrate m2 chips and when I try to run rails s I get the following error
`require': dlopen(/Users/list/.rvm/rubies/ruby-3.1.1/lib/ruby/gems/3.1.0/gems/mysql2-0.5.4/lib/mysql2/mysql2.bundle, 0x0009): symbol not found in flat namespace (_mysql_affected_rows)

I have tried the following solutions, none of them work
bundle config build.mysql2 "--with-ldflags=-L/usr/local/mysql/lib --with-cppflags=-I/usr/local/mysql/include"

 gem install mysql2 -v '0.5' -- --with-mysql-config=/usr/local/mysql/bin/mysql_config --with-ldflags="-L/usr/local/mysql/lib -L$(brew --prefix openssl)/lib" --with-cppflags=-I$(brew --prefix openssl)/include

How to solve this problem please?


text:
Q: Antd AutoComplete does not retain input and rerenders as a tiny box I've attempted updating antd to the latest version... and attempted controlled/uncontrolled ways, but I just cannot seem to understand why this component will simply rerender to a tiny box upon typing in the input.
GIF of AutoComplete box behaviour
Please find my latest attempt below, I'd be really grateful for some insight;
import React, { useState, useEffect } from 'react';
import { AutoComplete } from 'antd';
import { useQuery } from '@apollo/react-hooks';
import { withGroupsQuery } from './query';

const AutoCompleteField = props => {
    const [search, setSearch] = useState('');
    const { loading, error, data } = useQuery(withGroupsQuery, {
        variables: {
            search: search || undefined,
            ...other
        }
    })

    let options = []
    if (data) {
        options = parseGroupNode(data.groups).concat(parseUserNode(data.searchUsers))
    }

    const autoProps = {
        options,
        onSelect: (selected, option) => {
            if (props.onSelect) {
                props.onSelect(selected, option.label, option.group);
            }
        },
        onChange: search => {
            setSearch(search);
        },
        placeholder: props.placeholder,
        value: search,
    };

    return (
        <AutoComplete {...autoProps}/>
    )

A: You need to specify the width. All examples in antd's documentation have an explicit width. Try:
 <AutoComplete style={{ width: 200 }} {...autoProps}/>


text:
Q: jQuery Datepick plugin (Keith Wood) How to display only 2 month? Is there a way to display only 2 months in a datepicker?
What I already set up is the datepicker as inline version showing 2 months and hiding the month navigation.
On selecting the date, the form submits and default date is set to the selected date.
This works fine.
The problem is, when a date from second month is clicked, selected date is set as default date. But now, second and third months are active instead of first and second months.
Example:
Initially, only May 2014 and June 2014 are shown. When user clicks 4th June 2014, form submits and now 'June and July' are shown instead of 'May and June'.
I already tried setting monthOffset and dateRanges (minDate, maxDate). Did not fix my problem.
EDIT: Made two screenshots to show you the problem

And Here is the JS:
//program: overview datepicker
    var dpInputField = $('input#program-overview-datepicker-value');
    var defaultDate = (dpInputField.val() == '') ? '1399593600' : dpInputField.val(); // 1399593600 = 9th May 2014 00:00:00

    $('div#program-overview-datepicker').datepick({
        dateFormat: $.datepick.TIMESTAMP,
        monthsToShow: 2,
        changeMonth: false,
        altField: '#program-overview-datepicker-value',
        minDate: '1399593600', // 9th May 2014 00:00:00
        maxDate: '1402790400', // 15th June 2014 00:00:00
        onDate: showDayAndMonth,
        defaultDate: defaultDate,
    }, $.extend($.datepick.regional[window.language]));

    function showDayAndMonth(date) {
        var dayName =  $.datepick.formatDate('D', date);
        var dateName = date.getDate();
        var monthName = $.datepick.formatDate('M', date);

        return {content: '
'+dayName+'

'+dateName+'

'+monthName+'
', dateClass: 'showDAM'};
    }
    $('a.showDAM').click(function(e){
        $('#programoverview form').submit();
    });

A: What about this using native jquery ui
Demo 1 http://jsfiddle.net/9Uabd/1/embedded/result/

Demo 2 http://jsfiddle.net/9Uabd/2/embedded/result/
 $(function() {
    $( "#datepicker" ).datepicker({
      numberOfMonths: 3,
      showButtonPanel: true,
        minDate: '05/09/2014', // 9th May 2014 00:00:00
        maxDate: '06/15/2014'
    });
  });

A: Documentation: http://jqueryui.com/datepicker/#min-max
Set the beginning and end dates as

*

*actual dates (new Date(2009, 1 - 1, 26)),

*as a numeric offset from today (-20),

*as a string of periods and units ('+1M +10D').

If you know your date range, try using absolute dates
$("#datepicker").datepicker({
    changeYear: false,
    minDate: new Date(2014, 1 - 1, 1),
    maxDate: new Date(2014, 2 - 1, 28)
});

Herez a fiddle: http://jsfiddle.net/HL5ap/

A: Fixed it on my own by setting the default date to a date of the left month, but adding active CSS-Class to the actual selected date and keeping the correct value in the hidden input field.


text:
Q: Change remote 'origin' to 'upstream' with Git I've cloned a Git repo from the original source's upstream master repo to my local machine.
git remote -v returns:
origin  https://github.com/project.git (fetch)
origin  https://github.com/project.git  (push)

But I now know that I need to instead fork this upstream master branch to my personal GitHub account, clone that, create a new branch, and begin coding (so that I'm not making changes directly to the upstream repo, but rather to my own forked origin repo). I've forked the upstream master to my GitHub profile, but don't know how to proceed. I need to get git remote -v to look like this:
origin    https://github.com/myGitHubProfile/project.git (fetch)
origin    https://github.com/myGitHubProfile/project.git (push)
upstream    https://github.com/project.git (fetch)
upstream    https://github.com/project.git  (push)

How can I accomplish this, given that I've already cloned the upstream master from the original source and it's already set as origin?

A: It seems like you're looking for:
git remote rename origin upstream
git remote add origin https://github.com/myGitHubProfile/project.git

To give "old" origin remote a new upstream name and add new remote named origin.


text:
Q: StaticResource does not work in Xamarin forms I'm new to Xamarin
I have this code and the  Style="{StaticResource MyStyleButton}" doesn't work in an other Page.
componentPage.xaml
<ContentPage.Resources>
    <ResourceDictionary>
        <Style x:Key="MyStyleButton" TargetType="Button">
            <Setter Property="BackgroundColor" Value="#2196f3" />
            <Setter Property="WidthRequest" Value="300" />
            <Setter Property="CornerRadius" Value="20" />
            <Setter Property="FontSize" Value="Medium" />
            <Setter Property="TextColor" Value="White" />
        </Style>
    </ResourceDictionary>
</ContentPage.Resources>

Another xaml file
LogInPage.xaml

<ContentPage.Content>
    <StackLayout>
        <Button
            Command="{Binding Command1}"
            Style="{StaticResource MyStyleButton}"
            Text="Button1" />

    </StackLayout>
</ContentPage.Content>

If i put them in the same file the code works ,
what should i change

A: Step 1: Create new ContentPage example name ButtonStyles.xaml
Step 2: Edit
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="YourAppName.ButtonStyles"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    ...

</ContentPage>

To
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary
    x:Class="YourAppName.ButtonStyles"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    ....

</ResourceDictionary>

In CondeBehind
using Xamarin.Forms.Internals;
[Preserve(AllMembers = true)]
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ButtonStyles
    {
        public ButtonStyles()
        {
            InitializeComponent();
        }
    }

Step 3: Put your Styles in ButtonStyles.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary
    x:Class="YourAppName.ButtonStyles"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <Style x:Key="MyStyleButton" TargetType="Button">
        <Setter Property="BackgroundColor" Value="#2196f3" />
        <Setter Property="WidthRequest" Value="300" />
        <Setter Property="CornerRadius" Value="20" />
        <Setter Property="FontSize" Value="Medium" />
        <Setter Property="TextColor" Value="White" />
    </Style>

    <Style x:Key="MyStyleButton2" TargetType="Button">
        .....
    </Style>

</ResourceDictionary>

Step 4: In your App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application
    x:Class="YourAppName.App"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:YourAppName;assembly=YourAppName">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <local:ButtonStyles />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

</Application>

Step 5: In your any ContentPages
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="YourAppName.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <StackLayout>
        <Button
            Command="{Binding Command1}"
            Style="{StaticResource MyStyleButton}"
            Text="Button1" />
        <Button
            Command="{Binding Command2}"
            Style="{StaticResource MyStyleButton}"
            Text="Button2" />
        <Button
            Command="{Binding Command3}"
            Style="{StaticResource MyStyleButton}"
            Text="Button3" />
    </StackLayout>

</ContentPage>

A: You where close there is also this way , you also can put it in Application.Resources and use it in every page . https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/resource-dictionaries
In App.xaml
  <Application.Resources>
    <Style x:Key="MyStyleButton" TargetType="Button">
        <Setter Property="BackgroundColor" Value="#2196f3" />
        <Setter Property="WidthRequest" Value="300" />
        <Setter Property="CornerRadius" Value="20" />
        <Setter Property="FontSize" Value="Medium" />
        <Setter Property="TextColor" Value="White" />
    </Style>
</Application.Resources>

Use in any page you like
 <ContentPage.Content>
    <StackLayout>
        <Button
            Command="{Binding Command1}"
            Style="{StaticResource MyStyleButton}"
            Text="Button1" />
    </StackLayout>
</ContentPage.Content>


text:
Q: retrieving multi valued select 'value' Can anyone tell me how to get the 'value' of selected items from a multivalued select?
I have the following:
    <select id="category" name="category[]" multiple="multiple">';

        /* Select categories */
        [...]
        <option value"' . $row->id . '">' . $row->name . '</option>';

which would return:
                    <option value"1">itemName1</option>

Why is the code below giving me the selected text and not their values? What's wrong here?
                    $category = $_POST['category'];
        if (count($category) > 0){

            foreach ($category as $key => $value) {
                echo  $value . "<br>\n";
            }
        }

This is returning itemName1 and I need the actual value (1)
Thank you

A: Your HTML is invalid. You have:
<option value"1">itemName1</option>

while it should be:
<option value="1">itemName1</option>

A: mulple select will return a query like this (name = name and values = int)
name=1&name=4&name=99

so it return the selected values
the array would look like:
array(
    name => array(
        [0] => 1
        [1] => 4
        [2] => 99
    )
)

ps if you fix the HTML error, you will most likely get a valid result


text:
Q: Error while installing scrapy I am trying to install scrapy, it gives the following error:
Downloading/unpacking cryptography>=0.2.1 (from pyOpenSSL->Scrapy)
  Running setup.py egg_info for package cryptography
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    c/_cffi_backend.c:13:17: fatal error: ffi.h: No such file or directory
    compilation terminated.
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/nilesh/build/cryptography/setup.py", line 174, in <module>
        "test": PyTest,
      File "/usr/lib/python2.7/distutils/core.py", line 112, in setup
        _setup_distribution = dist = klass(attrs)
      File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 221, in __init__
        self.fetch_build_eggs(attrs.pop('setup_requires'))
      File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 245, in fetch_build_eggs
        parse_requirements(requires), installer=self.fetch_build_egg
      File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 576, in resolve
        dist = best[req.key] = env.best_match(req, self, installer)
      File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 821, in best_match
        return self.obtain(req, installer) # try and download/install
      File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 833, in obtain
        return installer(requirement)
      File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 294, in fetch_build_egg
        return cmd.easy_install(req)
      File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 608, in easy_install
        return self.install_item(spec, dist.location, tmpdir, deps)
      File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 638, in install_item
        dists = self.install_eggs(spec, download, tmpdir)
      File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 828, in install_eggs
        return self.build_and_install(setup_script, setup_base)
      File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 1105, in build_and_install
        self.run_setup(setup_script, setup_base, args)
      File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 1096, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1
    Complete output from command python setup.py egg_info:
    Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

Package libffi was not found in the pkg-config search path.

Perhaps you should add the directory containing `libffi.pc'

to the PKG_CONFIG_PATH environment variable

No package 'libffi' found

c/_cffi_backend.c:13:17: fatal error: ffi.h: No such file or directory

compilation terminated.

Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/nilesh/build/cryptography/setup.py", line 174, in <module>

    "test": PyTest,

  File "/usr/lib/python2.7/distutils/core.py", line 112, in setup

    _setup_distribution = dist = klass(attrs)

  File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 221, in __init__

    self.fetch_build_eggs(attrs.pop('setup_requires'))

  File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 245, in fetch_build_eggs

    parse_requirements(requires), installer=self.fetch_build_egg

  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 576, in resolve

    dist = best[req.key] = env.best_match(req, self, installer)

  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 821, in best_match

    return self.obtain(req, installer) # try and download/install

  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 833, in obtain

    return installer(requirement)

  File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 294, in fetch_build_egg

    return cmd.easy_install(req)

  File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 608, in easy_install

    return self.install_item(spec, dist.location, tmpdir, deps)

  File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 638, in install_item

    dists = self.install_eggs(spec, download, tmpdir)

  File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 828, in install_eggs

    return self.build_and_install(setup_script, setup_base)

  File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 1105, in build_and_install

    self.run_setup(setup_script, setup_base, args)

  File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 1096, in run_setup

    raise DistutilsError("Setup script exited with %s" % (v.args[0],))

distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1

Can you please help me in solving the error.

A: I have gotten this error in Ubuntu installing cryptography with pip. Installing libffi-dev fixed it for me. If that doesn't work, you may also need to install libssl-dev. What operating system are you using?

A: I faced the same problem.
I installed libffi-dev  with the following command
sudo apt-get install  libffi-dev

After that, I installed scrapy. There was no issue.

A: In CentOS (or Amazon Linux)
sudo yum install -y libffi libffi-devel
is useful for me


text:
Q: Round the nearest number I tried everything from round the nearest code. It is not the code that I'm looking for.
I tried round the nearest number 0.00750 to this 0.0080  How do around before decimal?
I want something like this:
0.0089 => 0.0090
0.0021 => 0.0020
0.1022 => 0.1020

A: math.h contains double round(double) which will address the rounding part. To round to some number of decimal places try something like:
double roundPlaces(double d, int places)
{
   double factor = pow(10, places); // pow also in math.h

   return round(d * factor) / factor;
}

and then for your examples roundPlaces(0.0089, 3) produces 0.009.

A: you can make your own function using standard C function...
There's no round() in the C++ std library. You can write one yourself though:
double round(double d)
{
  return floor(d + 0.5);
}

(you can use C function in objective C )


text:
Q: How to implement comparator in java This program is to implement comparator
everything is fine
import java.util.*;
public class Solocomparator implements Comparator<Solocomparator> {

    int age;
    String name;
    Solocomparator(int age,String name){
        this.age=age;
        this.name=name;
    }

    public int compare(Solocomparator nam) {
        return (this.name).compareTo(nam.name);
    }

    public static void main(String[] args) {
        ArrayList<Solocomparator> a1=new ArrayList<Solocomparator>();
        a1.add(new Solocomparator(21,"solomon"));
        a1.add(new Solocomparator(26,"solomons"));
        a1.add(new Solocomparator(20,"solomonjking"));
        Collections.sort(a1,new Solocomparator());
        for(Solocomparator i:a1)
            System.out.println(i.age+":" + i.name);
    }
}

in this program i have implemented comparator to sort the arary list by age ,
problem seems to be in this line of code
Collections.sort(a1,new Solocomparator());

A: Comparable and Comparator are two different interfaces, used for similar purposes.  Collections.sort wants a Comparator and this allows you the flexibility to modify the default way objects might be compared (or not, depends on what you want to achieve)
Start by creating a base object, which contains the values you need to store...
public class Solomon {
    private int age;
    private String name;

    public Solomon(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

}

Then create a Comparator which can compare the instances of Solomon the way you need to...
public class SolomanAgeComparator implements Comparator<Solomon> {

    @Override
    public int compare(Solomon o1, Solomon o2) {
        return o1.getAge() - o2.getAge();
    }

}

and/or
public class SolomanNameComparator implements Comparator<Solomon> {

    @Override
    public int compare(Solomon o1, Solomon o2) {
        return o1.getName().compareTo(o2.getName());
    }

}

Then use either one to sort the List of values...
List<Solomon> a1 = new ArrayList<Solomon>();
a1.add(new Solomon(21, "solomon"));
a1.add(new Solomon(26, "solomons"));
a1.add(new Solomon(20, "solomonjking"));
Collections.sort(a1, new SolomanNameComparator());

A: You don't say, but my guess is that your code is not compiling because class Solocomparator does not actually implement the methods required by the Comparator interface.
You seem to be confusing Comparator with Comparable. These are related but different interfaces. A Comparator compares two objects that are distinct from the comparator. You would need to implement a method with the signature:
public int compare(Solocomparator o1, Solocomparator o2)

A Comparable object, on the other hand, is one that knows how to compare itself to another object of the same type. This is what you've written, so you probably want your class to implement Comparable<Solocomparator>, not Comparator<Solocomparator>. You could then sort it with:
Collections.sort(a1);

If you want to implement a Comparator<Solocomparator>, then remove the comparison code from Solocomparator and put it in a separate class.


text:
Q: How to embed matplotlib.pyplot.colorbar in the PyQt user interface I'm new to python, so I need some advice with the project.
There is a window for displaying an image, there is a function for reading and displaying colors on it in the console, there is a function for creating a colorbar based on the received list of colors. Please tell me what needs to be done to output the colorbar to QMainWindow.
This is how it looks now:

So I would like it to look like:

Project code:
import sys
import coordCatch
import matplotlib as mpl

from PIL import Image
from PyQt5 import QtWidgets, QtCore

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from matplotlib.pyplot import *

class graphicsScene(QtWidgets.QGraphicsScene):
    clicked = pyqtSignal()

    def __init__(self, parent=None):

        super(graphicsScene, self).__init__(parent)

class ExampleApp(QtWidgets.QMainWindow, coordCatch.Ui_MainWindow):
    def __init__(self):
        super(ExampleApp, self).__init__()
        self.setupUi(self)
        self.resize(640, 640)

        self.gscene = graphicsScene()
        self.graphicsView.setScene(self.gscene)
        self.graphicsView.show()

        pic = 'image.png'
        self.image = QImage(pic)
        pixmap = QGraphicsPixmapItem(QPixmap.fromImage(self.image))
        self.graphicsView.scene().addItem(pixmap)

        self.selection = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle,
                                               self)
#-----Блок обработки изображения и создание списка цветов
        collorsList = []
        imag = Image.open(pic)
        collors = imag.getcolors()
        for cl in collors:
            if cl[0] > 30000:
                collorsList += [self.rgb_to_hex(cl[1])]
        collorsList.sort()
        print(collorsList)
#-------------------------

        self.radioButton.toggled.connect(lambda: self.colourBar(collorsList))

#----- Функция создания colorbar
    def colourBar(self, colLst):

        i = 0
        bins = []
        for clr in colLst:
            bins += [i]
            i += 0.5

        cmap = mpl.colors.ListedColormap(colLst)
        norm = mpl.colors.BoundaryNorm(boundaries=bins,
                                       ncolors=len(cmap.colors)-1 )

        fig, ax = subplots(figsize=(6, 1))
        fig.subplots_adjust(bottom=0.5)
        cb2 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
        norm=norm,
        boundaries= [-.1] + bins + [2.1],
        ticks=bins,
        spacing='uniform',
        orientation='horizontal')
        cb2.set_label('Custom colour bar')
        show()
#-------------

    def rgb_to_hex(self, rgb):
            return '#%02x%02x%02x' % rgb

def main():
    app = QtWidgets.QApplication(sys.argv)

    window = ExampleApp()
    window.show()
    app.exec_()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    main()

UI code:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(642, 491)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(10, 10, 441, 331))
        self.graphicsView.setObjectName("graphicsView")
        self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton.setGeometry(QtCore.QRect(490, 30, 131, 41))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.radioButton.setFont(font)
        self.radioButton.setObjectName("radioButton")
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(10, 390, 441, 80))
        self.widget.setObjectName("widget")
        MainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.radioButton.setText(_translate("MainWindow", "Линейка"))

The expected result is displayed in the question itself.

A: I would create a widget that has a figure and add this widget to my template
Something similar to this should work
class Grapth(QWidget):
    def __init__(self, figure, parent=None, toolbar=True, **kwargs):
        super().__init__(parent)
        self.figure = figure
        self.canvas = FigureCanvas(self.figure)
        layout = QVBoxLayout()
        self.toolbar = NavigationToolbar(self.canvas, self)
        if toolbar:
            layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        self.canvas.draw()


text:
Q: In windows, what is the difference between named and unnamed semaphores? What is the difference between named and unnamed semaphores?
For Example in Windows, we always do WaitforSingleObject( wait) and ReleaseSemaphore( Signal ) using the HANDLEs and not using names.

A: An unnamed semaphore can only be used by its handle, but if you have a named semaphore you can create a second handle using the name. The benefit of this is that you only need to have a static name to be able to use the same semaphore in different threads and processes.


text:
Q: What happens to a lock during an Invoke/BeginInvoke? (event dispatching)
Just to put the questions upfront (please no comments about the bad architecture or how to revise - suppose this is what it is):

*

*How does the "lock" statement apply when using Invoke/BeginInvoke

*Could the following code result in a deadlock?

Suppose I have the following BindingList that I need to update on the GUI Thread:
var AllItems = new BindingList<Item>();

I want to make sure that all updates to it are synchronized.
Suppose I have the following subroutine to do some calculations and then insert a new entry into the BindingList:
private void MyFunc() {
  lock(locker) {
    ... //do some calculations with AllItems

    AddToArray(new Item(pos.ItemNo));

    ... //update some other structures with the contents of AllItems
    }
}

And AddToArray looks like:
private void AddToArray (Item pitem)
{
   DoInGuiThread(() =>
     {
       lock (locker)
         {
           AllItems.Add(pitem);
         }
      });
 }

And DoInGuiThread looks like:
 private void DoInGuiThread(Action action) {
   if(InvokeRequired) {
       BeginInvoke(action);
    } else {
       action.Invoke();
    }
 }

A: The lock is held till you leave the lock block, your current code does not cause a deadlock however it also does not work correctly either.
Here is the sequence of events:

*

*On a background thread you call MyFunc.

*A lock is taken for the background thread for the object locker

*The background thread will "do some calculations with AllItems"

*The background thread calls AddToArray from MyFunc passing in pitem

*The background thread calls DoInGuiThread from AddToArray

*The background thread calls BeginInvoke from DoInGuiThread, the thread does not block, I will use A to signify the background thread
  and B to signify the UI thread, both of these are happening at the
  same time.

*A) BeginInvoke returns from it's call because it is non blocking.
  B) The UI hits lock (locker) and blocks because the lock is held by
  the background thread.

*A) DoInGuiThread returns.
  B) The UI is still locked up, waiting for the background thread to release the lock.

*A) AddToArray returns.
  B) The UI is still locked up, waiting for the background thread to release the lock.

*A) The background thread will "update some other structures with the contents of AllItems" (note, pitem has not yet been added to
  AllItems)
  B) The UI is still locked up, waiting for the background thread to release the lock.

*A) The background thread releases the lock for the object locker
  B) The UI thread takes the lock for the object locker

*A) MyFunc returns.
  B) pitem is added to AllItems

*A) Whoever called MyFunc continues to run code
  B) The UI thread releases the lock for the object locker

*A) Whoever called MyFunc continues to run code
  B) The UI thread returns to the message pump to process new messages and no longer appears to be "locked up" by the user.

Do you see the issue? AddToArray returns but the object is not added to the array until the end of MyFunc so your code after AddToArray will not have the item in the array.
The "usual" way to solve this is you use Invoke instead of BeginInvoke however that causes a deadlock to happen. This is the sequence of events, Steps up to 6 are the same and will be skipped.

*The background thread calls Invoke from DoInGuiThread

*A) Invoke waits for B to return to the message pump.
  B) The UI hits lock (locker) and blocks because the lock is held by the
  background thread.

*A) Invoke waits for B to return to the message pump.
  B) The UI is still locked up, waiting for the background thread to release
  the lock.

*A) Invoke waits for B to return to the message pump.
  B) The UI is still locked up, waiting for the background thread to release
  the lock.

*A) Invoke waits for B to return to the message pump.
  B) The UI is still locked up, waiting for the background thread to
  release the lock.

  (This repeats forever)

A: There's two different ways this is likely to go down.

*

*You're doing all of this on the GUI thread

*You're starting this call chain on some other thread

Let's deal with the first first.
In this case there won't be a problem. You take the lock in MyFunc, you call AddToArray which calls DoInGuiThread passing in a delegate. DoInGuiThread will notice that invoking is not required and call the delegate. The delegate, executing on the same thread that now holds the lock, is allowed to enter the lock again, before calling AllItems.Add.
So no problem here.
Now, the second case, you start this call chain on some other thread.
MyFunc starts by taking the lock, call AddToArray which calls DoInGuiThread passing the delegate. Since DoInGuiThread now detects that it needs to invoke it calls BeginInvoke passing in the delegate.
This delegate is queued on the GUI thread by ways of a message. Here's where things again diverge. Let's say the GUI thread is currently busy, so it won't be able to process messages for a short while (which in this context means "enough to let the rest of this explanation unfold").
DoInGuiThread, having done its job, returns. The message is not yet processed. DoInGuiThread returned back to AddToArray which now returns back to MyFunc which releases the lock.
When the message is finally processed, nobody owns the lock, so the delegate being called is allowed to enter the lock.
Now, if the message ended up being processed before the other thread managed to return all the way out of the lock, the delegate now executing on the GUI thread would simply have to wait.
In other words, the GUI thread would block inside the delegate, waiting for the lock to be released so it could be entered by the code in the delegate.


text:
Q: my .className variable has a null because it calls from an array at a later time. Cant figure out a work around I have this code currently:
load = function () {

    var hexArray = ["hexa", "hexb", "hexc", "hexd", "hexe", "hexf", "hexg", "hexh", "hexi", "hexj", "hexk", "hexl", "hexm"];
    var delayArray = ["delaya", "delayb", "delayc", "delayd", "delaye", "delayf", "delayg", "delayh", "delayi", "delayj", "delayk", "delayl", "delaym", "delaya", "delayb", "delayc", "delayd", "delaye", "delayf", "delayg", "delayh", "delayi", "delayj", "delayk", "delayl", "delaym"];
    var divHexArray = ["aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj", "ak", "al", "am", "an", "ao", "ap", "aq", "ar", "as", "at", "au", "av", "aw", "ax", "ay", "az", "ba", "bb", "bc", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bk", "bl", "bm", "bn", "bo", "bp", "bq", "br", "bs", "bt", "bu", "bv", "bw", "bx", "by", "bz", "ca", "cb", "cc", "cd", "ce", "cf", "cg", "ch", "ci", "cj", "ck", "cl", "cm", "cn", "co", "cp", "cq", "cr", "cs", "ct", "cu", "cv", "cw", "cx", "cy", "cz", "da", "db", "dc", "dd", "de", "df", "dg", "dh", "di", "dj", "dk", "dl", "dm", "dn", "do"];
    var pos = 0;

    function zip(a, b, f) {
        for(var i=0; i < hexArray.length; i++){
            f(a[i], b[i]);
        };
    }

    function phase(a, b, f) {
        for(var i=0; i < divHexArray.length; i++){
            f(a[i], b[Math.floor(Math.random()*26)]);
        };
    }

    wave = function(){
        if(pos < hexArray.length){
            document.getElementById(hexArray[pos]).className='wave';
            pos += 1;
        } else if (pos === hexArray.length) {
            document.getElementById(hexArray[pos]).className='wave';
        } else {
            false;
        }
    };

    for(var i = 0; i < hexArray.length; i++) {
        document.getElementById(hexArray[i]).addEventListener('animationend', wave, false);
        document.getElementById(hexArray[i]).addEventListener('webkitAnimationEnd', wave, false);
    };

    zip(hexArray, delayArray, function(x, y) {
        document.getElementById(x).className = 'transtart burn ' + y;
    });

}

document.addEventListener('DOMContentLoaded', load, false);

It works just fine. I and setting up a secondary function called phase() which you can see. phase() works in the same fashion as zip() does, however I do not want to call phase() on page load like I do with zip(), so Im trying to create a variable that calls phase at a different time.
This is the variable Im trying to add:
    var phaseStart = phase(divHexArray, delayArray, function(x, y) {
        document.getElementById(x).className = 'wave ' + y;
    });

The problem I assume Im running into my .className null error, is because of 'y' is a variable without a value. Mostly because while delayArray is named as the variable for y, delayArray doesnt yet have a value because for loop function hasnt been passed through yet to define values for delayArray in that instance. This isnt a problem with zip() because as soon as it is called on page load, the function to define the values runs immediately.
Ive tried a few if/else statements as work arounds, but nothing is seeming to work how I want it to. I am also trying to keep my script from ballooning. If anyone knows a work around I would be very grateful.

A: Answer based on jsfiddle.
var phaseStart = phase(divHexArray, delayArray, function(x, y) {
    document.getElementById(x).className = 'wave ' + y;
});

This code not caches function, but tries to execute it and apply return value (or undefined if there is no return in the function) to the phaseStart. If you want function with cached arguments to use later you need to return function to variable. For example like this:
var phaseStart = function() {
    phase(divHexArray, delayArray, function(x, y) {
        document.getElementById(x).className = 'wave ' + y;
    });
}

This way function will be created, but only accessible from inside load function. If you want to see it from outside you will need to define phaseStart variable outside of the load function. For example like this:
var phaseStart;

load = function() {
    ...
    phaseStart = function() {
        ...
    }
    ...
};

This way it will be visible from outside. And you will be able to call it with phaseStart();. But only after page loading completion, because it is defined inside load function.
Fixed: Removed unnecessary function wrapper. Now loop works all the way till "ci" element in array before breaking (there is no element with id="ci"). If you remove "ci" form array it works all the way to the end without errors.


text:
Q: Is it possible in Slack to move a message to a thread? Slack has threaded messages to avoid clutter. Unfortunately, not everyone is disciplined enough to start a thread when they answer a message.
When that happens, is it possible to either:

*

*Move a message to another message, and start a thread that way?

*Or start a thread on the original message, and then move the answering message to that thread?

I have a feeling the answer is 'no'. I can't find anything in their api description or their feature description.

A: Slack doesn't seem to be in much of a feature enhancement lifecycle currently like they were earlier in life. It's unfortunate because packing in "power user" features is what got Slack its huge user-base. I don't foresee them adding such (debatably) niche functionality like this any time soon. This is too common when a giant purchases an amazing start-up, in this case Salesforce, the bloat-ware B2B behemoth.
Your Outlined Options

*

*Move a message to another message, and start a thread that way?

*Or a thread on the original message, and then move the answering
message to that thread?

I'm not exactly sure what you mean with number one, but I'd recommend (as a work around to the feature you're hoping for of course) a third similar option.
My Workflow

*

*A question is asked, or a topic is raised that warrants a separate thread.

*Things start to get messy and the undisciplined someone replies in the channel.

*Instead of moving (or more accurately, copy/pasting) their message into a thread on the original message, reply to their message in a thread. If you want to coach them a little more to switch the conversation into that thread, @ mention them there. I'd do the same with anyone you'd like to move there as well. "@other-human, any thoughts?" I'll even follow up with another @ mention if some time has gone by, eg. "@broseph Any idea? ☝"

*You can quote the original message at the start of this new thread as you stated, and for bonus points, you can link the original question with something like, "In reference to [link to original question]: Can we partition the juice box drives into three [...]" This gives the thread traceability back into the channel.

*Be persistent. I've done this quite a bit and people tend to get the hint relatively quickly, even my most dense colleagues conform before long.

*Don't be afraid to bring this up with people directly. I'll sometimes say something like, "It's getting messy in here. Let's shift to this thread: [link to first message in thread, not the parent message the thread is on since that won't open the thread itself]". The concept of "moving" a message to a thread is actually sort of passive aggressive whereas this expresses the "why" and teaches a better workflow.

*If the thread itself gets messy, the same general workflow applies to a new group chat (which I almost always oppose) or much better, a new channel for the topic. This can be short lived, though you'll have to delete it manually after the discussion. I typically just "Leave" (exit) the temporary channel when I'm done, but leave it in place for posterity.

About Threads In General
Something that's important to consider that is people don't always like threads. They're not as feature-rich as channels. For one thing, you can't "Thread" a thread; there's no forking so when sub-threads become necessary you're forced to start quoting messages, which has its own limitations.
Also, the right-side Thread sidebar is narrow so code blocks and the like aren't very readable or formatted nicely. Even switching to the Threads view (top left in your left side bar) isn't perfect since all of your recent threads are interlaced which can make things cumbersome to sort through when you've got multiple threads going. This can sometimes be worse than a noisy channel.
Conclusion
This approach is more intuitive for the people you're trying to wrangle since you're interacting with their message instead of the original message that they're responding to. That makes it more apparent that you want to break out of the channel, and you want to speak to them directly. It's the equivalent of being in a meeting that's getting off-track and saying, "Let's side-bar after the meeting." Doubling-down with an @ mention in the thread can help a lot, even though they're already alerted to threaded responses on their message - it feels more personal and directed to them.
For anyone else that persists on with the conversation in the channel, again, just @ mention them in the thread to invite them into the conversation you want them to be a part of. Ignoring their message in the channel, or answering them where you want the conversation to take place is also a teaching tactic.
TL;DR
Respond to a person you want to pull into a thread on their message. Speak openly about it by stating the obvious: "Things are getting messy in here."

A:
It is not possible to move a slack message to a thread, but you can always reply to thread or you can attach your reply with the message you want by clicking on share message and then typing your content. You can refer to the pic; there is a tilt arrow which is share message icon.