text:
Q: Unexpected result subtracting decimals in ruby I'm doing a simple subtraction between 2 decimals in ruby, but am getting a suprisingly odd result.  If I run the following in IRB, I would have expected to get 0.011.  I realize I can do (0.942 - 0.931).round(3) to get the answer I'm expecting, but am wondering why ruby returns the result it does.
 1.9.3-p551 :004 > (0.942 - 0.931)
 => 0.010999999999999899


text:
Q: Why can't CASE be used on string values and only symbol values? In book 'land of lisp' I read

Because the case command uses eq for comparisons, it is usually used
  only for branching on symbol values. It cannot be used to branch on
  string values, among other things.

Please explain why?

A: Because (eq "foo" "foo") is not necessarily true. Each time you type a string literal, it may create a fresh, unique string. So when CASE is comparing the value with the literals in the cases with EQ, they won't match.

A: The other two excellent answers do answer the question asked. I will try to answer the natural next question - why does case use eql?
The reason is actually the same as in C (where the corresponding switch statement uses numeric comparison): the case forms in Lisp are usually compiled to something like goto, so (case x (1 ...) (2 ...) (3 ...)) is much more efficient than the corresponding cond. This is often accomplished by compiling case to a hash table lookup which maps the value being compared to the clause directly.
That said, the next question would be - why not have a case variant with equal hash table clause lookup instead of eql? Well, this is not in the ANSI standard, but implementations can provide such extensions, e.g., ext:fcase in CLISP.
See also why eql is the default comparison.

A: Two strings with the same content "foo" and "foo" are not EQL. CASE uses EQL as a comparison (not EQ as in your question). Usually one might want different tests: string comparison case and case insensitive, for example. But for CASE on cannot use another test. EQL is built-in. EQL compares for pointer equality, numbers and characters. But not string contents. You can test if two strings are the identical data objects, though.
So, two strings "FOO" and "FOO" are usually two different objects.
But two symbols FOO and FOO are usually really the same object. That's a basic feature of Lisp. Thus they are EQL and CASE can be used to compare them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Text floats out of its div I'm dealing with a text who goes out of its div. I've coded the frontpage. So, no matter how long the main content is, it should force the sub-content (the grey area and the footer) to move down.
You see how the dummy text is acting
URL http://nicejob.is/clients/pizzahollin/www/divproblem.htm
I've accomplish this before but somehow it's not working now.

A: You've set an explicit height on that div. For it to reshape itself to its content, you'll need to set height:auto. (or never set its height in the first place)
EDIT: As ANeve said, you'll need to remove the height on both .article and .opentext, as well you'll need to put a clear:left on .lower-container to push the footer down.

A: Just use wordwrap: break-word; for the div and it will break the word to the next line.

A: You have set the height property of your .article and .opentext divs.  If you remove this property, the content should expand accordingly.
However, you will also need to adjust the positioning of your background image.  You should set the background image of .footer itself, rather than relying on one statically-sized background image for the entire page.

A: If you have an element that only contains floating elements, the container's height will be zero. To fix this you can add a clearing div (

).
If you add a clearing div at the end of the #under-content section, it will automatically adjust the height of the section to it's contents.
The other issue you have is that you are using relative positioning on your .opentext div elements. When you set a 'top' property, it actually pushes the content down, causing it to overlap with your #lower-container. You're better off using the 'margin-top' property, which will expand the size the .opentext div to fit all the contents.
So in short:

*

*Add

 at the end of the #under-content

*Change the 'top:82px' to 'margin-top:82px' on your .opentext div

I hope this helps!


text:
Q: Problems with servlets and maven i am trying to build my first servlet using maven but don't know what i should add to the POM so the servlet
I have tried to add the below dependencies to the POM file (I found in one of the posts). The addition enables me to compile my servlet but when i try to run mvn package or to test my JUnits i am getting a ClassFormatError:
Initial SessionFactory creation failed.java.lang.ClassFormatError:
Absent Code attribute in method that is not native or abstract
in class file javax/validation/Validation

The pom.xml is:
<dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-web-api</artifactId>
  <version>6.0</version>
  <scope>provided</scope>
</dependency>

<repository>
  <id>java.net2</id>
  <name>Repository hosting the Java EE 6 artifacts</name>
  <url>http://download.java.net/maven/2</url>
</repository>

can someone explain and guide?
Thanks
:-)

A: At the outset, you may want to follow Senthil's comment above.
As for the error, it is because the specified dependency only has the APIs (method definitions) and not the implementation.
Typically, the implementation is provided by the app server. Hence the application should work in an app server which implements Java EE 6 (like Glassfish).
mvn package should not give any error - it is the test phase before packaging which fails, which you can circumvent, if interested using mvn package -DskipTests.


text:
Q: Select All + Copy/Paste A common pattern I find myself doing in a non-vim text editor is:
Cmd a Cmd c
to copy all the content in the entire file, and then open a new file and
Cmd v
to then paste in all that content. When all is said and done, I can usually do this entire copy-paste in about 0.5s. What would be the most common/efficient way to do this in vim?

A: I do the same quite often by running the following commands: ggVGy.
The first command, gg, jumps to the beginning of the file. Then we select the entire first line with V. Still in visual mode, we jump to the end of the file with G, before copying (yanking) everything with y.
You can make this even faster and easier by mapping all of these commands to one key. With the mapping below, pressing the leader key and X will copy the entire file.
nnoremap <leader>X ggVGy

If you need the content to be available to the system clipboard, and not only in Vim, you should use "+y instead of y. This will yank to the "+ register used for the system clipboard. You can find more information on this topic in this question.


text:
Q: How do I stop WordPress loading jQuery and jQuery-migrate? WordPress is loading the following 2 files in wp_head():
<script type='text/javascript' src='http://example.com/wp-includes/js/jquery/jquery.js?ver=1.10.2'></script>
<script type='text/javascript' src='http://example.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>

In an attempt to stop this from happening, I have tried deactivating all plugins and deregistering jQuery in functions.php, but nothing seems to get rid of it.
Any ideas how I can stop this?
I'm using Wordpress v3.6.

A: Wordpress has the jquery library and you should take advantage of this. If you want to remove this you can do something like this:
function deregister_qjuery() {
    if ( !is_admin() ) {
        wp_deregister_script('jquery');
    }
}

add_action('wp_enqueue_scripts', 'deregister_qjuery');

But consider how to load your JS files properly.
Further reading:
Dear theme developers, this is how you add scripts in WordPress themes
http://wpcandy.com/teaches/how-to-load-scripts-in-wordpress-themes/
Loading jQuery correctly
http://beneverard.co.uk/blog/wordpress-loading-jquery-correctly-version-2/
How to add a backup javascript file in Wordpress that initially loads off internet
How to add a backup javascript file in Wordpress that initially loads off internet

A: Use the wp_enqueue_script function of Wordpress instead of defining the scripts in your template. This way you won't import different versions of javascript libraries.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script

A: You might want to use this in your functions.php
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );

function remove_jquery_migrate( &$scripts){
    if(!is_admin()){
        $scripts->remove( 'jquery');
        $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1' );
    }
}

1.2.1 = latest version of jquery-migrate
If you want to check whether your site requires jquery-migrate, open wp-config.php and this line of code: define('SCRIPT_DEBUG', true);. That way you can monitor any errors.
Don't forget to remove this when you put your site live!
Hope that helps.

A: function dequeue_jquery_migrate($scripts){
    if(!is_admin() && !empty($scripts->registered['jquery'])){
        $jquery_dependencies = $scripts->registered['jquery']->deps;
        $scripts->registered['jquery']->deps=array_diff($jquery_dependencies,array('jquery-migrate'));
    }
}
add_action( 'wp_default_scripts', 'dequeue_jquery_migrate' );


text:
Q: How to concatenate two mp4 files using ffmpeg C code? I found many links about concatenating multiple mp4 files using ffmpeg command on shell environment. Such as:
Concatenate two mp4 files using ffmpeg
But I didn't find any information about using C code. There are some code snippet, but it seems not working.
static int setargs(char *args, char **argv)
{
    int count = 0;

    while (isspace(*args)) ++args;
    while (*args) {
        if (argv) argv[count] = args;
        while (*args && !isspace(*args)) ++args;
        if (argv && *args) *args++ = '\0';
        while (isspace(*args)) ++args;
        count++;
    }
    return count;
}

char **parsedargs(char *args, int *argc)
{
    char **argv = NULL;
    int    argn = 0;

    if (args && *args
        && (args = strdup(args))
        && (argn = setargs(args,NULL))
        && (argv = malloc((argn+1) * sizeof(char *)))) {
          *argv++ = args;
          argn = setargs(args,argv);
    }

    if (args && !argv) free(args);

    *argc = argn;
    return argv;
}

void freeparsedargs(char **argv)
{
    if (argv) {
        free(argv[-1]);
        free(argv-1);
    }
}

int main()
{
    char **argv;
    char *cmd;
    int argc;

    cmd = "ffmpeg -i infile outfile";
    argv = parsedargs(cmd,&argc);
    ffmpeg(argc, argv);
}

Can FFmpeg be used as a library, instead of a standalone program?
How to do it by using ffmpeg C code ?


text:
Q: How JOptionPane.showInputMessage() is implemented in Java I need that information so I can create custom login dialog.
public static void main(String args[]) {
     JOptionPane.showInputDialog("Enter username: ");
     // This will show dialog and after 'OK' button is clicked
     // into that dialog, it will return the input as string, right?

}

So, i created new class which extends JDialog it includes 2 labels, 2 text fields and 1 button, after that button is clicked i want to simulate something like JOptionPane.showInputDialog() i want to wait for user input before other code proceed.
public static void main(String args[]) {
   LoginDialog ld=new LoginDialog();
   ld.setVisible(true);
   // When that button is clicked i want this code to continue...
   dl.getUsername();
   dl.getPassword();
}


text:
Q: Why Is The Row Height Of These Two Tables Different? Please have a look at the simulator screen shot below wherein you will see:

*

*A horizontal stack view with three buttons

*A table view with a red header, a brown footer and a light grey background

*A horizontal stack view with three buttons

*A table view with a cyan header, an orange footer and a light dark background

I created that interface via a storyboard. In interface builder I was careful to create both of the tables in exactly the same way, with the exception of the colors.
I have included an Xcode screen shot that might be helpful. Notice that the labels added to the prototype cells have their edges pinned to the cell's edges.
Nowhere am I taking any action to set the table row heights. In the datasource's cellForRowAt method I am printing the cell heights: they are reported to be 44, which I understand is the default.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: UITableViewCell

    if tableView === upperTable {
        cell = tableView.dequeueReusableCell(withIdentifier: "upper")!
        (cell as! TableViewCell).label.text = upperData[indexPath.row]
        print("Upper table cell height = \(cell.bounds.height)")
    }
    else {
        cell = tableView.dequeueReusableCell(withIdentifier: "lower")!
        (cell as! TableViewCell).label.text = lowerData[indexPath.row]
        print("Lower table cell height = \(cell.bounds.height)")
    }

    return cell
}

Can anyone suggest a possible reason for the final row heights of the two tables being different?

A: In one table, the one with the pink header it looks like, your constraints set the content view's bottom edge to match the bottom of the label (so you are moving the bottom edge of the content view to the bottom of the label making the content view's height dependent on the label's height).
In the other you are setting the content view's bottom margin to match the label's bottom (so you are are moving the margin to correspond to the label's bottom, not the bottom edge of the view).


text:
Q: Setting text property to a button doesn't work This is my UserControl file:
<UserControl x:Class="myProject.ButtonWithImage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:myProject="clr-namespace:myProject;assembly=myProject.BusinessLogic"
         mc:Ignorable="d"
         Name="ImagedControl"
         d:DesignHeight="300" d:DesignWidth="300">
<Button Height="35" Width="90" FocusVisualStyle="{x:Null}" Foreground="White"
        Click="OnClick" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0 0 1 1">
    <StackPanel Orientation="Horizontal" Margin="3">
        <Image Source="{Binding ElementName=ImagedButton, Path=ImageSource}" Stretch="None" Margin="0 0 5 0" />
        <TextBlock Text="{Binding ElementName=ImagedButton, Path=Text}" FontSize="12" VerticalAlignment="Center" />
    </StackPanel>
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="border" CornerRadius="8">
                <Border.Background>
                    SlateBlue
                </Border.Background>
            </Border>
        </ControlTemplate>
    </Button.Template>
</Button>

And in a page I set up a button like this:
<myProject:ButtonWithImage ImageSource="/Resources/test.png" Text="Back" Name="btnBack1" Command="NavigationCommands.GoToPage" CommandParameter="ViewModel/Categories.xaml" />

However the text and the imagesource aren't on the button! They don't appear. What am I doing wrong?

A: Created Button Usercontrol
<Button x:Class="WpfApplication5.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300"
    FocusVisualStyle="{x:Null}" Content="ok" Foreground="White" Height="30" Width="90" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0 0 1 1">
<Button.Template>
    <ControlTemplate TargetType="{x:Type Button}">
        <Border x:Name="border" CornerRadius="8">
            <Border.Background>
                SlateBlue
            </Border.Background>
            <StackPanel Orientation="Horizontal" Margin="3">
                <Image Source="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}" Height="30" Width="30" Stretch="Fill" Margin="0 0 0 0" />
                <TextBlock Text="{Binding Path=Content,RelativeSource={RelativeSource TemplatedParent}}" FontSize="12" VerticalAlignment="Center" />
            </StackPanel>
        </Border>
    </ControlTemplate>
</Button.Template>

c# code
 public partial class UserControl1 : Button
{
    public UserControl1()
    {
        InitializeComponent();
    }
}

xaml window
<Window x:Class="WpfApplication5.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myProject="clr-namespace:WpfApplication5"
    Title="MainWindow" Height="350" Width="525">

<myProject:UserControl1  Content="Button Text" Tag="btn2.png" />

A: You have named your UserControl ImageControl, but then you have tried to access it in your XAML using the name ImageButton. You'll have more luck if you stick with the one name. Try this instead:
<UserControl x:Class="myProject.ButtonWithImage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:myProject="clr-namespace:myProject;assembly=myProject.BusinessLogic"
         mc:Ignorable="d"
         Name="ImagedControl"
         d:DesignHeight="300" d:DesignWidth="300">
<Button Height="35" Width="90" FocusVisualStyle="{x:Null}" Foreground="White"
        Click="OnClick" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0 0 1 1">
    <StackPanel Orientation="Horizontal" Margin="3">
        <Image Source="{Binding ElementName=ImagedControl, Path=ImageSource}" Stretch="None" Margin="0 0 5 0" />
        <TextBlock Text="{Binding ElementName=ImagedControl, Path=Text}" FontSize="12" VerticalAlignment="Center" />
    </StackPanel>
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="border" CornerRadius="8">
                <Border.Background>
                    SlateBlue
                </Border.Background>
            </Border>
        </ControlTemplate>
    </Button.Template>
</Button>

This also assumes that you have correctly declared two DependencyPropertys of the correct type, named ImagesSource and Text in your UserControl and have set appropriate values for them.


text:
Q: Exit C function cleanly I have a couple of functions. Basically a menu where a user can choose 1-n different options, and each of those options have a function associated with them. In this example it's been dumbed down.
What I am trying to determine is the best way to exit a function prematurely. For example, when the user presses enter whilst in the function of a menu option, I want the program to send them back to the menu without running anything else in that function.
In the case below, I simply call showMenu() and place a return statement after it. The only thing is, if the user quits multiple functions there will be a trail of return statements that needs to be unraveled at the end.
Could somebody please show me if there is a more efficient way to achieve this or whether I am on the money.
void showMenu()
{
   //Display menu

   //Prompt user for menu option

   //Run function of appropriate menu option
   runSelectedFunction();
}

void runSelectedFunction()
{
   //Get user input for the function and validate

   //Check if the user input was only a '\n' if so show the menu and exit
   showMenu();
   return;

   //Do the stuff that this function is meant to do.
}

A: Looks good to me. Or - since there are many around that are against having multiple exit points form a single function - you could do:
void func()
{
   //get input

   if ( checkMenu() )
   {
      //do the stuff I am meant to do
   }
   else
   {
      showMenu();
   }
}

so you are avoiding adding a second return to your function. Also you could have the showMenu() call always at the end of the function, depending on your needs
hth
Mario

A: The best way? In short, don't.
Why?
Although there's nothing technically wrong with it and you'll find it all over the place, it can sometimes lead to headaches when trying to track down bugs or memory leaks in complex code.
Use early returns only when absolutely necessary and even then try to find an alternative first :)

A: An alternative is to use the following pattern to ensure your function always returns from one place, giving you the opportunity to always free resources (or report errors, etc):
int func(void)
{
    int ret = 0;

    do
    {
        if (!allocate_resource())
        {
            ret = -1;
            break;
        }

        if (!allocate_more_resources())
        {
            ret = -2;
            break;
        }

        do_stuff();
    }
    while (0);

    free_allocated_resources();

    return (ret);
}


text:
Q: Почему не ставится фоновое изображение на страницу style.css
html {
    background-image: url(images/home-bg.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    height: 100%;
}

Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link href="style.css" rel="stylesheet">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

        <link href="../css/style.css" rel="stylesheet" type="text/css">

        <title>Home Page</title>

                KazNIC

Главная

Наш университет

Электронный журнал

Студенты

Фотогалерея

Карьера

Контакты

            <form class="navbar-form navbar-left" action="/action_page.php">

                    <input type="text" class="form-control" placeholder="Search" name="search">

                <button type="submit" class="btn btn-default">Поиск</button>
            </form>

            <form action="allStudents" method="post">
                 <input class="btn btn-primary" type="submit" value="Показать всех студентов">
            </form>

Расположение файлов

Вынес из папки

A: Попробуй вставить картинку через

~~
Если не получиться значит проблема в пути. Или может быть проблема в картинке, попробуй таким же способом вставить другую картинку.

Ты так же можешь добавить класс и манипулировать картинкой добавлять позиционирование и тд


text:
Q: No sound on chat notifications skype Can you tell me why my skype doesn't give any sound on chat notifications? I have win 10 pro desktop. All sounds are working fine on call and etc. The problem here is no sound on chat notification when Skype is on the taskbar. But it shows message coming notification on the taskbar icon. But no sound. Any clue?

A: I don't have this issue now. I didn't do anything myself for this. No idea something happened accidentally. But I strongly believe Windows latest updates fixed this issue. Now I can see and have sound through notification section when I have a skype message.

A: Check if the problem is related to specific user or a group like in my case !

*

*Right click on a group/contact,

*Click on "Manage group"

*Scroll to the bottom

*"Notifications" should be checked

*"Smart notifications" should be uncheched


text:
Q: C# Why is Serial.WriteLine() so slow? When I want to program a Teensy 3.5 micro-controller, I send it a .HEX file via a hardware serial port. I have two ways of doing this; one way is to use a serial comms app like Tera Term to send the file, and another way is via a small C# command-line app I wrote to do the same thing.
When I send a 3000+ line Hex file to the micro-controller, it takes approximately 14 seconds. When I do the same thing with my C# program, it takes twice as long (or longer!).  The baud rate for both Tera Term and my C# program are the same, and of course the Teensy setup is common to both.
When I looked as the serial transfer using a digital scope,  I see the following (same time scale in both photos):

The first photo shows the transfer when using Tera Term, and the second one shows the transfer when using my C# program using Serial.WriteLine() to transfer file contents line-by-line, as shown below:
using System;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Timers;
using System.Diagnostics;

/*
Small console app to facilitate over-the-air (OTA) updates to a Teensy 3.x/4.x controller,
using VS2019 with the Visual Micro extension as the Arduino IDE. It is called by a post-build
'hook' statement in a file called 'board.txt' located in whatever Teensy program is
being updated.  This app does the following:

 - Extract the project path and selected COMPORT number from the arguments to the call to Main()
 - Opens a UART serial port connection to the Teensy, typically one provided by a BT adaptor
   operating in 'pass-through' mode. The serial port COMPORT number is passed into this app
   as an argument.
 - Sends whatever command is required to put the existing Teensy firmware into 'update' mode
 - Using the path of the updating program (passed in as an argument), locates the .HEX file
   associated with the project, and sends it's contents to the Teensy, one line at a time, counting
   lines and confirming checksums line-by-line
 - Compares the number of lines sent to the Teensy with the number of lines received by the Teensy,
   and if there is a match, allows the Teensy update process to complete; otherwise aborts
*/

namespace TeensyFlash
{
    class Program
    {
        const string startCmdStr = "U"; //used in sketch's 'GetUserInput()' to start upload sequence
        static string rcvStr = string.Empty;
        private static System.Timers.Timer aTimer;
        private static bool bTimedOut;

        static void Main(string[] args)
        {
            //Extract the build path and selected COMPORT number from the arguments to the call to Main()
            Console.WriteLine("Teensy Flash Console");
            Console.WriteLine("Number of arguments in args = {0}\n", args.Length);
            int argindex = 0;
            string comPortStr = string.Empty;
            foreach (var item in args)
            {
                Console.WriteLine(item);
                if (item.Contains("COM"))
                {
                    comPortStr = args[argindex];
                }

                argindex++;
            }

            string build_path = args[0];
            string projectName = args[args.Length - 1];
            projectName = projectName.Substring(0, projectName.Length - 4); //remove extension
            build_path = build_path.Replace("\"", string.Empty).Trim();
            string hexfilename = build_path + "\\" + projectName + ".hex";
            Console.WriteLine("path = {0}", build_path);
            Console.WriteLine("comport = {0}", comPortStr);
            Console.WriteLine("build name = {0}", projectName);
            Console.WriteLine("path to HEX file = {0}", hexfilename);

            try
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                string[] lines = System.IO.File.ReadAllLines(hexfilename);
                foreach (string item in lines)
                {
                    Console.WriteLine(item);
                }

                Console.WriteLine("this took " + stopwatch.ElapsedMilliseconds + " Msec");

            }
            catch (Exception)
            {

                throw;
            }

            Console.WriteLine("Opening Serial Port...");

            try
            {
                SerialPort _serport = new SerialPort(comPortStr, 115200);
                _serport.WriteTimeout = 1000;
                _serport.WriteBufferSize = 20480;
                _serport.Open();
                _serport.DiscardOutBuffer();
                _serport.DiscardInBuffer();
                Thread.Sleep(100);

                Console.WriteLine("Sending Trigger Character " + startCmdStr);
                Console.WriteLine(startCmdStr);
                _serport.Write(startCmdStr);

                Console.WriteLine("Waiting for 'waiting' from Teensy...");
                rcvStr = string.Empty;
                aTimer = new System.Timers.Timer();
                //aTimer.Interval = 5000;
                aTimer.Interval = 25000;
                aTimer.Elapsed += OnTimedEvent;

                aTimer.Start();

                while (!rcvStr.Contains("waiting") && !bTimedOut)
                {
                    if (_serport.BytesToRead > 0)
                    {
                        rcvStr = _serport.ReadLine();
                    }
                }
                aTimer.Stop();

                if (bTimedOut)
                {
                    Console.WriteLine("Timed out waiting for 'waiting' response from Teensy");
                }
                else
                {
                    //if we get to here, the Teensy is ready to receive HEX file contents
                    Console.WriteLine("Received " + rcvStr + " from Teensy");

                    Stopwatch stopwatch2 = Stopwatch.StartNew();
                    int numlines = 0;
                    string[] lines = System.IO.File.ReadAllLines(hexfilename);
                    foreach (string item in lines)
                    {
                        numlines++;
                        _serport.WriteLine(item);
                    }
                    Console.WriteLine("total lines = {0}, time = {1} mSec", numlines, stopwatch2.ElapsedMilliseconds);

                    //now we wait for Teensy to emit "hex file: xx lines xx bytes..." and then "enter xx to flash..."
                    aTimer.Start();
                    while (!rcvStr.Contains("hex file:") && !bTimedOut)
                    {
                        if (_serport.BytesToRead > 0)
                        {
                            rcvStr = _serport.ReadLine();
                        }
                    }
                    aTimer.Stop();
                    aTimer.Dispose();

                    if (bTimedOut)
                    {
                        Console.WriteLine("Timed out waiting for 'hex file' response from Teensy");
                    }
                    else
                    {
                        //extract number of lines from Teensy string, and compare with numlines.
                        //If they match, then send the number back to Teensy to complete the update.
                        //Otherwise, send '0' to abort

                        int colonIdx = rcvStr.IndexOf(':');
                        int lineIdx = rcvStr.IndexOf("lines");
                        string compareStr = rcvStr.Substring(colonIdx + 1, lineIdx - colonIdx - 1);
                        compareStr = compareStr.Trim();
                        int numTeensyLines = Convert.ToInt16(compareStr);

                        Console.WriteLine("sent {0} teensy replied {1}", numlines, numTeensyLines);
                        if (numTeensyLines == numlines)
                        {
                            Console.WriteLine("numlines {0} matches numTeensyLines {1} - send confirmation",
                                numlines, numTeensyLines);

                            _serport.WriteLine(compareStr);
                        }
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }

            try
            {

                }
            catch (Exception)
            {

                throw;
            }
        }

        static string chksum(string input)
        {
            int TwosComplement(string s)
            {
                if (s.Length % 2 != 0)
                    throw new FormatException(nameof(input));

                var checksum = 0;

                for (var i = 0; i < s.Length; i += 2)
                {
                    var value = int.Parse(s.Substring(i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);

                    checksum = (checksum + value) & 0xFF;
                }

                return 256 - checksum & 0xFF;
            }

            //return string.Concat(":", input, " ", TwosComplement(input).ToString("X2"));
            return TwosComplement(input).ToString("X2");
        }
        private static void SetTimer()
        {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += OnTimedEvent;
            //aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                              e.SignalTime);
            bTimedOut = true;
        }
    }

}

The code that actually does the file transfer is:
Stopwatch stopwatch2 = Stopwatch.StartNew();
int numlines = 0;
string[] lines = System.IO.File.ReadAllLines(hexfilename);
foreach (string item in lines)
{
    numlines++;
    _serport.WriteLine(item);
}
Console.WriteLine("total lines = {0}, time = {1} mSec", numlines, stopwatch2.ElapsedMilliseconds);

When the '_serport.WriteLine(item);' line is commented out, the reported elapsed time is 0 mSec, as expected - so the 'ReadAllLines()' step isn't the problem.
Anyone have an idea why the 'WriteLine(item)' processing is so slow?

A: It depends on the structure of the method itself with the device, but I found on the same site an inquiry and means for it that help you
stackoverflow: console writeline slow


text:
Q: Sql Server, Select column from table 2 and column from table 1 where no relationship please can any one help me get get the correct query?
I have two tables holding title/salutation information. The first, 'Title' holds a definitive list of system / English definitions for title/salutations, and the other 'TitleTranslation' contains translation text where it has been added. The translation data  may be completely or partially missing for any language code, so the default system data must be provided when it is missing.
Title
-----
TitleId   INT PK
Name      VARCHAR(12) /* English (en) / system version */

TitleTranslation
----------------
TitleTranslationId    INT PK
TitleId               INT FK
LanguageCode          CHAR(2) /* 2 character ISO code (fr, es, ...) */
Name                  VARCHAR(12)

What I require to do for a given parameter which states the LanguageCode, for example 'fr', returns any translated title 'Name' where they exist in the system, or the default english system title 'Name' where they have not. In addition I need to be able to provide a filter on the name.
So far I have this query,
DECLARE @LanguageCode CHAR(2);
SELECT  @LanguageCode = 'fr';

DECLARE @NameFilter VARCHAR(12);
SELECT  @NameFilter = 'M';

SELECT          COALESCE([TitleTranslation].[name], [Title].[Name]) [Name]
FROM            [ref].[Title]
LEFT OUTER JOIN [ref].[TitleTranslation]
        ON      [ref].[TitleTranslation].[TitleId] = [ref].[Title].[TitleId]
WHERE          ([ref].[TitleTranslation].[LanguageCode] = @LanguageCode
OR              [ref].[TitleTranslation].[LanguageCode] IS NULL)
AND             COALESCE([TitleTranslation].[name], [Title].[Name]) Like '%' + @NameFilter + '%';

Is the COALESCE function with an OUTER JOIN the best way to achieve this? Or is there a better way to do so?


text:
Q: Connect with RDP RemoteApp to a published app in Citrix XenApp? Following link shows a nice graphic about the architectural differences between Microsoft and Citrix.
Based to this graphic, is it possible to use RDP RemoteApp to connect to a published app in Citrix XenApp? Or use RDP to connect to a XenDesktop server?
If yes,

*

*does anyone have experience with this kind of constellation?

*are there any known limitations with connecting with RDP instead of Citrix ICA?

*what RDP parameters do I need to connect to a RemoteApp in Citrix XenApp or/and what do I have to configure in the XenApp?

*are there any web resources?

A: Connecting to xenapp server using the remoteapp work, but you need to install the missing RDS's role correctly and to publish the app thru the RDS's console.
As you can guess you end up with two console. All the xenapp strategy (user or computer) will not be used as you use the rdp protocol.
For xendesktop you can rdp-in a VM, but if you have a streamed pool it will be illogical to do so. I used that tip for terminal that supported only rdp, but I needed a dedicated VM for the user. As keep in mind you bypass the desktop delivery controller that way, thus power-on, power-off, etc is all bypassed. (like xendesktop policy too). In the DDC the session will be flagged as non-brokered.


text:
Q: redefine Date() javascript The official calendar of our country is jalali!
Jalali is a type of calendar that has a mathematical relationship with the Gregorian calendar.
I want to change Date() in JS to returns jalali values.
there are many lib or func for this, but I don't want use them.
Can I redefine Date()?
Where can I view Date() source?

A: You can use toLocaleDateString();
let today = new Date().toLocaleDateString('fa-IR');
console.log(today);

fa-IR is for Farsi-Iran, but all the ISO country codes can be found here
also you can set options as second argument, for example:
let options = { year: 'numeric', month: 'long', day: 'numeric' };
new Date().toLocaleDateString('fa-IR', options);

A: Don't mess with objects you don't own. You can create your own date object called maybe jDate (after "jalali date", which I assume is the same as the Intl object's "persian" calendar) and implement methods there.
The Intl.DateTimeFormat constructor returns an object that has a formatToParts method that you can leverage to implement the Date methods you need, then you can work on a standard Date object underneath but return Jalali values from the methods. e.g. to get all the current date parts in English:

let f = new Intl.DateTimeFormat('en-GB-u-ca-persian',{
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: false,
});
console.log('Current Jalali date: ' + f.format(new Date()));

console.log('The parts:');
f.formatToParts(new Date()).forEach(part => console.log(part.type + ': ' + part.value));

For some things you have to run the format method more than once with different options, e.g. to get both the month name and number as both are specified by the month option: month: 'long' for the name and month: 'numeric' for the number.


text:
Q: SimpleDateFormat 24h I've got a SimpleDateFormat to parse a String into a Date:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");

When I'm parsing this:
format.parse("2011-08-29T12:44:00+0200");

The result will be, when using Date.toLocaleString:

29 aug. 2011 00:44:00

This should be ofcourse:

29 aug. 2011 12:44:00

And when I'm parsing this:
format.parse("2011-08-29T13:44:00+0200");

Then the result is as expected:

29 aug. 2011 13:44:00

How can I fix this?

A: Use HH instead of hh for the hours pattern:
H   Hour in day (0-23)  Number  0
k   Hour in day (1-24)  Number  24
K   Hour in am/pm (0-11)    Number  0
h   Hour in am/pm (1-12)    Number  12

A: java.time through desugaring
I suggest that you use java.time, the modern Java date and time API, for your date and time work.
Your string is in ISO 8601 format. Define a formatter for it:
private static final DateTimeFormatter ISO_FORMATTER
        = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                .appendOffset("+HHMM", "Z")
                .toFormatter(Locale.ROOT);

It could have been shorter with a format pattern string, but I prefer to reuse the built-in ISO_LOCAL_DATE_TIME, which already handles ISO 8601. As your question testifies, writing a format pattern string is error-prone. I have also specified that an offset of zero from UTC should be accepted as Z in accordance with ISO 8601 (the parser will accept +0000 too).
Parse like this:
    String isoString = "2011-08-29T12:44:00+0200";
    OffsetDateTime dateTime = OffsetDateTime.parse(isoString, ISO_FORMATTER);
    System.out.println(dateTime);

Output is:

2011-08-29T12:44+02:00

To obtain a string formatted for the user's locale use a second formatter:
private static final DateTimeFormatter LOCALE_FORMATTER
        = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);

We still need not write any format pattern string. Format like this:
    String localeString = dateTime.format(LOCALE_FORMATTER);
    System.out.println(localeString);

Output is exactly what it should be. I ran in nl_NL locale and got:

29 aug. 2011 12:44:00

Please skip the next section.
What if I need an old-fashioned java.util.Date?
No one should use the Date class anymore. Only if you indispensably need a Date for a legacy API that you cannot afford to upgrade to java.time right now, convert:
    Date oldfashionedDate = Date.from(dateTime.toInstant());
    System.out.println(oldfashionedDate);

Funnily output will be time zone dependent. In my time zone I got:

Mon Aug 29 12:44:00 CEST 2011

Question: Doesn't java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

*

*In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

*In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

*On older Android either use desugaring or the Android edition of ThreeTen Backport. It's called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*Wikipedia article: ISO 8601

*Java Specification Request (JSR) 310, where java.time was first described.

*ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

*Java 8+ APIs available through desugaring

*ThreeTenABP, Android edition of ThreeTen Backport

*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


text:
Q: Is a C++ reference to an object analogous to a double pointer in C? I am reading "Accelerated C++" by Koenig. In chapter 5, Koenig defines a function which has a reference to a vector parameter. In the function body, a new vector is created and assigned to the parameter.
Is a reference to an object analogous to a double pointer in C?
I am imagining a local variable which is a pointer to a data structure on the heap (a vector in this case). The address of this variable (a double pointer) is passed to a function and, in the function body, is dereferenced and assigned the address of a new data structure on the heap (in this case, a new vector).
I realize references have different properties than pointers and that references are not necessarily implemented as pointers. However, is the above a reasonable way to think about things?

A: A pointer is always a separate value, that is in the case of:
int x = 1;
int *y = &x;

There are two values here, x and y. These have different addresses such that:
&x != &y

In the case of references it's just a code alias, not an actual separate thing, so:
int x = 1;
int &y = x;

Where now you have two names for exactly the same thing:
&x == &y

As x and y are from that point forward effectively interchangeable.
Remember that pointers must be de-referenced to be used. A reference requires no such special handling.
Where there's similarity is that a pointer can be used to manipulate a shared value, or a pointer-pointer to manipulate a pointer, but there is a level of indirection that makes it different.
In C where you don't have references you use pointers instead, so you have functions like this:
void mutate(int* v);

Where that's a pointer meaning "mutable value", though in C++ it looks like:
void mutate(int& v);


text:
Q: VueJS failed to compile: dependency not found I have this file I am referencing in my VueJS project, that seems to cause a compilation error. The dependency is declared not found at the location, even though I can perfectly find it in my node_modules directories...
On the left of the picture are my directories, where you can see the desired file. At the bottom of the screen is my terminal, displaying the error. At the top of the screen is my import statement of the desired file.
I precise that typing the indicated command from npm fails, saying that the module has no package.json file.
Any advice or suggestion would be appreciated. Thank you in advance for passing by.

A: The file in node_modules is firestore_client.**d**.ts (note the "d" before the ".ts")
This is for type definition only so I doubt you can instantiate FirestoreClient importing this file.
If you really want to import this file, try adding the file extension in the import statement.


text:
Q: BigCommerce Stencil Custom Fields I currently have a use-case for a BigCommerce Stencil site where I have to display custom field values in various places on the Item Page. I know that I can use Handlebars to loop through the custom fields finding the specific one that I want, and then display it on the page. Does anyone have insight on how this will affect page speed? None of these loops will be nested or anything, there will just be multiple loops on the page.

A: We do this all the time, and several loops will not noticeably affect page speed. But if you do feel it's causing an issue, you can just loop through the custom_fields once, drop them in a json array, and use javascript loops to populate the data where necessary. We do this as well, because the supplied handlebars functions for conditionals and string replacement are so limited and it becomes much easier to handle it all with standard javascript.
<script>
var custom = [];
{{#each product.custom_fields}}
custom.push({'name':"{{name}}",'value':"{{value}}"});
{{/each}}
</script>


text:
Q: Automatically incrementing a build number in a Java project I'm using a versioning system that is represented by a.b.build where a is the overall version (will be 0 for prototype, alpha and beta versions, 1 for major release), b is the milestone version (along the lines of representing the proto, alpha, beta stages) and build represents literally the amount of times the project has been compiled.
At the moment, I have the app read from a text file, increment the number, and save to a text file when the app is run with a debug flag set.
I'm looking for a more "correct" way to do this using Java and Netbeans. Is there some way I can inject a build numberer into the build process somewhere? preferably saving the number into a source file that is shipped with the project - instead of relying on the existence of a nearby file.

A: You can use git commit count of the current branch as the build number. Use this command line to get the commit count: git rev-list HEAD --count.
Integrating with the build tools will be quite straightforward. If you are using Gradle then you can use this plugin: https://github.com/rockerhieu/Versionberg/

A: You can do it with without pom modification with the help of maven plugins and scripting.
For example to increment automatically the second digit of a version that doesn't have snapshot as prefix like in your case, on a linux system you can do :
#get the current pom version and store it into a variable
version=$(mvn -q -U -Dexpression=project.version -DforceStdout maven-help-plugin:evaluate)
#increment the second digit of the version and overwrite the variable
version=$(echo ${version} |  awk -F'.' '{print $1"."$2+1"."$3}' |  sed s/[.]$//)
#update the pom with the new version
mvn -U versions:set -DnewVersion=${version}

It works for versions with 3 digits but also 2 digits thanks to the sed.
Of course move the default increment part : "+1" on the digit that suits to your requirements :
# increment the first digit
awk -F'.' '{print $1+1"."$2"."$3}'

# increment the second digit
awk -F'.' '{print $1"."$2+1"."$3}'

# increment the last digit
awk -F'.' '{print $1"."$2"."$3+1}'

A: Nowadays I would recommend avoiding the Maven Release plugin, as well as the various handcrafted hacks mentioned in other answers.
Anything that results in file changes on a source code level is something that creates new commits and therefore needlessly pollutes your version history.
The only thing that should be responsible for managing version numbers for source code is your version control management system.
Git, in other words.
The good news is that there are a few very good options available, tools that will put your git tags in control of the version numbering instead of the other way around.
The one I would recommend in your case is jgitver, which supports both Maven and Gradle setups in the form of plugins and is very very configurable.
All you need to do is add some files to the root of your project, configure it to taste, and set your version number in pom.xml to 0. Done.
See jgitver usage, here.

A: There are a couple of popular Maven plugins that accomplish this feat:

*

*Maven Release Plugin

*Build Number Maven Plugin
The Maven Release Plugin from the Apache Maven Project is a bit overkill for simply updating the version number. Therefore use the latter plugin to create a version number (in the form of MAJOR.MINOR.BUILD; e.g., 3.1.4 where 4 is auto-incremented) as follows:

*

*Open the project's pom.xml file.

*Include the plugin within the build section (after the dependencies section):

  <scm>
    <connection>scm:svn:http://127.0.0.1/dummy</connection>
    <developerConnection>scm:svn:https://127.0.0.1/dummy</developerConnection>
    <tag>HEAD</tag>
    <url>http://127.0.0.1/dummy</url>
  </scm>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>buildnumber-maven-plugin</artifactId>
        <version>1.4</version>
        <executions>
          <execution>
            <id>buildnumber</id>
            <phase>validate</phase>
            <goals>
              <goal>create</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <format>{0,number}</format>
          <items>
            <item>buildNumber</item>
          </items>
          <doCheck>false</doCheck>
          <doUpdate>false</doUpdate>
          <revisionOnScmFailure>unknownbuild</revisionOnScmFailure>
        </configuration>
      </plugin>
    </plugins>
    <finalName>${project.artifactId}-${project.version}.${buildNumber}</finalName>
  </build>

*Ensure that the pom.xml defines the major and minor version in the version element near the top of the file. For example:

<version>3.1</version>

*Save the pom.xml file.

*Rebuild the project.

The version number should increase.

The plugin requires a configured source code management repository (<scm>) element. If you don't care about the repository check-in number use a dummy scm instead. This can be used to include the revision number from the repository, which is an exercise for the reader.

A: I have the some problem and using the answer of "Dave Jarvis". This adds the correct version and build number to the localy generated jar file like: myProject-3.1.1234.jar. But in the maven repository the artifact is installed as version "3.1" instead of (I have expected) "3.1.1234". The build number ist still missing there...
To install the artifact into the maven repository with the correct version and build number ("3.1.1234") you must do (additionally to the answer of "Dave Jarvis"):

*

*Adding a major/minor version property:

<properties>
  <!-- !!!!!!!!! SETTING HERE THE CORRECT MAJOR/MINOR VERSION NUMER !!!!!!!!!! -->
  <major.minor.version>1.0</major.minor.version>
</properties>

*Setting the correct version number to the artifact by using the nashorn-maven-plugin:

<!-- set "major.minor.revision" version -->
<plugin>
  <groupId>io.github.michaldo</groupId>
  <artifactId>nashorn-maven-plugin</artifactId>
  <version>0.0.1</version>
  <executions>
    <execution>
      <phase>validate</phase>
      <goals>
        <goal>eval</goal>
      </goals>
      <configuration>
        <script>
          $project.artifact.version = "${major.minor.version}.${buildNumber}";
        </script>
      </configuration>
    </execution>
  </executions>
</plugin>

After rebuilding/installing the project the artifact will be in the maven repository as version "3.1.1234" :-)
Please note: to increment the major or minor version you must only change the major.minor.version property!

A: Use the versions maven plugin via your CI/CD tool prior to the use case where you need your build incremented!
https://www.mojohaus.org/versions-maven-plugin/usage.html


text:
Q: Infer type of argument and return type based on other argument A function takes an object which can be either of TypeA or TypeB. The first parameter specifies the type of the object. The returned type also depends on this first parameter.
Problem: TypeScript does not infer the type of the object within a case (or within an if). The following code has errors.
I know I can fix this issue by be explicit about the types (add as TypeA) but I wanted to know if there are other solutions to avoid having to put the explicit cast.
type TypeA = {
  input: { foo: string }
  output: { foo: number }
}

type TypeB = {
  input: { bar: string }
  output: { bar: number }
}

type Types = {
  TypeA: TypeA
  TypeB: TypeB
}

type TypesName = keyof Types

/**
 * Takes TypeA or TypeB objects, and the return type is based on the type.
 */
function transform<N extends TypesName>(typeName: N, typeValue: Types[N]['input']): Types[N]['output'] {
  switch (typeName) {
    case 'TypeA':
      return transformTypeA(typeValue) // Argument of type '{ foo: string; } | { bar: string; }' is not assignable to parameter of type '{ foo: string; }'.
    case 'TypeB':
      return transformTypeB(typeValue) // Argument of type '{ foo: string; } | { bar: string; }' is not assignable to parameter of type '{ bar: string; }'.
  }
  throw new Error('Unknown type')
}

function transformTypeA(typeA: TypeA['input']): TypeA['output'] {
  return { foo: parseInt(typeA.foo) }
}

function transformTypeB(typeB: TypeB['input']): TypeB['output'] {
  return { bar: parseInt(typeB.bar) }
}

const transformedValue = transform('TypeA', { foo: 'lol' })
console.log(transformedValue) // transformedValue is of type { foo: number }

A: There is a way but it's probably not worth right now.
type Union<N extends keyof Types = keyof Types> = N extends N ? [typeName: N, typeValue: Types[N]['input']]: never;

function transform<N extends TypesName>(...p: Union<N>): Types[N]['output'] {
  switch (p[0]) {
    case 'TypeA':
      return transformTypeA(p[1])
    case 'TypeB':
      return transformTypeB(p[1])
  }
}

Playground Link
We need to use index access instead of defining separate parameters or destructuring the parameters as this is the only way typescript will see the two values are related. This might be supported at a later date as described here here

In particular, the pattern of destructuring a discriminant property and a payload property into two local variables and expecting a coupling between the two is not supported as the control flow analyzer doesn't "see" the connection.
For example:

type Data = { kind: 'str', payload: string } | { kind: 'num', payload: number };

function foo({ kind, payload }: Data) {
    if (kind === 'str') {
        payload.length;  // Error, payload not narrowed to string
    }
}

We may be able to support that pattern later, but likely not in this PR.

A: In TS 4.6 can use Wishlist: support for correlated union types #30581
type TypeA = {
  input: { foo: string }
  output: { foo: number }
}

type TypeB = {
  input: { bar: string }
  output: { bar: number }
}

type Types = {
  TypeA: TypeA
  TypeB: TypeB
}

type TypeMap = {
  TypeA: TypeA,
  TypeB: TypeB
};

type TypeMapAsGeneric<K extends keyof TypeMap = keyof TypeMap> = { [P in K]: TypeMap[P] }[K];

function transformTypeA(typeA: TypeA['input']): TypeA['output'] {
  return { foo: parseInt(typeA.foo) }
}

function transformTypeB(typeB: TypeB['input']): TypeB['output'] {
  return { bar: parseInt(typeB.bar) }
}

const transformers: { [K in keyof TypeMap]: (data: TypeMapAsGeneric<K>['input']) => TypeMapAsGeneric<K>['output'] } = {
  TypeA: transformTypeA,
  TypeB: transformTypeB
};

const transform = <K extends keyof TypeMap>(typeName: K, inputValue: TypeMapAsGeneric<K>['input']): TypeMapAsGeneric<K>['output'] => {
  const transformer = transformers[typeName];
  return transformer(inputValue);
}

const transformedValue = transform('TypeA', { foo: '123' })
console.log(transformedValue)

Playground link


text:
Q: How does one call a method with Tuples? I have a method that looks like the following:
public static IEnumerable<Tuple<double, double>> LargestTriangleThreeBuckets(List<Tuple<double, double>> data, int threshold)

How does one call such a method?  I currently have an array of doubles.  I have no experience with Tuples.  Thanks
Update: Many thanks to everyone. A little clarification: I am performing 16k fft's on a quadrature signal sampled at 192kHz. The resulting 16384 values need to be downsampled for the display which is typically less than 1920 pixels wide. To do this I have successfully implemented the LargestTriangleThreeBucket downsampling routine.  This routine is available on GitHub
I start with an array of doubles, outputBuffer[16384], put this in a Tuple list with x values going from 1 to 16384, and then call the method.
        var myList = new List<Tuple<double, double>>();

        for (int x = 0; x < fftOrder; x++)
        {
            myList.Add(new Tuple<double, double>(outputBuffer[x], x+1));
        }

        var result = LargestTriangleThreeBuckets(myList, 2048);

        temporaryBuffer = result.Select(item => item.Item1).ToArray();

        //output resulting buffer to the scope which is the user interface display of the signal

        scope1.Channels[0].Data.SetYData(temporaryBuffer, 0, fftOrder/8);

fftOrder is = 16384.  The code as is is executed in 1 millisecond, plenty fast enough for real time display. The result is a significant improvement over other methods of downsampling as far as I can determine.
Many thanks to all that helped here!

A: How about
var result = LargestTriangleThreeBuckets(
    new List<Tuple<double, double>>
        {
            Tuple.Create(0.0, 0.0),
            Tuple.Create(2.0, 1.0),
            Tuple.Create(0.0, 2.0)
        },
    42);

I think, the method you are looking for is Tuple.Create.

Just guessing but, PointF or something from System.Numerics.Vectors might be a better representation of the corner of a triangle than a Tuple<double, double>.

A: Tuples are just generic objects.  However you use the tuple, just imagine that you created a class with that many Items of the appropriate type.
For instance, Tuple< string, int, int> will give you myObj.Item1 as a string, and Items 2 and 3 as integer.  You can use it like this:
new Tuple<string, int, int>("Steve", 15, 22)

In the case of a list:
var myList = new List<Tuple<double, double>>();
myList.Add(new Tuple<double, double>(25, 23.333));
var result = LargestTriangleThreeBuckets(myList, 50);


text:
Q: Cannot make Nav Horizontal I've been working on this for ages and am trying everything under the sun to try to figure out how to make this navbar horizontal I've previously done it because I copied and pasted this from an old website I've done but it doesn't seem to be working. what am I doing wrong?  Ive done floating to the left display inline all that stuff. is it possible that I have something that could be overriding it?
PS. I'm working in Dreamweaver and using some of the bootstrap codings if that helps.

home

menu

about

webshop

/Nav Formatting/
.navbar-nav {
  width: 20%;
text-align: center;
}

.navbar-nav > li {
  float: right;
  display: inline-block;
}
.navbar-nav .nav > lu {
  float: right;
  display: inline;
}

/Nav Formatting: Hover animation/
.navbar-nav li {
  position: relative;
  float: left;
  margin: 0 20px;
}

.navbar-nav li:before {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:after {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  right: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:hover:before, li:hover:after {
  height: 100%;
}

.navbar-nav li:hover a {
  background-color: transparent;
  -webkit-transition: background-color 0.4s ease 0.4s;
  transition: background-color 0.4s ease 0.4s;
}

.navbar-nav li:hover a:before, li:hover a:after {
  width: 100%;
}

.navbar-nav a {
  display: inline;
  padding: 0 40px;
  height: 100%;
  font-weight:normal;
  font-size: 18px;
  line-height: 60px;
  color: #ABE1DB;
  text-decoration: none;
  -webkit-transition: background-color 0.4s ease;
  transition: background-color 0.4s ease;
}
.navbar-nav a:before {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

.navbar-nav a:after {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

A: You have set
.navbar-nav{
     width: 20%;
}

How can it expand? Try
.navbar-nav {
    width: 100%;
}

/*Nav Formatting*/

.navbar-nav {
  width: 100%;
  text-align: center;
}

.navbar-nav>li {
  float: right;
  display: inline-block;
}

.navbar-nav .nav>lu {
  float: right;
  display: inline;
}

/*Nav Formatting: Hover animation*/

.navbar-nav li {
  position: relative;
  float: left;
  margin: 0 20px;
}

.navbar-nav li:before {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:after {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  right: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:hover:before,
li:hover:after {
  height: 100%;
}

.navbar-nav li:hover a {
  background-color: transparent;
  -webkit-transition: background-color 0.4s ease 0.4s;
  transition: background-color 0.4s ease 0.4s;
}

.navbar-nav li:hover a:before,
li:hover a:after {
  width: 100%;
}

.navbar-nav a {
  display: inline;
  padding: 0 40px;
  height: 100%;
  font-weight: normal;
  font-size: 18px;
  line-height: 60px;
  color: #ABE1DB;
  text-decoration: none;
  -webkit-transition: background-color 0.4s ease;
  transition: background-color 0.4s ease;
}

.navbar-nav a:before {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

.navbar-nav a:after {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

home

menu

about

webshop

A: Your ul is to small. That's why it will press it together. Try
ul.nav.navbar-nav {
    width:100%;
}

A: *

*The outer container .navbar-nav was styled with 20% width. This forced the inner elements to wrap because there was not enough space. A width of 100% is not need here because  is an block element.

*If you only have 4 four inner elements, you can give them a width of 25% combined with floating left to stack them next to each other.

*Add a clearfix class or overflow:hidden (quick and dirty!) to the outer container to make sure it visally wraps the inner elements.

*Please see my updated code snippet for reference:

/*Nav Formatting*/

.navbar-nav {
}

.navbar-nav li {
  width: 25%;
  float: left;
  padding: 0;
  margin: 0;
  list-style: none;
  text-align: center;
}

.navbar-nav .nav > ul {
  float: right;
  display: inline;
  margin: 0;
}

/*Nav Formatting: Hover animation*/

.navbar-nav li {
  position: relative;
}

.navbar-nav li:before {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:after {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  right: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:hover:before,
li:hover:after {
  height: 100%;
}

.navbar-nav li:hover a {
  background-color: transparent;
  -webkit-transition: background-color 0.4s ease 0.4s;
  transition: background-color 0.4s ease 0.4s;
}

.navbar-nav li:hover a:before,
li:hover a:after {
  width: 100%;
}

.navbar-nav a {
  display: inline;
  padding: 0 40px;
  height: 100%;
  font-weight: normal;
  font-size: 18px;
  line-height: 60px;
  color: #ABE1DB;
  text-decoration: none;
  -webkit-transition: background-color 0.4s ease;
  transition: background-color 0.4s ease;
}

.navbar-nav a:before {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

.navbar-nav a:after {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

home

menu

about

webshop

A:

/*Nav Formatting*/

.navbar-nav {
  width: 100%;
  text-align: center;
}

.navbar-nav >li {
  float: right;
}

.navbar-nav .nav > ul {
  float: right;
}

/*Nav Formatting: Hover animation*/

.navbar-nav li {
  position: relative;
  margin: 0 20px;
}

.navbar-nav li:before {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:after {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  right: 0;
  width: 2px;
  height: 0;
  background-color: #ABE1DB;
  -webkit-transition: height 0.4s ease 0.4s;
  transition: height 0.4s ease 0.4s;
}

.navbar-nav li:hover:before,
li:hover:after {
  height: 100%;
}

.navbar-nav li:hover a {
  background-color: transparent;
  -webkit-transition: background-color 0.4s ease 0.4s;
  transition: background-color 0.4s ease 0.4s;
}

.navbar-nav li:hover a:before,
li:hover a:after {
  width: 100%;
}

.navbar-nav a {
  display: inline;
  padding: 0 40px;
  height: 100%;
  font-weight: normal;
  font-size: 18px;
  line-height: 60px;
  color: #ABE1DB;
  text-decoration: none;
  -webkit-transition: background-color 0.4s ease;
  transition: background-color 0.4s ease;
}

.navbar-nav a:before {
  content: '';
  display: inline;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

.navbar-nav a:after {
  content: '';
  display: inline;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 0;
  height: 2px;
  background-color: #ABE1DB;
  -webkit-transition: width 0.4s ease;
  transition: width 0.4s ease;
}

home

menu

about

webshop


text:
Q: Parameters of ajax request don't change I' m using cms ModX and want to send Ajax request to server using post method. The problem is that  the post data of the second, the third and so one requests doesn't  change and remains the same as in the first request.
To clarify the situation I provide the following example.
The javascript is the following:
var reqCount = 0;
$(document).ready(function () {
    $(window).scroll(function() {

    var dataToPost = {'reqCount' :reqCount};
    $.ajax({
        url:  'http://example.com/ajaxTest',
        method: 'POST',
        data: dataToPost,
        dataType:"json",
        success:  function(data){

            ajaxCountFromServer = data['ajaxCount'];

            reqCount=reqCount+1;
            }

        });
     }

}

Also I created resource with address http://example.com/ajaxTest in Modx with the code, running the snippet:
[[getAJAX]]

getAJAX snippet is the following:
<?php
    if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {

       $reqCount = $_REQUEST['reqCount'];

       $json_obj = array("ajaxCount" =>$reqCount);
       return json_encode($json_obj);
    }
?>

So, after the first scroll reqCount=0, it's passed to server and after the server responses(success callback) ajaxCountFromServer=0 and reqCount=1. There all works well.
However, after the second scroll reqCount=1 and after the server response ajaxCountFromServer=0,but it should be 1.
How to fix it?

A: The solution is quite simple. In the page customizing of the resource http://example.com/ajaxTest,  where snippet getAJAX is called,  I just unchecked the checkbox "Cacheable".

A: The correct way to do it is
[[!getAJAX]]

The snippet is not cached now


text:
Q: Show Elements Verticaly by CSS i have a list like this:

One

Two

Three

Four

Five

Six

and i want to show them like this picture

*that way In the beginning Fill in the first column and then second and etc.

A: Use column-count:

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  column-count: 2;
}

One

Two

Three

Four

Five

Six

My colomns number is dynamic and may change. But there are 3 items in one column(max).

Use flex:

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  height: 60px; /* 60 / 3 = 20 */
  display: flex;
  flex-flow: column wrap;
}

ul > li {
  height: 20px;
}

1

2

3

4

5

6

7

8

9

10

11

12

However, you'll have to add some fixed height.

A: With jQuery, you can make this dynamic.

$(document).ready(function() {
  var items = $("ul li").length;
  $("ul").css("column-count", Math.ceil(items / 3));
});
ul {
  list-style-type: none;
}

One

Two

Three

Four

Five

Six

If you want this in pure JS

var list = document.querySelector("ul");
var items = document.querySelectorAll("ul li").length;
list.setAttribute("style", "column-count :" + Math.ceil(items / 3));
ul {
  list-style-type: none;
}

One

Two

Three

Four

Five

Six

A: Try below:
https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_columns

ul {columns: 2;
  -webkit-columns: 2;
  -moz-columns: 2;}
ul li {list-style:none;}

One

Two

Three

Four

Five

Six


text:
Q: Transcations, API's and Designing for Failure I have been working on an application that needs to log credit card transactions which is dependent on using an external API. Within my application, I have the concept of an invoice with a total, and a transaction that when successful credit card payment is made, deducts from this total.
This is more of a platform independent question, but I am working with Django, Python and MySQL.
My question centers mainly around the use of transactions when dealing with external API's and how to design your software to handle potential failures. Both Django and MySQL support transactions, so that in itself is not an issue, but suppose the following scenario:

*

*Credit card submitted though the payment API

*Credit card is successfully processed

*This response is then logged to the database as a payment on that invoice

*There is an error saving the payment to the database for one reason or another

What do you do now?
If there was not an API call involved the answer would be clear, rollback the database transaction and raise an error. But having a call to an external API complicates matters, because this is not really a way to rollback on the external API call.
I am interested if anyone has run into this issue (for credit cards, or similar types of transactions) and how they addressed the problem, or in general some approaches for software design in this case.

A: It's hard to manage this in software. However, if your payment gateway is calling a callback to signify that the transaction is successful, it will presumably log an error if that callback fails to complete, and you should be able to configure it to alert you in that case, perhaps by email. Then it's up to you to rectify the situation manually.


text:
Q: Determine whether or not the function is coercive Determine whether or not the function is coercive.
$$f(x_1,x_2)=e^{x_1^2}+e^{x_2^2}-x_1^{200}-x_2^{200}$$
Intuitively, I know that this function is coercive because, for large enough $x_i$, we have that $e^{x_i^2}$ grows faster than $x_i^{200}$, and so if the norm of $x$ approaches infinity, then the function will also approach infinity. However, this is not rigorous enough to show that the function is coercive.
Could I get some help on proving that this function is coercive?


text:
Q: Qt Android notification, Cannot set image I am making an Android testapp in Qt using Java libraries for the notifications. Following the Qt Notifier example im trying recreate the same notification for starters but for some reason this line does not work:
m_builder.setSmallIcon(R.drawable.icon);

it says:
java:77: error: error: package R does not exist

I have tried adding:
import java.lang.Object;
import android.R.drawable;

I have also tried:
m_builder.setSmallIcon(android.R.drawable.icon);

but this gives me the error:
java:77: error: error: cannot find symbol

So I have checked the Qt Notifier app and I dont think i have made any mistakes but for some reason it won't work.
My question is: How do I set this icon correctly?
Here is the full piece of code:
package org.qtproject.qt5.example;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import java.lang.Object;
import java.lang.Throwable;
import java.io.Writer;
import java.io.StringWriter;
import java.io.PrintWriter;

import android.R.drawable;

public class NotificationClient extends org.qtproject.qt5.android.bindings.QtActivity
{
    private static NotificationManager m_notificationManager;
    private static Notification.Builder m_builder;
    private static NotificationClient m_instance;

    public NotificationClient()
    {
        try {
            m_instance = this;
        } catch(Throwable t) {
            t.printStackTrace();
        }
    }

    public static void notify(String s)
    {
        try {
            if (m_notificationManager == null) {
                m_notificationManager = (NotificationManager)m_instance.getSystemService(Context.NOTIFICATION_SERVICE);
                m_builder = new Notification.Builder(m_instance);
                m_builder.setContentTitle("A message from Qt!");
                //m_builder.setSmallIcon(android.R.drawable.icon);
            }

            m_builder.setContentText(s);
            m_notificationManager.notify(1, m_builder.build());

        } catch(Throwable e) {
            e.printStackTrace();
        }
    }
}

A: The problem for me was because of a wrong configuration in AndroidManifest.xml.
After editing the AndroidManifest correctly and cleaning and rebuilding the project, the problem was solved.

A: To fix this error make sure that package name in your java class and your AndroidManifest.xml are the same.
NotificationClient.java:
package com.mypackage;
...

AndroidManifest.xml:
<manifest package="com.mypackage"...
...


text:
Q: listview cell factory artifacts I am using the JavaFX ListView component and want to use a custom cell factory. When the dialog containing the list view is opened the items are rendered correctly. However, if I try to add or delete an item from the underlying observable list, the items in the list view are not rendered correctly. I will have cells duplicated or missing altogether. Here is the FXML for my custom cell:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<?import org.controlsfx.glyphfont.Glyph?>

<VBox fx:id="vbox" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="150.0" prefWidth="300.0" spacing="5.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <padding>
      <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
   </padding>
   <children>

         <graphic>
            <Glyph fontFamily="FontAwesome" icon="PHONE" />
         </graphic>

         <graphic>
            <Glyph fontFamily="FontAwesome" icon="ENVELOPE" />
         </graphic>

   </children>
</VBox>

and here is my custom ListCell subclass:
/**
 *
 * @author Stephen
 */
public class MemberListViewCell extends ListCell<MemberEntity> {

    @FXML
    private Label nameLabel;

    @FXML
    private Label mobileLabel;

    @FXML
    private Label emailLabel;

    @FXML
    private Label churchMemberLabel;

    @FXML
    private VBox vbox;

    private FXMLLoader loader;

    public MemberListViewCell() {
    }

    @Override
    protected void updateItem(MemberEntity item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setText(null);
        } else {
            if (loader == null) {
                loader = new FXMLLoader(getClass().getResource("/fxml/listcell.fxml"));
                loader.setController(this);
                try {
                    loader.load();
                } catch (IOException ex) {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("Open FXML");
                    alert.setHeaderText("FXML Error");
                    String msg = "Could not load FXML for list cell factory. Inform software engineer. Terminating program.";
                    msg += ex.toString();
                    alert.setContentText(msg);
                    alert.showAndWait();
                    System.exit(1);
                }
            }

            nameLabel.setText(item.getName().getFormattedName(Name.NameFormat.FORENAME_SURNAME));
            mobileLabel.setText(item.getMobileTelephone());
            emailLabel.setText(item.getEmailAddress());
            if (item.isChurchMember()) {
                churchMemberLabel.setText("Church Member");
                churchMemberLabel.setTextFill(Paint.valueOf("#388e3c"));
            } else {
                churchMemberLabel.setText("Not Church Member");
                churchMemberLabel.setTextFill(Paint.valueOf("#d32f2f"));

            }

            setText(null);
            setGraphic(vbox);

        }
    }
}

A: Since you set the graphic for non-empty cells, you need to set it back to null if the cell becomes empty:
@Override
protected void updateItem(MemberEntity item, boolean empty) {
    super.updateItem(item, empty);
    if (empty || item == null) {
        setText(null);
        setGraphic(null);
    } else {
        // existing code ...
    }
}


text:
Q: python boto3 enter tag name then convert that to ARN how do i use boto3 to get the ARN of a storage gateway by inputting the name?
like this
SG_NAME = input("Enter Storage Gateway name: ")

print(SG_ARN)

any idea how to convert the Name to ARN?

A: Looking at the docs, I believe you will have to call list_gateways() and iterate over the response in your Python code until you find a gateway with the name that matches what the user entered.


text:
Q: Why does my javascript code not work? I create new.html and new.js files .
new.html codes :
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>Untitled Document</title>

                6

                    <select id="seconde">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                    </select>

                X

And new.js codes:
$(document).keyup(function () {
    $(document).change(function () {
        var first= document.getElementById('first').innerHTML;
        var seconde= document.getElementById('seconde').value;
        var third= parseInt(first) * parseInt(seconde);
        document.getElementById('third').innerHTML = third;
    });
});

When I select a number, X not changed.
For example I want replace number 30 with X when I select 5 in select section . But X not change . How can I do that ?

A: your event bindings seem to be wrong... You need to bind to the change event on the select.
I think this is what you want:

    $('#seconde').change(function () {
        var first= document.getElementById('first').innerHTML;
        var seconde= document.getElementById('seconde').value;
        var third= parseInt(first) * parseInt(seconde);
        document.getElementById('third').innerHTML = third;
    });

                6

                    <select id="seconde">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                    </select>

                X

A:

$('#seconde').on('change',function () {
        var first= document.getElementById('first').innerHTML;
        var seconde= document.getElementById('seconde').value;
        var third= parseInt(first) * parseInt(seconde);
        document.getElementById('third').innerHTML = third;
});
<!DOCTYPE html>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>Untitled Document</title>

 6	  <select id="seconde"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> 	 X

A: You have to add the change handler onDocumentReady because in the select drop-down you don't type anything , has no sense to add the handler on keyup event

$(document).ready(function () {
    $(document).change(function () {
        var first= document.getElementById('first').innerHTML;
        var seconde= document.getElementById('seconde').value;
        var third= parseInt(first) * parseInt(seconde);
        document.getElementById('third').innerHTML = third;
    });
});
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>Untitled Document</title>

                6

                    <select id="seconde">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                    </select>

                X


text:
Q: Dual of homogeneous Besov space I am trying to prove a trace theorem from the homogeneous Besov space $\overset{\cdot}{B}_{2,1}^{1/2}(\mathbb{R}^n)$ to $L^2(K)$, where $K$ is a compact euclidean hypersurface. The homogeneous Besov space is defined by the semi-norm $$||u||_{\overset{\cdot}{B}_{2,1}^{1/2}}=\sum_{l\in\mathbb{Z}}2^{l/2}||P_l\,u||_{L^2},$$ where $P_l$ is the $l^{th}$ Littlewood-Paley projector.
I want to prove the trace estimate via duality, would it be safe to say that its dual is $\overset{\cdot}{B}_{2,\infty}^{-1/2}$? This space would be defined by the semi-norm
$$||u||_{\overset{\cdot}{B}_{2,\infty}^{-1/2}}=\sup_{l\in\mathbb{Z}}2^{-l/2}||P_l\,u||_{L^2}.$$
Thank you.


text:
Q: Using for loops (with Tuples in them) to populate a Tuple array So I'm making a card game and I need an array with 3 strings and a bool in it for each card and when I run the programme it creates two instances of Aces for each Suit and I don't why, probably missing something really obvious but I have no clue why it's doing that.
class Deck
    {
    Tuple<string, string, string, bool>[] DeckArray = new Tuple<string, string, string, bool>[56];

    public void DeckArrayAssigner()
    {
        string Number, Suit, Card;
        int Count = 0;
        int A = 1;
        int B = 1;

        for (Tuple<int, int> Assigner = new Tuple<int, int>(A, B); Assigner.Item2 <= 3; Assigner = new Tuple<int, int>(A, B++))
        {
            for (Assigner = new Tuple<int, int>(A, B); Assigner.Item1 <= 13; Assigner = new Tuple<int, int>(A++, B))
            {
                Number = NumericNumberSwitch(Assigner.Item1);
                Suit = NumericSuitSwitch(Assigner.Item2);
                Card = (Number + " of " + Suit);
                DeckArray[Count] = new Tuple<string, string, string, bool>(Number, Suit, Card, true);
                Count++;
                Console.WriteLine(Card);
            }
            Console.WriteLine();
            Assigner = new Tuple<int, int>(A = 1, B);
        }
    }

    public string NumericNumberSwitch(int NumericNumber)
    {
        string Number;
        switch (NumericNumber)
        {
            case 1: Number = "Ace"; break;
            case 2: Number = "Two"; break;
            case 3: Number = "Three"; break;
            case 4: Number = "Four"; break;
            case 5: Number = "Five"; break;
            case 6: Number = "Six"; break;
            case 7: Number = "Seven"; break;
            case 8: Number = "Eight"; break;
            case 9: Number = "Nine"; break;
            case 10: Number = "Ten"; break;
            case 11: Number = "Jack"; break;
            case 12: Number = "Queen"; break;
            case 13: Number = "King"; break;
            default: Number = "???"; break;
        }
        return Number;
    }

    public string NumericSuitSwitch(int NumericSuit)
    {
        string Suit;
        switch (NumericSuit)
        {
            case 1: Suit = "Hearts"; break;
            case 2: Suit = "Diamonds"; break;
            case 3: Suit = "Clubs"; break;
            case 4: Suit = "Spades"; break;
            default: Suit = "???"; break;
        }
        return Suit;
    }
}

Output is as follows:
Ace of Hearts
Ace of Hearts
Two of Hearts
Three of Hearts
Four of Hearts
Five of Hearts
Six of Hearts
Seven of Hearts
Eight of Hearts
Nine of Hearts
Ten of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts

Ace of Diamonds
Ace of Diamonds
Two of Diamonds
Three of Diamonds
Four of Diamonds
Five of Diamonds
Six of Diamonds
Seven of Diamonds
Eight of Diamonds
Nine of Diamonds
Ten of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds

Ace of Clubs
Ace of Clubs
Two of Clubs
Three of Clubs
Four of Clubs
Five of Clubs
Six of Clubs
Seven of Clubs
Eight of Clubs
Nine of Clubs
Ten of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs

Ace of Spades
Ace of Spades
Two of Spades
Three of Spades
Four of Spades
Five of Spades
Six of Spades
Seven of Spades
Eight of Spades
Nine of Spades
Ten of Spades
Jack of Spades
Queen of Spades
King of Spades

A: You can simplify your code a lot by replacing switch statements with arrays, dropping unnecessary use of tuples in your loops, and running simple loops to iterate the arrays:
static readonly string[] Ranks = new[] {"Ace", "Two", ..., "King"};
static readonly string[] Suits = new[] {"Hearts", ..., "Spades"};
...
int pos = 0;
foreach (rank in Ranks) {
    foreach (suit in Suits) {
        DeckArray[pos++] = Tuple.Create(rank, suit, $"{rank} of {suit}", true);
    }
}

Note: You would be much better off creating a class Card for the individual cards, because card.Rank and card.Suit read a lot better than card.Item1 and card.Item2.


text:
Q: Usage of 'Those' who/'Those students who'/'students who' I have question related to grammar. Can I change the phrase "those who" With "Those students who" and "Students who" In the following context?
Here is the example:
1-Dear students, On 26 th December, Tuesday We have arranged a blood donation camp on the campus . Those who are intersted in donating blood may please contact John Dayal, the principal of Xyz college.
I think the phrase 'those who' can be replaced with "those students who" and "students who". If I replace it, will that be grammatical? Can any native speaker please answer this?

A: "Those" simply stands in place of a particular noun. You can surely use "those who", "those students who" or "students who" and none of them will be a mistake. Look at these examples:

*

*We have many students in our class. Those who come from rich families have better books and clothes. ('Those' refers to 'students')
if you change "those who" to "those students who" or "students who" you simply repeat the particular noun again. The word "those" already substitutes for "students".
"those [noun]" is really okay if you are going to speak about a different particular noun or you're including something within the original substitution:

*

*We have many students in our class. Those of us who come from rich families have better books and clothes. (Here you mention that you too are with the students who are rich.)


text:
Q: What happens to the left hand side std::vector resources on move assignment? I was trying to find out if it's granted by the C++ 11 standard that the resources of a std::vector receiving a move assignment are freed.
I'll give you an example:
std::vector<int> a {1, 2};
std::vector<int> b {3, 4};
a = std::move(b);

Now what I'd be expecting is that both a and b are wrapping a regular array (usually) and they have a pointer to it, namely a_ptr and b_ptr. Now I think the move assignment among other things does a_ptr = b_ptr. Does the standard guarantee that the memory in a_ptr is freed before or by this?

A: By taking a look at Table 71: Container requirements it is stated that container's internal structure will be destroyed.
a = rv => All existing elements of a are either move assigned to or destroyed
As Howard Hinnant has mentioned in the comments, there is a special case which has also been stated in above sentence:

All existing elements of a are either move assigned to or
  destroyed.

This spacial case is related to move-assignment operator and simply has 3 different states:

*

*propagate_on_container_move_assignment is true in lhs:
In this case allocated memory in lhs is freed and the move operation is done. The allocator is also move assigned.

*propagate_on_container_move_assignment is false in lhs and the allocators from both sides are equal:
In this case same sequence of operations is done except that there is no need to assign to the lhs allocator.

*propagate_on_container_move_assignment is false in lhs and the allocators from both sides are not equal:
In this case because two allocators are not equal the allocator of lhs container cannot be used to manage the memory of the rhs container so the only option is to move assign rhs container items to the lhs container.
The last case explains why items in lhs container can be move assigned to. In any case the memory will be freed, reused or reallocated.


text:
Q: Ranking Number Array Values I've got an array of numbers and I'd like to display them in descending order but as a rank (1st, 2nd, 3rd, etc) instead of their number values while taking ties (equal number values) into consideration.
I've got the sorting as follows:
function mySorting(a, b) {
        a = a;
        b = b;
        return a == b ? 0 : (b < a ? -1 : 1)
    }

Which works fine with the call:
var myArray=[28,92,12,12,2];
myArray.sort(mySorting);

Can anyone point me in the right direction as to how I would then rank the values of myArray with 1st, 2nd, 3rd, etc. taking ties into account?
Thanks much in advance.

A: If you are using jQuery you can take advantage of 2 array methods $.inArray() and $.grep
Create an array of the unique values to use for rank:
var ranks = $.grep(myArray, function(item, idx) {
    return item != myArray[idx - 1];
}).reverse();/* your sort function is descending I added reverse to the ranks , remove if needed*/

Useage:
$.each(myArray, function(idx, item) {
    var rank= $.inArray( item, ranks)+1;/* index position and add one for 1st,second etc*/
    $('body').append('Rank of '+item+ ' is '+ rank+'<br>')

})

DEMO: http://jsfiddle.net/XWs5j/1/
API References:
http://api.jquery.com/jQuery.grep/
http://api.jquery.com/jQuery.inArray/
EDIT: Additional demo to create array of "ties" and modify output for values that tie
http://jsfiddle.net/XWs5j/2/


text:
Q: How to Parse Columns From Text Strings Using T-SQL I used C# to extract text from a PDF file containing health care provider information and then dumped that data into a SQL table for staging but I'm having challenges parsing the data.
There are 6 columns total to parse out:
[NPI],[Legal Name], [Service Address], [Effective Date], [End Date], [Comments]
[End Date] and [Comments] columns are nullable so there may or may not be data in those two columns. I was able to parse out the [NPI] and [Legal Name] so far but not so much anything else yet.
Because of the way the PDF is rendered, sometimes information can fall to a 2nd or 3rd line if all the text doesn't fit on the first line of that record. When that occurs, I need to concatenate that fragmented record(s) with the last record of the sequence.
For example, for record #4 the value 'Only' should be concatenated with record #3 which should read as "Payment Suspension Only". This value is the [Comment] for that particular line. The entire line should look like this before actually getting parsed into columns:
1414141414 All Health Community Health Center 7300 Santa Clause Avenue, Huntington Beach, CA 90255
7/5/2019 Payment Suspension Only

Another example, record #7 and #8 should be concatenated with record #6. So the entire line should look like this:
 1212131415 Desert Cities Midwifery dba Desert Cities Midwifery and Women's Health Care 1224 E
 Wardlow Rd, Long Desert, CA 92881-7262 5/12/2021

Last example of this occurring is records 21,22,and 23. Record #22 and #23 need to be concatenated with record #21 so it should look like this:
 1877808933 SQUARE OF TRUST INC 5755 Mountain Road Room 222 & C106 & Nurse''s Office, Los
 Angeles, CA 90028 12/20/2013

Here is the test data:
IF OBJECT_ID('tempdb..#T') IS NOT NULL
DROP TABLE #T
CREATE TABLE #T (ID INT,TXT VARCHAR(MAX))
INSERT #T
SELECT '1', 'NPI Legal Name Service Address Effective Date End Date Comments' UNION
SELECT '2', '1003889502 Hachi, Vendog 1000 Bontpeliar Dr., Suite 9, Modesto, CA 95555-1216 5/11/2019' UNION
SELECT '3', '1414141414 All Health Community Health Center 7300 Santa Clause Avenue, Huntington Beach, CA 90255 7/5/2019 Payment Suspension' UNION
SELECT '4', 'Only' UNION
SELECT '5', '1515151515 Desert Cities Midwifery dba  Desert Side Birth Center Long 1224 E Wardlow Rd, Long Desert, CA 90807-4833 5/12/2021' UNION
SELECT '6', '1212131415 Desert Cities Midwifery dba Desert Cities Midwifery and Women''s' UNION
SELECT '7', 'Health Care' UNION
SELECT '8', '23141 Moulton Pkwy, 108, Laguna Hills, CA 92653-1241 5/12/2021' UNION
SELECT '9', '1467590901 Desert Cities Midwifery dba Desert Cities Midwifery and Women''s' UNION
SELECT '10',    'Health Care' UNION
SELECT '11',    '32326 Coast Hwy, Suite G, Laguna Desert, CA 92651-6700 5/12/2021' UNION
SELECT '12',    'Restricted ProvidersNPI Legal Name Service Address Effective Date End Date Comments' UNION
SELECT '13',    '1313131313 Desert Cities Midwifery dba Desert Cities Midwifery and Women''s' UNION
SELECT '14',    'Health Care' UNION
SELECT '15',    '1224 E Wardlow Rd, Long Desert, CA 92881-7262 5/12/2021' UNION
SELECT '16',    '1423596601 Desert Cities Midwifery dba Desert Cities Midwifery and Women''s' UNION
SELECT '17',    'Health Care' UNION
SELECT '18',    '1222 New Rascal Rd, Riverside, CA 92000-7262 5/12/2021' UNION
SELECT '19',    '1356331573 Desert Cities Midwifery dba Desertside Birth Center 23141 Moulton Parkway, Suite 208, Laguna Hills, Ca 92653-1241 5/12/2021' UNION
SELECT '20',    '1003206681 Desert Cities Midwifery dba Desertside Birth Center 1353 Old Temescal Rd, Suite 203, Corona, CA 92881-7262 5/12/2021' UNION
SELECT '21',    '1877808933 SQUARE OF TRUST INC 5755 Mountain Road Room 222 & C106 & Nurse''s Office, Los Angeles, CA' UNION
SELECT '22',    '90028' UNION
SELECT '23',    '12/20/2013' UNION
SELECT '24',    '1902223666 SQUARE OF TRUST INC 651 Glenwood Road Rooms 2101 & 2115, Glendale, CA 91202 12/20/2013' UNION
SELECT '25',    '1566664665 SQUARE OF TRUST INC 928 N Avenue 53 Room 1 & 3, Los Angeles, CA 90022 12/20/2013'

SELECT * FROM #T
ORDER BY ID

SELECT
 [NPI] = CASE WHEN TXT LIKE '%[0-9]%' THEN SUBSTRING(TXT,1,10) END
,[Legal Name] = CASE WHEN SUBSTRING(TXT,12,1) LIKE '%[A-Z]%' THEN SUBSTRING(TXT,-1+PATINDEX('%[A-Z]%',TXT),PATINDEX('%[0-9]%', SUBSTRING(TXT,12,61))) END
,[Service Address] = ''
,[Effective Date] = ''
,[End Date] = ''
,[Comments] = ''
,*
FROM #T
ORDER BY ID