text:
Q: Data not transferred between 2 forms using php-echo I am working on making update functionality in an html form. I am sending data from one form to other through echo to be updated. But I am not able to populate other from catching the data send from 1st form.
The field id text box is blank.
Here is my code:
Sent key from from 1:

    <?= $row['field_id'] ?>
    <?= $row['description'] ?>
    <?= $row['corner_points'] ?>
    <?= $row['notes'] ?>
    <a target="_blank" href="Edit/edit-field.php?field_id=<?php echo $row['field_id'];?>">Edit

to receive data edit-field.php:
<?php

    if(isset($GET["field_id"]))
      {
       $field_id = $GET["field_id"];
      }

     try {
            $stmt = $conn->prepare("SELECT field_id, description, corner_points, notes FROM fields where field_id = $field_id");
            $stmt->execute();

            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $result = $stmt->fetchAll();
        }

        catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
        }
        ?>

   <form action="" method="post" class="needs-validation" novalidate enctype="multipart/form-data">

 Field

      Field ID
      <input type="number" class="form-control" name="field_id" id="field_id" value="<?php echo $result["field_id"];?>">

  <button class="btn btn-primary btn-sm" name="submit1" type="submit">Update Records</button>
</form>

A: In edit-field.php the variable for parameters passed via the URL is $_GET not $GET.
Change the start of that file to:
if(isset($_GET["field_id"])) {
   $field_id = $_GET["field_id"];
}

A: wouldn't you have to do a loop to fetch results? just like this example :
    <?php
// $pdo est un objet PDO
try{
    $stmt = $pdo->query('SELECT * FROM table');
    $rows = $stmt->fetchAll();
}
catch(Exception $e)
{
    exit('Catched exception at line '. $e->getLine() .' (code : '. $e->getCode() .') : '. $e->getMessage());
}
foreach($rows as $row) {
    var_dump($row);
    echo '
';
}


text:
Q: How to kill travis build with exit code 0 using command? Presently we are facing build failure problem in Travis because of https://github.com/travis-ci/travis-ci/issues/7702. I was just wondering if Travis has any command line option to kill it with exit code 0, then I can force travis to terminate 'after_success'. Will be a hacky way to deal with this situation until they solve this bug.

A: The shell function travis_terminate will help.
Alternatively, you can ensure to do set +e before the call to exit.
travis_terminate 0 is the best solution at the moment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: algorithm for alphabetical insert - special case I was getting an error of d.tagName is undefined in the code below.  This would happen when I inserted a new element into a list in alphabetical order and it was greater then the last element in the list.  In this case it should be inserted at the end of the list.  e and b are the elements to be inserted and d is the element they are to be inserted before in order to maintain alphabetical order.  It works fine except for the case I mentioned where the elements are the last in the list.
  while(d=d.nextSibling)
    {
    if(d.tagName=="undefined")
      {
      a.insertBefore(e,d);
      a.insertBefore(b,d);
      break;
      }
    else if(d.tagName.toLowerCase()==="a" && (b.innerHTML<d.innerHTML))
      {
      d=d.previousSibling;
      a.insertBefore(e,d);
      a.insertBefore(b,d);
      break;
      }
    }
    return 1;

A: Algorithm is thus (is pseudo code)
set inserted to false
go through the list
if the current item of the list is alphabetic comes after the one to be inserted
then
insert it before
mark it as inserted ie inserted is true

If after going though the whole list (ie inserted is false) then just append it to the list


text:
Q: Cygwin from Windows is very slow/ laggy Suddenly all Cygwin commands I start from the Windows command line have a ~10-20 second lag
before they execute, so that Cygwin becomes totally unusable. I already tried to reinstall without success.
Executing the commands from within a Bash shell window, works fine (while starting Bash I see the lag). Removing all entries from my local PATH variable doesn't have an influence. I use Windows 7 x64 and Cygwin x64 v 1.7.34 (0.285/5/3).

A: Occasionally I work in a Windows domain with thousands of users.
I don't want to do any best-guess approach. I would prefer Cygwin to cache user information on an as-needed basis. It turns out this is easy to do.
Simply run cygserver on login.
To set this up properly, run cygserver-config once only. This will set up cygserver to run as a Windows service with the correct credentials.
Do this from an administrator Cygwin window.
$ cygserver-config
Generating /etc/cygserver.conf file

Warning: The following function requires administrator privileges!

Do you want to install cygserver as service?
(Say "no" if it's already installed as service) (yes/no) yes

The service has been installed under LocalSystem account.
To start it, call `net start cygserver' or `cygrunsrv -S cygserver'.

Further configuration options are available by editing the configuration
file /etc/cygserver.conf. Please read the inline information in that
file carefully. The best option for the start is to just leave it alone.

Basic Cygserver configuration finished. Have fun!

What does cygserver do for me?
Have a look at the documentation over at the Cygwin site. Basically it does the user caching stuff, together with ensuring IPC works between all Cygwin processes.
Your mileage may vary of course, but this is now my preferred way of working. I should have done it years ago.

A: As a footnote, I just found that I had to rebuild the passwd and group files after a Cygwin update. As the slow behaviour was happening again, the autorebase part of the install took several days to complete.
I also did not need to modify the default nsswitch.conf on my (Windows 10) system.
By the way, the slow behaviour also showed itself with the Windows command prompt and portable applications. Some portable applications took several hours to produce a window when started.

A: Read the update below, this turned out not to be the issue.
I've been suffering from an extreme version of this problem, although it's intermittent. When the problem exists, all commands take between 20 seconds and in the most extreme cases several minutes. It will occur for several days, and then it will go away for several days. BTW, I have an extremely fast system with lots of DRAM, SSD drives, etc.
I now finally have a candidate theory that might explain things. I just updated Cygwin via setup-x86_64.exe (which I do infrequently) and afterwards things are extremely responsive again (literally 1000s of times faster than before). I'm guessing the rebaseall at the end of the update is what made the difference.
Update
The speedup I saw before was apparently a coincidence; when the problem reappeared a month later, this didn't fix it. It turns out that disabling Windows Defender live protection instantly resolved the slowdown.

A: It seems to be to do with authentication. For me, 40 seconds to get something to execute. After that though, process creation in that process tree seems pretty quick.
https://www.cygwin.com/faq.html#faq.using.startup-slow
So, I

*

*Made a cache of my local authentication, and my own Active Directory (AD) credentials
$ mkpasswd -l -c >/etc/passwd
$ mkgroup -l -c >/etc/group

*Told Cygwin just to use these two files
$ echo 'passwd: files' >/etc/nsswitch.conf
$ echo 'group: files' >>/etc/nsswitch.conf

I killed all Cygwin processes and started again. Everything now runs nice and fast. I will remove this hack on every Cygwin DLL file update and see how I get on.
This is just a sketch—you will at least want to keep backups!
EDIT
Deprecated.
See my more recent answer to this question for a better (IMHO) solution.

A: This is how this problem manifested for me. For the first, say 20, commands entered at the Cygwin prompt it was fast, but then it abruptly became painfully slow.
I tried the above authentication fix. It didn't work for me.
The Cygwin FAQ reports that Cygwin doesn't like spaces in user or group names.
See My Windows logon name has a space in it, will this cause problems?.
My group name had a space in it, so I changed it in the /etc/group file generated in the authentication fix to an underscore. That didn't work either.
Other postings for the same problem have reported it to result for the virus scanner. I replaced my existing virus scanner (System Center Endpoint Protection) with Sophos. That fixed the problem for me.
I hope this helps.

A: I've had an issue with slow execution of builds for a while on cygwin.
I was forced to update yesterday and ran into the issue of rebaseall simply failing to execute. This forced me to dig into other things and I found a report that Trusteer Rapport/End Point Protection has been known to cause issues with rebaseall, and slow response times.  So I removed it, via the normal Windows Uninstall Programs method via Control Panel.
I then did a rebaseall from the dash interface run as admin.
So this means, (win7) from the start menu type dash. The dash shortcut will appear, Right click to run as administrator. Then when it's up, execute :
/usr/bin/rebaseall -v
Go for a coffee...  It will sit for a few seconds before it should display output, if it sits and does nothing for more than 5 minutes, you have another issue.
This fixed the rebaseall, but has also massively increased the speed of my build. Worth checking to see if you have it installed, try removing it.

A: I have limited permissions on my machine where this happened.  However, as a real hack drop-in substitute, I found that this worked fairly well for me:
find . -maxdepth 1 -ls

It still returned a bit slowly for me, but a lot faster than native ls.


text:
Q: java extends javax.swing.jframe and inputverifier I have need
to extends javax.swing.jframe and inputverifier. Can i resilienza this problema? ?? I try to use more classes But this doesn't work. Can I use a inner class?
Public class framePrincial extends     javax.swing.jframe {
Abstract verifica extends inputverifier  {
}

}

A: Certainly you can use an inner class. You cannot extend more than one class. You can extend one class and implement as many interfaces as you like. There is no way to tell you a good way to do what you want to do without knowing what you want to do.


text:
Q: How to create a spring bean with specific number of maximum instances I need to create a spring prototype bean in a server with limited RAM.
One option is to use a spring bean which is a mix of Singleton and Prototype scopes, where i can specify maximum number of instances and threads.
Is there any way in Spring to create multi instance beans?
If not how to we avoid out of memory errors when using spring prototype beans.

A: If you really want to use spring for your purposes I would suggest using factory bean.
Your context:
<beans ...>
    <bean id="tool" class="com.example.ToolFactory"/>
</beans>

An example of a factory bean:
public class ToolFactory implements FactoryBean<Tool> {
    private AtomicInteger currentId = new AtomicInteger();

    @Override
    public Tool getObject() throws Exception {
        return new Tool(currentId.incrementAndGet());
    }

    @Override
    public Class<?> getObjectType() { return Tool.class; }

    @Override
    public boolean isSingleton() { return false; }
}

public class Tool {
    private final int id;
    public Tool(int id) { this.id = id; }
    public int getId() { return id; }
}

In Toolfactory.getObject()  you can implement any logic you wish.
You can create a Pool of beans inside this factory.
Or you could throw an exception when bean count limit is reached.
How to use the Spring FactoryBean?
What's a FactoryBean?


text:
Q: Is there a way to print directly to printer from Java by bypassing Windows spooler? Is there a way to print directly to usb printer by bypassing Windows spooler?
I need a get an immediate feedback is printing job was succeeded or not. When I send it to spooler and it stuck, I have no any indication did it success or not.
Update: now, when I try to print directly (in printer properties check check-box, Print directly to the printer) I get the following error:

Reboot doesn't help :(
I also tried download reference example from Oracle site http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java
same error, is there any workaround, settings to overcome this issue?
Thank you very much!
Update2:  We use printer Citizen CT-S801

A: Problem was solved by replacing 801 driver with old one from 310 series, after this 'patch' direct printing works flawlessly. Most angered me in this story Citizen's support. They even haven't checked my problem, just said that problem in my Java application and they won't debug program for me.


text:
Q: Can the Google Speech API be configured to return only numbers / letters? Can the Google Speech API be configured to only return numbers and letters, as opposed to full words?
The use case is translating Canadian postal codes.
Ex. M 1 B 0 R 3. Google may return "Em 1 Be 0 Are 3"
We have tried:

*

*Using speechContexts and feeding in letters A - Z, as individual phrases. This improved the accuracy for us. We did not have much success passing in individual numbers (ex 1, 2, 3).

*Specifying the codec and sample rate of our WAV file using the encoding and sampleRateHertz configuration options. We saw no improvement in doing this as we believe Google already does a great job of auto-recognizing the the sample rate and encoding.

Our audio file is 8000hz and encoded with "M-ULAW". We have no flexibility in changing the sample rate or encoding.
Is there a way to get a more accurate response from Google for this use case? Even ideas for better speechContexts phrases are welcome.
Thank you

A: We are experiencing the same results, we would love to have a syntax based "context" suggestion or a parameter to force only digit return variable.
Changes in api version isn't fixing the way the digits are recognised, not even using model: phone_call.
What actually was better for recognising some kind of numbers, was to switch to en_US locale and that in turn forced the recognition engine to identify a list of numbers as a phone. So it was returned in phone-like syntax with +XXX-XXX-XXX-XXXX and this made detection really really good.
So I don't understand why Google has syntax matching behind the curtains and doesn't make it available through their api.


text:
Q: Как выровнять сетку цен woocomerce? Помогите пожалуйста. Интернет магазин сделан на движке WP с плагином woocomerce. Помогает только если загружать фото одного размера, но это не всегда возможно и когда фото не одинакового размера, товары начинают съезжать. В этом деле новичок и не разбираюсь с стилями. Может кто сталкивался с такой проблемой. Хочется что бы цены были вровень , не в зависимости от размера фото. Буду очень благодарен за помощь.

A: Как вариант, задать обертку для картинок с фиксированными размерами. И сделать изображение responsive: добавить стиль к изображению (display: block; max-width: 100%; height: auto;)

По поводу стилей для обертки:
width: 300px; height: 300px; overflow: hidden;
width - должно совпадать с шириной блока
height: указывать размер совпадающий с шириной блока (в данном случае 300px)
overflow: hidden - убирать все что выходит за рамки указанных размеров блока

A: Если блоки товаров фиксированной высоты, просто можно прижать блок с ценой к низу, сделав его absolute и спозиционировав, как вариант.
Уточняю. Делаем блок карточки товара () фиксированной высоты, например, 300px, делаем ей position: relative. Блоку, где находится цена делаем position: absolute и свойством top прижимаем к низу блока. Таким образом, если размер картинки меньше нужного, цена все равно будет везде одинаково. Максимальный размер картинки придется ограничивать, тем не менее

A: Решал подобную задачу в магазине обуви - где часть фото горизонтально часть вертикально. При парсинге нереально обработать все 1000+ фото одинаково если они с разных магазинов.
Для этого:
Для списка товаров определяем нужный или близкий нам размер, меньше которого нужно растянуть блок. Остальные фото визуально выравниваем под этот размер если фото ниже то его центрирует вертикально/горизонтально.
Оборачиваем фото списка товара в свой Див:
function img_top_prew()
{echo '
';};
add_action( 'woocommerce_before_shop_loop_item', 'img_top_prew', 10 );
function img_top_bottom()
{echo '
';};
add_action( 'woocommerce_before_shop_loop_item_title', 'img_top_bottom', 10);

 Стили
.imgcat {
 min-height: 266px;
 position: relative;
}
.imgcat img {
    vertical-align: middle;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}

И получаем вместо такого

Визуально все ровные фото товаров. Следовательно с этим подровняет и названия товаров, цены и все что ниже под фото.


text:
Q: Angular2+: How to make parent router-outlet apply to differently to different child components In my Angular app, I have a root app.component and several child components.
My app.component.html simply looks like this:
<app-top-navigation></app-top-navigation>

    <router-outlet></router-outlet>

The problem for me is that I want all my subcomponent pages to be surrounded with the <div class="container-fluid", but with an exception for the home.component. I don't want my home.component.html to be constrained the in the box that .container-fluid puts it in.
Is there an Angular way to do this?
P.S. I know that in my simplified example here I could just apply some special CSS in home.component but suppose it was a larger project and there were a few sub-commponents that required this exceptional treatment.

A: Your home component could be simple as this.
Make sure you have a separate global route set for home.
componentRoutes: Routes = [
{
  path: '/home',
  component: HomeComponent
},{
  path: '',
  component: MainComponent
}];

You could also keep home path to ' ' if you need to
Home component Template -
home.html
<app-top-navigation></app-top-navigation>

    # Home page content


text:
Q: Pandas / matplotlib stacked horizontal percentage barchart
df_new.plot(

kind = 'barh',
x = 'Measure',
stacked = True,
title = 'Stacked Bar Graph',
mark_right = True)

This gives me a key error on Measure - can't figure out why?

A: You need to tranpose your dataframe with pandas.DataFrame.T to get one horizontal stacked bar:
Try this:
(
    df_new
      .T
      .plot(kind = 'barh',
            stacked = True,
            title = 'Stacked Bar Graph',
            mark_right = True)
)

# Output :


text:
Q: Create a SOAP based Web Service that stores data from request to database I have been asked to create a SOAP based web service (company is typically Microsoft-centric and I will attempt to do this in Visual Studio/C#) which does the following:

*

*Listens for a SOAP request from another system that will contain the values for 3 fields (report name, run date, user ID)

*Logs the inbound SOAP request/outbound response to a SQL database table

*Stores the 3 values sent in the inbound SOAP request to a database table

Can anybody point me in the right direction for how this should be done? Thank you in advance for any advice.

A: I dont know if I understood your question, but you can create a symple API (web service) with project ASP.NET core web aplication.
On the Visual Studio 2017 updated - > File - > New Project - > Web - > ASP.NET core Web Aplication - > API.
If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.
Create a class in the controller like this:
[Route("api/Client")]
public class ClientController : Controller
{
    public IActionResult Client(string name, DateTime date, int id)
    {
        string return1 = "return1", return2 = "return2";

        return Ok(new { return1, return2});
    }
}

Your client can call this class by the url www.sample.com/api/client


text:
Q: Proof of uniform convergence on $\mathbb{R}$ Prove that the sequence {$k_n$}$_{n=1}^\infty$, defined by $$k_n (x) = \frac{x}{1+nx^2}$$ for all x $\in \mathbb{R}$ and each positive integer n, converges uniformly on $\mathbb{R}$.
Any help would be appreciated.

A: Note that, you need to find the following

$$ \sup_{-\infty<x<\infty} \Bigg| \frac{x}{1+n x^2}  - 0\Bigg|. $$

Let

$$ g(x)= \frac{x}{1+n x^2}.$$

Using the derivative technique, the max of $g$ is achieved at $x=\frac{1}{\sqrt{n}}$ (by the second derivative test) and it's given by

$$ g(1/\sqrt{n})=\frac{1}{2\sqrt{n}} \implies \frac{1}{2\sqrt{n}}< \epsilon  $$


text:
Q: How to animate camera to focus on object within GLTF and disable mapcontrols until clicked off Im trying to emulate the behaviour on this website, when the user clicks an object the camera zooms in and rotate slightly to focus on the object and all controls are disabled until the user clicks anywhere again and the animation is reversed and controls are enabled.
Currently I have it working to the point where you click and the camera is animated to focus on the object 'Tree006', but it's not working very well.

var mesh=[];

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2()

function onClick(event) {
    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( scene.children, true );

    if ( intersects.length > 0 && intersects[0].object.name==="Tree006") {
        var object = intersects[0].object;
        gsap.to( camera.position, {
            duration: 1,
            x: mesh["Tree006"].position.x,
            y: mesh["Tree006"].position.y,
            z: mesh["Tree006"].position.z,
            onUpdate: function() {
                camera.lookAt(0,0,0);
            }
        } );
        console.log( 'Intersection:', intersects[ 0 ] );

    }
}


text:
Q: Overflow issue when using mudblazor blazor hybrid This code has an overflow issue. Please look right upper corner and end of tab panel. Couldn't able to find the error. Can anyone suggest a solution. I used mudbalzor as a library. going to implement a blazor hybrid app for tabs.
<MudGrid Justify="Justify.Center">

    <MudAppBar Style="background-color:#053B71;color:white;width:contain" Fixed="false" Dense="false" DisableGutters="false" Class="mt-2">
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" Class="ml-2" />
        <MudText Class="ml-4" Style="font-weight:800;font-size:large">BLX Super Mart</MudText>
        <MudSpacer />
        <MudIconButton Icon="@Icons.Material.Filled.Logout" Style="color:white;background-color:aqua" Href="/" Class="ml-2" />
    </MudAppBar>

    <MudGrid >
        <MudItem xs="7" Style="background-color:yellow">
            <MudTabs Elevation="2" Rounded="true" PanelClass="pa-6" PrevIcon="@Icons.Material.Filled.SkipPrevious" NextIcon="@Icons.Material.Filled.SkipNext"
                     AlwaysShowScrollButtons="true" Color="@Color.Primary" Style="border:thin;border-color:darkgray;border-radius:10px">
                @foreach (string category in tabscat)
                {
                    <MudTabPanel Text=@category ToolTip="Choose a Category" OnClick="() => LoadItems(category)"  >
                        <MudGrid>
                            @foreach (var item in tabscatitm)
                            {

                            }
                        </MudGrid>
                    </MudTabPanel>
                }
           </MudTabs>
       </MudItem>
    </MudGrid>

A: Try move you MudAppBar outside of the main MudGrid and use the MudLayout component
<MudLayout>
    <MudAppBar Style="background-color:#053B71;color:white;width:contain" Fixed="false" Dense="false" DisableGutters="false" Class="mt-2">
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" Class="ml-2" />
        <MudText Class="ml-4" Style="font-weight:800;font-size:large">BLX Super Mart</MudText>
        <MudSpacer />
        <MudIconButton Icon="@Icons.Material.Filled.Logout" Style="color:white;background-color:aqua" Href="/" Class="ml-2" />
    </MudAppBar>

    <MudMainContent>
        <MudContainer MaxWidth="MaxWidth.Medium">
            <MudGrid Justify="Justify.Center">
                <MudGrid>
                    <MudItem xs="7" Style="background-color:yellow">
                        <MudTabs Elevation="2" Rounded="true" PanelClass="pa-6" PrevIcon="@Icons.Material.Filled.SkipPrevious" NextIcon="@Icons.Material.Filled.SkipNext"
                                AlwaysShowScrollButtons="true" Color="@Color.Primary" Style="border:thin;border-color:darkgray;border-radius:10px">
                                <MudTabPanel Text="AAAA" ToolTip="Choose a Category"  >
                                    <MudGrid>
                                    </MudGrid>
                                </MudTabPanel>
                                <MudTabPanel Text="BBBB" ToolTip="Choose a Category"  >
                                    <MudGrid>
                                    </MudGrid>
                                </MudTabPanel>
                                <MudTabPanel Text="CCCC" ToolTip="Choose a Category"  >
                                    <MudGrid>
                                    </MudGrid>
                                </MudTabPanel>
                        </MudTabs>
                    </MudItem>
                </MudGrid>
            </MudGrid>
        </MudContainer>
    </MudMainContent>
</MudLayout>

https://try.mudblazor.com/snippet/camducPHecwyvTIz


text:
Q: why does not ScheduledThreadPoolExecutor provide finite queue? ScheduledThreadPoolExecutor extends ThreadPoolExecutor, but with less constructor, ScheduledThreadPoolExecutor provide an infinite delayQueue, so that  if I submit too many many task, it may cause jvm OOM, why does not it provide a finite queue and reject policy(reject when can't submit new task)?

A:
Why does not it provide a finite queue and reject policy(reject when can't submit new task)?

You would need to ask the designers, but the fact that they decided not to support this suggests that they thought it would not be useful.  (Or at least, not useful enough to justify the extra complexity.)
There is another reason.  The implementation of ScheduledThreadPoolExecutor depends on the queue returning elements in the correct order.  If you look at the source code, you will see that it uses a custom queue class for this.  There is a comment that says this:

Using a custom queue (DelayedWorkQueue), a variant of unbounded DelayQueue. The lack of capacity constraint and the fact that corePoolSize and maximumPoolSize are effectively identical simplifies some execution mechanics (see delayedExecute) compared to ThreadPoolExecutor.

Also, it is clear that the delay queue implementation has to have specific operational properties for the executor to work properly and efficiently.  That is probably why they don't permit you to provide your own queue implementation.
Finally, if you want your application to impose a bound on the delay queue size, you could use yourPool.getQueue().length() to check the queue length before scheduling a new task.


text:
Q: Getting a:hover to adjust more than one class/id Been struggling with getting something to work and I've looked a bunch of places already, any help greatly appreciated.
Basically I have a nav menu that is made up of a few rollover images (normal state 'left top', hover state 'left bottom', they are currently configured to rollover upon over individually via css - these look like this:

Home

Archives

Contact

About

#menu {
list-style: none;
padding: 0;
margin: 0 auto;
height: 24.6em;
width: 79em;
position: relative;
}

#menu a {
display: block;
text-indent: -900%;
position: absolute;
outline: none;
}

#menu a:hover {
background-position: left bottom;}

#menu .home {
width: 520px;
height: 124px;
background: url(images/Home Menu.png) no-repeat;
left: 0px;
top: 122px;
}

#menu .archives {
width: 263px;
height: 57px;
background: url(images/Archives Menu.png) no-repeat;
left: 0px;
top: 189px;
}

and so on for the rest of the links.

Now what I'm trying to achieve, is to have all of them roll over when I hover any of them. So say I hovered over "archives"; the following would roll over "archives, contact, about"
I've already tried the following and it didn't work (the opacity clause did exactly what I wanted it to do, but for some reason this doesn't seem to work for "background-position"):
#menu:hover .archives {background-position: left bottom; opacity: 0.5}
#menu:hover .contact {background-position: left bottom; opacity: 0.5}
#menu:hover .about {background-position: left bottom; opacity: 0.5}

How would I go about achieving this? thanks in advance for any help!

A: ohnno,
You were on the right track, but its not working due to specificity requirements. Try going this route:
#menu:hover a { background-position: left bottom; opacity:0.5; }

If it is still not working, try:
#menu:hover li a { background-position: left bottom; opacity:0.5; }

Finally, you may also apply an !important to the rule to enforce the  rule. !important is a special flag for CSS that tells the browser "This overrides whatever you may think" (kinda).Here is an example:
#menu:hover li a { background-position: left bottom !important; opacity:0.5; }

For more information on specificity, check out this article at the W3C. In short, specificity defines which styles are used at which times. Applied Element Style is defined, on a rule by rule, by the style with highest specificity for each of the styles that may apply.
FuzzicalLogic

A: left-bottom may not be changing enough so you don't notice the change. try right?


text:
Q: How to integrate Stripe Connect with Drupal 8? I need help to create a module that uses Stripe Connect with Drupal 8.7, Drupal Commerce 2.14 and Commerce Stripe RC3 :
https://www.drupal.org/project/commerce
https://www.drupal.org/project/commerce_stripe
Currently there is no module with Drupal 8 to use Stripe Connect, it's a shame because Drupal Commerce makes it easy to set up a marketplace (a site with several merchants).
I set up my Stripe account to use Stripe Connect on the page :
https://dashboard.stripe.com/account/applications/settings
I want to use Standard Stripe accounts and charge a 10% commission on each transaction :
https://stripe.com/docs/connect/standard-accounts
https://stripe.com/docs/connect/direct-charges
Here is a diagram of what I want to do :
https://stripe.com/img/docs/connect/direct_charges.png
I found some documentation to integrate Stripe Connect :
https://stripe.com/docs/building-extensions
There is a patch for Commerce Stripe but it does not work :
https://www.drupal.org/project/commerce_stripe/issues/3032908
How can I charge 10% commission on each sale ?
I created a role in Drupal "premium merchant" :

*

*When a merchant connects his Stripe account, the "premium merchant" role must be added.

*When a merchant disconnects his Stripe account, the "premium merchant" role must be removed.


text:
Q: 'Mandatory fields are missing' response from APIGEE API I am using nimbus-jose-jwt library in Android to generate encrypted JWT (JWE), to send it in the body of an APIGEE API.
I have used the following code to generate encrypted JWT:
public class EncryptedJWTGenerator {
    String jweString;
    Map<String, Object> map = new HashMap<>();

    @RequiresApi(api = Build.VERSION_CODES.O)
    public EncryptedJWTGenerator() throws NoSuchAlgorithmException, JOSEException, InvalidKeySpecException {

        String publicKey = <my_public_key>;

        try {
            // create Gson instance
            Gson gson = new Gson();

            URL url = getClass().getResource("Payload.json"); //JSON file having the Payload

            // create a reader
            Reader reader = Files.newBufferedReader(Paths.get(url.toURI().getPath()));

            // convert JSON file to map
            map = gson.fromJson(reader, Map.class);

            // print map entries
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }

            // close reader
            reader.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        JWEAlgorithm alg = JWEAlgorithm.RSA_OAEP_256;
        EncryptionMethod enc = EncryptionMethod.A256GCM;

        byte[] publicBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);

        // Generate the preset Content Encryption (CEK) key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(EncryptionMethod.A256GCM.cekBitLength());

        SecretKey cek = keyGenerator.generateKey();

        JOSEObjectType joseObjectType = new JOSEObjectType("JWT");
        JWEHeader jweHeader = new JWEHeader(alg, enc, joseObjectType, null, null, null, null, null, null, null, null, null, null,
                null, null, null, null, 0, null, null, null, null);

        // Encrypt the JWE with the RSA public key + specified AES CEK
        JWEObject jweObject = new JWEObject(new JWEHeader(jweHeader), new Payload(map));

        jweObject.encrypt(new RSAEncrypter((RSAPublicKey) pubKey, cek));

        jweString = jweObject.serialize();
    }
}

But when I use this JWE in the body of the API, I get the following response:
{
    "Code": 0,
    "Response": {},
    "Message": "Mandatory Fields are missing"
}

But when I use this tool -> https://dinochiesa.github.io/jwt/ to generate the JWE and use it with  the APIGEE API, it works fine.
Am I missing something in my code for JWE generation?

A: Solved it by passing my JSON as String for Payload instead of reading from file and converting to map and passing it for Payload.
Replaced JWEObject jweObject = new JWEObject(new JWEHeader(jweHeader), new Payload(map)); with:
 JWEObject jweObject = new JWEObject(new JWEHeader(jweHeader), new Payload(<my_json_string>));


text:
Q: AWS Api Gateway invalid model schema I am trying to create a model for my api. But aws returns 3x invalid model schema error, couldn't figure out the reason:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "EmailInputModel",
"type":"object",
"properties":{
"email":{
    "type":"string",
    "required":true,
    "patternProperties":{
        "^((\"[\\w-\\s]+\")|([\\w-]+(?:\\.[\\w-]+)*)|(\"[\\w-\\s]+\")([\\w-]+(?:\\.[\\w-]+)*))(@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$)|(@\\[?((25[0-5]\\.|2[0-4][0-9]\\.|1[0-9]{2}\\.|[0-9]{1,2}\\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\\]?$)/i": {}
        }
    },
"message":{
    "type":"string",
    "required":true
},
"sender":{
    "type":"string",
    "required":true
}
}

}
Thanks in advance for help and efforts.

A: Looks like the usage of required attribute should be fixed. Try below.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "EmailInputModel",
"type": "object",
"properties": {
    "email": {
        "type": "string",
        "patternProperties":{
    "^((\"[\\w-\\s]+\")|([\\w-]+(?:\\.[\\w-]+)*)|(\"[\\w-\\s]+\")([\\w-]+(?:\\.[\\w-]+)*))(@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$)|(@\\[?((25[0-5]\\.|2[0-4][0-9]\\.|1[0-9]{2}\\.|[0-9]{1,2}\\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\\]?$)/i": {}
        }
    },
    "message": {
        "type": "string"
    },
    "sender": {
        "type": "string"
    }
},
"required": ["email", "message", "sender"]
}


text:
Q: How to get the actual type of a swift struct in the disguise of a `__SwiftValue` I'm using YapDatabase to encode/decode my Swift value types. After decoding, the type information seems to be lost, that is type(of:element) returns __SwiftValue instead of, e.g., Reservation.
If I call po element in the debugger though, it seems that the type information is still retained:
(lldb) po element
SecureTruckParking.Reservation(reservationId: 12625, accessInformations: [SecureTruckParking.AccessInformation(accessInformationId: 12706, accessTypeId: 1, accessTypeKey: Optional("1"), accessTypeTenantKey: Optional("ROOT"), encodedValue: "XXX", displayedValue: "XXX"), SecureTruckParking.AccessInformation(accessInformationId: 12707, accessTypeId: 51, accessTypeKey: Optional("51"), accessTypeTenantKey: Optional("ROOT"), encodedValue: "918296", displayedValue: "918296")], customerId: 3156, areaId: 552, productId: 1004, state: "PENDING", startTime: 2020-09-10 08:23:00 +0000, endTime: 2020-09-11 08:23:00 +0000, earliestEntryTime: 2020-09-10 08:23:00 +0000, latestExitTime: 2020-09-11 08:23:00 +0000, totalAmount: 2750.0, currency: "€", netPrice: 2311.0, taxPrice: 439.0, invoiceItems: [SecureTruckParking.InvoiceItem(amount: 1, itemText: "Parkplatzreservierung, 10.09.2020 10:23 - 11.09.2020 10:23 \nREWE Logistikzentrum Neu-Isenburg -> REWE Logistikzentrum Neu-Isenburg", netPrice: 2311.0, taxPrice: 439.0, taxRate: 19.0)], productAttributes: [SecureTruckParking.Attribute(key: "early_bird_count", value: Optional("1"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "early_bird_count", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "DETAILS", value: nil, definitionId: nil), SecureTruckParking.Attribute(key: "INFO_DETAILS", value: nil, definitionId: nil), SecureTruckParking.Attribute(key: "early_bird", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "early_bird", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "manualBackofficeCancellationConfirmation", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "manualBackofficeCancellationConfirmation", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "manualBackofficeCancellationConfirmationThreshold", value: Optional("1"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "manualBackofficeCancellationConfirmationThreshold", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "product_icon", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "product_icon", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "product_image", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "product_image", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "product_tariff_group", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "product_tariff_group", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading_dates_fixed", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading_dates_fixed", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading_immediate", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading_immediate", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading_mail", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading_mail", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading_price_surcharge", value: Optional("false"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading_price_surcharge", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "early_bird_duration", value: Optional("1440"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "early_bird_duration", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "recurring_max_trips", value: Optional("1"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "recurring_max_trips", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading_mail_max_lead_time", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading_mail_max_lead_time", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "upgrading_mail_min_lead_time", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "upgrading_mail_min_lead_time", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "bstp_product_type", value: Optional("Reservation"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "bstp_product_type", tenant: "ROOT")))], areaAttributes: [SecureTruckParking.Attribute(key: "product_icon", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "product_icon", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "product_image", value: nil, definitionId: Optional(SecureTruckParking.DefinitionId(key: "product_image", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "Parking_Area_UST", value: Optional("22222222222222"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "Parking_Area_UST", tenant: "MAN_BOSCH"))), SecureTruckParking.Attribute(key: "ipaw_id", value: Optional("4651"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "ipaw_id", tenant: "ROOT"))), SecureTruckParking.Attribute(key: "bstp_area_type", value: Optional("PROFESSIONAL"), definitionId: Optional(SecureTruckParking.DefinitionId(key: "bstp_area_type", tenant: "ROOT")))])

What is this __SwiftValue and is there a way to get the actual type (besides any horrible approaches of parsing the String(describing: element)?

A: First of all you're seeing the __SwiftValue because the struct has been wrapped with as AnyObject cast. You can easily verify this yourself:
struct TestStruct {}
let ourStruct = TestStruct()
let structSwiftValue = ourStruct as AnyObject
print(type(of: ourStruct))
print(type(of: structSwiftValue))

outputs:
TestStruct
__SwiftValue

Good discussion on the topic: https://forums.swift.org/t/anyobject/35659/9
Now to the essence of your question, unfortunately I believe there's no convenient public API for the time being that would allow you to extract original metadata Type from __SwiftValue.
Still the topic is too interesting not to venture into private API territory for educational purposes.
Let's begin with __SwiftValue itself https://github.com/apple/swift/blob/master/stdlib/public/runtime/SwiftValue.mm
There is promising API available through obj-c:
// Private methods for debugging purposes.

- (const Metadata *)_swiftTypeMetadata {
  return getSwiftValueTypeMetadata(self);
}
- (id /* NSString */)_swiftTypeName {
  TypeNamePair typeName
    = swift_getTypeName(getSwiftValueTypeMetadata(self), true);
  id str = swift_stdlib_NSStringFromUTF8(typeName.data, typeName.length);
  return [str autorelease];
}
- (const OpaqueValue *)_swiftValue {
  return getValueFromSwiftValue(self).second;
}

Let's start with something fairly simple:
print(structSwiftValue.value(forKey: "_swiftTypeName")!)

outputs:
ModuleName.TestStruct

Just a String type, but not bad for starters. The next promising candidate to explore seems:
- (const Metadata *)_swiftTypeMetadata()

We can call it like this (in depth details on this particular way of invoking selectors in Swift can be found here)
let selector: Selector = NSSelectorFromString("_swiftTypeMetadata")
let methodIMP: IMP! = structSwiftValue.method(for: selector)
let metadataPtr = unsafeBitCast(methodIMP,to:(@convention(c)(Any?,Selector)->OpaquePointer).self)(structSwiftValue,selector)

Now the challenge is to somehow make use of Metadata * (i.e. the OpaquePointer after bridging to Swift) in a type(of:) manner.
I found a way to do it, albeit a very hacky one.
We begin with a metadata Type variable of some dummy object or struct (doesn't really matter). The general idea is eventually we'd like to replace the metadata  pointer with one we got from our previous stage. I noticed the result of type(of:) yields a pointer pointing at the metadata, so there's extra level of indirection, we will have to accommodate for that:
var placeholderTypeVar: Any.Type = type(of: NSObject())
print(placeholderTypeVar)
withUnsafeMutablePointer(to: &placeholderTypeVar) {
    let unsafePtr = UnsafeMutablePointer<OpaquePointer>.allocate(capacity: 1)
    unsafePtr.pointee = metadataPtr
    $0.assign(from: UnsafePointer<Any.Type>.init(OpaquePointer(unsafePtr)), count: 1)
}
print(placeholderTypeVar)
print(type(of: structSwiftValue))

outputs:
NSObject
TestStruct
__SwiftValue

The middle one is the answer. And moreover it's identical to result of type(of: ourStruct) down to memory level (the Metadata * equivalent yielded internally is the very same address!).
More read about metadata which is a very interesting topic in Swift:
https://medium.com/ios-os-x-development/types-and-meta-types-in-swift-9cd59ba92295
https://kateinoigakukun.hatenablog.com/entry/2019/03/22/184356
https://medium.com/@weswickwire/creating-a-swift-runtime-library-3cc92fc486cc


text:
Q: BlazeDS vs. GraniteDS Anyone have any experience evaluating BlazeDS and GraniteDS? I'm curious about which is better at integrating with Spring/Hibernate.

A: If you are just looking for simple RPC and messaging, I would go with Blaze. The implementations are more mature and better proven, especially with respect to messaging.  The messaging in Granite is based on Comet and still pretty new from what I remember.  More details below...
Blaze DS is basically a stack that includes RPC and some simple messaging services over HTTP.  Integration with Spring is achieved easily using the SpringFactory implementation of FlexFactory: just google the class name and you'll find the code.  It doesn't offer any additional support for things Hibernate-related.
Granite DS is growing rapidly in terms of features.  It competes more with LCDS than Blaze DS.  It includes the ability to parse Hibernate object graphs and deal with lazy proxies in a clean fashion.  They also have a tool called "Tide" that creates an analog of a Session in the Flex client to ensure uniqueness of entities.  They also have explicit support for services exposed via Spring, EJB3 and Seam.  Granite also has a utility for generating AS3 classes from your Java classes (although this not hard to write yourself if you want to).
I worked with Granite about a year ago and had some problems getting it properly parse object graphs; the Flash Player would throw some nasty low-level exceptions.  My guess is that the documentation and implementation have matured since so that these are no longer issues.  However, I'm still a bit hesitant to recommend it since I ran into issues and switching to Blaze immediately resolved them with no trouble at all.

A: A few side notes on Cliff's comments:

*

*GraniteDS was created late 2006, about one year before BlazeDS. It is widely used in demanding production environments and could be at least considered as mature and proven than BlazeDS.

*GraniteDS messaging was introduced in the 1.0 release (late 2007, few weeks after the first BlazeDS release), it is now very mature and proven as well in demanding production environments.

*The Flash player exceptions encountered by Cliff are generally caused by failing to compile all generated AS3 classes in the SWF. It is only a matter of using a Flex compiler option that forces the inclusion of these missing classes, which are part of the data graph model and required at deserialization time but not explicitly used in the MXML/AS3 code.

*Most of the GraniteDS users are coming from BlazeDS/LCDS because these two frameworks are not dealing correctly with complex data models (no or faulty lazy-loading support, bad transaction isolation, etc.)

So, IMHO, unless you are developing a small application with a rather trivial data model, you should go to GraniteDS.


text:
Q: Functionally create associative arrays? I wish to shorten the amount of code in my PHP file by using a function which creates arrays, however the array contents need to be referencing other array components... so, this code alone works:
$array['sql'] = "SQL Statement";
$array['result'] = $db -> query( $array['sql'] );
$array['single'] = $array['result'] -> fetch_assoc();

I realise this is fairly hard, but then I had the idea to do this:
$array = array( array( 'db_sql1', "SQL Statement 1" ), array( 'db_sql2', "SQL Statement 2" ) );
foreach ( $array as $items ) {
    $$items[0]['sql'] = $items[1];
    $$items[0]['result'] = $db -> query( $$items[0]['sql'] );
    $$items[0]['single'] = $$items[0]['result'] -> fetch_assoc();
}

But this doesn't work because (I believe at least), the ['sql'] is being used in order to name the $$items, rather than writing to them. How is it possible (if at all) to do this?
I understand if this is not possible because of whatever reason, but I thought it would be useful to try find out.

A: Yes if you use arrays combined with variable variables you need to tell PHP if the index/key is now for the variable name, or to access the variable itself. To clarify this just use {}, e.g.
$array = array( array( 'db_sql1', "SQL Statement 1" ), array( 'db_sql2', "SQL Statement 2" ) );

foreach ( $array as $items ) {
    ${$items[0]}['sql'] = $items[1];
    ${$items[0]}['result'] = $db -> query( ${$items[0]}['sql'] );
    ${$items[0]}['single'] = ${$items[0]}['result'] -> fetch_assoc();
}

Side note:
With using curly brackets you also make your code for PHP 7 backwards compatible, since from PHP 5 to 7 the right-to-left evaluation will change to left-to-right as you can see here: http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling


text:
Q: Kronecker symbol vs. Koblitz symbol In Koblitz, Introduction to Elliptic Curves and Modular Forms on page 188 it is defined
$$\left( \frac{-1}{j}\right)=0$$
in case $j$ is even. Apart from that definition $\left( \frac{c}{d}\right)$ is pretty much defined like the Kronecker symbol. The Kronecker symbol is $0$ if and only if $c$ and $d$ have a common factor, so in particular $\left( \frac{-1}{j}\right)\ne 0$.
Can you explain why Koblitz is defining it a little bit different? Is that on purpose or a mistake?
What is the exact relation between the Kronecker symbol and Koblitz symbol? In which cases is which definition useful?

A: There exist various definitions of the Kronecker symbol. I prefer to view the Kronecker symbol as giving the splitting behaviour of a prime $p$ in a quadratic number field with discriminant $\Delta$, and thus define  $(\Delta/p)$ only for discriminants $\Delta$. This is what Koblitz is doing; in his case, $\Delta = -4$,
hence $(-1/p) = (-4/p)$ should be $0$ when $p$ and $\Delta$ have a factor in common.


text:
Q: Upgrade from 12.10 to 13.04 affecting other systems I'm quite new to using Ubuntu. I have a dual-booted computer, running Windows 7 & Ubuntu 12.10. I'm planning to get an upgrade to 13.04. In terminal, I know the command is "do-release-upgrade". But, when I install it, will it leave my other systems alone? I'm expecting it will just add the option to boot into Ubuntu 13.04 when I turn on my computer?
So I would have the options:
Windows 7,
Ubuntu 12.10 &
Ubuntu 13.04
Correct? All in my GRUB menu.
Help is greatly appreciated, I just really want to make sure nothing will be harmed. Thanks in advance.

A: Although the upgrade should go without any problem you should back up your data first just in case. Upgrades can fail for any number of reasons. You should also read the release notes first.
https://wiki.ubuntu.com/RaringRingtail/ReleaseNotes
Especially the "known issues" section
https://wiki.ubuntu.com/RaringRingtail/ReleaseNotes#Known_issues
There is no reason to believe the upgrade would affect windows.
Once you upgrade, you will no longer be able to boot 12.10 and there should not be an option to do so.

A: Since you already have a working dual boot (windows 7 and ubuntu 12.10) go ahead and upgrade.
12.10 will be upgraded to 13.04 thereby eliminating any previous version in GRUB. Think of 13.04 as a new 12.10
Also since GRUB is handling the master bootloader, nothing will happen to your current setup as your new setup after the upgrade will be:
-Ubuntu 13.04
-Windows 7
So go ahead and upgrade. GRUB really handles Windows 7 very well.
Hope this helps.


text:
Q: Terraform: wait till the instance is "reachable" I have some Terraform code with an aws_instance and a null_resource:
resource "aws_instance" "example" {
  ami           = data.aws_ami.server.id
  instance_type = "t2.medium"
  key_name      = aws_key_pair.deployer.key_name

  tags = {
    name = "example"
  }

  vpc_security_group_ids = [aws_security_group.main.id]
}

resource "null_resource" "example" {
  provisioner "local-exec" {
    command = "ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -T 300 -i ${aws_instance.example.public_dns}, --user centos --private-key files/id_rsa playbook.yml"
  }
}

It kinda works, but sometimes there is a bug (probably when the instance in a pending state). When I rerun Terraform - it works as expected.
Question: How can I run local-exec only when the instance is running and accepting an SSH connection?

A: There is an ansible specific solution for this problem. Add this code to you playbook(there is all so pre_task clause if you use roles)
- name: will wait till reachable
  hosts: all
  gather_facts: no # important
  tasks:
    - name: Wait for system to become reachable
      wait_for_connection:

    - name: Gather facts for the first time
      setup:

A: For cases where instances are not externally exposed (About 90% of the time in most of my projects), and SSM agent is installed on the target instance (newer AWS AMIs come pre-loaded with it), you can leverage SSM to probe the instance. Here's some sample code:
instanceId=$1
echo "Waiting for instance to bootstrap ..."
tries=0
responseCode=1
while [[ $responseCode != 0 && $tries -le 10 ]]
do
  echo "Try # $tries"
  cmdId=$(aws ssm send-command --document-name AWS-RunShellScript --instance-ids $instanceId --parameters commands="cat /tmp/job-done.txt # or some other validation logic" --query Command.CommandId --output text)
  sleep 5
  responseCode=$(aws ssm get-command-invocation --command-id $cmdId --instance-id $instanceId --query ResponseCode --output text)
  echo "ResponseCode: $responseCode"
  if [ $responseCode != 0 ]; then
    echo "Sleeping ..."
    sleep 60
  fi
  (( tries++ ))
done
echo "Wait time over. ResponseCode: $responseCode"

Assuming you have AWS CLI installed locally, you can have this null_resource required before you act on the instance. In my case, I was building an AMI.
resource "null_resource" "wait_for_instance" {
  depends_on = [
    aws_instance.my_instance
  ]
  triggers = {
    always_run = "${timestamp()}"
  }
  provisioner "local-exec" {
    command = "${path.module}/scripts/check-instance-state.sh ${aws_instance.my_instance.id}"
  }
}

A: The null_resource is currently only going to wait until the aws_instance resource has completed which in turn only waits until the AWS API returns that it is in the Running state. There's a long gap from there to the instance starting the OS and then being able to accept SSH connections before your local-exec provisioner can connect.
One way to handle this is to use the remote-exec provisioner on the instance first as that has the ability to wait for the instance to be ready. Changing your existing code to handle this would look like this:
resource "aws_instance" "example" {
  ami           = data.aws_ami.server.id
  instance_type = "t2.medium"
  key_name      = aws_key_pair.deployer.key_name

  tags = {
    name = "example"
  }

  vpc_security_group_ids = [aws_security_group.main.id]

}

resource "null_resource" "example" {
  provisioner "remote-exec" {
    connection {
      host = aws_instance.example.public_dns
      user = "centos"
      file = file("files/id_rsa")
    }

    inline = ["echo 'connected!'"]
  }

  provisioner "local-exec" {
    command = "ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -T 300 -i ${aws_instance.example.public_dns},  --user centos --private-key files/id_rsa playbook.yml"
  }
}

This will first attempt to connect to the instance's public DNS address as the centos user with the files/id_rsa private key. Once it is connected it will then run echo 'connected!' as a simple command before moving on to your existing local-exec provisioner that runs Ansible against the instance.
Note that just being able to connect over SSH may not actually be enough for you to then provision the instance. If your Ansible script tries to interact with your package manager then you may find that it is locked from the instance's user data script running. If this is the case you will need to remotely execute a script that waits for cloud-init to be complete first. An example script looks like this:
#!/bin/bash

while [ ! -f /var/lib/cloud/instance/boot-finished ]; do
  echo -e "\033[1;36mWaiting for cloud-init..."
  sleep 1
done


text:
Q: can i use gps to track my location when i an offline I want to make an app for android phones which will gives some notification when it reaches certain point . Is it possible to do it using GPS ? And is it possible to make user download maps and then use that map to track location using GPS system , i mean can i track device location without internet using GPS and gives notification when phone is offline .if it is possible then please give me some guidance how can I do it

A: you can get location with no cell tower by satellite. it is free and called fine location. cell towers are less accurate form of location. The map used to display the location must have a connection to the internet however and you get maps via google This is free to develop apps but when you sell the app google takes a cut.

A: yeah we can get our current location in offline by using FUSED LOCATION
refer here


text:
Q: Vector fields, diffeomorphism subgroups and lie group actions Let $M$ be a compact smooth manifold. Since any vector field is complete we get a $1$-parameter subgroup for each vector field. Consider the following generalization:
Let $\{X_j\} \in Vect(M)$ be a finite "basis" of some integrable subbundle of $TM$ (meaning that their locally linearly independent and closed under lie bracket). We have $Span\{X_j\} \cong \mathfrak{g}$ for some finite dimensional lie algebra. The exponential map $\varphi : \mathfrak{g} \to G$ gives a group equipped with a natural action $\rho: G \to Diff(M)$. Denoting the flow of $X$ by $\varphi_t^X$ the action looks like:
$$\rho : g=e^{X_1}e^{X_2}\dots e^{X_n} \mapsto \varphi_1^{X_1}\circ e_1^{X_2}\circ\dots \circ\varphi_1^{X_n}(-)$$

Question 1: Is this map well defined?

In any case if $\mathfrak{g}$ is abelian the action is well define and we get a product of circles and lines inside $Diff(M)$. For every point $x \in M$ the action of the torus part will carve an embedded submanifold of $M$ and the action of the euclidean part will carve an immersed submanifold.

Question 2: Is there anything more substantial to say here? When will the
  action of the torus part yield an actual torus?
Question 3: Does this construction give a $G/\ker\rho$-fiber bundle? (does it help if $G$ is compact?).

A: Every orbit of a torus is a torus, since every orbit of a Lie group action is a homogeneous space of the Lie group.


text:
Q: Why I can't implement this simple CSS <!DOCTYPE html>

        <title>Enjoy BluePrint</title>

        <link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection">
        <link rel="stylesheet" href="css/blueprint/print.css" type="text/css" media="print">

This is my site

Frank Chimero is a graphic designer, illustrator, teac`her, maker, writer,  thinker-at-large in Portland, Oregon.

                    contact

DISCOVERY

My fascination with the creative process, curiosity, and visual experience informs all of my work in some way. Each piece is the part of an exploration in finding wit, surprise, honesty, and joy in the world around us, then, trying to document those things with all deliberate speed before they vanish.

Our creative output can have a myriad intended outcomes: to inform, to persuade or sell, or delight. There are many other creative people who do well in servicing the needs to inform or persuade, but there are not many out there who have taken up the mantle of delighting people. I'll try my best.

It's not about pretty; it is about beauty. Beauty in form, sure, but also beauty in the fit of a bespoke idea that transcends not only the tasks outlined, but also fulfilling the objectives that caused the work to be produced in the first place.

The best creative work connects us by speaking to what we share. From that, we hope to make things that will last. Work made without staying power and lasting relevance leads to audiences that are fickle, strung along on a diet of crumbs.

The work should be nourishing in some way, both while a creative person is making it, but also while someone consumes it. When I think of all my favorite books, movies, art and albums, they all make me a little less alone and a little more sentient. Perhaps that is what making is for: to document the things that make us feel most alive.

                Awards

                Right sidebar

I'm 100% sure the code works, and I can't replace image at h1.logo . I try to use live-editing CSS tool and it works fine .
Thanks for reading :)

A: its not script its style.


text:
Q: Convert string to function in v8 I'm trying to hardcode a function as string, turn it into a function and run it.
Local<Function> cb = "function(){ console.log('HELLO BOSS'); }";
int argc=0;
v8::Handle<v8::Value> * argv;
cb->Call(Context::GetCurrent()->Global(),argc,argv);

Compiler sais I can't do it directly:
      error C2664: 'v8::Handle<T>::Handle(T *)' : cannot convert parameter 1 from 'const char *' to 'v8::Function *'
      with
      [
         T=v8::Function
      ]
      Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
      x.cpp(15) : see reference to function template instantiation 'v8::Local<T>::Local<const char>(S *)' being compiled
      with
      [
         T=v8::Function,
         S=const char
      ]

How can I do it then? Also, where are all the goodies (eval, new Function, etc)?

A: I did it. Boy I love this stuff.
v8::Script::Compile(v8::String::New(
    " console.log('WORKS BOSS'); "
    " console.log('Happy?'); "
    " console.log('2+2=' + (2+2)); "
))->Run();

I don't know if it's right (right as in "any risk associated") but it seems to work.


text:
Q: Can you use admob during alfa and beta testing in google play? Simple question - can you use live AdMob ads (i.e. not in test mode) during alpha and beta testing in Google Play?

A: Yes. Alpha and Beta are supposed to be a restricted rollout to a small number of users, they have no effect on admob.
Read about it in this guide.


text:
Q: Mongodb find doesn't return array I'm not sure what I'm missing here. I would like to query a MongoDB Database within a Nodejs function. The jobs variable below, keeps returning undefined. I'm expecting it to return an array. If I run a console.log within collection.find it outputs the array I'm trying to return.
async function getDataFromMongoDB(page) {
  const MongoClient = require("mongodb").MongoClient;
  const uri = "mongodb://localhost:3001";
  const client = new MongoClient(uri, { useNewUrlParser: true });
  client.connect(async function(err) {
    console.log(5, err);
    const collection = client.db("meteor").collection("jobs");

    const jobs = await collection.find().toArray((err, items) => {
      return items;
    });
    console.log("jobs", jobs);

    // return jobs;
    // console.log(jobs);

    // perform actions on the collection object
    client.close();
  });
}

A: client.connect is async function and accepts callback. You cannot access the jobs variable outside the callback scope.
To do so you can wrap the client.connect method into a function and can return promise from there.
async function getDataFromMongoDB(page) {
  const MongoClient = require("mongodb").MongoClient;
  const uri = "mongodb://localhost:3001";
  const client2 = new MongoClient(uri, { useNewUrlParser: true });
  const client = await connectToMongodb(client2)
  const collection = client.db("meteor").collection("jobs");
  const jobs = await collection.find().toArray();
  console.log("jobs", jobs);
}

connectToMongodb(client) {
  return new Promise((resolve, reject) => {
    client.connect(function(err) {
      return resolve(client)
    });
  })
}


text:
Q: Will updating iPod touch erase songs/apps? I have an iPod touch (not mine) connected to my PC (authorized and linked to the same account of the iPod's owner). The thing is configured for manual sync, current music and apps are on a different PC. Will updating the OS erase music/apps? If so how can I backup them before? Right clicking on the iPod and selecting "Backup" runs too fast, I don't think it copied the whole 3Gb over.

A: As commenters above suggest iTunes will only backup configuration files and whatnot. All content is supposed to be available in the iTunes library with which the iPod syncs, so iTunes will happily erase it, leaving to you the "burden" to restore stuff after the update. In my case I solved the problem using Sharepod to get content off the iPod before updating.


text:
Q: É possível salvar um arquivo em "Downloads" utilizando Totalcross? Para contextualizar..
Inicialmente eu estava tentando implementar a abertura de um PDF utilizando Totalcross como pode ser visto nessa questão: Como abrir um PDF utilizando Totalcross?
Porém, não há uma solução para tal problema.
Sendo assim, uma outra saída é salvar o arquivo no dispositivo do cliente, e apresentar o caminho/diretório para que o mesmo possa navegar até o local e abrir o arquivo PDF.
Pois bem, criar diretórios e inserir o arquivo em tal é possível fazer.
A minha dúvida é.. existe algo que o Totalcross implemente o diretório padrão de downloads das plataformas?
Como por exemplo, em código nativo Android, é possível acessar a pasta de "Downloads" utilizando o seguinte trecho:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Desde já, agradeço o apoio! :)


text:
Q: Polygon area calculation in Ruby (on Rails, rgeo, PostGIS and GEOS) in sqare meters In a Ruby-on-Rails application, I need the area  in square meters (or any other surface measure, be it ares, hectares, square kilometers, but not in pseudo surface measure like square degrees) of a geographic polygon.
The application already uses rgeo and PostGIS (via the activerecord-postgis-adapter) and already requires rgeo's optional libGEOS support. So I'd like to make use of these tools for the area calculation, too.
I can use PostGIS (via the activerecord-postgis-adapter) to compute the area of any rgeo geometry:
def calculate_area(geometry)
  ActiveRecord::Base.connection.execute("
  SELECT
    ST_Area(
      geography(
        ST_Transform(
          ST_GeomFromText('#{geometry.as_json}', #{geometry.srid}),
          4326
        )
      )
    ) AS area;
  ")[0]['area'].to_f
end

(Nesting ST_Area()'s argument in geography() is what causes the result to be in square meters.)
However, having to extract the result from execute()'s return value and having the lengthy SQL code embedded in Ruby is rather ugly.
Also, rgeo already provides an area method on the RGeo::Feature::Surface module, which RGeo::Feature::Polygon includes. Its default implementation just isn't all that useful:
srs_db = RGeo::CoordSys::SRSDatabase::ActiveRecordTable.new
wgs84_factory = RGeo::Geographic.spherical_factory(srid: 4326, srs_database: srs_db)

# 1/8 of the Earth, should be around 6.4e13 sqm
polygon = wgs84_factory.parse_wkt('POLYGON ((0 0, 0 90, 90 0, 0 0))')

polygon.area # RGeo::Error::UnsupportedOperation: Method Surface#area not defined.

I have installed rgeo such that it can use libGEOS, which I can verify like so:
RGeo::GEOS.supported? # true

Thus, I thought that I might be luckier with a GEOS-specific factory:
geos_wgs84_factory = RGeo::Geos.factory(srid: 4326, srs_database: srs_db)
geos_polygon = RGeo::Feature.cast(polygon, geos_wgs84_factory)
geos_polygon.area # 4050.0

Well, that's the area in square degrees (90° ⨉ 90° / 2). How can I get the area in square meters without calculating it myself and without longish SQL?
Must I convert my polygon to an area-preserving projected coordinate reference system? (Those seem to come with a working area method in rgeo.) That'd feel kinda wrong to me, but maybe it's still the right thing to do.

A: Yes, if you want ST_Area() on a bare geometry to return a planar area, you need to use an area-preserving CRS. GEOS is not magic, it just works in whatever units are handed to it, assuming cartesian math, so the expectation in a planar CRS if you want useful areas/lengths etc.

A: Get the geometry from json, convert it to a projected CRS, and then do your calculation on the converted geometry.


text:
Q: Security of Isolated Storage on Windows Phone 7 and Network Transfers In my game I plan to save the users highest score to then be transferred to my server at a later time, I was planning to do this by saving the score in a .txt file in Isolated Storage.
What precautions should I take to avoid users from editing the file itself or being able to spoof packets to trick the server into saving fake scores?
I'm considering encrypting the data before saving in a way my server can read later on.
So how secure is Isolated Storage?
What encryption should I look at implementing considering my App is .NET(C#) and my server uses PHP.

A: Use ProtectedData, and store the byte[] to IsolatedStorage.
ProtectedData Class (MSDN)
Edit: If you want this to work serverside, encrypt with, say using AesManaged using a key. use ProtectedData to store the key for your AES encryption. That way, the user cannot find out your key.


text:
Q: Proving a series is less than an expression In the book I am reading I am asked to prove the following:
$$\sum_{n=1}^k{\cos n}<\frac{1}{2\sin{\frac{1}{2}}}-\frac{1}{2}$$
My attempt:
$$\sum_{n=1}^k{\cos n}=\frac{1}{2\sin{(1/2)}}\sum_{n=1}^k{2\sin{(1/2)}\cos n}\\
\frac{1}{2\sin{(1/2)}}\sum_{n=1}^k{2\sin{(1/2)}\cos n}=\frac{1}{2\sin{(1/2)}}\sum_{n=1}^k{\sin{(1/2+n)}-\sin{(1/2-n)}}\\
\frac{1}{2\sin{(1/2)}}\sum_{n=1}^k{\sin{(1/2+n)}+\sin{(-1/2+n)}}=\frac{1}{2\sin{(1/2)}}\sum_{n=1}^k{\sin{(\frac{2n+1}{2})}+\sin{(\frac{2n-1}{2})}}$$
From here the series seems to telescope, but the thing is that I cannot find the patter to simplify it. After doing this I can get an expression that is equal to the initial sum, replace it in the orginal inequality and prove it, but right now I am stuck.
Any hint or ideas is welcome!

A: Hint: You made a small mistake:
$$
2\sin\frac12\cos n=\sin(n+\frac12)-\sin(n-\frac12).
$$
After this correction the series will telescope.

A: Hint...$$\sum_{n=1}^k{\cos(a+(n-1)b)=\frac{\cos [a+ (k-1)b]\sin\frac {kb}{2}}{\sin\frac b2}}$$
In This case $a=1$ and $b=1$,so,
$$\sum_{n=1}^k{\cos(n)=\frac{\cos [\frac {k+1}{2}]\sin\frac {k}{2}}{\sin\frac 12}}$$


text:
Q: R mapping slope and intercept from a table with linear models after facet wrap using the mtcars dataset, I used pivot_longer to get a long dataframe with the numeric variables.
mtcars_numeric <- mtcars %>%
  dplyr::select(car, origin, mpg, disp, hp, drat, wt, qsec)

mtcars_long_numeric <- pivot_longer(mtcars_numeric, names_to = 'names', values_to = 'values', 4:8)

I also now have created my own table. I've created different linear models and picked out the slope and intercept for different variables against mpg. Here is the table I created:
structure(list(terms = c("intercept", "intercept", "intercept",
"intercept", "intercept", "slope", "slope", "slope", "slope",
"slope"), names = c("wt", "disp", "drat", "hp", "qsec", "wt",
"disp", "drat", "hp", "qsec"), values = c(37.2851, 29.59985,
-7.525, 30.09886, -5.114, -5.3445, -0.04122, 7.678, -0.06823,
1.412)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))

Here is a screenshot of what it looks like:

I then split this new table I created into two: one table with information about the slope and one with information about the intercept. (Not sure if this is the best idea)
mapping_df_intercept <- mapping_df %>%
  filter(terms == "intercept")

mapping_df_slope <- mapping_df %>%
  filter(terms == "slope")

I'm now trying to get a graph with a unique geom_abline for each facet.
ggplot(mtcars_long_numeric, aes(x = values, y = mpg)) +
  geom_point() +
  facet_wrap(~names, scales = 'free') +
  geom_abline(mapping = aes(intercept = values, data = mapping_df_intercept), aes(slope = values, data = mapping_df_slope), linetype = 'dashed')

This isn't working. Maybe geom_abline can't take two different aes sections.
If instead I try to use just one dataframe with both intercept and slope information and I try to put filtering into the argument, I can't get that to work either.
ggplot(mtcars_long_numeric, aes(x = values, y = mpg)) +
  geom_point() +
  facet_wrap(~names, scales = 'free') +
  geom_abline(mapping = aes(intercept = mapping_df$values[mapping_df$terms == "intercept"], slope = mapping_df$values[mapping_df$terms == "slope"]), data = mapping_df, linetype = 'dashed')

I understand that I can just use geom_smooth and it's more simple but I'm trying something else just to practice this geom_abline mapping situation.
ggplot(mtcars_long_numeric, aes(x = values, y = mpg)) +
  geom_point() +
  facet_wrap(~names, scales = 'free') +
  geom_smooth(method = 'lm')

A: I think the main struggle is trying to do this with a mapping_df that is longer than is convenient for this purpose. It becomes easier if the aes() parameters are columns in that data.
mapping_df2 <- mapping_df %>%
  pivot_wider(names_from = terms, values_from = values)

ggplot(mtcars_long_numeric, aes(x = values, y = mpg)) +
  geom_point() +
  geom_abline(
    data = mapping_df2,
    aes(intercept = intercept, slope = slope)
  ) +
  facet_wrap(~ names, scales = "free")

Created on 2021-08-18 by the reprex package (v1.0.0)
Code below was run before code at the top, but doesn't address the question. Appending this for reproducibility reasons.
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(tidyr)

mtcars_numeric <- mtcars %>%
  mutate(car = rownames(.)) %>%
  dplyr::select(mpg, wt, disp, drat, hp, qsec)

mtcars_long_numeric <- pivot_longer(mtcars_numeric, names_to = 'names', values_to = 'values', 2:6)

mapping_df <- structure(list(
  terms = c("intercept", "intercept", "intercept",
            "intercept", "intercept", "slope", "slope", "slope", "slope",
            "slope"),
  names = c("wt", "disp", "drat", "hp", "qsec", "wt",
            "disp", "drat", "hp", "qsec"),
  values = c(37.2851, 29.59985,
             -7.525, 30.09886, -5.114, -5.3445, -0.04122, 7.678, -0.06823,
             1.412)
), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))


text:
Q: Mysql Counting different column with group by I have a table where each row represent a correction with an id, date and a causes
id | date                | causes
___________________________________

1  | 2018-01-29 08:49:19 | crash
2  | 2018-08-08 10:03:37 | timeout
3  | 2018-06-26 07:48:12 | other

I use this sql request to get the number of correction by month
SELECT YEAR(date) Year, MONTH(date) Month, count(*) Total FROM correction group by YEAR(date), MONTH(date)

It gives me a result like this
Year | Month | Total
____________________

2018 |   1   | 42
2018 |   2   | 69
2018 |   3   | 50

Is it possible to modify the request to also get the number of result for each causes and have a result like :
 Year | Month | Total | crash | timeout | other
 ____________________________________________

 2018 |   1   | 42   | 10     | 12      | 20
 2018 |   2   | 69   | 9      | 50      | 10
 2018 |   3   | 50   | 10     | 20      | 20

A: You need conditional aggregation :
SELECT YEAR(date) Year, MONTH(date) Month, COUNT(*) Total,
       SUM(causes = 'crash') crash,
       SUM(causes = 'timeout') timeout,
       SUM(causes = 'other') other
FROM correction c
GROUP BY YEAR(date), MONTH(date);


text:
Q: what I have to do with this error in android studio Cannot launch AVD in emulator.
what I have to do with this error in android studio
Output:
Hax is enabled
Hax ram_size 0x60000000
HAX is working and emulator runs in fast virt mode.
emulator: WARNING: UpdateCheck: Failure: No error
none.xml:1: parser error : Extra content at the end of the document
s=Windowsversion=25.2.2.0&coreVersion=C%3A\Users\zigorat\.android">Found
                                                                               ^
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
[8652]:WARNING:./android/base/files/IniFile.cpp:158:Failed to process .ini file C:\Users\zigorat\.android\emu-update-last-check.ini for reading.
none.xml:1: parser error : Extra content at the end of the document
90f9e0a9&os=Windowsversion=25.2.2.0&coreVersion=qemu2%202.2.0">Found
                                                                               ^
emulator: WARNING: UpdateCheck: Failure: No error
emulator: WARNING: UpdateCheck: failed to get the latest version, skipping check (current version '25.2.

A: C:\Users\zigorat.android\emu-update-last-check.ini for reading. none.xml:1: parser error : Extra content at the end of the document

look this xml white spaces or close tags


text:
Q: Ruby Building an Array Argh. Having trouble here trying to work out how to build my array in Ruby.
So I am looping through a result and I want to add the category field as the key and have it so that if the next row has the same category it gets put into that category. If not, it makes a new array and adds it to that.
Here is what I have so far.
data = Array.new
results.each do |row|
   data[row.category].push row.field
end

Which is not going to work I know. I want data[row.category] to eventually be (after the loop) an array containing all the row.field's
So I end up with an array that looks like this.
[['Dogs', 5, 12, 2], ['Cats', 4, 5, 9], ['Fish', 25, 82, 23]]

So no matter how many loops I do, if I push it into an array that already exists in data then it just appends it, if the array doesn't exist it creates it and then appends it.
In PHP I would simply do this:
$data[$row['category']][] = $row['field']

With the empty [] denoting to create a new array if there is none. How do I do this in Ruby???

A: Yeah, you seem to be confused by PHP and its associative arrays (which aren't called arrays in any other language :) ). You need a hash. Try this snippet:
data = results.each_with_object({}) do |row, memo|
  memo[row.category] ||= []  # create array unless it exists
  memo[row.category] << row.field
end

A: Unlike PHP, you cannot use any object as index for an Array. In Ruby, we use Hashes to associate arbitrary objects with other objects.
Your code should work if you change it to:
data = Hash.new { |hash, key| hash[key] = [] }

results.each do |row|
   data[row.category] << row.field
end


text:
Q: update data saved in an array in my frontend the problem here is that i bring my friend list from backend and i stored it in an array in frontend so i can use it but when  a user in my friend list update his picture it didn't update in the my list so the challenge here for me is that i want a way to update this data in array i figure a way but it work on click only so this is not acceptable for good user experience and this should by dynamically and i also i tried socket io but this data is already stored in my array so i can't see socket is going to be useful in this any one face a problem like this before and if there is a better way please tell me , i worked with react,redux,mongodb and Node
exports.getFriendList = async (req, res) => {
  try {
    let user = req.user;
    const myFriendList = await Friend.findOne({ user: user.id });
    io.emit('get friend', myFriendList);
    res.json(myFriendList);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ msg: err.message });
  }
};

this is how data come from database the follower and following array remain the same after other user update there image i tried to get my friend list after i update my image with socket io as a test but it didn't work

A: If you want the images to update in the front-end autonomously upon update, Socket.io (or similar websocket library) is precisely what you need.
Your objective is to establish listeners for updating a profile image, and emitting a message to those listening out for that event.
You seem to be very concerned about the images already being in the array in the frontend, but there's no reason you can't modify the array after it is initialised.
For arguments sake, your emit could be something like this:
app.post(`/api/update-avatar`, function (req, res) => {

//Deal with updating the image here
//............

//Then emit the image
io.emit(`user-image-updated`, {userId: 2, userAvatar: yyyyyyyyy})

})

Your front-end listener could look something like this:

const FriendList = (props) => {
  const [friends, setFriends] = React.useState([
    { userId: 1, userAvatar: null, userId: 2, userAvatar: null },
  ]);

  socket.on(`user-image-updated`, (data) => {
    setFriends((currentListOfFriends) => {
      return currentListOfFriends.map((eachFriend) => {
        if (eachFriend.userId == data.userId) {
          return data;
        } else {
          return eachFriend;
        }
      });
    });
  });

  return (

      {friends.map((friend) => (

      ))}

  );
};

A: Although your question isn't that clear,
There many ways to about this...
You could use socket to send the friend list, so whenever a new data comes from your server it replaces the existing data in the friend list  array in your frontend.


text:
Q: H2 database - concurrent connections strategy I have several identical applications running independently. Each read a row from the database (based on some criteria), perform a series of operations and finally updating that row.
Therefore I want to make sure that a row started to be processed by an application, will not be processed by another. In other words, i want that an application to select the next available row.
How can I implement this?
I try'it different strategies using "select ... for update", MVCC, different type of transaction isolation, but no luck for moment.

A: A common solution is to use a 'state' column:

*

*0 not processed

*1 processing

*2 processed

When processing the row, set the state to 1. Once it's processed, set it to 2. This will work in all databases.
If you want to protect against rows being stuck in the 'processing' state (for example because the session/connection was closed), then you could add a column 'processing_session' and fill it with the current session (function SESSION_ID()) when processing. To find out if a session is still alive, use table INFORMATION_SCHEMA.SESSIONS.


text:
Q: Google map don't display / endlessly loading js script I have a strange issue. I want to display a google map on the site I'm working on. I use a map.php including html code and my initMap and createMap fonction to create my map with Map class and a constructor in a file named class.map.js .
The web page seems to be loading endlessly like the class.map.js, there is no error in the console, the repet in the console is a console.log("repet") placed in the constructor showing that the class.map.js is doing a sort of looping. any clue ?

 // Class to store the maps functions
 // @class Map

class Map {

    constructor(googleApiKey, locale, lat, lng, latLngRef, filter, geo) {
        ///////////////////////// <- VARIABLES -> ////////////////////////////////
        /////////////////////////////////////////////////////////////////////////
        /*The global parameters */
        this.googleApiKey = googleApiKey; // The Api key

        // locale ? this.locale = locale.split('_')[0] : this.locale = 'fr';

        this.locale = 'fr';
        // locale.split('_')[0]; // The country

        this.filter = filter; // the filter above the IM
        this.defaultZoomLevel = 13;

        this.boolZoomDisplay = true;
        // Used by refreshData to determine if a displayData() is needed

        this.isGeo = geo; // == true if the geolocation is available; else == false

        // If geo == true : lat / lng = My current position
        // else : lat / lng = the ref ground position (or NaN if there isn't any)

        this.lat = lat;
        this.lng = lng;
        this.latLng = {lat: lat, lng: lng};
        this.latLngRef = latLngRef; // User ref ground geoloc, can value NaN

        this.countryLatLng = {lat: 48.6, lng: 2.3};
        console.log("repet")
        // The coordinate of the country
        // if the navigator object is available we set the countryLatLng value to the value obtained by a text file
        // if(navigator.language != null){
        //     let pays = navigator.language.split('-')[1];
        //     // Do a $.ajax, and not a $.JSON, to make the call not asynchronous
        //     let _latLng;
        //     $.ajax({
        //         url: "countryCoordinates.json",
        //         dataType: 'json',
        //         async: false,
        //         success: function(data) {
        //             let obj = data[pays] || data['FR'];
        //             let lat = obj['lat'];
        //             let lng = obj['lng'];
        //             // let lat = 48.6;
        //             // let lng = 2.3;

        //             _latLng = {lat: lat, lng: lng};

        //         }
        //     });

        //     this.countryLatLng = _latLng;
        // }

        this.markersArray = []; // Contains all the markers already created
        this.newMarkers = []; // Contains all the markers undisplayed
        this.mouseDownPos = null; // used for the workaround to disable the click event onscroll

        // The currently opened infoWindow
        this.selectedInfoWindow = new google.maps.InfoWindow({});

        // Temporary marker (to creat a new ground)
        this.tempMarker;

        // == True if the click is on a cluster; else == false
        this.clusterClicked = false;

        // Configuration du style de la carte : https://snazzymaps.com
        this.styles = [
            { "featureType": "all", "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#333333" }, { "lightness": 40 }] },
            { "featureType": "all", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }, { "lightness": 16 }] },
            { "featureType": "all", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] },
            { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#fefefe" }, { "lightness": 20 }] },
            { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#fefefe" }, { "lightness": 17 }, { "weight": 1.2 }] },
            { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#f5f5f5" }, { "lightness": 20 }] },
            { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#f5f5f5" }, { "lightness": 21 }] },
            { "featureType": "poi.park", "elementType": "geometry", "stylers": [{ "color": "#dedede" }, { "lightness": 21 }] },
            { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "color": "#858585" }] },
            { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "lightness": 17 }] },
            { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#ffffff" }, { "lightness": 29 }, { "weight": 0.2 }] },
            { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#ffffff" }, { "lightness": 18 }] },
            { "featureType": "road.arterial", "elementType": "geometry.fill", "stylers": [{ "color": "#c7c7c7" }] },
            { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#ffffff" }, { "lightness": 16 }] },
            { "featureType": "road.local", "elementType": "geometry.fill", "stylers": [{ "color": "#c7c7c7" }] },
            { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#f2f2f2" }, { "lightness": 19 }] },
            { "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#e9e9e9" }, { "lightness": 17 }] },
            { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "color": "#c7c7c7" }] }
        ];

        // generate clusterStyles
        // probably better to move clusterStyles and mcOptions
        let clusterStyles = [
            {
                textColor: 'white',
                url: 'assets/img/ui/m1.png',
                width: 55,
                height: 54,
            },
            {
                textColor: 'white',
                url: 'assets/img/ui/m2.png',
                width: 58,
                height: 57,
            },
            {
                textColor: 'white',
                url: 'assets/img/ui/m3.png',
                width: 68,
                height: 67,
            },
            {
                textColor: 'white',
                url: 'assets/img/ui/m4.png',
                width: 80,
                height: 79,
            },
            {
                textColor: 'white',
                url: 'assets/img/ui/m5.png',
                width: 92,
                height: 91,
            },
        ];

        this.mcOptions = {
            gridSize: 50,
            styles: clusterStyles,
            maxZoom: 12
        };

        // document.addEventListener('DOMContentLoaded', function() {
        this.map = new google.maps.Map(document.getElementById('map'), {

            styles: this.styles,

            // Default zoom value
            zoom: 11,
            minZoom: 1,
            streetViewControl: false, // Disables the street view ("Petit bonhomme jaune")
            gestureHandling: "greedy",

            zoomControl: true, // The 2 ('+' & '-') buttons that control the zoom
            fullscreenControl: false, // The button that controles the fullscreen
            });

        // Creates the marker clusterer
        this.markerClusterer = new MarkerClusterer(this.map);
        // })

A: So i found the error, my class Map was named like the constructor provided by google to display the map.


text:
Q: Can't do an SCP pull despite SSH working fine I have setup key authentication between two servers and I can ssh in without a key, for example:
ssh backup@hostname

this works fine and logs me in.
But when I try an SCP to pull a file, I get no files.
The target files have chmod 777 done to them for troubleshooting purposes but it's like it just doesn't find any files to copy even though they are there.
Here is the (ip's obfuscated) output of
scp -vvv backup@hostname:/var/stuff/backups/*.tgz /data/backups/

from the point it authenticates onward.
debug1: Authentication succeeded (publickey).
Authenticated to xxx.xxx.xxx.xxx ([xxx.xxx.xxx.xxx]:22).
debug2: fd 4 setting O_NONBLOCK
debug2: fd 5 setting O_NONBLOCK
debug2: fd 6 setting O_NONBLOCK
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug1: Entering interactive session.
debug2: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: packet_set_tos: set IP_TOS 0x08
debug2: client_session2_setup: id 0
debug1: Sending environment.
debug3: Ignored env XDG_SESSION_ID
debug3: Ignored env TERM
debug3: Ignored env SHELL
debug3: Ignored env SSH_CLIENT
debug3: Ignored env SSH_TTY
debug3: Ignored env http_proxy
debug3: Ignored env USER
debug3: Ignored env LS_COLORS
debug3: Ignored env MAIL
debug3: Ignored env PATH
debug3: Ignored env QT_QPA_PLATFORMTHEME
debug3: Ignored env PWD
debug1: Sending env LANG = en_AU.UTF-8
debug2: channel 0: request env confirm 0
debug3: Ignored env SHLVL
debug3: Ignored env HOME
debug3: Ignored env LANGUAGE
debug3: Ignored env LOGNAME
debug3: Ignored env SSH_CONNECTION
debug3: Ignored env LESSOPEN
debug3: Ignored env XDG_RUNTIME_DIR
debug3: Ignored env LESSCLOSE
debug3: Ignored env _
debug3: Ignored env OLDPWD
debug1: Sending command: scp -v -f /var/stuff/backups/*.tgz
debug2: channel 0: request exec confirm 1
debug2: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel 0: rcvd adjust 131072
debug2: channel_input_status_confirm: type 99 id 0
debug2: exec request accepted on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug2: channel 0: rcvd eof
debug2: channel 0: output open -> drain
debug2: channel 0: obuf empty
debug2: channel 0: close_write
debug2: channel 0: output drain -> closed
debug2: channel 0: rcvd close
debug2: channel 0: close_read
debug2: channel 0: input open -> closed
debug3: channel 0: will not send data after close
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
  #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cc -1)
debug1: fd 0 clearing O_NONBLOCK
debug1: fd 1 clearing O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
Transferred: sent 3736, received 2280 bytes, in 0.0 seconds
Bytes per second: sent 764498.2, received 466556.7
debug1: Exit status 1
backup@ar-secubn03:/var/scripts$

A: Try this:
scp -vvv 'backup@hostname:/var/stuff/backups/*.tgz' /data/backups/

If that doesn't work try this:
scp -vvv 'backup@hostname:/var/stuff/backups/\*.tgz' /data/backups/

A: I was having a similar issue that I could exercise ssh commands, but not scp commands.  I went through Kenster good debug techniques which still didn't get me anywhere, but very handy!  I finally found out the issue was related to echo commands in my .bashrc script (after inserting additional ones).  Once I commented out all the echo commands in the script I was able to successfully execute the scp command.

A: debug1: Sending command: scp -v -f /var/stuff/backups/*.tgz
debug2: channel 0: request exec confirm 1
debug2: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel 0: rcvd adjust 131072
debug2: channel_input_status_confirm: type 99 id 0
debug2: exec request accepted on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
...
debug1: Exit status 1

These lines indicate that the local scp instance requested the expected scp command to run on the remote system, and the remote server launched a process in response to the request. But the remote process exited with status code 1 almost immediately, and without emitting any output.
If the remote scp instance couldn't read the files to be copied, or if those files didn't exist, you would have gotten an error message to that effect. If the remote scp program couldn't be found or wasn't executable, then the exit code would have been 126 or 127 instead of 1.
I suspect one of these things is happening:

*

*Something in the remote account's .bashrc or .bash_profile is causing the shell to exit early. It may be sensitive to the fact the session doesn't have a TTY, for example.

*The scp program on the remote system is corrupt or malfunctioning.

*The scp program on the remote system has been replaced with something else which isn't working like scp. Someone might have replaced it with a poorly written shell script, for example, or a copy of '/bin/false'.

*The SSH software has been configured to block people from running scp. The key which you're using may be set in authorized_keys to run a specific command, or there may be a ForceCommand directive in the remote server's sshd_config file.

The simplest way to check these would be to ask the remote system administrator, or log into the remote system and inspect the scp executable. Running scp -h will print an scp-specific usage message, for example.
If you have to troubleshoot this remotely, the next thing I'd try is something like this:
$ ssh -T backup@hostname cat /etc/group

This should write the remote system's group file to your terminal. This would prove that you can run arbitrary commands on the remote system.
$ ssh -T backup@hostname scp -v -f /etc/group < /dev/zero

This simulates the remote part of an scp session. If the remote scp program is working, you should get output something like this:
C0644 674 group
root:x:0:
daemon:x:1:
[...]
devuser:x:1001:
Sending file modes: C0644 674 group
$

If all of that works, the question becomes why scp fails for "/var/stuff/backups/*.tgz" but works for "/etc/group". You could run this to confirm whether it's working or not:
ssh -T backup@hostname 'scp -v -f /var/stuff/backups/*.tgz' < /dev/zero

If that continues to fail, the nuclear option would be to arrange to run the remote session under strace and see exactly what each program is doing.

A: Your problem is clearly identified in these lines:
debug2: exec request accepted on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug2: channel 0: rcvd eof

which shows your channel is shut down as soon as it is opened, though the reason is not stated.
Normally,this occurs because of a faulty configuration in the /etc/passwd file, see for instance this Server Fault post. You may follow the suggestions in this post, or, better still, you may check the logs on the target machine,
 tail /var/log/auth.log

for further details.

A: I think you do 1st backups/* .tgz to change backups*.tgz
make sure don't use any space. might be 99% issue solved.

A: I had the same bad experience. I slight modification of the .bashrc on the remote system was the problem. I once added 'ulimit' and got the this problem during the next scp (ssh worked). After removing this line all was fine.

A: I've got a similar problem : impossible to use SCP between two VMs under CENTOS whereas SSH key was exhanged, and ssh works fine...
But, after weeks...it appeared by both CENTOS does not use the same SHELL.
One was with .tcshrc, whereas the other was this .bashrc
Consequently, the SCP command was always misinterpreted by the host.
I aligned both SHELL on both VMs, and now, it works fine !