text:
Q: dispose is not a member of GDI+ Image class So I have a program that pulls random images from a folder and creates a collage out of them, and set it to the windows wallpaper.  Which seems to work fine.  So I thought I would put in a sleep timer and let it automatically update itself without me having to run it every half hour or what ever.  I did that and it works great, but I ran into a problem of a memory leak that wasn't noticed before I started looping it.  I am attempting to dispose of the GDI+objects, but I keep getting the error that dispose is not a member of GDIplus::Image
I am loading an picture into an Image object, then resizing it and putting it into an array of Images, then I would like to dispose of the first Image.  I would then like to dispose of the array after I finish working with the images in it.
This is being done with an old copy of VS2005.
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
#include <string>
#include <iostream>
#include <vector>
#include <dirent.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include "cwp05rnd.h"

using namespace Gdiplus;
using namespace std;
#pragma comment (lib,"Gdiplus.lib")
#pragma comment (lib, "user32.lib")

int main()
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR           gdiplusToken;
HDC                 hdc;
Graphics            graphics(hdc);

GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
CLSID jpegClsid;
GetEncoderClsid(L"image/jpeg", &jpegClsid);

SetCurrentDirectoryA("E:\\Photos");
ofstream outfile;
outfile.open ("outimgs.txt");
ofstream outfile2;
outfile2.open("imgpos.txt");

srand(time(NULL));
init_genrand(time(NULL));

vector<string>  dirlist;
DIR             *d;
struct          dirent *dir;

int i=0;
d=opendir(".");
if (d)
{
    while ((dir=readdir(d)) != NULL)
    {
        i++;
        dirlist.push_back(dir->d_name);
    }
    closedir(d);
}
Image   wp(L"E:\\Dropbox\\Photos\\wallpaper.jpg");
Graphics* wpimage = Graphics::FromImage(&wp);
int r;
int rvsize=100;
int rv[100]={0};
string img;
std::wstring wimg;
const wchar_t* rimg;
double cwidth;
double cheight;
double ratio;
int nheight;
int counter=0;
    int full = 0;
    int tries = 0;
    int hfull = 0;
    int imgnum =0;
    int last=0;
    Image* newpic[10];

    while ( tries <10)
    {
        redo:
        tries++;
        int newrv=0;
        while (newrv ==0)
        {

            r=genrand_int32()%i;
            for (int k=0; k < rvsize; k++)
            {

                if (rv[k] > 0 && rv[k]==r )
                {
                    break;
                }
                if (rv[k]==0 && r < i)
                {
                    newrv =1;
                    rv[k]=r;
                    last=k;
                    break;
                }
                if (rv[k] ==0)
                {
                    break;
                }
            }

        }
        img = dirlist[r];
        if (img[0]=='.')
        {
            newrv=0;
            goto redo;
        }
        wimg = std::wstring(img.begin(),img.end());

        rimg = wimg.c_str();

        Image pic(rimg);

        cwidth = pic.GetWidth();
        cheight = pic.GetHeight();
        if (cheight ==0)
        {
            outfile2 << "error" << img << endl;
            rv[last]=0;
            system("pause");
            goto redo;
        }
        ratio = cwidth/cheight;
        nheight = nwidth/ratio;
        pic.RotateFlip(Rotate180FlipNone);
        pic.RotateFlip(Rotate180FlipNone);
        newpic[imgnum] = pic.GetThumbnailImage(nwidth,nheight,NULL,NULL);
                    delete pic[0];
                    imgnum = imgnum + 1;
        }

then there is a long section of flips and rotates on the images in newpic, according to various random values.
wpimage->DrawImage(newpic[k],(j*nwidth),(((k+1)*whitespace)+htot),nwidth,nh[k]);
wp.Save(L"C:\\Temp\\wallpaper\\nwallpaper.jpg", &jpegClsid, NULL);
delete newpic;
setWall();
delete wpimage;
delete wp;
return 0;
}

When I attempt to delete the Image objects, I get an error that says either it can not delete objects that are not pointers, or it cannot convert from GDIplus::Image to void*
Any advice would be appreciated.

A: I noticed you have Image pic(rimg);
But you are doing delete pic[0];
pic is not a pointer.. not dynamically allocated or something... nor is a array (or maybe it is.. but intuitively I think no..)
* Add *
Oh yeah, if you already solved this, suggests you close the question or at least mention it...


text:
Q: second monitor blank after login on Kubuntu Primary monitor is DVI (apparently, it is detected by Kubuntu as HDMI)
I added a second monitor, VGA.
At sign-in screen, both monitors show the same display
After login, the second monitor is blank.
In Displays -- System Settings the second monitor is greyed out and unconfigurable.
System:
  Host: Kubuntu Kernel: 5.3.0-29-generic x86_64 bits: 64
  Desktop: KDE Plasma 5.16.5 Distro: Ubuntu 19.10 (Eoan Ermine)
Machine:
  Type: Desktop Mobo: ASUSTeK model: B150M-K D3 v: Rev X.0x
  serial: <filter> UEFI: American Megatrends v: 2604 date: 02/21/2018
CPU:
  Topology: Quad Core model: Intel Core i5-6500 bits: 64 type: MCP
  L2 cache: 6144 KiB
  Speed: 800 MHz min/max: 800/3600 MHz Core speeds (MHz): 1: 800 2: 800
  3: 800 4: 800
Graphics:
  Device-1: Intel HD Graphics 530 driver: i915 v: kernel
  Display: x11 server: X.Org 1.20.5 driver: modesetting
  unloaded: fbdev,vesa resolution: 1920x1080~60Hz
  OpenGL: renderer: Mesa DRI Intel HD Graphics 530 (Skylake GT2)
  v: 4.5 Mesa 19.2.8
Audio:
  Device-1: Intel 100 Series/C230 Series Family HD Audio
  driver: snd_hda_intel
  Device-2: JMTek LLC. USB PnP Audio Device type: USB
  driver: hid-generic,snd-usb-audio,usbhid
  Sound Server: ALSA v: k5.3.0-29-generic
Network:
  Device-1: Realtek RTL8111/8168/8411 PCI Express Gigabit Ethernet
  driver: r8169
  IF: enp2s0 state: up speed: 100 Mbps duplex: full mac: <filter>
Drives:
  Local Storage: total: 1.14 TiB used: 560.51 GiB (48.1%)
  ID-1: /dev/sda vendor: Crucial model: CT250BX100SSD1 size: 232.89 GiB
  ID-2: /dev/sdb vendor: Western Digital model: WD10EZEX-00BN5A0
  size: 931.51 GiB
Partition:
  ID-1: / size: 42.81 GiB used: 14.10 GiB (32.9%) fs: ext4 dev: /dev/sda5
Sensors:
  System Temperatures: cpu: 29.8 C mobo: 27.8 C
  Fan Speeds (RPM): cpu: 0
Info:
  Processes: 206 Uptime: 25m Memory: 7.66 GiB used: 5.97 GiB (77.9%)
  Shell: bash inxi: 3.0.36

A: It might help to load arandr (the "Screen Layout Editor") and reorient your monitors using the gui. Let arandr generate an xrandr line for you (Layout --> Save As).  arandr is apt-get if you don't already have it.
If execution of the xrandr line displays the output of both monitors, the line can be appended to ~/.profile.  Alternately, one can use the xrandr information in xorg.conf.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable the address autocomplete for an input on Chrome? I started with this solution:
<input autocomplete="off"/>

which worked for current safari and firefox, and some chromes. But then I am now trying to do this:
<input autocomplete="hello-<timestamp>-<randomnumber>"/>

That works for firefox, chrome, and safari on Mac, but not for windows. I only want to disable some of the inputs in a form, not all.
How do I get this to work on Chrome for Windows?
This is for a non-password field, like a phone number or username. I understand that you can't really disable autocomplete for passwords these days.

A: Add to all fields autocomplete="off". Then check which fileds still perform an autocomplete (for the address), and set the ones to autocomplete="address-level4" (thank you @michael crenshaw).
Also I found out, that the autocpmlete happens depending on the naming of the id of the input. So if you want to disable it just do not set the id (which probably isnt what you want depending on how you process the input, thus this is not really a good clean solution).


text:
Q: Why do my Cypher queries yield different results? Why do these two queries yield different results:
MATCH (keanu:Person {name:"Keanu Reeves"})-[:ACTED_IN]->(kMovie)<-[:ACTED_IN]-(actor:Person),
(actor)-[:ACTED_IN]->()<-[:ACTED_IN]-(actor2)
WHERE NOT (actor2)-[:ACTED_IN]->(kMovie)
RETURN actor2.name, COUNT(actor2)
ORDER BY COUNT(actor2) DESC
LIMIT 3;

And the second one is:
MATCH (keanu:Person {name:"Keanu Reeves"})-[:ACTED_IN]->(kMovie)<-[:ACTED_IN]-(actor:Person),
(actor)-[:ACTED_IN]->()<-[:ACTED_IN]-(actor2)
WHERE NOT (actor2)-[:ACTED_IN]->()<-[:ACTED_IN]-(keanu)
AND keanu <> actor2
RETURN actor2.name, COUNT(actor2)
ORDER BY COUNT(actor2) DESC
LIMIT 3;

The second one gives me the correct result but I don't know why the first one's result is different?
First result:
╒═════════════╤═══════════════╕
│"actor2.name"│"COUNT(actor2)"│
╞═════════════╪═══════════════╡
│"Emil Eifrem"│"6"            │
├─────────────┼───────────────┤
│"Tom Hanks"  │"4"            │
├─────────────┼───────────────┤
│"Stephen Rea"│"3"            │
└─────────────┴───────────────┘

Second result:
╒═════════════╤═══════════════╕
│"actor2.name"│"COUNT(actor2)"│
╞═════════════╪═══════════════╡
│"Tom Hanks"  │"4"            │
├─────────────┼───────────────┤
│"Stephen Rea"│"3"            │
├─────────────┼───────────────┤
│"Ben Miles"  │"3"            │
└─────────────┴───────────────┘

The dataset is the sample movie graph dataset that can be created from example graphs part in Neo4j.

A: Your queries are asking different questions.
The first query is asking:
Find Keanu Reeves, one specific movie he's acted in, and a coactor in that one specific movie, and with that coacter, find a coactor of THEM (coactor2) where coactor2 never acted in that one specific movie we selected earlier.
The second query is asking:
Find Keanu Reeves, one specific movie he's acted in, and a coactor in that one specific movie, and with that coacter, find a coactor of THEM (coactor2) where coactor2 never coacted with Keanu Reeves in any movie (also, make sure coactor2 is not actually Keanu Reeves).
In the results, "Emil Eifrem" co-acted with Keanu in The Matrix, so Emil would never appear in results in the second query no matter which one specific movie is used each row.
The reason Emil appears in the first query results is that, for some rows in the result set, the one specific movie you matched on (kMovie) was not The Matrix, but some other movie. In those rows, Emil is a coactor (coactor2) of those coactors for other movies, and did not act in whatever one specific movie was matched for that row.
As one concrete example of a row here, that one specific movie matched was The Matrix Reloaded, where Hugo Weaving was a coactor. Hugo Weaving coacted with Emil in The Matrix, and Emil never acted in The Matrix Reloaded.
The reason Emil has a count of 6 in the first query is because there are 3 coactors with Keanu (Laurence Fishburne, Hugo Weaving, and Carrie-Anne Moss) on 2 different movies that are not The Matrix (The Matrix Reloaded and The Matrix Revolutions), and all 3 of those coactors coacted with Emil on The Matrix, and Emil never acted in The Matrix Reloaded or The Matrix Revolutions. 3 (coactors) * 2 (movies) = 6 rows emitted where Emil appears in the result set.
I hope that explains the differences between the two queries adequately.

A: Since you're saying your second query gets you the results that you want, let's break that one down.
MATCH (keanu:Person {name:"Keanu Reeves"})-[:ACTED_IN]->(kMovie)<-[:ACTED_IN]-(actor:Person) is identifying the Person(s) with the name Keanu Reeves as keanu that ACTED_IN something what we call kMovie, that at least another Person called actor ACTED_IN.
(actor)-[:ACTED_IN]->()<-[:ACTED_IN]-(actor2) WHERE NOT (actor2)-[:ACTED_IN]->()<-[:ACTED_IN]-(keanu) AND keanu <> actor2 That actor also ACTED_IN something that (another) actor2 ACTED_IN, which didn't ACTED_IN something together with keanu (but isn't keanu himself).
RETURN actor2.name, COUNT(actor2) Now you're simply interested in the name of that Person and in how many results (rows) that Person shows up, actually you're only interested in the top 3 results: ORDER BY COUNT(actor2) DESC LIMIT 3
On why this yields different results compared to the first query.
WHERE NOT (actor2)-[:ACTED_IN]->(kMovie) remember, that kMovie is a movie that both keanu and actor acted in. Which is different to the second query of just asking for movies where keanu didn't act in (not caring about actor's participation or not.


text:
Q: Blurring images server side or with CSS I have a website which has images uploaded by the user which is blurred with the following CSS:
.blur {
  -webkit-filter:blur(40px);
  filter:blur(40px);
  filter:progid:DXImageTransform.Microsoft.Blur(PixelRadius='40')
}

However there is little support with this as seen here.
One way of allowing this to work across all browsers is by blurring the image server side (I'm using Python with Flask so I could use the pill Python library, blur it and then save that image.)
However there are also disadvantages to using this such as greater storage costs.
So, should I blur the images server side or is there a CSS workaround? Thanks.

A: I know this is an old question but it came up in my search. For anyone else looking into this, one thing to consider is the client-side processor overhead required to blur with a radius of 40px. I am building a page that blurs a scrolling section over a fixed background (this is for visual effect, not to obscure content/security), and while scrolling, my CPU usage was unusually high. This was causing perceptible lag on a recent model laptop. I ended up going with server-side pre-blurred images instead of the CSS filter, and CPU usage while scrolling the page is substantially lower.
In general, as @taesu noted, a visual effect like this is usually best done with CSS, but be sure you're not incurring a performance hit that negatively impacts your user experience.


text:
Q: Array created using dayjs outputs undefined elements I am trying to make a react calendar using dayJs library, I create a 2d array for month using the following code :
import dayjs from "dayjs";

export const getMonth = (month = dayjs().month()) => {
    const year = dayjs().year();
    const firstDayOfMonth = dayjs(new Date(year, month, 1)).day();
    let currentMonthCount = 0 - firstDayOfMonth;
    const daysMatrix = new Array(5).fill([]).map(() => {
        return new Array(7).fill(null).map(() => {
            currentMonthCount++
            return dayjs(new Date(year, month, currentMonthCount))
        })
    });
    return daysMatrix;
};

now when I import the function in my app.js file and pass it onto another component month.js which displays the array using the following code :
import React, { Fragment } from 'react';
import Day from '../components/Day';

const Month = ({ month }) => {
  if(month) {
    month.map((e) => console.log(e));
  }
  return (

      {month.map((row, i) => (
        <Fragment key={i}>
          {row.map((day, j) => (
            <Day day={day} key={j} />
          ))}
        </Fragment>
      ))}

  )
};
export default Month;

here, the console log outputs the month array as it should but I get an error in the return section stating unable to read properties of undefined reading map, could someone please explain why am I getting this error although the map worked fine for the console.log statement?
my app.js file :
import React, { useState } from 'react';
import './App.css';
import { getMonth } from './util';
import { Fragment } from 'react';
import CalendarHeader from './components/CalendarHeader';
import Sidebar from './components/Month';
import Month from './components/Month';

function App() {
  const [currentMonth, setCurrentMonth] = useState(getMonth());
  return (
    <Fragment>

        <CalendarHeader />

          <Sidebar />
          <Month month={currentMonth} />

    </Fragment>
  );
}

export default App;

A: unable to read properties of undefined reading map this kind of error can occur when you are trying to loop over or using the map method over an undefined value.
To resolve this you can use Optional chaining (?.).
In your case, you need to use this in Month component as done below:
{month?.map((row, i) => (
        <Fragment key={i}>
          {row?.map((day, j) => (
            <Day day={day} key={j} />
          ))}
        </Fragment>
      ))}

Let me know if this works for you.


text:
Q: Difference between hamiltonian path and euler path Can some one tell me the difference between hamiltonian path and euler path. They seem similar!

A: Eulerian path must visit each edge exactly once, while Hamiltonian path must visit each vertex exactly once.

A: They are related but are neither dependent nor mutually exclusive. If a graph has an Eurler cycle, it may or may not also have a Hamiltonian cyle and vice versa.

Euler cycles visit every edge in the graph exactly once. If there are vertices in the graph with more than two edges, then by definition, the cycle will pass through those vertices more than once. As a result, vertices can be repeated but edges cannot.
Hamiltonian cycles visit every vertex in the graph exactly once (similar to the travelling salesman problem).  As a result, neither edges nor vertices can be repeated.

A: I'll use a common example in biology; reconstructing a genome by making DNA samples.
De-novo assembly
To construct a genome from short reads, it's necessary to construct a graph of those reads. We do it by breaking the reads into k-mers and assemble them into a graph.

We can reconstruct the genome by visiting each node once as in the diagram. This is known as Hamiltonian path.
Unfortunately, constructing such path is NP-hard. It's not possible to derive an efficient algorithm for solving it. Instead, in bioinformatics we construct a Eulerian cycle where an edge represents an overlap.

A: A Hamiltonian path visits every node (or vertex) exactly once, and a Eulerian path traverses every edge exactly once.

A: Euler Path - An Euler path is a path in which each edge is traversed exactly once.
Hamiltonian Path - An Hamiltonian path is path in which each vertex is traversed exactly once.
If you have ever confusion remember E - Euler E - Edge.

A: An Euler path is a path that passes through every edge exactly once. If it ends at the initial vertex then it is an Euler cycle.
A Hamiltonian path is a path that passes through every vertex exactly once (NOT every edge). If it ends at the initial vertex then it is a Hamiltonian cycle.
In an Euler path you might pass through a vertex more than once.
In a Hamiltonian path you may not pass through all edges.

A: Graph Theory Definitions
(In descending order of generality)

*

*Walk: a sequence of edges where the end of one edge marks the beginning of the next edge

*Trail: a walk which does not repeat any edges. All trails are walks.

*Path: a walk where each vertex is traversed at most once.
(paths used to refer to open walks, the definition has changed now) The property of traversing vertices at most once means that edges are also crossed at most once, hence all paths are trails.
Hamiltonian paths & Eulerian trails

*

*Hamiltonian path: visits every vertex in the graph (exactly once, because it is a path)

*Eulerian trail: visits every edge in the graph exactly once (because it is a trail, vertices may well be crossed more than once.)

A: An Euler path is a path that uses every edge of a
graph exactly once.and it must have exactly two odd vertices.the path starts and ends at different vertex.                                                          A Hamiltonian cycle is a cycle that contains every vertex of the graph hence you may not use all the edges of the graph.

A: Euler path is a graph using every edge(NOTE) of the graph exactly once. Euler circuit is a euler path that returns to it starting point after covering all edges.
While hamilton path is a graph that covers all vertex(NOTE) exactly once. When this path returns to its starting point than this path is called hamilton circuit.


text:
Q: itextsharp 5.5.10 converting gridview to pdf in c# with a heading for pdf ? (beginner) Every code found on net is either showing absolute or not working !Using dropdownlist on Ajax update panel and on its index change showing gridview.
Gridview is working . is there any better practice for converting pdf ? or help to convert gridview to pdf using itextsharp 5.5.10

A: *

*First Pass Gridview Dt to Itextsharp function.

*

*like void PrintPDF(Datatable dt)

*then use below code for Datatable Printing .

*I've show you just little part of my code, You should design Table as per your requirement.
for (int k = 0; k < dt.Rows.Count; k++)
          {
            PdfPTable tableinside = new PdfPTable(1);
            tableinside.WidthPercentage = 100;
            tableinside.HorizontalAlignment = 0;
            tableinside.DefaultCell.BorderColor = iTextSharp.text.Color.WHITE;
        PdfPCell cell28 = new PdfPCell(new Phrase(dt.Rows[k]["Name"].ToString(), topfont1));
        cell28.BorderWidthTop = 0.5f;
        cell28.BorderWidthLeft = 0.5f;
        cell28.Border = 0;
        cell28.PaddingTop = 5f;
        cell28.PaddingLeft = 10f;
        cell28.PaddingBottom = 8f;
        cell28.BorderColor = iTextSharp.text.Color.WHITE;
        tableinside.AddCell(cell28);

}


text:
Q: Twisted IRC Bot threading I need help with my Twisted IRC Bot. If there is a big text that is called when using some command (ex. !text) - I need to wait for the bot to finish sending that text before it executes other commands.
Is it possible to make !text threaded so it keeps sending the text to the channel while in the same time listening and executing other commands.

A: You really don't need to use threading in order to accomplish anything like this.  Sending the text happens almost instantly; Twisted will buffer it for you, and you can go off and do other things.  In the case of IRC in particular, you can set the lineRate attribute on the client and messages will automatically be throttled to a particular speed (to avoid being flood-kicked, which is what I think you're really asking), without your code having to do anything.


text:
Q: How to publish posts on the home page? I have some code:
models.py (model Posts):
STATUS = (
    (0,"Draft"),
    (1,"Publish")
)

 class Post(models.Model):

    title = models.CharField(max_length=200, unique=True db_index=True )
    slug = models.SlugField(max_length=200, unique=True)
    updated_on = models.DateTimeField(auto_now= True)
    publish = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)

views.py
class PostList(generic.ListView):

    queryset= Post.objects.filter(status=1).order_by('-publish')
    template_name = 'index.html'
    paginate_by = 6

urls.py
 path('', views.PostList.as_view(), name='home'),

After I create an article in the admin panel, I click publish, the article is not displayed on the main page. But if you restart the server (manage.py run server), then the article appears on the main page.
Question:
How to make the article appear on page reload and does not require server reboot?

A: I had a similar issue for a website I had a while back. What I had found is that the cache was not refreshing often enough (since the update/changed page was not cached in my browser, it was like it was invisible to it). The solution for this was (on the server end) to update the .htaccess file. 'Cache-control' is the key function. In my case, the code looked like this:
<filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|html)$">
    Header set Cache-Control "max-age=1200, public, must-revalidate"
</filesMatch>

Here is more information:
https://www.imperva.com/learn/performance/cache-control/

A: It turned out that with such a construction:
views.py

class PostList(generic.ListView):
  queryset= Post.objects.filter(status=1).order_by('-publish')
  template_name = 'index.html'
  paginate_by = 6

we read posts from the database only at the moment of server restart.
I created just such a function and it helped to solve the problem
def postlist(request):
  queryset= Post.objects.filter(status=1).order_by('-publish')
  return render (request, index.html, {'queryset': queryset})


text:
Q: Function to update total cost not working I am building a simple shopping cart using simpleCart.js.
I have been able to display items, add them to my basket and checkout. However, i am trying to add a dropdown to allow the users to select a country to determine the shipping cost.
Plunker: http://plnkr.co/edit/aB6JLxmYcPpWR4IsUqEZ?p=preview
I have added the following select, however how can i connect this to the simpleCart.js? I believe the Update() needs to be called:
JS:
<select class="item_Shipping" id="AddShipping">
  <option value="4.99">England £4.99</option>
  <option value="5.99">Ireland £5.99</option>
  <option value="7.99">Europe £7.99</option>
</select>

A: See http://plnkr.co/edit/CIZsHALaRqMbRQNb6hgF?p=preview
First you need a way to get the shipping cost:
simpleCart({
    shippingCustom: function(){
        var ddl = document.getElementById("AddShipping");
        return ddl.options[ddl.selectedIndex].value;
    }
});

and then when drop down changes, update the values:
document.getElementById("AddShipping").addEventListener("change", function(){
    simpleCart.update();
});


text:
Q: How to remove old branch HWE kernels? today I ran the usual update on my ubuntu server version 20.04.whatever and I see this, as usual:
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.15.0-58-generic
Found linux image: /boot/vmlinuz-5.15.0-57-generic
Found initrd image: /boot/initrd.img-5.15.0-57-generic
Found linux image: /boot/vmlinuz-5.15.0-56-generic
Found initrd image: /boot/initrd.img-5.15.0-56-generic
Found linux image: /boot/vmlinuz-5.4.0-137-generic
Found initrd image: /boot/initrd.img-5.4.0-137-generic
Found linux image: /boot/vmlinuz-5.4.0-136-generic
Found initrd image: /boot/initrd.img-5.4.0-136-generic

So, my system, due to newer HWE, has kernel version 5.15 but I still have installed (and updated but not used) kernel branch 5.4.
While update process works correcly, and autoremove correctly older version: can I get rid once for all kernel 5.4?

A: You can use Synaptic and remove all 5.4 kernel image and headers.
This should also remove linux-generic, linux-image-generic and linux-headers-generic packages.
This will stop upgrading non-HWE kernels.


text:
Q: SQL server 2000 how to find transaction history for a table/row How do you find the modification history for a certain table / row in SQL server 2000? Thanks.

A: you need to get a product that can read the transaction log like SQL Log Rescue or Apex SQL Log


text:
Q: Kendo UI Grid Manual Save I have a Kendo Grid and a datasource for the grid that is binding a bunch of rows to it. Each row that is being pullef rom the datasource is a model that has a navigation property. However, when I create a new row and save it using the default kendo "save" function for the grid, the navigation properties are not initialized. I need to be able to create a new table for the navigation property in my grid. I have the following setup.
        $('#grid').kendoGrid({
            dataSource: viewmodel.model.AChecklistCompleteSource,
            filterable: true,
            sortable: true,
            pageable: true,
            columns: [{
                field: "createdBy",
                title: "Created By",
                width: 200
            },
            {
                field: "dateCreated",
                title: "Date Created"
            },
            {
                field: "dateModified",
                title: "Date Modified"
            },
            { command: { text: "View Checklist", click: viewmodel.model.showDetails }, title: " ", width: "180px" }
            ],
            toolbar: [{ name: "create", text: "Create Checklist" }, { name: "save", text: "Save Checklist" }, "cancel"],
            editable: "inline",
            saveChanges: function (e) {
                 //How do I manually save here so that my navigation property is not null for this row's model?
                if (!confirm("Are you sure you want to save all changes?")) {
                    e.preventDefault();
                }
            },
            height: 500
        });

EDIT:
Here is my entity framework code first model with two navigation properties that are null when the kendo grid creates a new row:
    public partial class AChecklistComplete
{
    [Key]
    public int AChecklistCompleteID { get; set; }
    public string createdBy { get; set; }
    public DateTime dateCreated { get; set; }
    public DateTime dateModified { get; set; }
    public virtual ChecklistTop AChecklistTop { get; set; }
    public virtual Aircraft Aircraft { get; set; }
}

My AChecklistCompleteSource  just has a list of these models. When kendo creates a new row, it lets me create and save a row with this model, but Aircraft and AChecklistTop are null, and I would like to manually initialize them(or automatic if possible) so that I can bind to them on my form at some point(i.e somefield=AChecklistComplete.Aircraft.SomeField)


text:
Q: Selecting a subset of a sqlite database with dplyr I'm trying to pull down a subset of rows in a sqlite database using dplyr.  Since slice doesn't work with tbl_sql objects, I'm using the window function row_number.  But I get the following error:
Source: sqlite 3.8.6
[/Library/Frameworks/R.framework/Versions/3.2/Resources/library/dplyr/db/nycflights13.sqlite]
Error in sqliteSendQuery(con, statement, bind.data) :
error in statement: no such function: ROW_NUMBER

dplyr version 0.4.3.9000, RSQLite version 1.0.0.  Reproducible example:
library(dplyr)
library(nycflights13)

flights_sqlite <- tbl(nycflights13_sqlite(), "flights")

filter(flights_sqlite, row_number(month) == 1L) %>% collect()

A: Probably there's a more efficient and faster way, but head seems to do the job.

To extract first n rows, for instance first 10 records:

head(flights_sqlite, 10) %>% collect()

Output:
   year month day dep_time dep_delay arr_time arr_delay carrier tailnum flight origin dest air_time distance hour minute
1  2013     1   1      517         2      830        11      UA  N14228   1545    EWR  IAH      227     1400    5     17
2  2013     1   1      533         4      850        20      UA  N24211   1714    LGA  IAH      227     1416    5     33
3  2013     1   1      542         2      923        33      AA  N619AA   1141    JFK  MIA      160     1089    5     42
4  2013     1   1      544        -1     1004       -18      B6  N804JB    725    JFK  BQN      183     1576    5     44
5  2013     1   1      554        -6      812       -25      DL  N668DN    461    LGA  ATL      116      762    5     54
6  2013     1   1      554        -4      740        12      UA  N39463   1696    EWR  ORD      150      719    5     54
7  2013     1   1      555        -5      913        19      B6  N516JB    507    EWR  FLL      158     1065    5     55
8  2013     1   1      557        -3      709       -14      EV  N829AS   5708    LGA  IAD       53      229    5     57
9  2013     1   1      557        -3      838        -8      B6  N593JB     79    JFK  MCO      140      944    5     57
10 2013     1   1      558        -2      753         8      AA  N3ALAA    301    LGA  ORD      138      733    5     58

A percentage of the first rows

head(flights_sqlite, nrow(flights_sqlite)*0.1) %>% collect()

To subset any specific number of rows. For instance rows 578 and 579:

head(flights_sqlite, nrow(flights_sqlite))[578:579, ] %>% collect()

Output:
    year month day dep_time dep_delay arr_time arr_delay carrier tailnum flight origin dest air_time distance hour minute
578 2013     1   1     1701        -9     2026        11      AA  N3FUAA    695    JFK  AUS      247     1521   17      1
579 2013     1   1     1701         1     1856        16      UA  N418UA    689    LGA  ORD      144      733   17      1


text:
Q: Jquery datepicker plugin only works for first textbox, not the second I have the jquery datepicker plugin, which works fine on the first textbox. You can click it and the calender will popup. Now how do I go about havign it do that on a second textbox? So that when that is clicked, it will also bring the popup up?
Jquery function:
    $(function() {
$("#datepicker").datepicker({dateFormat: 'dd/mm/yy'});
});

Html input box:
<input type="text" id="datepicker" />

A: Create a class like below
$(".test").datepicker({dateFormat: 'dd/mm/yy'}); });

Apply to input text by just adding a class.
<input type="text" id="datepicker" class="test"/>
<input type="text" id="datepicker2" class="test"/>

A: You cannot use duplicate id's in a page. Give each a different id and then call like this -
$('#datepciker1, #datepicker2').datepicker(....

A: The reason it isn't working on the second element is because presumably you've given the second input the same ID as the first - ID's should be unique, use a class instead:
$(function() {
  $(".datepicker").datepicker({dateFormat: 'dd/mm/yy'});
});

<input type="text" class="datepicker" />
<input type="text" class="datepicker" />


text:
Q: Avoid MemoryAllocationFailure in code with big list I wrote some code that should find number k (10 digits long), where each digit (0-9) is used only once and satisfying the following conditions:

*

*The first digit of k should be divisible by 1 (duh)

*The first two digits of k should be divisible by 2

*...

*The first ten digits of k should be divisible by 10

Here is the code:
k = Table[i, {i, 0, 9999999999}];
Select[%, IntegerLength[#, 10] == 10 &];
Select[%, Divisible[#, 10] &];
Select[%, Divisible[IntegerPart[#/10], 9] &];
Select[%, Divisible[IntegerPart[#/100], 8] &];
Select[%, Divisible[IntegerPart[#/1000], 7] &];
Select[%, Divisible[IntegerPart[#/10000], 6] &];
Select[%, Divisible[IntegerPart[#/100000], 5] &];
Select[%, Divisible[IntegerPart[#/1000000], 4] &];
Select[%, Divisible[IntegerPart[#/10000000], 3] &];
Select[%, Divisible[IntegerPart[#/100000000], 2] &]

Unfortunately I got an error: SystemException["MemoryAllocationFailure"]
What can I do to avoid this error? Is there a more neat way to solve my problem in Mathematica?
Thanks a lot!
EDIT: I am a real beginner with Mathematica, so even basic tips for improvement are appreciated!

A: You can construct such number starting from the most significant digits.
First, find all possible highest digits, then all possible combinations of highest two digits and so on...
iFindNextDigit[digits_List]:= Module[
    {newdigits, candidateNumbers, result},
    newdigits = Complement[Range[0,9], digits];
    candidateNumbers = Map[Join[digits, {#}]&, newdigits];
    result = Select[candidateNumbers, (Divisible[FromDigits[#], Length[digits]+1] )&];
    If[result == {}, Nothing, result]
    ];

findNextDigit[x_]:=Flatten[Map[iFindNextDigit,x],1];

Nest[findNextDigit, iFindNextDigit[{}], 9]

{{3, 8, 1, 6, 5, 4, 7, 2, 9, 0}}

This solution uses 0.06 MB of memory according to MaxMemoryUsed. Your original solution will need more than 80 GB of RAM to run.

A: The original brute force approach is also fine, provided the initial candidate list is better chosen:
k = 10*Map[FromDigits, Permutations[Range[9]]];
Select[%, Divisible[IntegerPart[#/10], 9] &];
Select[%, Divisible[IntegerPart[#/100], 8] &];
Select[%, Divisible[IntegerPart[#/1000], 7] &];
Select[%, Divisible[IntegerPart[#/10000], 6] &];
Select[%, Divisible[IntegerPart[#/100000], 5] &];
Select[%, Divisible[IntegerPart[#/1000000], 4] &];
Select[%, Divisible[IntegerPart[#/10000000], 3] &];
Select[%, Divisible[IntegerPart[#/100000000], 2] &]

(* {3816547290} *)

The above can also be written in a more compact way as
Fold[Function[{l, d}, Select[l, Divisible[IntegerPart[#/10^d], 10 - d] &]], k, Range[8]]

A: To resolve similar issues, i have increased the Java heap size using the following in my "init.m" file:
    <<JLink`;
    InstallJava[];
    ReinstallJava[JVMArguments -> "-Xmx512m"];

From Wolfram Support and Stack Exchange as well.
Does that work for you?


text:
Q: How to get multiple selected rows in jqGrid I am having an issue with selarrrow function (it returns null) - is there an alternative way to retrieve row ids when several rows are selected?
PS: I am not interested in debugging jqGrid, I just need to retrieve selected row ids.

A: You can use onSelectAll event fires when multiselect option is true and you click on the header checkbox. It has attributes : aRowids,status
aRowids array of the selected rows (rowid's).
status - boolean variable determining the status of the header check box - true if checked, false if not checked.
Note that the aRowids always contain the ids when header checkbox is checked or unchecked.
Lastly you  can make your own custom array on every select by following code. Note the key which is set to true will be the id.
var rowid = $(this).closest("tr.jqgrow").attr("id")


text:
Q: Find COM object (Corel.Application) for multiple instances having process ID or MainWindowHandle I have an Client Server application doing the next:
The server starts and listen to a specific port.
Many corelDraw sesions manually or programmatically start. Each corel session (client) connect to server sending the current process ID. The server keeps all connections in a listView and based on each connection EndPoint can change (send and receive) messages.
Now I would like to use COM object of a specific such process ID.
I tried:
using corel = Corel.Interop.VGCore;

int processID = Convert.ToInt32(lstClients.SelectedItems[0].SubItems[4].Text);//process ID string
Process corProc = Process.GetProcessById(processID);
int hwnd = (int)Process.GetProcessById(corProc).MainWindowHandle
this.Activate();
bool IsCom = corProc.GetType().IsCOMObject; // return false...
corApp = (corel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Corel.Application") // returns just the last session (not according to existing process ID
//tried also:
corApp = (corel.Application)System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(corProc.Handle); // error...
//tried:
corApp = (corel.Application)Convert.ChangeType(corProc, typeof(corel.Application)); // error: 'Object must implement IConvertible.'

Is there a way to obtain corel COM object to give me the oportunity to use Corel.Application object like that?
MessageBox.Show(corApp.Documents.Count.ToString());

Thanks in advance!

A: There is no general purpose mechanism to get an object from a PID, but depending upon the implementation of the OLE server, you may be able to use AccessibleObjectFromWindow.  See Launching Office Apps Programmatically for a similar example targeting PowerPoint.
You may also try using RotView to see if the application is registered in the Running Object Table.  Visual Studio, for example, registers with a moniker of !VisualStudio.DTE.14.0:21604 where 14.0 is the version and 21604 is the process id.


text:
Q: ARM template - CustomLinuxScript extension failure: Malformed status file (000003)Invalid status/status: failed I have an ARM template having 12 virtual machine resources. Each VM has 1 CustomLinuxScript extension resource associated with it.
Some of the CustomLinuxScript extensions fails with error: Malformed status file (000003)Invalid status/status: failed.
While some of them execute successfully. I deployed the same ARM template yesterday and none of them executed successfully. A few days ago all of them executed successfully. Does it seem like a bug in Azure?

A: So the answer was to go to the VM extension logs and look at the errors to verify that the shell scripts were to blame
The overview of the extension:
https://github.com/Azure/azure-linux-extensions/tree/master/CustomScript
near the of the document (readme.md) you can find where to locate the logs

A: There is no bug in Azure. There is a mistake in my shell scripts which is causing this error.


text:
Q: StrictTemplates and union type in Interface I have this interface
export interface User{
  name: string
  birthday: number | Timestamp
  ...
}

with strictTemplates:false I use this interface when I get server data with birthday in Timestamp and when I put data in local Store with birthday in number. No errors.
In strictTemplates: true I have this error:
Types of property 'birthday' are incompatible.
Type 'number | Timestamp' is not assignable to type 'number'.
  Type 'Timestamp' is not assignable to type 'number'.

What's the best practices here? I have made three interfaces:
 //without birthday
export interface User{
  name: string
  ...
}

export interface UserFromFirestore extends User {
  birthday: Timestamp;
}
export interface UserInLocal extends User {
  birthday: number;
}

And my function (in pseudo-code) is:
getUser(id: string):Observable<UserInLocal>{
  this.getDataFromFirestore(id).pipe(
  map((user:UserFromFirestore) => userWithBirthdayInNumber(user)))
}

I can do better right? My solution is too verbose right?

A: You can use generics here.
more info : generics
export interface User<T>{
  name: string
  birthday: T
}

  obj1: User<number>;
  obj2: User<Timestamp>;


text:
Q: Check proof that $p^i(1-p)^{n-i }\gt p^{i+1}(1-p)^{n-(i +1)}$ for every $p\in (0,\frac{1}{2})$, $n\in\mathbb N$ and $i\in\{0,\ldots,n-1\}$ I'd like to ask wether my proof of the following proposition is correct. Thanks..

Proposition:
(Prop.1):
$\forall p\in (0,\frac{1}{2}),\forall n\in\mathbb{N},\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }\gt p^{i+1}(1-p)^{n-(i +1)}$
(Prop.2):
$\forall p\in \{\frac{1}{2}\},\forall n\in\mathbb{N},\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }= p^{i+1}(1-p)^{n-(i +1)}$
(Prop.3):
$\forall p\in (\frac{1}{2},1),\forall n\in\mathbb{N},\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }\lt p^{i+1}(1-p)^{n-(i +1)}$

Proof:
(Prop.1):
Let $p\in (0,\frac{1}{2})$ and $n\in\mathbb{N}$, We'll prove that $\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }>p^{i+1}(1-p)^{n-(i +1)}$:
Since $n\in\mathbb{N}$, We have $1\leq n$, And thus $0\leq n-1$, And we conclude that $0\in\{0,...,n-1\}$, And thus we'll prove it first for the case $i=0\in\{0,...,n-1\}$:
For $i=0$ we have:
(Eq.1) $p^i(1-p)^{n-i }=p^0(1-p)^{n-0}=(1-p)^n$
And:
(Eq.2) $p^{i+1}(1-p)^{n-(i +1)}=p^{0+1}(1-p)^{n-(0+1)}=p(1-p)^{n-1}$
Now since $p\lt \frac{1}{2}$, We get that $2p\lt 1$, And so (Ineq.1) $p\lt 1-p$, But since $0<p$, We get by (Ineq.1) that it is also the case that $0\lt 1-p$, And thus $0\lt (1-p)^{n-1}$ (because the exponential function is always positive),
Now by multiplying (Ineq.1) by $(1-p)^{n-1}>0$, We conclude that $p(1-p)^{n-1}\lt (1-p)(1-p)^{n-1}=(1-p)^n$, But this implies by (Eq.1) and (Eq.2) that $p^{i}(1-p)^{n-i }\gt p^{i+1}(1-p)^{n-(i +1)}$ as was to be shown.
Now since $n\in\mathbb{N}$ we get that there are two cases (case 1) $n=1$ or (case 2) $2\leq n$:
(case 1): If $n=1$, Then we get $n-1=0$, And thus $\{0,...,n-1\}=\{0\}$,
But since we've already shown that for $i=0$, We have $p^{i}(1-p)^{n-i }\gt p^{i+1}(1-p)^{n-(i +1)}$, We conclude that $\forall i\in\{0\}, p^i(1-p)^{n-i }>p^{i+1}(1-p)^{n-(i +1)}$, And thus $\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }>p^{i+1}(1-p)^{n-(i +1)}$.
(case 2): If $2\leq n$, Then we have $0\leq n-2$, And thus $0\in\{0,...,n-2\}$.
Now we'll prove by terminating induction on $i$ that $\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }>p^{i+1}(1-p)^{n-(i +1)}$:
(Note: We use terminating induction since $i\in\{0,...,n-1\}$ and thus we have to terminate the induction at some point)
(base case):
For $i=0\in\{0,...,n-2\}$, We have to show that $p^i(1-p)^{n-i }>p^{i+1}(1-p)^{n-(i +1)}$, But this is exactly what we've already shown at the beginning.
(inductive step):
Now suppose that for some $i=k\in\{0,...,n-2\}$ we have $p^k(1-p)^{n-k }>p^{k+1}(1-p)^{n-(k +1)}$, And we'll prove that for $i=k+1\in\{1,...,n-1\}$ we have $p^{k+1}(1-p)^{n-(k+1) }>p^{k+2}(1-p)^{n-(k +2)}$:
(Note: Note that we ensure in the inductive step that both $k$ and $k+1$ are within $\{0,...,n-1\}$ and do not get out of the bounds)
Since $0\lt p$ and since we've already shown that $0\lt 1-p$, We have $0\lt \frac{p}{1-p}$, Now since by the induction hypothesis we have $p^k(1-p)^{n-k }\gt p^{k+1}(1-p)^{n-(k +1)}$, We get by multiplying this inequality by $\frac{p}{1-p}\gt 0$ that:
$p^{k+1}(1-p)^{n-(k+1)}=\frac{p}{1-p}p^k(1-p)^{n-k }\gt \frac{p}{1-p}p^{k+1}(1-p)^{n-(k +1)}=p^{k+2}(1-p)^{n-(k +2)}$ as was to be shown.
Thus we see from cases (case 1) and (case 2) that it is always the case that  $\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }>p^{i+1}(1-p)^{n-(i +1)}$ as was to be shown.
Q.E.D.
(Prop.2):
Let $p\in \{\frac{1}{2}\}$, $n\in\mathbb{N}$, and $ i\in\{0,...,n-1\}$, We'll prove that $p^i(1-p)^{n-i }=p^{i+1}(1-p)^{n-(i +1)}$:
Since $p\in\{\frac{1}{2}\}$, We get that $p=\frac{1}{2}$, And thus $1-p=1-\frac{1}{2}=\frac{1}{2}=p$, But this implies that $p^{i+1}(1-p)^{n-(i +1)}=p^i\cdot p\cdot(1-p)^{n-i-1}=p^i\cdot (1-p)\cdot (1-p)^{n-i-1}=p^i(1-p)^{n-i}$
as was to be shown.
Q.E.D.
(Prop.3):
Let $p\in (\frac{1}{2},1)$ and $n\in\mathbb{N}$, We'll prove that $\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }<p^{i+1}(1-p)^{n-(i +1)}$:
Since $\frac{1}{2}<p<1$, We get that $-1<-p<-\frac{1}{2}$, And this implies that $0=1-1<1-p<1-\frac{1}{2}=\frac{1}{2}$, And thus $1-p\in (0,\frac{1}{2})$, Now let's define $q:=1-p$, And we get that $1-q=1-(1-p)=1-1+p=p$ and that $q\in (0,\frac{1}{2})$, And thus by (Prop.1) we conclude that (Fact.1) $\forall i\in\{0,...,n-1\}, q^i(1-q)^{n-i }\gt q^{i+1}(1-q)^{n-(i +1)}$,
Now we'll prove that (Fact.2) $\forall i\in\{0,...,n-1\}, p^{n-i}(1-p)^{i }\gt p^{n-(i+1)}(1-p)^{i+1}$:
Let $i\in\{0,...,n-1\}$, Then by (Fact.1) we get that $q^i(1-q)^{n-i }\gt q^{i+1}(1-q)^{n-(i +1)}$, But since $q^i(1-q)^{n-i }=(1-p)^i p^{n-i}=p^{n-i}(1-p)^i$ and since $q^{i+1}(1-q)^{n-(i +1)}=(1-p)^{i+1}p^{n-(i +1)}=p^{n-(i+1)}(1-p)^{i+1}$, We conclude that $p^{n-i}(1-p)^{i }\gt p^{n-(i+1)}(1-p)^{i+1}$ as was to be shown.
Now we'll finnish the proof by showing that $\forall i\in\{0,...,n-1\}, p^i(1-p)^{n-i }<p^{i+1}(1-p)^{n-(i +1)}$:
Let $i\in\{0,...,n-1\}$, Then $0\leq i\leq n-1$, And thus $-n+1\leq -i\leq 0$, Which implies that $1=n-n+1\leq n-i\leq n$, And thus $0=1-1\leq n-i-1\leq n-1$, But this implies that $n-i-1\in\{0,...,n-1\}$, And thus we can conclude by (Fact.2), That $p^{n-(n-i-1)}(1-p)^{n-i-1 }\gt p^{n-(n-i -1+1)}(1-p)^{n-i -1+1}$, But since $p^{n-(n-i-1)}(1-p)^{n-i-1 }=p^{i+1}(1-p)^{n-(i +1)}$ and since $p^{n-(n-i -1+1)}(1-p)^{n-i -1+1}=p^i(1-p)^{n-i}$, We conclude that $p^i(1-p)^{n-i}\lt p^{i+1}(1-p)^{n-(i +1)}$ as was to be shown.
Q.E.D.


text:
Q: How to create a function to calculate days of years? I want to create function to calculate the days of year as code below. While the python throw out typeError: 'int'object is not callable. How to solve this problem? Thanks!
def DaysOfYear(year, month, day):
import datetime

dt=datetime.datetime(year,month, day, 0, 0)
tt=dt.timetuple().tm_yday()

DaysOfYear(2012, 11, 7)
The below code with specific days works. But I need to call function with variable (year, month,day) What should I do to revise the above code?
from datetime import date
dt=date(2012,11,7)
print(dt.timetuple().tm_yday)

A: Replace
tt=dt.timetuple().tm_yday()

by
dt.timetuple().tm_yday

tm_yday is an attribute (with value int, being non-callable since its not a function) in datetime.timetuple() of type time.struct_time.
>>> dt=datetime.datetime(2019, 12, 24, 0, 0)
>>> dt.timetuple()
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=358, tm_isdst=-1)

A: The following implements what the others stated and works:
def DaysOfYear(year, month, day):
    import datetime
    dt=datetime.datetime(year,month, day, 0, 0)
    tt=dt.timetuple().tm_yday
    return tt

print( DaysOfYear(2011,11,1) )


text:
Q: Windows 2008 VPN Connection I have a Windows 2008 Server that I was looking into connecting to a secure VPN. However the server is public facing and hosts a website. If I have this server connect to the secured VPN will this server be public facing?

A: It depends largely on what your definition of "Secure VPN" is, how said VPN is configured, and what's on the other side of that VPN.
Some VPN configurations force all traffic through the tunnel. In this case, then no, your website will no longer be accessible except through the VPN.
If, on the other hand, your VPN implements split tunnelling, then yes, it's most likely that your website will remain available to the public internet and only specific subnets will be routed over the VPN tunnel.

A: Yes it will remain public facing if your VPN service provider has "split Tunneling" functionality which actually split the VPN tunnel for your specified applications. It will allow you to direct some traffic or applications through a VPN tunnel while sending other traffic directly through a local network's default gateway.
Hope this answers your question or for more info please read 3rd screenshot on this http://www.purevpn.com/purevpn-dialer/


text:
Q: How to poll UART while processing lots of other stuff I have a GPS device which I need to pull data from (the NMEA strings.) However, many times per second my MCU will be busy processing something else. Is there any way to "pause" an UART/RS232 TTL signal or buffer it while my MCU does stuff? I'm looking at either a dsPIC33FJ128GP802 or an AT32UC38x.
The processing of my OSD cannot be interrupted, so interrupts are out.

A: I believe some of the dsPIC family have DMA support in the MSSP peripheral, that will allow buffering of the input stream without cpu intervention up to a point, limited by available memory.
Use an interrupt for processing the GPS data in chunks, just make sure the interrupt for your video processing work is set to a higher priority so it can bump the GPS handling interrupt.

A: Two things.

*

*Make it so you have a buffer and the
interrupts just queues up the data
into it until you have time. Make it
so parsing the GPS string is
interrupt driven.

*I have helped 5
different people do this. This is
especially simple when you only need
a small part of the string, like
position.

I can go into more detail on either method if more clarity is required.
Side note for microchip. I think their wizard for the c18 compiler(have not used the c30 much yet) will give you a library to handle queuing the data from UART for you.
You have other interrupts that cannot ever be delayed?
If your screen controller is all done in interrupts, can you not just put it in a higher level interrupt?
This means that whenever you leave your interrupt the RX data interrupt has time to put the data in a queue. This also means that whenever your other interrupts are triggered they will get the priority you expect.
Then place in your main control loop that is not interrupt driven the processing for your GPS data. This keeps things nicely compartmentalized. Remember at most GPS baud rates you have a long time to pull chars from the character string as 4800 or 9600 baud is slow...

A: It sounds like you really need to have your PIC dedicated to the display, 80-90% CPU usage is a lot. I see some similarities between a computer and its video card. I think you should strongly consider splitting your project into 2 PICs, 1 will handle all of the video (like a video card) and the other will handle any other processing. This second PIC can have some flow control setup between your video PIC such that the video PIC lets you know when it has some free CPU time. As soon as your 2nd PIC sees that there is extra time it will dump data to it.
Addition:
The GPS packet probably includes lot more information then what your display needs, your separate PIC can "clean up" the data to get you exactly what you want/need.
Also, if your second PIC isn't doing much, you can probably get away with a very cheap PIC (sub $3). This cost is probably well worth the time you will save in coding and debugging on a single PIC.

A: Another possible reason to go with the Propeller chip that was discussed in the other thread -- built-in timing for the video, and you can use a separate cog for RS232 without impacting the video.
It appears the AT32UC3B1256 also has a peripheral DMA capability, so you can receive data from the GPS without using interrupts.

A: I've done video overlay in an application which required polling during the data display.  If you have a spare FSR available, insert:

  btfsc  INTCONx,RCIF   ; I forget which INTCON it's in
   movff RCREG,POSTINC2 ; Or whichever FSR is free

at least once every 16 lines (it may be most convenient to do it every line).  Only three cycles per line.  If you do not have a spare FSR available, but your display code is expanded out rather than looped, then at least once every sixteen lines you need to use:

  movff  INTCONx,SerStatus+N  ; N=0 for the first one, 1 for the next, etc.
... and then (not necessarily immediately)
  btfsc  SerStatus+N
   movff RCREG,SerData+N

at a cost of three cycles on one line and two on another; at the end of the display:

  lfsr   0,SerData
  btfsc  SerStatus+0
   movff SerData+0,POSTINC0
  btfsc  SerStatus+1
   movff SerData+1,POSTINC0
  btfsc  SerStatus+2
   movff SerData+2,POSTINC0
  ...
  movlw  (SerData & 255)
  subwf  FSR0L,w
  ; W will now hold number of bytes received
  ; Data will be in SerData+0 to SerData+(W-1)

The trick is not to worry about figuring out what to do with data while showing the display.  Just throw it someplace and sort it out later.

A: Assuming that your GPS unit is outputting NMEA strings at 4800bps - you should be able to find a few spare cycles in your video generator to decode a serial bitstream.
Failing that:

*

*If your GPS unit supports hardware flow control, you might be able to service it between frames or when your device is idle

*Another option would be an external SPI/I2C to UART bridge. Some of these devices have reasonable sized FIFOs, allowing it to buffer up outside of your PIC. Again, service it during your idle time

A: 4800 baud is one character every 2ms. This is a dog's-age to most microcontrollers (PICs included) and you shouldn't have ANY problem collecting the data from the UART's holding register. Remember that even the most simple UART has a built-in 2 character FIFO (the holding register and the shift register). If you can't find a few cycles every 2ms to pick up a character then you need to find a beefier processor, one with a FIFO or split the job up as other people have mentioned.
The dsPIC you mentioned has 4-byte FIFOs on the UART and also has DMA capability. While 90% is a high system load for OSD (are you sure you're doing your OSD in the most efficient manner possible?) I don't know why you'd have trouble pulling in a 4800 byte NMEA stream at this system load. Missing the odd GPS update probably won't affect your application all that much, either.

A: Most serial devices implement some sort of 'flow control' == this is either via extra wires (RTS 'Request to Send', CTS 'Clear to Send') a 'handshake' that lets the recieving device set CTS hi or lo to suspend transmission ..
.. OR (for those devices that use only a RxD/TxD lines) 'software flow control' ( == you send them some specific ascii code to say 'stop sending' and onother to say 'ok, start again now')
Look up 'Flow control' in your GPS data sheet ..


text:
Q: Query Variable Table without storing variables Salesforce Marketing Cloud queries do not allow variables or temporary tables according to the "SQL Support" section of this official documentation (http://help.marketingcloud.com/en/documentation/exacttarget/interactions/activities/query_activity/)
I have a data extension called Parameters_DE with fields Name and Value that stores constant values. I need to refer to this DE in queries.
Using transact-SQL, an example is:
Declare @number INT
SET @number = (SELECT Value FROM Parameters_DE WHERE Name='LIMIT')
SELECT * FROM Items_DE
WHERE Price < @number

How can the above be done without variables or temporary tables so that I can refer to the value of the 'LIMIT' variable that is stored in Parameters_DE and so that the query will work in Marketing Cloud?

A: This is what I would have done anyway, even if variables are allowed:
SELECT i.*
FROM Items_DE i
INNER JOIN Parameters_DE p ON p.Name = 'LIMIT'
WHERE i.Price < p.Value

Wanting to a use a variable is indicative of still thinking procedural, instead of set-based. Note that, if you need to, you can join to the Parameters_DE table more than once (give a difference alias each time) to use the values of different parameters at different parts in a query.
You can also make things more efficient for this type of query by having a parameters table with one row, and a column for each value you need. Then you can JOIN to the table one time with a 1=1 condition and look at just the columns you need. Of course, this idea has limitations, too.

A: You could just use the SELECT which retrieves the number in your WHERE clause:
SELECT * FROM Items_DE
WHERE Price < (SELECT Value FROM Parameters_DE WHERE Name='LIMIT')

A: This can be done with a join
SELECT i.*
FROM Items_DE i
INNER JOIN Parameters_DE p
 ON p.Name = 'LIMIT'
AND p.Price > i.Value


text:
Q: twitter bootstrap dropdown-toggle disabled not working The disable part is not working in dropdown-toggle. Here's the code.

HOME

ABOUT ME

                GALLERY

Unit & Events

Personal

CONTACT

A: When you're disabling links in the menu, you have to add class="disabled" to the list item, and not the anchor.
Links will still be active even if the list item is disabled, so you will have to use javascript or a server-side language to prevent the links from firing. If you're dynamically generating the list, you can set the anchor's href to href="#" or you can do the same with javascript.
http://getbootstrap.com/components/#dropdowns-disabled

HOME

ABOUT ME

jQuery example:
$('li.disabled > a:link').on('click', function(e) {
  e.preventDefault();
});


text:
Q: How to describe plastic deformations in muscle? If someome does some sports intensively, the muscle deforms plastically; that can be felt a day after in the pain of the muscle that is stretched intensively.
I have learned plasticity theory in terms of continuum mechanics. This approach of plasticity theory uses yield surfaces and other assumptions. But I think plasticity theory can be formulated without these "engineering" constructions.
Furthermore, a muscle is an anisotropic material. Is it possible to describe plastic behavior of materials by the Liouville equation:
$\partial_tf(x,p,t) + v \partial_x f(x,p,t) + F\partial_p f(x,p,t)= 0$?
In the force function $F$ all interatomic interactions are encoded. Is Statistical mechanics an alternative to plasticity theory in continuum mechanics?

A: I don't think that a plastic model is the right one. It is well known that muscle microfiber rupture can be better explained by a continuous damage model (which by the way also uses damage surfaces, in a slightly different way than they are used in plasticity proper).
On the other hand, The self-regeneration of microfibers is another biological process that is far from being adequately resolved, although models of muscle growth have been proposed relating it to mechanical stress.


text:
Q: Formatting a 2D list using iteration - even spacing problem I have the following 2D list:
table = [['Position', 'Club', 'MP', 'GD', 'Points'],
         ['1', 'Man City', '38', '51', '86'],
         ['2', 'Man Utd', '38', '29', '74'],
         ['3', 'Liverpool', '38', '26', '69'],
         ['4', 'Chelsea', '38', '22', '67'],
         ['5', 'Leicester', '38', '18', '66']]

I am wanting to print it so that the format is as following:
Position       Club           MP             GD             Points
1              Man City       38             51             86
2              Man Utd        38             29             74
3              Liverpool      38             26             69
4              Chelsea        38             22             67
5              Leicester      38             18             66

My issue is with the even spacing. My attempt at solving this was using:
for i in range(len(table)):
     print(*table[i], sep=" "*(15-len(table[i])))

However, I realised that problem is that 'i' refers to the number of items within each row, rather than the length of each individual item, which is what it would take to make even spacing - I think.
How can I get my desired format? And is my approach okay or is there a much better way of approaching this?
I have looked at this - 2D list output formatting - which helped with aspects but not with the even spacing problem I don't think
Any help would be much appreciated, thank you!

A: You can use str.format for formatting the table (documentation):
table = [
    ["Position", "Club", "MP", "GD", "Points"],
    ["1", "Man City", "38", "51", "86"],
    ["2", "Man Utd", "38", "29", "74"],
    ["3", "Liverpool", "38", "26", "69"],
    ["4", "Chelsea", "38", "22", "67"],
    ["5", "Leicester", "38", "18", "66"],
]

format_string = "{:<15}" * 5

for row in table:
    print(format_string.format(*row))

Prints:
Position       Club           MP             GD             Points
1              Man City       38             51             86
2              Man Utd        38             29             74
3              Liverpool      38             26             69
4              Chelsea        38             22             67
5              Leicester      38             18             66

A: You should use the string formatting approach, but the problem with your current solution is that you need to consider the length of each item in the row. So you want something like:
for row in table:
    for item in row:
        print(item, end=' '*(15 - len(item)))
    print()

Note, you almost never want to use for index in range(len(some_list)):, instead, iterate directly over the list. Even in the cases where you do need the index, you almost certainly would end up using enumerate instead of range. Here's the equivalent using ranges... but again, you wouldn't do it this way, it isn't Pythonic:
for i in range(len(table)):
    for j in range(len(table[i])):
        print(table[i][j], end=' '*(15 - len(table[i][j])))
    print()


text:
Q: How do input more than one word for translation in Python? I'm trying to make a silly translator game as practice. I'm replacing "Ben" with "Idiot" but it only works when the only word I input is "Ben". If I input "Hello, Ben" then the console prints out a blank statement. I'm trying to get "Hello, Idiot". Or if I enter "Hi there, Ben!" I would want to get "Hi there Idiot!". If I input "Ben" then it converts to "Idiot" but only when the name by itself is entered.
I'm using Python 3 and am using function def translate(word): so maybe I'm over-complicating the process.
def translate(word):
translation = ""
if word == "Ben":
    translation = translation + "Idiot"

return translation

print(translate(input("Enter a phrase: ")))

I'm sorry if I explained all of this weird. Completely new to coding and using this website! Appreciate all of the help!

A: use str.replace() function for this:
sentence = "Hi there Ben!"
sentence=sentence.replace("Ben","Idiot")
Output: Hi there Idiot!
#str.replace() is case sensitive

A: At first, you must split string to words:
s.split()

But that function, split string to words by white spaces, it's not good enough!
s = "Hello Ben!"
print(s.split())

Out: ["Hello", "Ben!"]

In this example, you can't find "Ben" easily.
We use re in this case:
re.split('[^a-zA-Z]', word)

Out: ["Hello", "Ben", ""]

But, we missed "!", We change it:
re.split('([^a-zA-Z])', word)

Out: ['Hello', ' ', 'Ben', '!', '']

and finally:
import re
def translate(word):
    words_list = re.split('([^a-zA-Z])', word)
    translation = ""
    for item in words_list:
        if item == "Ben":
            translation += "Idiot"
        else:
            translation += item

    return translation

print(translate("Hello Ben! Benchmark is ok!"))

P.S:
If we use replace, we have a wrong answer!
"Hello Ben! Benchmark is ok!".replace("Ben", "Idiot")

Out: Hello Idiot! Idiotchmark is ok!


text:
Q: Autoit script to automate the audacity track down menu with dynamic mouseclick I am trying to automate some 600 mp3 files for church to combine instrument and voice into one track so I can use the mixer to do left or right channel. when I combined two sounds file, I need to select left channel for first track and right channel for second track.
the problem is that if audacity is fixed screen/location, the mouseclick is working fine. But I moved the script to laptop/Desktop, it won't work since mouse coordinates are not same.
Is there a way to select down track menu from audacity to select left or right channel? There are no shortcuts at current version.  If someone can help, I appreciate for you opinion and times.
Br, Adnrew
This codes worked great for me. Thanks, guys.
 Opt("MouseCoordMode", 0) ;1=absolute, 0=relative, 2=client

 ;set left channel
 ControlClick($FileNameL, "","","Left",1,90,13)
 Send("{SHIFTDOWN}l{SHIFTUP}")
 Sleep(1000)

 ;set right channel
 ControlClick($FileNameL, "","","Left",1,60,162)
 Send("{SHIFTDOWN}r{SHIFTUP}")
 Sleep(1000)
 Send("{CTRLDOWN}a{CTRLUP}")
 ;MsgBox(0,"File Size","waiting")
 Send("{ALTDOWN}tx{ALTUP}")

A: You just need
Opt("MouseCoordMode", 0) ;1=absolute, 0=relative, 2=client

This will make your clicks relative to the window you are  working with.
Use window info Tool to find those coordinates.
Go to options and set Coord mode to Window.
You can also use
ControlClick ( "title", "text", controlID [, button [, clicks [, x [, y]]]] )

Any of these two methods are not dependant on your screen resolution.


text:
Q: Manual Assembly vs GCC Disclaimer: I'm just starting out with x86 assembly. I did learn a bit of SPIM at university, but that's hardly worth mentioning.
I thought I start with what's probably the most simple function in libc, abs(). Pretty straightforward in C:
long myAbs(long j) {
    return j < 0 ? -j : j;
}

My version in assembly:
    .global myAbs
    .type   myAbs, @function
    .text

myAbs:
    test %rdi, %rdi
    jns end
    negq %rdi
end:
    movq %rdi, %rax
    ret

(This doesn't work for 32bit integers, probably because RAX is a 64bit register and the sign is probably at the wrong position - I have to investigate that).
Now here's what gcc does (gcc -O2 -S myAbs.c):
        .file   "myAbs.c"
        .section        .text.unlikely,"ax",@progbits
.LCOLDB0:
        .text
.LHOTB0:
        .p2align 4,,15
        .globl  myAbs
        .type   myAbs, @function
myAbs:
.LFB0:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        subq    $4144, %rsp
        orq     $0, (%rsp)
        addq    $4128, %rsp
        movq    %rdi, %rdx
        sarq    $63, %rdx
        movq    %fs:40, %rax
        movq    %rax, -8(%rbp)
        xorl    %eax, %eax
        movq    %rdi, %rax
        xorq    %rdx, %rax
        subq    %rdx, %rax
        movq    -8(%rbp), %rcx
        xorq    %fs:40, %rcx
        jne     .L5
        leave
        .cfi_remember_state
        .cfi_def_cfa 7, 8
        ret
.L5:
        .cfi_restore_state
        call    __stack_chk_fail@PLT
        .cfi_endproc
.LFE0:
        .size   myAbs, .-myAbs
        .section        .text.unlikely
.LCOLDE0:
        .text
.LHOTE0:
        .ident  "GCC: (Gentoo Hardened 5.1.0 p1.2, pie-0.6.3) 5.1.0"
        .section        .note.GNU-stack,"",@progbits

Why this big difference? GCC produces substantially more instructions. I can't imagine that this won't be slower than my code.
Am I missing something? Or am I doing something seriousely wrong here?

A: Many of the beginning calls are to setup the stack and save the return address (something which you are not doing). Seems like theres are some stack protection going on. Perhaps you could tune your compiler settings to get rid of some overhead.
Perhaps adding flags to you compiler such as: -fno-stack-protector could minimise this difference.
Yes this probably is slower than your handwritten assembly, but offers much more protection and is probably worth the slight overhead.
As for why the stack protection still exists even though it is a leaf function see here.

A: For those who wonder what the generated code comes from, first note that when GCC compile myAbs with stack protection it transform it into this form
long myAbs(long j) {
    uintptr_t canary = __stack_chk_guard;

    register long result = j < 0 ? -j : j;

    if ( (canary = canary ^ __stack_chk_guard) != 0 )
        __stack_chk_fail();
}

The code to simply perform j < 0 ? -j : j; is
movq    %rdi, %rdx     ;RDX = j
movq    %rdi, %rax     ;RAX = j
sarq    $63, %rdx      ;RDX = 0 if j >=0, 0fff...ffh if j < 0
xorq    %rdx, %rax     ;Note: x xor 0ff...ffh = Not X, x xor 0 = x
                       ;RAX = j if j >=0, ~j if j < 0
subq    %rdx, %rax     ;Note: 0fff...ffh = -1
                       ;RAX = j+0 = j if j >= 0, ~j+1 = -j if j < 0
                       ;~j+1 = -j in two complement

Analyzing the generated code we get
    pushq   %rbp
    movq    %rsp, %rbp       ;Standard prologue

    subq    $4144, %rsp      ;Allocate slight more than 4 KiB
    orq     $0, (%rsp)       ;Perform a useless RW operation to test if there is enough stack space for __stack_chk_fail

    addq    $4128, %rsp      ;This leave 16 byte allocated for local vars

    movq    %rdi, %rdx       ;See above
    sarq    $63, %rdx        ;See above

    movq    %fs:40, %rax     ;Get the canary
    movq    %rax, -8(%rbp)   ;Save it as a local var
    xorl    %eax, %eax       ;Clear it

    movq    %rdi, %rax       ;See above
    xorq    %rdx, %rax       ;See above
    subq    %rdx, %rax       ;See above

    movq    -8(%rbp), %rcx   ;RCX = Canary
    xorq    %fs:40, %rcx     ;Check if equal to the original value
    jne     .L5              ;If not fail

    leave
    ret
.L5:
    call    __stack_chk_fail@PLT  ;__stack_chk_fail is noreturn

So all the extra instructions are for implementing the Stack Smashing Protector.
Thanks to FUZxxl for pointing out the use of the first instructions after the prologue.


text:
Q: Postgres PGSimpleDataSource changing database name This is what I am trying, I want to connect to a default admin database, create a new database and immediately switch to it.
Below is my pseudo-code:
// Create a new datasource
dataSource = PGSimpleDataSource()
dataSource.setURL("jdbc:postgresql://mydbserver:5432/admin")
dataSource.setUser("test")
dataSource.setPassword("testing")

// get connection to admin db and create a new database named 'mynewdb'
connection = dataSource.getConnection()
cs = connection.createStatement()
cs.executeUpdate("create database mynewdb")
cs.close()
connection.close()

// switch to the newly created database using the **same datasource**
dataSource.setDatabaseName(mynewdb)
connection_to_new_db = dataSource.getConnection()
ps = connection_to_new_db.preparedStatement()

....start doing transactions on the newly created database...
....start doing transactions on the newly created database...

Above code seems to work fine.
Questions:

*

*is it legal to change the database name on the fly on an existing datasource? Are there any repercussions?

*is this the right way to accomplish what I am trying or is there a better way?


text:
Q: AddDays() not working within a while loop Is there anything that stops the DateTime AddDays() method that doesn't run within a while loop. I have this simple bit of code;
DateTime last_day = monthCalendar2.SelectionRange.End;
DateTime first_day = new DateTime(year, month, day);

//Insert dates into vector
while (first_day != last_day)
{
  dates.Add(first_day);
  first_day.AddDays(1);
}

I step through the program and first_day never changes, anyone know why?!

A: DateTime can't be changed, so instead do.
first_day = first_day.AddDays(1);

A: The reason being is that DateTime is Immutable, this means that you can't directly modify it and instead need to create a new instance of it. Strings are another type that behave in this way which you may be more used to.
first_day = first_day.AddDays(1);

A: DateTime is immutable. You should do
first_day = first_day.AddDays(1);

UPDATE:
If you check DateTime.AddDays method description: Returns a new System.DateTime that adds the specified number of days to the value of this instance. That relates to all operations (such as Add, Substract, AddHours etc) on DateTime structure - any calculation does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation. That's because DateTime is immutable struct. I.e. instance value cannot be changed after it was created.


text:
Q: Sharing code between projects using TypeScript and webpack I want to share code between two TypeScript projects. I don't want to publish shared code to NPM-- just want to put shared code in one project and use it in another project. I'm using Webpack and awesome-ts-loader. Current folder structure (simplified) is like this:
/devroot/
  mainProject/
    tsconfig.json
    src/
      shared/
        SomeSharedTypes.ts
  apiProject/
    tsconfig.json
    webpack.config.js
    src/
      UseSomeSharedType.ts

In UseSomeSharedType.ts, I want to be able to import types from SomeSharedTypes.ts.
I tried an obvious solution like this:
import {SharedType} from '../../mainProject/src/shared/SomeSharedTypes'

But the TS compiler gave me this error:

TS6059: File '/devroot/mainProject/src/shared/SomeSharedTypes.ts' is
  not under 'rootDir' '/devroot/apiProject'. 'rootDir' is expected to
  contain all source files.

A: The first idea I got from this Medium article, which was to use TypeScript's non-relative module imports feature. This would allow me to write my imports like this:
import {SharedType} from '@foo/SomeSharedTypes'

Using the techniques described in the article, I added a paths configuration to my tsconfig.json:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@foo/*": ["../mainProject/src/shared/*"],
    },
    "rootDir": "./",
    ...
  }
}

Then, again as the article recommends, for users of awesome-typescript-loader, I had to modify my webpack.config.js to add a resolution plugin:
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');
. . .
  resolve: {
    extensions: ['.js', '.json', '.ts'],
    plugins: [
      new TsConfigPathsPlugin(),
    ],
  }

Important: this plugin needs to go into the resolve/plugins section of the file, not the root-level "plugins" section!  If you put the resolver plugin in the wrong place, you'll get this error:

resolver.ensureHook is not a function

The steps above got me further along in the process-- TypeScript was now able to find my files!--but I still got the same error later in webpack's execution: 'rootDir' is expected to contain all source files.
After a lot more Googling, I found a solution in this StackOverflow answer: instead of a single rootDir configuration, TS has a rootDirs setting that allows multiple roots. I removed my rootDir setting from tsconfig.json and added a rootDirs setting:
"rootDirs": [
  "./",
  "../mainProject",
],

Next, I ran into a webpack error on the other-project TypeScript file I was including:

Module parse failed: Unexpected token (3:15)
You may need an appropriate loader to handle this file type.

After another hour of troubleshooting, I figured out that I need to tell the webpack loader about my new shared folder. Like this:
const path = require('path');
. . .
  rules: [
    {
      test: /\.[jt]sx?$/,
      loader: "awesome-typescript-loader",
      include: [
        __dirname,
        path.resolve(__dirname, "../mainProject/src/shared/")
      ],
      exclude: /node_modules/
    },

That worked!  The nice part about this solution is that I can refactor my folder structure without changing source code. All I'd need to change is tsconfig.json and webpack.config.js.
I'm admittedly new to using webpack and TypeScript, so there may be a better solution than the one above... but the one above worked for me!
Sharing the solution here to make it easier for the next developer to find it.

A: I would strongly recommend using the Nx workspace management tool as it is specifically build to solve these kind of setup issues. You can simply create a library within your repository that can then be imported everywhere (see: https://nx.dev/angular/tutorial/08-create-libs). Me and my team are heavily relying on Nx now for over 6 months and could not imagine managing a TypeScript repository without it, give it a try! https://nx.dev
If using Nx is not an option for you, you can model the way the implemented code-sharing:

*

*Create a new folder

*Add an index.ts file which exports everything that should be accessible from outside the library

*Add an entry inside your tsconfig.json -> compilerOptions -> paths that points to the index.ts of your library

*Import the shared code via the import name you specified inside the tsconfig.json


text:
Q: php and regular expressions Ok i have tried this quite a few times now.  I still cannot figure it out.
Thisis my problem.  I want to take any

 and turn it into

So this is what i do

    $test = ereg_match("/

/", "
", "

Test

");
    echo $test;

It produces $test == "Test" rather than $test = "
Test
"
Any help?  Then i would like to expand it so that any
\s*
 So that any two seperated by space can be turned into 1.  Any help?

A: You can just use str_replace
<?php

$str = "

Test

";

echo str_replace("

", "
", $str);

Update
Example:
http://codepad.org/MWzg81Qy
To replace 2 or more br's(with unlimited spacing)... you can do preg_replace:
<?php

$str = "

Test

";

echo preg_replace("/(\s*
)+/", "
", $str);

http://codepad.org/CrltyhSs

A: Perhaps not the answer you're after but using str_replace will be considerably more efficient than a regular expression.
i.e.: $test = str_replace('

', '
', $sourceString);
Incidentally, I'd be tempted to replace the
 tags with
 in this day and age as well. :-)

A: You most certainly have a typo in your function names. The preg_* functions have mostly replaced the old ereg_ functions.
Your second regex should be written as:
print preg_replace("#
\s*
#", "
", "

Test");

The ? is shorthand for your {0,1}, and by using # as delimiter you spare the extraneous escaping of forward slashes.

A: Can you try this:
preg_replace("#
]*>
]*>#", "
", "

Test

");

Both these lines produce same output:
var_dump(preg_replace("#
]*>
]*>#", "
", "

Test

"));
var_dump(preg_replace("#
]*>
]*>#", "
", "

Test

"));

OUTOUT: string(12) "
Test
"

A: Exactly 2 BR separated by optional whitespace:
$str = preg_replace('/
]*>(?:\s*
]*>){1}/', '
', $str);

2 or more BR separated by optional whitespace:
$str = preg_replace('/
]*>(?:\s*
]*>){1,}/', '
', $str);

A: As Mike Lewis says, use string manipulation if you don't need to account for variation in the input string. On the other hand, if you want to collapse any multiple
 or
 tags into a single tag, allowing for whitespace inside them, this should work for you:
$result = preg_replace('#(<\s*br\s*(/\s*)?>){2,}#', '
', $subject);

I'm not totally sure why your version isn't working, but if the above doesn't work, there's probably something else going on here.

A: Found the answer.  I am so stupid.
In a seperate file i had

    define("ALLOWED_TAGS", "");
    ...
    ...
    ...
    define("ALLOWED_TAGS", "my tags blah blah blah");

Sorry for wasting everyones time.  GG

A: Use str_replace where you can.  Given your comments on stuff such as wanting to replace

 with just 1
, do this:
while(strpos($inputstring,'

'))  //while

 can be found in string
{
    $inputstring = str_replace('

', '
', $inputstring);  //replace

}

PHP has a bad implementation of regular expressions, and they take a much much longer time to do in PHP than it's string manipulations.  Like a whole greater order of magnitude time longer.
To catch various different potential issues with the tags, you can do:
$searchArray = array('

','

','other potential spellings');
while(stripos($inputstring,$searchArray))  //while case insensitive search strings are in string
{
    $inputstring = str_ireplace($searchArray, '
', $inputstring);  //replace case insensitive strings
}

You can also use strip_tags just to remove any unwanted tags all together:
$inputstring = strip_tags($inputstring, '
<other allowed tags>');

But, of course, this would remove all
 tags.


text:
Q: Converting Tensorflow object detection model to Keras model I am using tensorflow object detection API to call Faster R-CNN model
I want to convert it into Keras model , As Keras creator mentioned here
However I tried this code
model_name = 'faster_rcnn_inception_v2_coco_2018_01_28'
detection_model = load_model(model_name)
input_tensor = tf.keras.layers.Input(shape=(640, 640, 3), name="Input")
class LayerFromSavedModel(tf.keras.layers.Layer):
  def __init__(self):
    super(LayerFromSavedModel, self).__init__()
    self.vars = detection_model.variables
  def call(self, inputs):
    return detection_model.signatures['serving_default'](input_tensor)

model = tf.keras.Model(input, LayerFromSavedModel()(input_tensor))
model.save('saved_model')

but have this error
TypeError: Exception encountered when calling layer "layer_from_saved_model_1" (type LayerFromSavedModel).

pruned(inputs): expected argument #0(zero-based) to be a Tensor; got method (<bound method Kernel.raw_input of <google.colab._kernel.Kernel object at 0x7f0b8d2c5510>>).

Call arguments received:
 • inputs=<bound method Kernel.raw_input of <google.colab._kernel.Kernel object at 0x7f0b8d2c5510>>

I am working on Colab notebook


text:
Q: show flutter test coverage I am a bit new to testing world in flutter.
what I want to achieve is to determine my test coverage in flutter.
but I don't know any way to determine my test coverage ,
any help is appreciated.
Thanks.

A: Running the tests with
flutter test --coverage

should generate a file
/coverage/Icov.info

Which holds the information you need.
You can now extract infos from the file in various methods as described here

A: In a easy way, you can determine the test coverage threshold using this package https://pub.dev/packages/dlcov
usage example:
dlcov --lcov-gen="flutter test --coverage" --coverage=100
--lcov-gen Generate the lcov.info file
--coverage=100 To determine if the test coverage threshold is 100%


text:
Q: How to deal with 302 redirect under path rewrite? I'm newbie on Azure Application Gateway, and wonder to know how to deal with 302 redirect under path rewrite?
For example, I have a application gateway named https://my.appgw.com, and have a auth website (myauth.azurewebsites.net) with some redirect rule below.

*

*https://myauth.azurewebsites.net/ -> https://myauth.azurewebsites.net/hr

*https://myauth.azurewebsites.net/hr -> https://myauth.azurewebsites.net/hr/login
When I hosted it on azure app service the redirect operation worked perfectly, but it broken after proxied my web app behind azure application gateway.
I've set path-based rewrite rule in app gw, the path /auth/* would indicate my auth web app.
But when I test the redirect action, the redirect path didn't include my path-based prefix /auth, and then throw 404 not found.

*

*https://my.appgw.com/auth/ -> https://my.appgw.com/hr (404)

What my expectation is:

*

*https://my.appgw.com/auth/ -> https://my.appgw.com/auth/hr (302)

*https://my.appgw.com/auth/hr -> https://my.appgw.com/auth/hr/login (302)

How can I configure it? thanks.


text:
Q: Using Gradle Source Sets to Swap resources directory between dev/prod I have Java application that uses Gradle.  Currently my resources directory contains Typesafe Config and Log4J configuration files.
Both of these files would have different settings based on whether my application is built for dev or production.  For example, I would want Log4J to only log at the INFO level in production.
I am unable to use environment variables to swap these settings, and my only option is doing it through these resource files.
Ideally I'd like to be able to have 2 source sets in my Gradle config--one for dev (main) and one for prod--and have Gradle build a jar for each of these source sets.  The main source set would continue to use src/main/resources as the resource directory, and the prod source set would use src/main/resources-prod as the resource directory.
I'm fine with these resource directories are in other locations--the above is just an example.
Right now, the only custom portions of my Gradle config are the following (outside of adding compile dependencies):
task buildZip(type: Zip) {
    from compileJava
    from processResources
    into('lib') {
        from configurations.runtime
    }
}

build.dependsOn buildZip

Does anyone know how to achieve this?


text:
Q: How to correctly use readWave in Rstudio Im getting this error while executing this line in RStudio, I have tuneR lib installed.
birds <- readWave("birds.wav")

Error in readBin(con, int, n = 4, size = 1, endian = "little", signed = FALSE) %*%  :
non-conformable arguments
In addition: Warning message:
In readChar(con, 4, useBytes = TRUE) : truncating string with embedded nuls

Tried to look for examples and can´t find any that helps me.


text:
Q: Get operating system size android programmatically? i try to use this code, from How to find the amount of free storage (disk space) left on Android?
    File pathOS = Environment.getRootDirectory();//Os Storage
    StatFs statOS = new StatFs(pathOS.getAbsolutePath());
    long   total_OS_memory=0;long free_OS_memory=0;
total_OS_memory= (statOS.getBlockCountLong()*statOS.getBlockSizeLong());

but size of Operting system not same with hardware on mobile.

On my phone value is 3.4 G, but when i use my code result is 1.17.

And this is compare between my real phone with my code result.
Name            |Phone|MyCode
Total Storage   |8    |5.81
System          |3.4  |1.17
Internal Storage|4.64 |4.64

How to get operating sistem size in android?


text:
Q: Persist Google Cardboard forward direction across scene loads in Unity3D 4.6.7? I'm having trouble trying to maintain what Google Cardboard considers forward for the device after a scene load.  Although I can't find any obvious call to this in the SDK c# code, it appears that the Google Cardboard SDK will automatically call Recenter after each scene load.  I've tried calling DontDestroyOnLoad on the cardboard instantiated prefab, and on the Cardboard.SDK object (which is mentioned on line 328 of Cardboard.cs).  This persists those objects across the load, but the view is still re-centered based on the current orientation of the device.
I want to avoid the recenter because some of the gaze-based menu items that can initiate a load are off to the user's left or right - which then makes the new center be to the left/right after the scene load.  The user then has to physically move their body to be facing towards the new forward.
Is anyone else attempting the same thing?  Am I missing something obvious?
Any suggestions very much appreciated!

A: The function Cardboard.OnLevelWasLoaded() calls device.Reset(), which in the base class implementation just calls Recenter(), which has the effect you are seeing.  If you comment out that line, or guard it with a variable you can control, the facing should not reset.

A: I had the same problem but on Gear VR (Unity 5). In case anyone else is looking for this, I've answered it here.
Briefly, if you're also using OVR Utilities from Oculus:

*

*Locate the OVR Manager script attached to the OVRCameraRig

*Uncheck 'Reset Tracker On Load'


text:
Q: Formatting output with 'printf' in Perl I'm trying to format my output to look like it's in columns. I'm trying to use the printf function.
Here's what I have:
printf("%s %10s %12s %10s\n", "Qty", "Desc.", "Unit \$", "Total");

for ($he = 0; $he <= 6; $he++) {
    if (@quantity[$he] != 0) {
        printf("%d %10s %12.2f %10.2f\n", @quantity[$he], @selections[$he], @prices[$he], @prices[$he] * @quantity[$he])
    }
}

I'm trying to make it so that the second printf inside of the if statement of the for loop lines up with the "Qty", "Desc.", "Unit \$" and "Total."

A: You need to use the same numbers in the two formats:
printf("%3s %10s %15s %13s\n", "Qty", "Desc.", "Unit \$", "Total");

and
printf("%3d %10s %12.2f %10.2f\n", @quantity[$he], @selections[$he], @prices[$he], @prices[$he]*@quantity[$he])

Note that 12.2 means (12 digits + 1 point + 2 digits), which is why I wrote 15 in the first format.  The same goes for the 13.

Also note that you're accessing array elements incorrectly.
Instead of @quantity[$he] use $quantity[$he].  That is, replace the @ with a $.

A: Long time ago, Perl was mainly used for formatting files. It still has these capabilities although I haven't seen it used in a program since Perl 4.x came out.
Check out the perlform documentation, the format function, and the write function.
I'd give you an example on what the code would look like except I haven't done it in years. Otherwise, use the printf statement. You can limit the size of a text field with a %-10.10s type of format. This says to left justify the string, and pad it out to 10 characters, but not more than 10 characters.
I also suggest you get a book on modern Perl. One that will teach you about references.
I've rewritten your program to use references. Notice that all of the data is now in a single array instead of spread over four separate arrays that you hope you keep the index together.
I can talk about the ENTREE of $item[1] by saying $item[1]->{ENTREE}. It's easier to read and easier to maintain.
Also note that I've changed your for loop. In yours, you had to know that you had seven items. If you added a new item, you'd have to change your loop. In mine, I use $#menu to get the last index of my menu. I then use (0..$#menu) to automatically loop from 0 to the last item in the @menu array.
And, while you're at it:

*

*Notice the printf statement formats.

*Notice the use of use strict; and use warnings;. That will catch a lot of errors.

*Notice the preferred way I use parentheses and curly braces to mark off blocks of code. This is the preferred method.

And, now the program:
use strict;
use warnings;

my @menu = (
    { ENTREE => "Hamburger",    PRICE => 3.49, QUANTITY => 3 },
    { ENTREE => "Frankfurter",  PRICE => 2.19, QUANTITY => 0 },
    { ENTREE => "French Fries", PRICE => 1.69, QUANTITY => 0 },
    { ENTREE => "Large Coke",   PRICE => 1.79, QUANTITY => 4 },
    { ENTREE => "Medium Coke",  PRICE => 1.59, QUANTITY => 0 },
    { ENTREE => "Small Coke",   PRICE => 1.39, QUANTITY => 0 },
    { ENTREE => "Onion Rings",  PRICE => 1.19, QUANTITY => 8 },
);

printf "%-3.3s %-10.10s %-6.6s %s\n\n", 'Qty', 'Desc.', 'Unit $', 'Total';

# Use $#menu to get the number of items in the array instead of knowing it's 6

foreach my $item (0..$#menu) {

    # Dereference $menu[$item] to make $menu_item a hash
    # This makes the syntax easier to read.
    my %menu_item = %{ $menu[$item] };

    if ( $menu_item{QUANTITY} ) {
        printf "%3d %-10.10s %9.2f %7.2f\n",
        $menu_item{QUANTITY}, $menu_item{ENTREE}, $menu_item{PRICE},
        $menu_item{QUANTITY} * $menu_item{PRICE};
    }
}

OUTPUT:
Qty Desc.      Unit $ Total

  3 Hamburger  3.49   10.47
  4 Large Coke 1.79    7.16
  8 Onion Ring 1.19    9.52


text:
Q: Textbox Valid using Vue Js Please Help me .. Sir ...
I want to check if one text input is null, which causes an error indicated by a red border. But when i fill one input the error border appears on both of text inputs.
<el-form-item label="Deadline Building" :error="errorBag.leased_land_year || errorBag.leased_land_month">

              <el-input name="leased_land_year" v-model="form.leased_land_year" placeholder="2007" style="width: 180px;">
                   <template slot="append">Y</template></el-input>

              <el-input name="leased_land_month" v-model="form.leased_land_month" placeholder="2" style="width: 150px;" >
                    <template slot="append">M</template></el-input>

</el-form-item>


text:
Q: How to keep the dropdown value after button click in Dash? I have an application in which I want to update the dropdown values when the user inputs some text into the dropdown. So far, I managed to get the text from an Input text that the user inputs, but not from the dropdown. The dropdown keeps reseting after clicking in any part of the screen or on the button.
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State

app = dash.Dash(
    external_stylesheets=[
        dbc.themes.BOOTSTRAP])

app.layout = html.Div(
    [
        dcc.Input(id='helper'),
        dcc.Dropdown(id="my-dynamic-dropdown", options=[]),
        html.Br(),
        html.Br(),
        html.Br(),
        html.Br(),
        html.Br(),
        html.Br(),
        html.Br(),
        dbc.Button('Add to Dropdown', id='dropdown_button', n_clicks=0, color="info",
                   className="mr-1")
    ],

)

options = []

@app.callback(
    Output("my-dynamic-dropdown", "options"),
    Input('dropdown_button', 'n_clicks'),
    [State('my-dynamic-dropdown', 'options'),
    # State('helper', 'value')
    State('my-dynamic-dropdown', 'search_value')
     ]
)
def update_options(n_clicks,existing_options,helper_value):
    if helper_value is None:
        print("none value")
        return options
    else:
        print("helper value ",helper_value)
        options.append({'label': helper_value, 'value': helper_value})
        return options

if __name__ == "__main__":
    app.run_server(debug=True)

A: The dropdown allows a user to search through the existing options, but what you're trying to do is not what the dropdown was designed for. You would either need to write a custom component, use some combination of dropdown and input components, or find a different solution to whatever problem you're trying to solve.


text:
Q: Xcode9-beta2 destroyed my project/compiler/environment My project works fine in Xcode 8.3.3. When I compile my project with Xcode 9, it shows compile error in some C++ files which have been included into my project for a long time. Then I switch to Xcode 8.3.3 and just want it built successfully, however, Xcode keeps on showing the previous error in Xcode 9.
Clean project/delete derived data/relaunch Xcode/reboot/uninstall Xcode9 and reinstall Xcode 8.3.3, all of them don't work. I think some of configurations are destroyed by Xcode9-beta2.
Anyone could help.


text:
Q: Dynamic Programming Help: Binary Tree Cost Edge Given a binary tree with n leaves and a set of C colors. Each leaf node of the tree is given a unique color from the set C. Thus no leaf nodes have the same color. The internal nodes of the tree are uncolored. Every pair of colors in the set C has a cost associated with it. So if a tree edge connects two nodes of colors A and B, the edge cost is the cost of the pair (A, B). Our aim is to give colors to the internal nodes of the tree, minimizing the total edge cost of the tree.
I have working on this problem for hours now, and haven't really come up with a working solution. Any hints would be appreciated.

A: I am going to solve the problem with pseudocode, because I tried writing explanation and it was completely not understandable even for me. Hopefully the code will do the trick. The complexity of my solution is not very good - memory an druntime in O(C^2 * N).
I will need couple of arrays I will be using in dynamic approach to your task:
dp [N][C][C] -> dp[i][j][k] the maximum price you can get from a tree rooted at node i, if you paint it in color j and its parent is colored in color k
maxPrice[N][C] -> maxPrice[i][j] the maximum price you can get from a tree rooted in node i if its parent is colored in color j
color[leaf] -> the color of the leaf leaf
price[C][C] -> price[i][j] the price you get if you have pair of neighbouring nodes with colors i and j
chosenColor[N][C] -> chosenColor[i][j] the color one should choose for node i to obtain maxPrice[i][j]
Lets assume the nodes are ordered using topological sorting, i.e we will be processing first leaves. Topological sorting is very easy to do in a tree. Let the sorting have given a list of inner nodes inner_nodes
for leaf in leaves:
   for i in 0..MAX_C, j in 0..MAX_C
       dp[leaf][i][j] = (i != color[leaf]) ? 0 : price[i][j]
   for i in 0..MAX_C,
       maxPrice[leaf][i] = price[color[leaf]][i]
       chosenColor[leaf][i] = color[leaf]
for node in inner_nodes
   for i in 0..MAX_C, j in 0..MAX_C
       dp[node][i][j] = (i != root) ? price[i][j] : 0
       for descendant in node.descendants
           dp[node][i][j] += maxPrice[descendant][i]
   for i in 0...MAX_C
       for j in 0...MAX_C
         if maxPrice[node][i] < dp[node][j][i]
             maxPrice[node][i] = dp[node][j][i]
             chosenColor[node][i] = j

for node in inner_nodes (reversed)
   color[node] = (node == root) ? chosenColor[node][0] : chosenColor[node][color[parent[node]]

A: As a starting point, you can use a greedy solution which gives you an upper bound on the total cost:
while the root is not colored
    pick an uncolored node having colored descendants only
        choose the color that minimizes the total cost to its descendants


text:
Q: Keyboard keys not working in chrome.app when in full-screen When switching to full-screen in a Google Chrome Packaged app (using webkitRequestFullScreen), most of the keyboard keys are not working except for the space button, enter, backspace and arrows.
Is there any way that the other keys (all numbers and letters) are functional when in full-screen mode?
I noticed that most keys do not trigger keydown, keypress and keyup events.
This is a problem especially when working on apps like for example a VNC client, where key events are crucial.

A: There are two fullscreen implementations, which differ by a single character. Use the newer HTML Fullscreen specification with webkitRequestFullscreen (lower case 'screen').
The older specification accessed with webkitRequestFullScreen (upper case 'Screen') needs Element.ALLOW_KEYBOARD_INPUT for keyboard support. Avoid, as this is likely to be deprecated.


text:
Q: IO timeout value for Linux and Windows? If a disk has some problems, the disk driver usually retries it. For example, sometimes Linux SCSI driver will get BUSY status from SCSI drives  and resend the IO. The upper layers (e.g., FS) will wait until:
1. The disk driver can't handle the IO error and directly report error.
2. The disk driver still retries but timeout occurs.
My question is that what's the timeout value in Windows and Linux platforms? For example, if I invoke "write" to send some data to disk synchronously, how long will the system call return if it can't really write data?
Thanks!

A: As Brian notes, it's driver dependent.  The write returns when the driver gives up.  How and why the driver gives up is driver and device dependent.  There is no timeout, per se, like reads often have.

A: On Linux, you can get the IO timeout value from each block device by reading the value on :
/sys/block/mydevice/device/timeout
By default, the value is 60s.