text:
Q: Using AI service to recognize a free text search field question? Is there an API service, paid or not paid (IBM Watson, Google Natural Language), that can accept a free text "ask a question" field and convert it into a set of keywords to be used for a regular keyword search?
For example if my website has a search field "Ask a question about our products", and a user types in "Do you have red dresses?", is there an API we can integrate into our code that can just convert this to "red dress" which we then simply feed into our regular keyword search for "red dress"?
Ideally it can handle variations of questions such as:
"How do you return a product?" -- return product
"Do you accept Mastercard?" -- mastercard
"Where can I find blue shoes?" -- blue shoes

A: You can extract noun chunks and then use those as keywords.
For example using Spacy, you can extract noun chunks as follows:
import spacy
nlp = spacy.load('en_core_web_md')

def getNounChunks(doc):
    inc = ['NN', 'NNP', 'NNPS', 'NNS', 'JJ', 'HYPH']
    incn = ['NN', 'NNP', 'NNPS' ,'NNS']
    excl = ['other', 'some', 'many', 'certain', 'various']
    lspans = []
    chunk =[]
    for t in doc:
        if t.text.lower() in excl:
            continue
        if chunk:
            if chunk[-1].tag_ == 'HYPH':
                chunk.append(t)
                continue

        if t.tag_ in inc:
            if t.tag_ != 'JJ':
                chunk.append(t)
            else:
                if not any([t.tag_ in incn for t in chunk]):
                    chunk.append(t)

        else:
            if chunk:
                if any([t.tag_ in incn for t in chunk]):
                    lspans.append(doc[chunk[0].i:chunk[-1].i + 1])
                chunk = list()
    return(lspans)

questions = [
"How do you return a product?" ,
"Do you accept Mastercard?" ,
"Where can I find blue shoes?",
"Do you have red dresses?",]

for q in questions:
    doc = nlp(q)
    print(getNounChunks(doc))

#output:
#[product]
#[Mastercard]
#[blue shoes]
#[red dresses]


text:
Q: Using MetalLB and Nginx-Ingress for exposing ports 80, 443 and 5432 (Postgres) I'm working on a school project where I have bare metal VPS and I'm trying to deploy web application (nginx ingress) with Postgres database (which has to be reachable from the outside I.e. :5432).
I went through tens of link in Google and on StackOverflow and nothing actually worked out - I'm still getting Connection refused. Is the server running on host "<>" and accepting TCP/IP connections on port 5432?
I've successfully deployed MetalLB with few simple steps:

*

*Install metallb

kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.5/manifests/namespace.yaml
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.5/manifests/metallb.yaml
kubectl create secret generic -n metallb-system memberlist --from-literal=secretkey="$(openssl rand -base64 128)"

kubectl get configmap kube-proxy -n kube-system -o yaml | \
sed -e "s/strictARP: false/strictARP: true/" | \
kubectl apply -f - -n kube-system

*

*Created config.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: production
      protocol: layer2
      addresses:
      - <VPS-external-IP>-<VPS-external-IP>

*Created LoadBalancer Service

apiVersion: v1
kind: Service
metadata:
  name: nginx-balancer
  namespace: nginx
spec:
  ports:
  - name: http
    port: 80
    protocol: TCP
    targetPort: 80
  - name: https
    port: 443
    protocol: TCP
    targetPort: 443
  - name: db
    port: 5432
    protocol: TCP
    targetPort: 5432
  selector:
    app: nginx
  type: LoadBalancer

*And created Nginx deployment (nginx-deployment.yaml)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: nginx
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
        - containerPort: 443

Now after runnign kubectl apply -f config.yaml and kubectl apply -f nginx-deployment.yaml I'm able to resolve "Welcome to nginx!" curl <VPS-external-IP>:80
with output of:
<!DOCTYPE html>

<title>Welcome to nginx!</title>

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.

For online documentation and support please refer to
nginx.org.

Commercial support is available at
nginx.com.

Thank you for using nginx.

kubectl get pods
NAME                                READY   STATUS    RESTARTS   AGE
nginx-deployment-7f8d9cf649-cssrb   1/1     Running   0          117m
nginx-deployment-7f8d9cf649-f7q9w   1/1     Running   0          117m
nginx-deployment-7f8d9cf649-fmntb   1/1     Running   0          117m

kubectl get svc -n nginx
NAME             TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)                                     AGE
nginx            ClusterIP      10.108.97.186   <none>         80/TCP,443/TCP                              26m
nginx-balancer   LoadBalancer   10.103.72.75    46.36.38.200   80:32529/TCP,443:30432/TCP,5432:31081/TCP   42m

kubectl get pods -n metallb-system
NAME                          READY   STATUS    RESTARTS   AGE
controller-57c458c998-r78wn   1/1     Running   0          13h
speaker-clr6j                 1/1     Running   0          13h

kubectl get configmap -n metallb-system
NAME               DATA   AGE
config             1      13h
kube-root-ca.crt   1      13h

But the real issue comes now. I need to access Postgres Database using :5432 but I'm honestly just lost in Kubernetes...
I've created all the neccessary stuff for Postgres in order to make it run such as:

*

*PersistentVolume and PersistentVolumeClaim (I don't think it's neccessary to share here, since it's just basic PersistentVolume and PersistentVolumeClaim yaml)

*Secrets (I don't think it's neccessary to share here, since it's just basic secrets yaml)

*ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-configmap
  namespace: postgres
data:
  POSTGRES_DB: db_production

*Postgres Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres-deployment
  namespace: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:latest
        ports:
          - containerPort: 5432
        envFrom:
          - secretRef:
              name: postgres-secrets
          - configMapRef:
              name: postgres-configmap
        volumeMounts:
        - name: postgres-pv-claim
          mountPath: /var/lib/pgsql/data
      volumes:
      - name: postgres-pv-claim
        persistentVolumeClaim:
          claimName: postgres-pv-claim

*And of course - Postgres Service

apiVersion: v1
kind: Service
metadata:
  name: db
  namespace: postgres
  labels:
    run: postgres
spec:
  selector:
    name: postgres
  ports:
  - port: 5432
    targetPort: 5432
    protocol: TCP

The postgres by itself seems to work.
kubectl get pods -n postgres
NAME                                   READY   STATUS    RESTARTS   AGE
postgres-deployment-74fff7c576-6kb5q   1/1     Running   0          96m

kubectl get svc -n postgres
NAME   TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
db     ClusterIP   10.102.5.192   <none>        5432/TCP   93m

kubectl get deployments -n postgres
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
postgres-deployment   1/1     1            1           94m

kubectl get pv -n postgres
NAME          CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                        STORAGECLASS   REASON   AGE
postgres-pv   1Gi        RWO            Retain           Bound    postgres/postgres-pv-claim   manual                  55m

kubectl get pvc -n postgres
NAME                STATUS   VOLUME        CAPACITY   ACCESS MODES   STORAGECLASS   AGE
postgres-pv-claim   Bound    postgres-pv   1Gi        RWO            manual         55m

(I've deleted and it recreated it many times (hence why so low ages... :-( ))
So even though I've got postgres/db service running on 5432 and MetalLB LoadBalancer with Nginx working, it just simply doesn't expose 5432 to the world.
I'll be very happy for all suggestions because I'm starting to loose the hype I had in the beginning about how nice it'd be to set up Kubernetes... :-)
Thank you.
Update 31.1.2022
I've installed Kubernetes using Kubeadm pretty much step by step using several tutorials online and official docs.
Output of kubectl version
Client Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.3", GitCommit:"816c97ab8cff8a1c72eccca1026f7820e93e0d25", GitTreeState:"clean", BuildDate:"2022-01-25T21:25:17Z", GoVersion:"go1.17.6", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.3", GitCommit:"816c97ab8cff8a1c72eccca1026f7820e93e0d25", GitTreeState:"clean", BuildDate:"2022-01-25T21:19:12Z", GoVersion:"go1.17.6", Compiler:"gc", Platform:"linux/amd64"}

and kubeadm version

kubeadm version: &version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.3", GitCommit:"816c97ab8cff8a1c72eccca1026f7820e93e0d25", GitTreeState:"clean", BuildDate:"2022-01-25T21:24:08Z", GoVersion:"go1.17.6", Compiler:"gc", Platform:"linux/amd64"}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keyboard does not hide, when focused TextField leaves the LazyColumn Perhaps this is the normal behaviour, but i wish it was different. I had tried to google the solution, but did not find anything suitable (or merely missed it).
Sample code (for simplicity i hold mutable states right here, not using ViewModel):
@Composable
fun Greeting() {
    Scaffold(topBar = {
        TopAppBar(title = { Text(text = "Some title") })
    }) {
        val focusManager = LocalFocusManager.current
        LazyColumn(
            contentPadding = PaddingValues(all = 16.dp),
            verticalArrangement = Arrangement.spacedBy(space = 16.dp)
        ) {
            items(count = 20) { index ->
                val (value, onValueChange) = rememberSaveable { mutableStateOf("Some value $index") }
                TextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = Modifier.fillMaxWidth(),
                    label = { Text(text = "Some label $index") },
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
                    keyboardActions = KeyboardActions(onNext = {
                        if (!focusManager.moveFocus(FocusDirection.Down))
                            focusManager.clearFocus()
                    }),
                    singleLine = true
                )
            }
        }
    }
}

Compose version 1.0.5

A: You could try just hiding the keyboard whenever scrolling occurs. This is okay as long as you don't have a large set of items. But since you're using TextFields, it isn't likely that you'll have such a large number. This sample illustrates hiding the keyboard when scrolling occurs:
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivity(intent)

        setContent {
            Greeting(this)
        }
    }
}

@Composable
fun Greeting(activity: Activity) {

    Scaffold(topBar = {
        TopAppBar(title = { Text(text = "Some title") })
    }) {

        val lazyListState = rememberLazyListState()
        val ctx = LocalContext.current

        LaunchedEffect(lazyListState.firstVisibleItemIndex) {
            val inputMethodManager = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(activity.window?.decorView?.windowToken, 0)
        }

        LazyColumn(
            state = lazyListState,
            contentPadding = PaddingValues(all = 16.dp),
            verticalArrangement = Arrangement.spacedBy(space = 16.dp)
        ) {
            items(
                count = 20,
                key = { index ->
                    // Return a stable + unique key for the item
                    index
                }
            ) { index ->
                val (value, onValueChange) = rememberSaveable { mutableStateOf("Some value $index") }
                TextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = Modifier
                        .fillMaxWidth(),
                    label = { Text(text = "Some label $index") },
                    singleLine = true
                )
            }
        }
    }
}


text:
Q: OpenLayers making icons clickable I'm making a map with OpenLayers that pulls data from a database and parses that data through an API to display it onto the map, and that section is working completely fine (see: https://i.imgur.com/z8ItBxr.png) however, when trying to make the icons clickable I'm running into issues.  I'm not sure if I have to do something different when accounting for multiple icons, but I've tried to follow the documentation at https://openlayers.org/en/latest/examples/icon.html to no help.  I'm essentially trying to display the MMSI (ID of the vessels) above the ships as a pop-up when the ship is clicked on, but it isn't really working properly.  It'll mouse over the icons properly, but clicking doesn't really do anything. If anyone can help, it's greatly appreciated.  I've attached my index.js below:
const { Client } = require('pg')
import "ol/ol.css";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import Map from "ol/Map";
import View from "ol/View";
import Overlay from 'ol/Overlay';
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { defaults as defaultControls, FullScreen } from "ol/control";
import OSM from "ol/source/OSM";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import { Icon, Style } from "ol/style";

const newportLonLat = [-71.307607, 41.529193];
const newportWebMercator = fromLonLat(newportLonLat);

//const text = 'SELECT DISTINCT mmsi, MAX(basedatetime), lat, lon FROM public.vessels GROUP BY mmsi, lat, lon ORDER by MAX(basedatetime) DESC, mmsi, lat, lon'

function loadJSON() {
  var data_file = "http://localhost:3000/latlong";
  var http_request = new XMLHttpRequest();
  try{
     // Opera 8.0+, Firefox, Chrome, Safari
     http_request = new XMLHttpRequest();
  }catch (e) {
     // Internet Explorer Browsers
     try{
        http_request = new ActiveXObject("Msxml2.XMLHTTP");

     }catch (e) {

        try{
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
        }catch (e) {
           // Something went wrong
           alert("Your browser broke!");
           return false;
        }

     }
  }

  http_request.onreadystatechange = function() {

     if (http_request.readyState == 4  ) {
        // Javascript function JSON.parse to parse JSON data
        console.log(http_request);
        var jsonObj = JSON.parse(http_request.responseText);
        var allIcons = [];
        for(var i = 0; i < jsonObj.length - 1; i++){
          console.log("-----------")
          console.log("Latitude:  ", jsonObj[i]['lat'])
          console.log("Longitude: ", jsonObj[i]['lon'])
          console.log("ID: ", jsonObj[i]['mmsi'])

          var lat = jsonObj[i]['lat']
          var long = jsonObj[i]['lon']
          var mmsi = jsonObj[i]['mmsi']

          var iconFeature = new Feature({
            geometry: new Point(fromLonLat([long, lat])),
            name: mmsi,
            population: 4000,
            rainfall: 500
          });

          var iconStyle = new Style({
            image: new Icon(
              /** @type {olx.style.IconOptions} */ ({
                anchor: [0.5, 46],
                anchorXUnits: "fraction",
                anchorYUnits: "pixels",
                src: "https://i.imgur.com/P30vpnp.png",
                scale: 0.5

              })
            )
          });
          iconFeature.setStyle(iconStyle);
          allIcons.push(iconFeature);

        }
        var map = new Map({
          controls: defaultControls().extend([new FullScreen()]),
          layers: [
            new TileLayer({
              source: new OSM()
            }),
            new VectorLayer({
              style: function(feature) {
                return feature.get("style");
              },
              source: new VectorSource({ features: allIcons })
            })
          ],
          target: document.getElementById('map'),
          view: new View({
            center: newportWebMercator,
            zoom: 3
          })
        });
        var element = document.getElementById('popup');

var popup = new Overlay({
  element: element,
  positioning: 'bottom-center',
  stopEvent: false,
  offset: [0, -50]
});

map.addOverlay(popup);

// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
    function(feature) {
      return feature;
    });
  if (feature) {
    var coordinates = feature.getGeometry().getCoordinates();
    popup.setPosition(coordinates);
    $(element).popover({
      placement: 'top',
      html: true,
      content: feature.get('name')
    });
    $(element).popover('show');
  } else {
    $(element).popover('destroy');
  }
});

// change mouse cursor when over marker
map.on('pointermove', function(e) {
  if (e.dragging) {
    $(element).popover('destroy');
    return;
  }
  var pixel = map.getEventPixel(e.originalEvent);
  var hit = map.hasFeatureAtPixel(pixel);
  map.getTarget().style.cursor = hit ? 'pointer' : '';
});

     }
  }

  http_request.open("GET", data_file, true);
  http_request.send();
}
loadJSON();


text:
Q: How to define a function which takes a real number and gives as a result the closest $\le$ natural number? How can I define a function which takes as an only parameter a real number and gives as a result the closest smaller natural number? E.g. $f(3.554)=3, f(4.95485)=4, f(2.001)=2$.

A: First, if your real number $k < 1$, then the function $f$ is not defined at $k$ since there is no natural number lesser than the value of $k$.
The function $f$ you are trying to define is just a subset of the floor function where $f:\{x|x\ge 1\} \mapsto \mathbb{N}$. Thus we can define your function as $f(x) = \max (y\in \mathbb{N}|y\le x), x \in [1,\infty)$.

A: You can define such a function directly by it's desired properties, i.e. for $x\geq 1$, define
$$ f(x) :=\max \left\{ n\in\mathbb{N}:n\leq x  \right\}. $$
As has already been pointed out, $f(x)$ is commonly denoted by $\lfloor x\rfloor$. Clearly $f$ is discontinuous, so it cannot be expressed as a finite composition of continuous functions (which probably is what you've actually been looking for) or a power series.
One obvious representation of $f$ would be to write it as a limit of step functions:
$$ f = \lim_{n\rightarrow \infty}\sum_{k=1}^n k \cdot\chi_{[k,k+1)}$$
where $\chi_I$ is the characteristic function of the interval $I$, but this is really nothing more than toying with the definition.


text:
Q: Can see my HDD in Windows, but not from Linux live boot I've just gotten a new laptop (Acer Aspire A315-56), where I can't see my HDD from a Linux live boot. When I'm opening GParted, it's only showing one disk and it's the USB Drive from where I've live booted it. My laptop came preinstalled with Windows 10 Home.
I've looked up Ask Ubuntu and similar forums, and according to the suggestions, I've tried out the following:
Set the SATA Mode to "AHCI" from "Optane without RAID"

Disabled Fast Boot from BIOS

Disabled Secure Boot

Disabled Fast Startup and Hibernate from Windows 10 Power Options

Unfortunately, none of those turned out to work for me.
As I'm not able to see the HDD from Linux, I'm not able to install it. Can anyone help me out with making the HDD visible from Linux? Using a Virtual Machine isn't really a solution.
Also, I've checked that upon hitting sudo lshw in the terminal, the SATA Controller shows up there. So, the SATA controller's driver is in the kernel.
I'm live booting Ubuntu, if that helps.

A: Its not really a solution more of a workaround, put the laptop to sleep and wake it backup and the SATA drive will appear.
If your kernel has the debugging enabled for power management you add test_suspend=mem and suspend.pm_test_delay=2 to the boot time options.
unfortunately most kernels are released without them compiled in.
The main thing is after getting the OS installed, you have to wait for the kernel to start booting shut the lid or use the keyboard shortcut to put it to sleep wait a second wake it up and let the computer finish booting, or compile a custom kernel and enable the power management debugging and suspend test options in the config.


text:
Q: jqGrid resolve the grid pager ID dynamically? I have 3 simple questions.

*

*I have some code that tells me if a jqGrid object is present in the page:
//Check if there is a jqGrid on the page and if present, reloads its data ;)
var jqGrid = $('div.ui-jqgrid-bdiv table');
if (jqGrid.length) {
    //time to reload
    $(jqGrid).trigger('reloadGrid');
}

I would like to find the pager ID element if there is one. Is there any way to do this?

*Suppose I have a custom class in my jqGrid table:

How do I check the presence of customclass inside my jqGrid dynamically?
EDIT:
With Oleg help I have been able to code a reconfigPermissions() function that show/hide default Add, Edit and Delete buttons. Here is the function:
function reconfigPermissions(gridID) {
    var enableRegistry = CanModifyRegistry();
    var ops = ['#add_' + gridID, '#edit_' + gridID, '#del_' + gridID];
    $.each(ops, function (ix, value) {
        var $td = $(value);
        if (enableRegistry === true) {
            $td.show();
        } else {
            $td.hide();
        }
    });
}

This function get called when the user select another range of dates in a combo box defined elsewhere in the page.
The problem is the following: if, when the grid is initially loaded, the user has rights to the default period (selected in the combo box) everything works. You can switch the date range in the combo and the buttons appear and disappear correctly.
Unfortunately if the user has no rights on the default period initially selected (so the first creation of the grid has {add: false, edit: false, del: false}) even switching to a period where the user has rights does not add the buttons at all.
This is the code binded to the combo box change event handler
$.ajax({
    url: GetBaseWSUrl() + 'MyWebService.asmx/ChangeCurrentPeriod',
    type: "post",
    dataType: "json",
    async: false,
    data: JSON.stringify({ periodID: $(this).val() }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        //Check if there is a jqGrid on the page and if present, reloads its data
        var jqGrids = $('div.ui-jqgrid-bdiv table');
        jqGrids.each(function (ix, jqGrid) {
            var gridID = $.jgrid.jqID(jqGrid.id)
            reconfigPermissions(gridID);
            jqGrid.trigger('reloadGrid');
        });
    }
});

Any suggestion?

A: You can find the jqGrids existing on the page in many ways. For example you can use $('table.ui-jqgrid-btable') instead of $('div.ui-jqgrid-bdiv table'). Moreover you should not forget that it can be more as one jqGrid on the page in general. I recommend you to write your code so that it will work with many jqGrids of the page even if you currently use only one jqGrid per page.
If you find in any way the table element of jqGrid you can get the DOM element of the first found grid with jqGrids[0]. jqGrid use some extenders of the DOM. It add additional properties grid and p. In every jqGrid method will be checked whether the grid is initialized by verifying that grid property exist. The p property gives you all jqGrid parameters inclusive p.pager. You can create up to two pager on on grid: one on top edge of the grid and another on the bottom (see this for more information). So the code which you need could looks like
var jqGrids = $('table.ui-jqgrid-btable');
if (jqGrid.length > 0) {
    jqGrid.each(function(i) {
        if (this.grid) {
            // one more test for the jqGrid
            // jqGrid[i] is a jqGrid
            if (this.p.toppager) {
                // this.id + '_toppager' is the id of the top pager
            }
            if (this.p.pager) {
                // this.p.pager is the id of the bottom pager
            }
        }
    });
}

To test whether the table element has some customclass class you can use jQuery.hasClass.
UPDATED: In the comment you asked me how to hide or to show the buttons in the navigator bar dynamically. I prepared the demo which demonstrate this:

If one checks the buttons which are placed above the grid the corresponding button from the navigator bar will be hide. Unchecking will show the corresponding button back.
The code just call $('#add_list').hide() or $('#add_list').show() to hide/show the "Add" button. In the example the last part of the id="add_list" is the id of the
 element used to create the grid. Other standard buttons have the ids starting with the following prefixes: 'edit_', 'view_', 'del_', 'search_', 'refresh_'. More common code which works if the id of the grid has special characters looks as following:
var grid = $("#list"),
    gid = $.jgrid.jqID(grid[0].id);

$('#cbAdd').change(function () {
    var $td = $('#add_' + gid);
    if ($(this).is(':checked')) {
        $td.hide();
    } else {
        $td.show();
    }
});

To find the custom navigator buttons added by navButtonAdd I use title attribute:
$('#cbChooseColumns').change(function () {
    var $td = $(grid[0].p.pager + '_left ' + 'td[title="choose columns"]');
    if ($(this).is(':checked')) {
        $td.hide();
    } else {
        $td.show();
    }
});


text:
Q: Using multiple computers for number crunching I'm currently running some computationally intensive simulations, but they are taking a long time to complete. I've already split the workload across all the available physical cores in my processor. What I'm wondering is how to go about splitting the workload further and assigning it to other computers. I'm contemplating buying a couple Xeon servers and using them for the number crunching.
The one big issue I have is that I'm currently running the program within Visual Studio (Ctrl F5) as there are two methods which I'm constantly making small changes to.
Any suggestions on how/if it's possible to assign the workload to other computers / if it's possible to still run the program with VS or would I need to create an *.exe each time I wanted to run it?

A: It depends on the problem you're solving.
You can use map/reduce and Hadoop if it's easily parallelizable, like SETI@Home.
You can use something like MPI if it's not, like linear algebra.

A: Isn't the crux of your problem in this statement "The one big issue i have is that im currently running the program within Visual Studio (Ctrl F5) as there are two methods which im constantly making small changes to."?
Is it the "one big issue" because if you distribute then you can't afford modifying the code on all of the nodes when doing the job so you think about something distributing it for you? If this is the case then I assume that you already know how to split the algo or data in a way that nodes can take take of small parts of the job.
If it's the case - sorry if I misunderstood - then externalise the part that you are "constantly making small changes to" into a file or a DataBase encoded in some simple or more elaborate form depending on what you are changing so you don't need to have your nodes change constantly. Deploy the code on all nodes, connect them to the DB or file which contains the varying bit and enjoy your new Ferrari!

A: You could use the WMI service to start your process on the remote computers. You would build your exe to a shared directory that is visible to the remote computer, then use WMI on the remote computer to launch the exe.
There are plenty of examples out there to do this, but to illustrate, a simple method which assumes no authentication complications is to use a .VBS script file:
strComputer = "acomputer"
strCommandLine = "calc.exe"

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objProcess = objWMIService.Get("Win32_Process")

intReturnValue = objProcess.Create(strCommandLine, , , intPID)
WScript.Echo "Process ID: " & intPID

You can also use PsExec from SysInternals to handle all the details of making this work.
After building the exe in Visual Studio, you could run it on your local machine to ensure it does what you want, then when you are ready to launch it on the remote systems, you can execute a batch script similar to the above VBS to launch the exe on the remote systems.
You will still need to provide some mechanism to divide up the workload so that each client knows what part of the problem it is supposed to work on. You could provide this information in the command line used to start the remote apps, in a config file in the directory with the exe, in a database table, or use a separate command-and-control type server that the clients connect back to (although with that approach you'll soon get to the stage where you would have been better off with learning to use an existing solution rather than rolling your own).
You may also want to include a remote 'kill switch' of some sort. You could use PsKill from SysInternals, or if you want a more graceful shutdown, something simple like the existence of a particular file in the same directory as the exe can serve as a flag for the remote processes to shut themselves down.
You could also consider adding CSScript support to the client so that the remote client programs are static and load and compile a CSScript file to do the work. This might be useful if you encounter some kind of difficulty in frequently redeploying and restarting the client programs, or if you need them to all be slightly different (you might write a program to generate separate script files for each client for example).


text:
Q: Why isn't this simple NHibernate one-to-many relation bidirectional? I'm trying to set up a simple association in NHibernate (this is the first project in which I want to make use of it from the ground up) - it seems like a simple, contrived, book example, but for some reason I can't get the relation to work bidirectionally.
I have a class called Contact which can contain many Addresses.
Here is the simplified Contact class:
public class Contact {

// firstName, lastName, etc, etc omitted

// ixContact is the identity value
public virtual int ixContact { get; set; }
public virtual ICollection<Address> addresses { get; set; }

}

and here is Address:
public class Address {
       public virtual int ixAddress { get; set; }
       public virtual Contact contact { get; set; }
}

here is the relevant part of the mapping file, Contact.hbm.xml:
<id name="ixContact">
    <generator class="hilo" />
</id>

<bag name="Addresses" inverse="true" cascade="save-update">
     <key column="ixContact" />
     <one-to-many class="Address />
</bag>

here is the relevant part of the Address.hbm.xml mapping file:
<id name="ixAddress">
    <generator class="hilo" />
</id>

<many-to-one name="contact" class="Contact" column="ixContact" />

Given that setup, I run the following code:
_configuration = new Configuration();
    _configuration.Configure();
    _configuration.AddAssembly(typeof(Contact).Assembly);

    _sessionFactory = _configuration.BuildSessionFactory();

    _session = _sessionFactory.OpenSession();

    new SchemaExport(_configuration).Execute(false, true, false);

    Contact firstContact = new Contact { firstName = "Joey", middleName = "JoeJoe", lastName = "Shabadoo" };

    using( ITransaction tx = _session.BeginTransaction()) {

           firstContact.Addresses = new List<Address>();
           Address firstAddress = new Address { /* address data */ };

        firstContact.Addresses.Add(firstAddress);

      _session.SaveOrUpdate(firstContact);

      tx.Commit();
    }

    _session.Close();

    _session.Dispose();

Once I run this code, the Contact is inserted into the Contact table just fine, and the Address is also inserted into the Address table, except that the Address's ixContact field is NULL, not associated with the value of the Contact's ixContact field, as I would expect.
If I explicitly specify the other side of the relation and say firstAddress.Contact = firstContact, it works fine, but I was under the impression that NHibernate took care of this automagically?
If so, what am I doing wrong? Or do I have to specify RandomContact.Addresses.Add(foo), foo.Contact = RandomContact every time?

A: Hmm, it looks like you're missing the call _session.Save(firstContact); before calling tx.Commit();

A: You do need to set both sides of the relationship explicitly.


text:
Q: Getting error while runnign gatling project "object gatling is not a member of package io import io.gatling.app.Gatling" I am trying to run a test recorded as har script from browser and imported to the project in Intellij IDE. When I am running the project it is giving error:
object gatling is not a member of package io import io.gatling.app.Gatling

Below is the screenshot attached.

Any leads would be helpful.

A: As noted in my comment on your question, you need to add the Gatling package into your Maven build configuration in the pom.xml file. The IntelliJ Idea help page on Maven has instructions to add a Maven package:

Add a new Maven module to an existing project
You can add a Maven module to the project in which you are already
working.

*

*In the Project tool window, right-click the project folder and select
New | Module.

*Alternatively, from the main menu, select File |
New | Module to open the New Module wizard.

If you used main menu to add a module then the process of adding a module is the same as Creating a new Maven project.
If you are adding sub modules by right-clicking the root folder then the process of adding a new module is shorter.

*

*You need to specify the name of your module in the Name field.
The rest of the information is added automatically and you can use either the default settings or change them according to your preferences.


text:
Q: Weird Messages by executing Process.Start command We have a project which creates an Excel file and save it in Network shared drive and after that it opens up that file,
application works fine but I get a weird messages.
Consider the following piece of codes
using Excel = Microsoft.Office.Interop.Excel;
....
xlsAppClass = new Excel.Application();
Process excelPID = GetExcelProcessId(xlsAppClass);

//
// All codes generate and save the excel file...
// and return the filePath which is located in Network Shared drive.
//

xlsWorkBook.Close();
xlsAppClass.Quit();
Marshal.ReleaseComObject(xlsSheets);
Marshal.ReleaseComObject(xlsWorksheet);
Marshal.ReleaseComObject(xlsWorkBook);
Marshal.ReleaseComObject(xlsAppClass);
if (excelPID != null) excelPID.Kill();

// When program reaches this line of code excel file created, saved and Excel process killed
// I checked the TaskManager, nothing's there.

Then I opens up the generated file via the following code
System.Diagnostics.Process.Start(filePath);

at this moment System opens up the file but I get the following message as well which I couldnt figure it out WHY
"Microsoft Office Communicator 2007 is already running"

A: Actually I restarted the PC, and issue resolved!


text:
Q: Scraping items using scrapy I have written the following spider for scraping the webmd site for patient reviews
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

class MySpider(BaseSpider):
    name = "webmd"
    allowed_domains = ["webmd.com"]
    start_urls = ["http://www.webmd.com/drugs/drugreview-92884-Boniva"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select("//p")
        title = titles.select("//p[contains(@class, 'comment')and contains(@style, 'display:none')]/text()").extract()
        print(title)

Executing this code gives me desired output but with a lot of duplication i.e. the same comments are repeated for at least 10 times.
Help me to solve this issue.

A: You can rewrite your spider code like this:
import scrapy

# Your Items
class ReviewItem(scrapy.Item):
    review = scrapy.Field()

class WebmdSpider(scrapy.Spider):
    name = "webmd"
    allowed_domains = ["webmd.com"]
    start_urls = ['http://www.webmd.com/drugs/drugreview-92884-Boniva']

    def parse(self, response):
        titles = response.xpath('//p[contains(@id, "Full")]')
        for title in titles:
            item = ReviewItem()
            item['review'] = title.xpath('text()').extract_first()
            yield item

        # Checks if there is a next page link, and keeping parsing if True
        next_page = response.xpath('(//a[contains(., "Next")])[1]/@href').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

It selects only full customer reviews without duplicate and saves them in Scrapy Items.
Note: instead of HtmlXPathSelector you can use more convenient shortcut response. Also, I change deprecated scrapy.BaseSpider to scrapy.Spider.
For saving reviews to a csv format you can simply use Scrapy Feed exports and type in console scrapy crawl webmd -o reviews.csv.

A: You can use sets to get unique comments. I hope you know that the selector returns the result as a list so if you use sets then you ll get only unique results. So
def parse(self,response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select("//p")
    title = set(titles.select("//p[contains(@class, 'comment')and contains(@style, 'display:none')]/text()").extract())
    print (title) #this will have only unique results.


text:
Q: Difficulty in Prolog I need to solve a logic problem using Prolog. I have just one problem:
In the answer, the name of the attributes doesn't appear. My code to generate the attributes is:
gera(p(Prof, AlunosProf, Tema, AlunosTema)) :-
       member(Prof, [palmira, roberta, selma]),
       member(AlunosProf, [40, 45, 50]),
       member(Tema, [transito, culinaria, reciclagem]);
       member(AlunosTema, [40, 45, 50]).

But after doing the query it looks like this:
S = [p(palmira, _G2046, transito, 45),
    p(roberta, 50, reciclagem, _G2053),
    p(selma, _G2056, culinaria, _G2058)]

Where is "_G*something" I want to appear the name of the attribute (in this case only the number of students).
Edit:
Adding the entire code:
gera(p(Prof, AlunosProf, Tema, AlunosTema)) :-
       member(Prof, [palmira, roberta, selma]),
       member(AlunosProf, [40, 45, 50]),
       member(Tema, [transito, culinaria, reciclagem]),
       member(AlunosTema, [40, 45, 50]).

dif(p(P1, Q1, T1, Q12), p(P2, Q2, T2, Q22)) :-
    P1 \= P2, Q1 \= Q2, Q12 \= Q22, T1 \= T2.

tudoDif(P1, P2, P3) :-
    dif(P1, P2), dif(P1, P3), dif(P2, P3).

gera_ef(P1, P2, P3) :-
    P1 = p(palmira, _, _, _),
    P2 = p(roberta, _, _, _),
    P3 = p(selma, _, _, _).
    gera(P1), gera(P2), gera(P3),
    tudoDif(P1,P2,P3).

solucao(S) :-
        S = [P1, P2, P3],
    gera_ef(P1, P2, P3),
    member(p(palmira, X, transito, 45), S),
        member(p(selma, Z, culinaria, W), S),
        member(p(roberta, 50, reciclagem, R), S),
    !.

A: You are relaxing the constraint of you statement when you use ; instead of ,.
When you use ; you're stating that, either what came before or what is coming now is acceptable.
Since when you start saying "what is coming now" you only define the values of AlunosTema, the other values will receive any value, represented by what you saw -- "_G233...".
Try the following:
gera(p(Prof, AlunosProf, Tema, AlunosTema)) :-
       member(Prof, [palmira, roberta, selma]),
       member(AlunosProf, [40, 45, 50]),
       member(Tema, [transito, culinaria, reciclagem]),
       member(AlunosTema, [40, 45, 50]).

Edit:
Considering the whole code you posted, you may change some couple of things:
...

gera_ef(P1, P2, P3) :-
    P1 = p(palmira, _, _, _),
    P2 = p(roberta, _, _, _),
    P3 = p(selma, _, _, _),
    gera(P1),
    gera(P2),
    gera(P3),
    tudoDif(P1,P2,P3).

solucao(S) :-
    S = [P1, P2, P3],
    gera_ef(P1, P2, P3),
    member(p(palmira, _, transito, 45), S),
    member(p(selma, _, culinaria, _), S),
    member(p(roberta, 50, reciclagem, _), S),
    !.

The problem here is that you had a . instead of a , in:
gera_ef(P1, P2, P3) :-
    ...,
    P3 = p(selma, _, _, _).
    ...

that wouldn't allow the rest of the code to execute.
Another change was the replacement of the unbounded variables in solucao with _; note X, W, R have been removed.

A: You have a typo in your code. You put a colon where you meant a comma:
The line
member(Tema, [transito, culinaria, reciclagem]);

should read
member(Tema, [transito, culinaria, reciclagem]),


text:
Q: Vertical alignment of feynmp-graphs in equations I find myself often in the situation where I have to arrange graphs generated with feynmp in equations. This works usually fine, but I have to play around with the space, i.e. I need to add some at the bottom for the text and the graph not to overlap.
Consider the following code
\documentclass{article}
\usepackage{lipsum}
\usepackage{mathtools}
\usepackage{feynman-auto}

\setlength{\unitlength}{.09cm}

\begin{document}

\lipsum[10]

\begin{fmffile}{operator_2}
    \begin{align*}
      (a)-(b):=
      \fmfframe(2,12.5)(2,-12.5){%
        \begin{fmfgraph*}(40,25)
          \fmfleftn{i}{2}
          \fmfrightn{o}{2}
          \fmf{dashes}{i1,v,o1}
          \fmf{fermion}{i2,v,o2}
          \fmfblob{0.15w}{v}
          \fmflabel{$p_2$}{i2}
          \fmflabel{$p_4$}{i1}
          \fmflabel{$p_3$}{o1}
          \fmflabel{$p_1$}{o2}
        \end{fmfgraph*}%
      }
      -
      \fmfframe(2,12.5)(2,-12.5){%
      \begin{fmfgraph*}(40,25)
        \fmfleftn{i}{2}
        \fmfrightn{o}{2}
        \fmflabel{$p_2$}{i2}
        \fmflabel{$p_4$}{i1}
        \fmflabel{$p_3$}{o1}
        \fmflabel{$p_1$}{o2}
        \fmf{photon,tension=2,fore=red}{i1,v4}
        \fmf{photon,tension=2,fore=red}{o1,v1}
        \fmf{dashes,tension=2}{o2,v2}
        \fmf{dashes,tension=2}{i2,v3}
        \fmfdotn{v}{4}
      \end{fmfgraph*}%
    }
    \end{align*}
\end{fmffile}

\lipsum[10]

\end{document}

which should result in the following output:

The math and the graph are nicely aligned, but I would need to add something like \\\\\\ after the last \fmfframe{} command to make enough space for the text to fit... Also, it seems that there is unnecessary space between the upper text and the graph. Can this be reduced?
If possible I would like to apply these changes to all environments of the form
\begin{fmffile}{name}
    \begin{align*}
         \fmfframe()(){}
         .
         .
         .
    \end{align*}
\end{fmffile}

I'm not sure if it would be smart to create a new environment for this (and I lack the skill to do it anyways...). Also, I am not interested in solutions that are based on tikz-feynman.

A: I'd use gathered, but with a twist, because labels in Feynman diagrams are often outside the bounding box.
\documentclass{article}
\usepackage{lipsum}
\usepackage{mathtools}
\usepackage{feynmp-auto}

\newcommand{\eqgraph}[3]{%
  % #1 = adjustment above, #2 = adjustment below, #3 = graph
  \begin{gathered}
  \raisebox{0pt}[\dimexpr\height+#1][\dimexpr\depth+#2]{\ignorespaces#3\unskip}%
  \end{gathered}
}

\setlength{\unitlength}{.09cm}

\begin{document}

\lipsum[10]

\begin{fmffile}{operator_2}
\[
      (a)-(b):=
\mspace{30mu}
\eqgraph{0ex}{2ex}{
        \begin{fmfgraph*}(40,25)
          \fmfleftn{i}{2}
          \fmfrightn{o}{2}
          \fmf{dashes}{i1,v,o1}
          \fmf{fermion}{i2,v,o2}
          \fmfblob{0.15w}{v}
          \fmflabel{$p_2$}{i2}
          \fmflabel{$p_4$}{i1}
          \fmflabel{$p_3$}{o1}
          \fmflabel{$p_1$}{o2}
        \end{fmfgraph*}
}
\mspace{30mu}
      -
\mspace{30mu}
\eqgraph{0ex}{1.8ex}{
      \begin{fmfgraph*}(40,25)
        \fmfleftn{i}{2}
        \fmfrightn{o}{2}
        \fmflabel{$p_2$}{i2}
        \fmflabel{$p_4$}{i1}
        \fmflabel{$p_3$}{o1}
        \fmflabel{$p_1$}{o2}
        \fmf{photon,tension=2,fore=red}{i1,v4}
        \fmf{photon,tension=2,fore=red}{o1,v1}
        \fmf{dashes,tension=2}{o2,v2}
        \fmf{dashes,tension=2}{i2,v3}
        \fmfdotn{v}{4}
      \end{fmfgraph*}
}
\]
\end{fmffile}
\lipsum[10]

\end{document}

I'm afraid you need to do the adjustment by eye.


text:
Q: Spline terminology: Can a spline be represented by a Bézier curve? In this question it was stated that a B-spline is just a representation of a Bézier curve. I wonder if this also holds true for Bézier curves. Splines are defined piecewise by polynomials and so are Bézier curves. Is it correct to say that Bézier curves are splines? Is the term spline like a umbrella term for B-splines, Bézier curves, composite Bézier curves, NURBS etc.? Are they all splines at the end? Or are they all just representatives?

A: A spline is a piecewise continuous curve. Each piece (or segment) of the spline could be represented by polynomial functions, trigonometric functions, exponential functions,...., etc with polynomial function being the most popular choice.
A B-spline curve (sometimes referred as B-splines for simplification) is a polynomial spline and each segment of a B-spline curve is geometrically equivalent to a Bezier curve (of the same degree). A NURBS curve is basically a rational B-spline curve where each piece is a rational polynomial function.
A Bezier curve is also a polynomial curve and we can analytically convert a polynomial curve into a Bezier curve or a Bezier curve into a polynomial curve. However, a Bezier curve is not really a spline and it would be confusing or even inappropriate to use terms like "Bezier spline".


text:
Q: DateTime required in ModelState, however never set to be I have a DateTime field in my form. For whatever reason, everytime I submit the form ModelState comes back as invalid and a message that my date time field (called PostDate) is required, even though in the view model I don't have the required attribute set.
Does anyone know why this would be happening as I'm going around in circles trying to figure it out.
Here is the view model
public class BlogViewModel
        {
            [Required]
            public string Title { get; set; }
            [Required]
            public string Content { get; set; }
            public bool Published { get; set; }
            public DateTime PostDate { get; set; }
        }

Here is the controller actions
            public ActionResult Create()
            {
                return View();
            }

            //
            // POST: /Admin/Blog/Create

            [HttpPost]
            [ValidateInput(false)]
            public ActionResult Create(BlogViewModel model)
            {
                if(ModelState.IsValid)
                {
                    model.Content = HtmlSanitizer.SanitizeHtml(model.Content);
                    Services.BlogService.CreateBlogPost(model.Title, model.Content, User.Identity.Name);
                    return RedirectToAction("Index");
                }
                return View(model);
            }

Here is the View
    @using Payntbrush.Infrastructure.Mvc.Extensions
    @model Payntbrush.Presentation.Demo.MVC3.Areas.Admin.Models.BlogViewModel

    @Html.Resource(Html.ScriptTag("Areas/Admin/js/plugins/wysiwyg/jquery.wysiwyg.js"), ResourceType.Js)

    @using (Html.BeginForm((string)ViewBag.Action, "Blog", FormMethod.Post, new { Id = "BlogEditor" }))
    {
        @Html.ValidationSummary(true)

                @Html.LabelFor(model => model.Title)

                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title)

                @Html.LabelFor(model => model.Content)

                @Html.TextAreaFor(model => model.Content, new { @class = "wysiwyg blog-editor" })
                @Html.ValidationMessageFor(model => model.Content)

                Time of post (Only set this if you want to make a post appear to have been published at a different date.)

                @Html.TextBoxFor(model => model.PostDate, new{@class="datetimepicker"})
                @Html.ValidationMessageFor(model => model.PostDate)

                Published (Check to make this post live on the site)

                @Html.CheckBoxFor(model => model.Published)
                @Html.ValidationMessageFor(model => model.Published)

                <input class="large awesome" type="submit" value="Create" />
                @Html.ActionLink("Cancel", "Index", "Blog", null, new { @class = "large awesome cancel-button" })

    }

A: If you leave the corresponding field empty your model will be invalid because DateTime is a value type. You should use a nullable DateTime if you want to allow empty values:
public DateTime? PostDate { get; set; }


text:
Q: Jenkins - How do I publish coverage report to github I am trying to use github-pr-coverage-status-plugin, the documentation says I need to run the following on my master branch:

step([$class: 'MasterCoverageAction'])

But when I add this to my pipeline I get the following error:
java.lang.UnsupportedOperationException: Can't find GIT_URL or CHANGE_URL in envs: {BRANCH_NAME=master, BUILD_DISPLAY_NAME=#41, BUILD_ID=41, BUILD_NUMBER=41, BUILD_TAG=jenkins-testci-master-41, BUILD_URL=https://jnkns-ci.myserver.com/job/testci/job/master/41/, CLASSPATH=, HUDSON_HOME=/var/jenkins_home, HUDSON_SERVER_COOKIE=01f6aedeea333d1f, HUDSON_URL=https://jnkns-ci.myserver.com/, JENKINS_HOME=/var/jenkins_home, JENKINS_SERVER_COOKIE=01f6aedeea333d1f, JENKINS_URL=https://jnkns-ci.myserver.com/, JOB_BASE_NAME=master, JOB_DISPLAY_URL=https://jnkns-ci.myserver.com/job/testci/job/master/display/redirect, JOB_NAME=testci/master, JOB_URL=https://jnkns-ci.myserver.com/job/testci/job/master/, RUN_CHANGES_DISPLAY_URL=https://jnkns-ci.myserver.com/job/testci/job/master/41/display/redirect?page=changes, RUN_DISPLAY_URL=https://jnkns-ci.myserver.com/job/testci/job/master/41/display/redirect}
    at com.github.terma.jenkins.githubprcoveragestatus.PrIdAndUrlUtils.getGitUrl(PrIdAndUrlUtils.java:85)
    at com.github.terma.jenkins.githubprcoveragestatus.MasterCoverageAction.perform(MasterCoverageAction.java:71)
    at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:80)
    at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:67)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution$1$1.call(SynchronousNonBlockingStepExecution.java:49)
    at hudson.security.ACL.impersonate(ACL.java:260)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution$1.run(SynchronousNonBlockingStepExecution.java:46)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

I have tried multiple ways to inject these variables. In my latest try, I even looked at the source code for this class, so I changed my pipeline to be:
pipeline {

  agent any

  options {
    skipDefaultCheckout()
  }
  environment {
    // calling credentials() actually sets 3 environment variables
    // GIT_HUB with  <username>:<password>
    // GIT_HUB_USER with <username>
    // GIT_HUB_PSW with <password>

    GIT_HUB = credentials('tmhjenkins')
    DOCKER_REPO  = 'mobilityhouse'
    DOCKER_HUB   = credentials('tmhitadmin')
    GIT_URL_PROPERTY = "https://$GIT_HUB@github.com/mobilityhouse/testci.git"
  }

  stages{
    ...
    ...
stage('Coverage & Tests') {
      steps {
        sh 'pip3 install -e .'
        sh 'make coverage-xml'
        script {
          currentBuild.result = 'SUCCESS'
          sh(script: 'export GIT_URL_PROPERTY="https://$GIT_HUB@github.com/mobilityhouse/testci.git"')
          env.GIT_URL_PROPERTY = "https://$GIT_HUB@github.com/mobilityhouse/testci.git"
          step([$class: 'MasterCoverageAction'])
        }
      }
    }

...

}
Alas, this fails too. So how am I supposed to properly use this plugin from within the pipeline? Any help would be appreciated.

A: After beating around the bush for a while, I decided to take a deeper look what this Jenkins plugin does (an issue report in github wasn't yielding much ...)
It turned out that the master coverage reports are stored properly for example with the environment variable properly set:
  step([$class: 'MasterCoverageAction',
              scmVars:
                [GIT_URL:
                 "https://github.com/xxx/testci.git",]
            ])

This would have added an entry in the XML log file in JENKINS_HOME, how ever the plugin would complain:
Can't find master coverage repository: https://github.com/xxx/testci/pull/8 in stored: {https://github.com/myorga/testci/pull/5=0.6923, https://github.com/xxx/testci/pull/6=0.6923, https://****@github.com/myorga/testci.git=0.5385, https://github.com/xxx/testci/pull/7=0.5385}

This lit a red light, so I dug into the code and found the problem. Which is that the PR is detected by the plugin as: https://github.com/xxx/testci/pull/6 however master coverage action should have only saved https://github.com/xxx/testci so the key is not found in the configuration file (which is parsed to a hash map). After reading through the code, it was pretty easy to fix the code.
In githubprcoveragestatus/CompareCoverageAction.java I replaced:
final float masterCoverage = masterCoverageRepository.get(gitUrl);

with the following lines to
float masterCoverage;
if (gitUrl.contains("pull/")) {
    final String myCorrectURL = "https://github.com/" + GitUtils.getUserRepo(gitUrl);
    // Using  masterCoverageRepository.get(myCorrectURL); is failing because URL is
    // https://github.com/USER/REPO/pull/PR_ID
    buildLog.println(BUILD_LOG_PREFIX + "myCorrectURL:" + myCorrectURL);
    masterCoverage = masterCoverageRepository.get(myCorrectURL);
} else {
    masterCoverage = masterCoverageRepository.get(gitUrl);
}

This solved my problem, in the good spirit of open source, I made a pull request to fix how a URL for Pull Request is detected, such that others can benefit from this fix.


text: Q: Creating flutter sliders dynamically For instance, I have a list of lengths 20. I want to create sliders dynamically depending on the list length. My main problem is on changing the values of each slider independently. As of now I have the sliders but when I slide one all the sliders are changed ,they a appear as one


text:
Q: how to make google map coordinates request more precise/accurate with c# winform? Im building a winform project using Google maps api. im sending an address and i get the address coordinates as a result. However, im not getting the most accurate results...
here is my code:
using System.Net;
using System.Runtime.Serialization.Json;

namespace WinForm_Project
{
   class GoogleMaps
   {
       public static GeoResponse GetGeoCodedResults(string address) and uses google maps to retrieve the address's coordinates.
       {
           string url = string.Format("http://maps.google.com/maps/api/geocode/json?address={0}&region=dk&sensor=false",HttpUtility.UrlEncode(address));
           var request = (HttpWebRequest)HttpWebRequest.Create(url);
           request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
           request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
           DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse));
           var res = (GeoResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
           return res;
       }
   }
}

this part works just fine. (just to be clear - my winform app does not contain a google map)
i noticed when i type an address on google maps's website i get certain coordinates - but the coordinates (Latitude, longitude) become more accurate when i zoom-in...
is there a way to change the request\code to get from google a more accurate results? such as Max zoom-in will display on google maps.
Thanks

A: Using Google's JSON option, your result will contain something like this.
...
"geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 40.91525559999999,
              "lng" : -73.70027209999999
           },
           "southwest" : {
              "lat" : 40.495908,
              "lng" : -74.2590879
           }
        },
        "location" : {
           "lat" : 40.7143528,
           "lng" : -74.00597309999999
...

The exact 'point' will be under results-->geometry-->location.  However, if your query is an area, say New York City, then you will get a bounding box for that area (results-->geometry-->bounds).  If that's the case, the exact location given would probably be the center of that area or a commonly accepted point.


text:
Q: Show that two discrete spaces are homeomorphic iff they have the same cardinality I have the following question:
Show that two discrete spaces are homeomorphic iff they have the same cardinality:
I have tried the following:
Let $f: (X, \mathcal{T}_{discrete}) \to (Y, \mathcal{T}_{discrete})$
$(\Rightarrow )$
As we have that the topology is the discrete then in particular each $\{x\} \in X$ is an open set, as we have that $f$ in a homeomorphism then $\{f(x)\} \in Y$ is an open set, this allows to conclude that both spaces have the same cardinality.
$(\Leftarrow )$
Let suppose that both spaces have the same cardinality, since both spaces are discrete then we have that each $\{x\} \in X$ is an open set and analogous each $\{y\} \in Y$ is an open set.
If we define the function $f$ as
$$f: (X, \mathcal{T}_{discrete}) \to (Y, \mathcal{T}_{discrete}) \text{ as } x_i \to y_i i \in |X|$$
then we have that is a bijective map, and for the affirmation that I made before $f$ and $f^{-1}$ are continuous. So we have that both spaces are homeomorphic.

Is correct what I have done?, thank you

A: If both sides have discrete topology, then any map is continuous. So as long as you have a bijection it is a homeomorphism. Thus this is true iff the underlying sets have same cardinality.

A: Hint: Every homeomorphism is a bijection and every function whose domain considered with discrete topology is automatically continuous irrespective of the topology in the codomain .


text:
Q: Giving an asymptotically tight bound on sum $\sum_{k=1}^n (\log_2 k)^2$ I am trying to give an asymptotically tight bound for the sum $\displaystyle\sum_{k=1}^{n} (\text{lg}k)^{2}$, where lg denotes the base 2 logarithm.
I really have no idea where to begin, and I've tried looking at consecutive ratio terms, I've tried changing the summand to $2^{2\text{lg}\text{lg}k}$, etc.
I know that $\Theta$ is linear, so really I just need an asymptotically tight bound on $(\text{lg}k)^{2}$, and I should be fine from there. But still, no luck...
Any help, hints, etc. would be greatly appreciated.

A: I will give two answers below -- the first one is simple, and applies if you do not care about getting the exact constant in the asymptotic (i.e., if a $\Theta(\cdot)$ result is enough). The second is a tad longer, but gives the exact leading term; and actually more (i.e., it will also give the two or three next low-order terms, in this particular case).

Method 1: Upper and lower bounds.
You have
$$
\sum_{k=\lfloor n/2\rfloor }^n (\log k)^2 \leq \sum_{k=1}^n (\log k)^2 \leq n (\log n)^2
$$
and
$$
\sum_{k=\lfloor n/2\rfloor }^n (\log k)^2 \geq \frac{n}{2}\left(\log \left\lfloor\frac{n}{2}\right\rfloor\right)^2 \geq \frac{n}{2}\left(\log \frac{n}{2} - 1\right)^2 = \frac{n}{2}\left(\log n - 2\right)^2 \operatorname*{\sim}_{n\to\infty}  \frac{1}{2} n(\log n)^2.
$$
Putting it together,
$$
\sum_{k=1}^n (\log k)^2 = \Theta\left( n \log^2 n \right).
$$

Method 2: Using integrals, often much easier to handle than sums.
Intuitively, a comparison series-integral would most likely do the trick. Indeed, $f\colon x > 1\mapsto (\ln x)^2$ is increasing, which is a good hint it'd work. (I am dropping the base 2 of the logarithm, since it is only a constant factor in the end result.)
Now, for every $k \geq 1$, for all $x\in[k,k+1)$
$$
(\ln k)^2 \leq (\ln x)^2\leq (\ln(k+1))^2
$$
so that
$$
\sum_{k=1}^{n-1} (\ln k)^2 \leq \sum_{k=1}^{n-1} \int_{k}^{k+1}(\ln x)^2 dx
= \int_{1}^{n}(\ln x)^2 dx \leq \sum_{k=1}^{n-1} (\ln(k+1))^2=\sum_{k=2}^{n} (\ln k)^2.
$$
This implies, rearranging terms (and since $\ln 1 = 0$), that
$$
\int_{1}^{n}(\ln x)^2 dx \leq \sum_{k=1}^{n} (\ln k)^2 \leq \int_{1}^{n}(\ln x)^2 dx+ (\ln n)^2
$$
and now, it only remains to compute (e.g., by integration by parts):
$$
\int_{1}^{n}(\ln x)^2 dx = \big[x(\ln^2 x - 2\ln x +2)\big]^n_1 = (1+o(1) n \ln^2 n
$$
in order to conclude:
$$
\sum_{k=1}^{n} (\ln k)^2 \operatorname*{\sim}_{n\to\infty}n \ln^2 n
$$
and, actually,
$$
\sum_{k=1}^{n} (\ln k)^2
= n \ln^2 n -2n \ln n + 2n +o(n)
$$
since the difference between the upper and lower bounding integrals is $\ln^2 n = o(n)$.

To sum up:
$$
\sum_{k=1}^{n} (\log_2 k)^2
= n \log_2^2 n -({2}{\ln 2})n\log_2 n + {2}{(\ln 2)^2}n +o(n)
$$


text:
Q: How to remove duplicate rows from JTable? In this class, I am trying to only keep one of each value in the JTable. The Data is coming from a Database. I dont need repetative data though.
public JTable getHeute(){

            DBconnect verbinden = new DBconnect();
            verbinden.erstelleVerbindung();

            JTable Habwesend=new JTable();
            Habwesend.setBounds(10, 30, 290, 400);
            Habwesend.setEnabled(false);
            DefaultTableModel dm=new DefaultTableModel();

            try {
            ResultSet rs= verbinden.sqlStatement.executeQuery("select MA_ID from AB_Spanne where(Date() >= Start and Date() <= Ende)");
            ResultSetMetaData rsmd=rs.getMetaData();
            //Coding to get columns-
            int cols=rsmd.getColumnCount();
            String c[]=new String[cols];
            for(int i=0;i<cols;i++){
                c[i]=rsmd.getColumnName(i+1);
                for (int k = 0; k < c.length; k++) {
                    dm.addColumn(c[k]);
                }

            }

            Object row[]=new Object[cols];
            while(rs.next()){
                for(int i=0;i<cols;i++){
                        row[i]=rs.getString(i+1);
                    }
                dm.addRow(row);
            }

            Habwesend.setModel(dm);
            verbinden.schliesseVerbindung();

    }

A: Change your query to:
"SELECT DISTINCT MA_ID from AB_Spanne where(Date() >= Start and Date() <= Ende)"

You can do it in java like (unrecommended and unperformant):
//UNTESTED CODE
List<Object> Objectlist = new List<Object>();
// ...
Object row[]=new Object[cols];

while(rs.next()){

   for(int i=0;i<cols;i++){
      row[i]=rs.getString(i+1);
   }

   if !(Objectlist.Contains(row)){
      dm.addRow(row);
   }
}

// I guess in order to the contains methode to work you may need to create own objects in which you override the equality / comparrision methods.

A: Instead of the List, use a Set and keep the rest of your code the same. That's your java solution, to whit:
// Set dm = new HashSet();
  Object row[]=new Object[cols];
            while(rs.next()){
                for(int i=0;i<cols;i++){
                        row[i]=rs.getString(i+1);
                    }
                dm.addRow(row);
            }
           Habwesend.setModel(dm);
            verbinden.schliesseVerbindung();


text:
Q: Update postmeta database for plugin in WooCommerce Sorry for the stupid question, but I need to update the postmeta WordPress database for a plugin that I develop. The specific data that I want to update is: _transaction_id
I have searching and found a code:
add_post_meta($post_id, $meta_key, $meta_value, $unique);

But, I really don't if this work properly or how to use.
Thanks

A: It is very simple. You need to use update post meta function.
$postid = your order id or post id.
$metakey = _transaction_id;
$metavalue = uniqid();
 update_post_meta( $postid ,'_transaction_id', uniqid());


text:
Q: Is it possible to use a static template variable in a template function? For example, in this instance (the code is pretty self-explanatory):
enum types : bool
{
    READ,
    WRITE
};

template<typename T>
auto function(types i, T data)
{
    static T datas;
    if (i == WRITE)
    {
        datas = data;
    }
    else if (i == READ)
    {
        return datas;
    }
}

int main()
{
    function(WRITE, "hello");
    std::cout << function(READ, NULL);
}

The expected output is:
hello

but it ends up in an exception.
Is there any way to fix this or is it not possible?

A: You should be able to use this kind of logic, but the issue here is that the type parameters for both calls are different.
(There's also another issue of a function with return type T not returning anything, but I'll ignore this for now.)
The first call uses char const* as template parameter and the second one either int or std::nullptr_t depending on how the NULL macro is defined.
Your code results in an uninitialized value being returned by the second call which is undefined behaviour.
You need to make sure the same template parameter is used in both cases:
int main()
{
    function(WRITE, "hello");
    std::cout << function(READ,static_cast<char const*>(nullptr));
}

or
int main()
{
    function(WRITE, "hello");
    std::cout << function<char const*>(READ, nullptr);
}


text:
Q: Deleting records in a sqlite db in iOS won't decrease the database size I'm currently trying to reduce the size of my database by deleting records from my sqlite database in my iOS application but the size will stay the same (size of all the files associated with the database, i.e. the .sqlite file, the .sqlite-shm file and the .sqlite-wal file). I have read that this is the expected behaviour (Ref: change sqlite file size after "DELETE FROM table"). This link suggests to use the sqlite "vacuum" tool and this should clean up the unused memory fragment. However, by doing this, this allocates a lot of memory in the rollback on disk memory (more specifically, the .sqlite-wal file). So this doesn't help since the total size of the files associated with the database didn't decrease.
I was wondering if anybody has any idea what to do in that case? Any help is appreciated.
Thanks
JB

A: You can disable the use of Write ahead logging (sqlite-wal) in initialisation of your persistent store coordinator (typically in appdelegate) (Check stack overflow or google). This will mean that any changes made to the SQL db are reflected on disk on your device immediately as you appear to be expecting.
It might look something like this:
 if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                               configuration:nil
                                                         URL:storeURL
                                                     options:@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES, NSSQLitePragmasOption : @{@"journal_mode" : @"DELETE"}}
                                                       error:&error])


text:
Q: A basic question about the big bracket and Lie algebra Definition: The big bracket is the graded Lie algebra structure on algebraic functions on $V\oplus V^*$ defined as follows:
$\bullet$ For $u,v\in B^{-1}\oplus B^{-1}=k\oplus V\oplus V^*$:
$$[u,v]=\begin{cases}
      \langle u,v\rangle & \text{if}\ u\in V\oplus V^*\ \text{and}\ v\in V\oplus V^*;\\
      0 & \text{if}\ u\in k\ \text{or}\ v\in k .
     \end{cases}$$
$\bullet$ The bracket on other terms is defined by linearity and the graded Leibniz rule: for $u\in B^k$, $v\in B^l$, $w\in B^m$,
$$[u,v\wedge w]=[u,v]\wedge w+(-1)^{kl}v\wedge[u,w].$$
$$B=\bigoplus_{j\geq-2}B^j, \text{where}\ B^j=\bigoplus_{p+q=j}\left(\bigwedge^{p+1}V^*\otimes\bigwedge^{q+1}V\right), j\geq-1, \text{and}\ B^{-2}=\mathbb{K}.$$
The above definition is copied from https://arxiv.org/pdf/math/0601301.pdf page 4. And the Proposition 7 in the same paper states that for a vector space $V$ and an element $l\in V^*\wedge V^*\otimes V$, $[l,l]=0$ will give a Lie algebra structure on $V$ by defining the Lie bracket as $\{x,y\}=[[l,x],y]$. The proof is very simple, just say that $[l,l]=0$ is exactly the Jacobi identity. But when I write out as $l=f\wedge g\otimes v$ and try to compute directly, I still cannot figure out the equivalence of the condition $[l,l]=0$ and the Jacobi identity. This is how I compute:
$$\begin{aligned}
    &[l,l]\\
=&[f\wedge g\otimes v,f\wedge g\otimes v]\\
    =&[f\wedge g\otimes v,f]\wedge g\otimes v-f\wedge[f\wedge g\otimes v,g\otimes v]\\
    =&[f,f\wedge g\otimes v]\wedge g\otimes v+f\wedge[g\otimes v,f\wedge g\otimes v]\\
    =&([f,f]\wedge g\otimes v-f\wedge[f,g\otimes v])\wedge g\otimes v+f\wedge([g\otimes v,f]\wedge g\otimes v+f\wedge[g\otimes v,g\otimes v])\\
    =&2f\wedge[g\otimes v,f]\wedge g\otimes v.
   \end{aligned}$$ I searched it on google, and find no proof to it. I guess it should be very simple. Maybe there is a stupid mistake in my computation. Or maybe I totally misunderstood the whole concept. Can anyone help me with it? Thanks a lot in advance.


text:
Q: Syncrhonize timescale db to work with custom intervals I am willing to collect candle price  stock data on specific time intervals using timescaledb continous aggregations, such as 37 minutes and my intervals will start every day at 00:00.
So for example, I am willing to have an interval starts each day at 00:00, 00:37, 01:14... until 23:26, and then start all over from 00:00, 008:37... and so forth until 23:26 again.
So a data for example will be:
06/09 00:00 interval candle
06/09 00:37 interval candle
06/09 01:14 interval candle
...
06/09 23:26 interval candle
07/09 00:00 interval candle
07/09 00:37 interval candle
...
And so on
Of course that I would like to make them at the same view and not create every day a new hyper table for this.
How can i make this up using timescaledb?
I have looked it up at the docs and wasn't sure what should I use... Is it refresh policies? Origin?
Of course I can use bucket of 37 minutes, but my problem starts after the first day. The last candle of the day will be at 23:26 and the following candle afterwards will be at 00:03 instead of 00:00 and I will lose sync
Thank you very much, your help is super appreciated!

A: You can use time_bucket('37 min', time_column) in your SELECT statement. For example if you have minute-level data, and want to generate candlestick data in 37-min intervals, you'd do something like this:
SELECT
time_bucket('37 min', time) AS bucket
, FIRST(price_open, time) AS open_price
, LAST(price_close, time) AS close_price
, MIN(price_low) AS lowest
, MAX(price_high) AS highest
, SUM(trading_volume) AS volume
, symbol
FROM stocks_intraday
WHERE symbol = 'TSLA'
GROUP BY bucket, symbol
ORDER BY bucket desc

Result:
2021-08-31 20:00:00|  733.8901|      734.0|733.8901|   734.0|   4816|TSLA  |
2021-08-31 19:23:00|    733.98|      734.0|  733.64|   734.0|   8950|TSLA  |
2021-08-31 18:46:00|     734.0|     733.55|  733.55|   734.2|   4737|TSLA  |
2021-08-31 18:09:00|     734.5|      733.8|   733.8|   734.7|   4231|TSLA  |
2021-08-31 17:32:00|  734.6899|     734.47|  733.86|734.6899|   7902|TSLA  |
2021-08-31 16:55:00|     736.2|      734.5|  734.05|   736.2| 294596|TSLA  |
etc...

Then use this to create the continuous aggregate. (without the ORDER BY)


text:
Q: How to copy from a list of items using multiple command buttons in Excel? I am looking to build an Excel worksheet that has a list of items in column A, each paired with a command button in column B. Ideally it would look like this:

When pressing a button, the value in the adjacent column A would be copied to a different worksheet. I understand this is possible to do with a CommandButton_Click() sub, but I will have around 200 buttons and from my understanding, I'd have to do a different sub for each one. Is there a way to avoid this? Is there some code that would apply to all buttons and if a button is pressed it would copy the adjacent column? An example of my current sub is:
Sub CommandButton_Click()
Dim rs As Integer
rs = ActiveSheet.Buttons(1).TopLeftCell.Row
Worksheets("Sheet1").Range("A" & rs).Copy _
Worksheets("Sheet2").Range("A" & rs)
End Sub

Hopefully you guys understand what I'm trying to do here. Any help is appreciated!

A: Your button-creating code:
Sub AddButtons()
On Error Resume Next
Dim c As Range, myRange As Range
Set myRange = Selection
For Each c In myRange.Cells
ActiveSheet.Buttons.Add(c.Left, c.Top, c.Width, c.Height).Select
With Selection
.Characters.Text = "ADD"
.Name = c.Address ' names with cell address
End With
Next
myRange.Select
End Sub

Handler:
Sub ButtonClicked()
   Dim c as Range
   Set c = Activesheet.Range(Application.Caller)
   c.entirerow.copy sheets("Sheet2").cells(c.row,1)
End Sub


text:
Q: FindWindow() doesn't find my window [C++] This is not a complex question. I'm having trouble finding the handle that belongs to iTunes. But although iTunes is running in the background, it keeps telling me it can't find the window. So I went on checking whether I miss typed the window name, but spy++ pointed out to me that I was using the correct window name and class name (see below). I'm sure it's a small mistake but I can't seem to find it. Does anyone have an insight? Thanks in advance.
        HWND hwnd;
        hwnd = FindWindow((LPCWSTR)"iTunes",(LPCWSTR)"iTunes");
    if (hwnd != 0){
        cout << "WINDOW FOUND" << endl;
    } else {
        cout << "WINDOW NOT FOUND" << endl;
        cout << hwnd << endl;
    }

A: You are using ANSI strings with what appears to be the Unicode version of FindWindow.
Many Win32 functions are actually a pair of function and a macro. For example, FindWindow is defined approximately like this:
HWND WINAPI FindWindowA(LPCSTR lpClassName, LPCSTR lpWindowName);
HWND WINAPI FindWindowW(LPCWSTR lpClassName, LPCWSTR lpWindowName);

#if (UNICODE)
#  define FindWindow FindWindowW
#else
#  define FindWindow FindWindowA
#endif

Try explicitely calling FindWindowA or using wide strings like this:
HWND hwnd = FindWindow(L"iTunes", L"iTunes");


text:
Q: Multiline js chart with support for irregular plot intervals Does anyone know of a js chart that can plot multiple lines that can have different plot intervals? I can only find HighCharts but need an Open Source one. A great example of what I'm looking for is available on highcharts demo page:
http://www.highcharts.com/demo/combo-timeline
Thanks

A: I have use Google charts in the past, they are pretty easy to inject in your code, and they support multiline. Check em out.
https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart


text:
Q: C# Thread Synchronization I have a problem with C# threads.

*

*I have eendless process "worker", which do some and after iteration sleep 3 seconds.

*I have a timer function that runs at a given time.
I need the "timer function" do something, then wait for the end "worker" iteration and then pause "worker" until "timer function" is done own task , after that timer function starts a "worker" again.
How can I do that?
Best regards Paul

A: You could use wait handles to control the methods - something like:
private AutoResetEvent mWorkerHandle = new AutoResetEvent(initialState: false);
private AutoResetEvent mTimerHandle = new AutoResetEvent(initialState: false);

// ... Inside method that initializes the threads
{
    Thread workerThread = new Thread(new ThreadStart(Worker_DoWork));
    Thread timerThread = new Thread(new ThreadStart(Timer_DoWork));

    workerThread.Start();
    timerThread.Start();

    // Signal the timer to execute
    mTimerHandle.Set();
}

// ... Example thread methods
private void Worker_DoWork()
{
    while (true)
    {
        // Wait until we are signalled
        mWorkerHandle.WaitOne();

        // ... Perform execution ...

        // Signal the timer
        mTimerHandle.Set();
    }
}

private void Timer_DoWork()
{
    // Signal the worker to do something
    mWorkerHandle.Set();

    // Wait until we get signalled
    mTimerHandle.WaitOne();

    // ... Work has finished, do something ...
}

This should give you an idea of how to control methods running on other threads by way of a WaitHandle (in this case, an AutoResetEvent).

A: You can use a lock to pause a thread while another is doing something:
readonly object gate = new object();

void Timer()
{
    // do something
    ...

    // wait for the end "worker" iteration and then
    // pause "worker" until "timer function" is done
    lock (gate)
    {
        // do something more
        ...
    }
    // start the "worker" again
}

void Worker()
{
    while (true)
    {
        lock (gate)
        {
            // do something
            ...
        }

        Thread.Sleep(3000);
    }
}

A: Do you need paralel work of Worker and another operation? If not, You can do somthing similar:
EventWaitHandle processAnotherOperationOnNextIteration = new EventWaitHandle(false, EventResetMode.ManualReset);

Worker()
{
   while(true)
   {
       doLongOperation();
       if (processAnotherOperationOnNextIteration.WaitOne(0))
       {
           processAnotherOperationOnNextIteration.Reset();
           doAnotherOperation();
       }
       Thread.Sleep(3000);
   }
}

in timer
 void Timer()
 {
    processAnotherOperationOnNextIteration.Set();
 }


text:
Q: Laravel 4 [API] how do i check if i already logged in from the consumer? I've been creating API and consumer by following Simple API Development with Laravel from Aaron Kuzemchak. I got the problem after I success to auth via API from my consumer; I do not know how to check it, if the consummer already success logged in or not at the other pages...
For example, at the first; I show the login page, click the submit button to check the credentials via API. The login attempt is working, success to logged in and redirect to dashboard. But, if I haven't logged in and accessed the dashboard from URL, i got the dashboard :O
The API server and the consumer have separated machine and the database only exists at the API server.

*

*Am I doing this right (with the flow for the API and Consumer) ?

*At the consumer, how can I get to know if the user already logged in or not (after success attempt the credential)? (somehow? someidea?)

Thank you before... :)

A: This question is very confusing, probably because I haven't watched that screencast yet, but shouldn't Auth::check() be what you are looking for?  It will return true or false depending on if the user is logged in.

A: Just to make sure:

*

*You have a back end API built from the tutorial posted here: http://kuzemchak.net/blog/entry/laracon-slides-and-video

*You're using HTTP Basic authentication as described in the above tutorial

*You're building a (consumer) front end web interface for users on a separate server

*Your consumer interface uses forms based authentication (a login form)

The backend API uses HTTP basic authentication (and the consumer sends an API key for the user with each request). As such, the backend won't keep track of a user being logged in. That means your consumer interface will need to do this.
You could use the Laravel Auth class for this normally, but your front end would normally have access to the database and the bundled authentication drivers could just check a username/password.
I'd say your options are:

*

*Store details of the user in a session using the Session class (feels a bit nasty but simple)

*Write an authentication driver and then use the Auth class (advanced but cleaner: http://www.karlvalentin.de/1903/write-your-own-auth-driver-for-laravel-4.html)

*Just talk straight to the database using the existing Auth class and Eloquent


text:
Q: After combining my reducer using combineReducer, action is not dispatching This was my reducer file. everything works fine If I use this.
https://gist.github.com/ashiqdev/9129d43c4397ff752f88739cc1f4309f
I want to split it into multiple file using combineReducer. but after splitting it, redux action is not dispatching.
This is my product reducer:
import { SET_PRODUCTS } from '../actionTypes';

const init = {
  products: [],
  keyword: '',
  cartItems: {},
};

const productReducer = (state = init, action) => {
  if (action.type === SET_PRODUCTS) {
    return {
      ...state,
      products: action.payload,
    };
  }
  return state;
};

export default productReducer;

and here I am combining it:
import { combineReducers } from 'redux';

import productReducer from './productReducer';
import cartItemReducer from './cartItemReducer';
import keywordReducer from './keyWordReducer';

const reducers = combineReducers({
  products: productReducer,
  keyword: keywordReducer,
  cartItems: cartItemReducer,
});

export default reducers;

what I am missing here?

A: You have given wrong initial state on productReducer.
It should be a plain empty array. and you should return only the products array.. not the whole state.
const productReducer = (state = [], { type, payload }) => {
  if (type === SET_PRODUCTS) {
    return [...payload]
  }
  return state;
};

or if you dont want to change the productReducer, you have to consume the store variable using store.products.products.
const products = useSelector((state) => state.products.products)

A: It seems that there is a mistake in the reducer function
const productReducer = (state = init, action) => {
  if (action.type === SET_PRODUCTS) {
    // here you have to return the new state for `state.products` and not for `state`
    return {
      ...state,
      products: action.payload,
    };
  }
  return state;
};

Try this reducer instead
const productReducer = (state = [], action) => {
  if (action.type === SET_PRODUCTS) {
    return [...action.payload];
  }
  return state;
};


text:
Q: Remote debugging Java applets in Safari on OS X? I have an applet that is problematic under Safari only (works everywhere else) and I need to debug it running in Safari.
The args to enable remote Java debugging are
-Djava.compiler=NONE -Xnoagent -Xdebug -Xrunjdwp:transport=dt_socket,address=2502,server=y,suspend=n

However, Java Preferences on OS X doesn't allow you to set any args for the VM and I can't find anywhere else that might allow it.
Anyone know where JVM flags can be set for Safari?

A: It may depend on which version of OSX you're using.
In some versions, you should be able to do this using Java Preferences (in /Applications/Utilities). Either there's a Java Applet Runtime Preferences box directly visible in the General tab, or (depending on the version), after selecting a VM in the list (still in the General tab), clicking on Options... opens a dialog box for setting these parameters in Applet Runtime Parameters.
Alternatively, there is some documentation here: http://support.apple.com/kb/HT3210


text:
Q: stacked bar charts using html 5 by reading values from an array Want to plot a stacked bar chart in Rgraph .I want to show the graph based on the values from an array.Any solution?

A: There's really a bunch of APIs out there. For instance the google chart tools. Or google for some jquery plugins.


text:
Q: How to find out what filters were selected when inputting data I am working on a database and I am inputting data in new columns based on other data within the spreadsheet.
When inputting data into one of my columns I believe I accidentally had a filter (or combination of filters) selected meaning that a significant sample of qualifying data for input has been missed. However on rectifying this, the unknown filter actually produced significantly better results so I wondered if it was possible to work out what filters were enabled when I initially input my data?
I have a version of the spreadsheet with the initial entry (but all filters cleared) and a version of the spreadsheet which has been completed correctly.

A: This will create an array named currentFilterSettings where each element in the first dimension represents a column and the filter settings are saved in the second dimension.
You might want to run it with a break on the last available line and use the locals window to review the structure.
Sub GetCurrentFilterSettings()
    Dim ws As Worksheet
    Dim currentFilterSettings()
    Dim i As Long
    Set ws = ActiveSheet
    With ws.AutoFilter.Filters
    ReDim currentFilterSettings(1 To .Count, 1 To 3)
        For i = 1 To .Count
            With .Item(i)
                If .On Then
                    currentFilterSettings(i, 1) = .Criteria1
                    If .Operator Then
                    currentFilterSettings(i, 2) = .Operator
                        If .Operator = xlAnd Or .Operator = xlOr Then
                            currentFilterSettings(i, 3) = .Criteria2
                        End If
                    End If
                End If
            End With
        Next i
    End With
End Sub


text:
Q: ghc - square brackets on command line? On this page:
http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Parsing
it shows ghc being called thusly:
ghc -package parsec -o simple_parser [../code/listing3.4.hs listing3.4.hs]

What are the square brackets for? I get an error with I use it with ghc 7.0.4. Is this some sort of way to specify a search path for input files?

A: GHC doesn't accept any such command-line syntax; to compile listing3.4.hs, you should use:
ghc -o simple_parser listing3.4.hs

(You don't have to specify packages these days; GHC will automatically link them in as required.)
This is a wiki markup mistake, caused by an automatic conversion of the original Write Yourself a Scheme in 48 Hours to wiki format. On this page, you can see that in the corresponding code block, listing3.1.hs is linked to a copy of the file. This relative link was converted to the MediaWiki external link syntax, which, of course, does not work inside code blocks. (Even if it did, a relative path is used, so it wouldn't link anywhere useful.)


text:
Q: I cannot input a character. My program terminates Here is my code for my project. It's not yet done because I'm stuck with the last scanf (after printf("Enter option:")). My program terminates after pressing two keys. I also tried char and %c but it didn't work. Hope you can help me.
void main()
{

    char user[20], pass[500];
    int i, a;
    clrscr();
    gotoxy(30,7); printf("ACCESS THE SYSTEM");
    gotoxy(28,9); printf("Username: ");
    gets(user);
    gotoxy(28,11); printf("Password: ");
    for(i = 0; i< 500; i++)
    {
        pass[i] = getch();
        if(pass[i] == 13)
        {
            pass[i] = 0;
            break;
        }
        printf("*");
    }
    gotoxy(30,15);printf("ACCESS GRANTED!");
    gotoxy(24,20);printf("Please press any key to proceed: ");
    scanf("%d", &a);
    topics();
    getch();
}

int topics(){

    int opt;
    clrscr();
    gotoxy(25,5);printf("ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»");
    gotoxy(25,6);printf("º Computer Programming Topics: º");
    gotoxy(25,7);printf("ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ\n");
    gotoxy(13,9);printf("Choose one:");
    gotoxy(13,11);printf("[A] Conditional Statements");
    gotoxy(13,13);printf("[B] Looping Statements");
    gotoxy(13,15);printf("[C] Functions");
    gotoxy(13,17);printf("[D] Arrays");
    gotoxy(13,19);printf("[E] Strings");
    gotoxy(13,22);printf("Enter option:");
    gotoxy(13,23);scanf("%d", &opt);
    getch();
}

A: given this code, in main()
    gotoxy(24,20);printf("Please press any key to proceed: ");
    scanf("%d", &a);
    topics();
    getch();

the line: `scanf("%d", &a); required the input to end with a 'return' key which puts a newline in the input stream, that is not consumed here.
the topics() function contains a getch() which does get the 'return' key from the input stream.
Note: a 'return' key is not a valid input for the topics() function.
then the user has to input another keystroke for the final getch() in main().  Then the execution runs off the end of main() which results in the program exiting.
Suggest:  in main() the line: scanf("%d", &a); be replaced with getch()
The posted code, after calling topics() (which gets a keystroke) then, one more keystroke and the program exits.
If you want the program to continue executing,  then the call to topics() needs to be followed by some other code to execute.


text:
Q: JFFs Partition for DD-WRT yes or no? I have a Asus RT-N16 Router with Kongmod Build of DD-WRT.
On the USB port i have a 1TB HDD and have 3 Partitions on this drive.
/opt
/swap
/data
The DD-WRT guide clearly states multiple times not to use the JFFs partition on ANY USB drive. It is only needed for SD cards, and using it on USB drives may cause problems. They repeat it multiple times, so I guess it is important.
On another officcial DD-WRT guide (optware the right way) they state that you must have JFFs enabled, or IPKG wont work.
If both statements are true, you couldnt use IPKG unless you use a SD card. What is actually true? Should i have a JFFs partition on a 1 TB HDD?
Thanks

A: Not a proper answer, but to long for just comments:
Spinning rust (aka classical HDD)s can be written many times. Flash cells are more fragile and will fails with far fewer writes.
If you combine a filesystem which is not aware of that (e.g. FAT which keeps its directory listing in one place and updates that quite often) with raw access to flash based storage then one part of your flash is likely to die before the device is obsolete.  Obviously, we want to avoid this.
Note that his is true for internal flash, as well as flash on USB pen drives, SSDs, SD card etc etc.
There are two ways to work around this:

*

*Make sure that the device is aware of its strage method and have the device work around this. (The controllers on an SSD are an extreme example of this).

*Or create a filesystem which is aware of this and which tries to avoid this particlular weakness of flash cells.

JFFS is such a filesystem. One of the things it does is spread out writes over the flash cells (wear leveling). If you arase a file and recreate that file then it is very likely recreated on different flash cells. fort flash, this is a good thing.
For routers whose internal storage is flash you do want to use JFFS or a similar aware filesystem for their internal storage.
You do not want to use it on other devices, such as a classical HDD.
If you have an old dumb USB pendrive, then you do want to use it (read: I disagree with the 'do not use it on ANY USB device). If you have a modern USB pen drive then might already have an internal solution to mitigate wear leveling and a using JFFS is likely to conflict with that.

A: Enabling Optware is not the same as enabling JFFS. JFFS is used as an alias for the partition at /jffs. It's usually hosted on the router's flash memory. However, you can use mount --bind to place it on virtually any partition. (Enabling it on internal flash may be required anyway.)
To enable JFFS on internal flash, follow these instructions:

The steps to enable JFFS through the router web page are very specific. To avoid having to reset and reprogram your router, it's smart to make a backup here of your settings. If you follow these steps exactly, it should not lock up.

*

*On the router web page click on Administration.

*Scroll down until you see JFFS2 Support section.

*Click Enable JFFS.

*Click Save.

*Wait couple seconds, then click Apply.

*Wait again. Go back to the Enable JFFS section, and enable Clean JFFS.

*Do not click "Save". Click Apply instead.
The router formats the available space.

*Wait till you get the web-GUI back, then disable "Clean JFFS" again.

*Click "Save".

*It may be wise to Reboot the router, just to make sure

If you don't see the Enable JFFS option on your Administration page, it is likely because your router has insufficient flash memory to hold both DD-WRT and a JFFS partition. If you have a 4MB router, you may be able to work around this by using the mini version of DD-WRT