text:
Q: how can i get useState value inside useCallback (react hook) i can't get the useState value that inside of useCallback. when i run the code below,
import React, { useCallback, useEffect, useRef, useState } from 'react';

const DBLab = () => {
    const [hashHistory, setHashHistory] = useState("initial_value");
    const [inputValue, setInputValue] = useState("");
    const didAuthMountRef = useRef(false);

    const set = useCallback(() => {
        const decodeHash = decodeURI(window.location.hash);
        console.log();
        console.log("decodeHash: " + decodeHash);
        console.log("hashHistory: "+ hashHistory);
        setHashHistory(decodeHash);
    },[hashHistory]);

    useEffect(() => {
        const startFunc = async() => {
            set();
            window.addEventListener('hashchange', set);
            didAuthMountRef.current = true;
        }
        if(!didAuthMountRef.current) {
            startFunc();
        }
    }, [set]);
    return (

dblab

{hashHistory}

            <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)}/>

    )
}

export default DBLab;

in web console, i get
decodeHash: #/dblab#first

hashHistory: initial_value

which is right. but when i change url to http://localhost:3000/#/dblab#next, i get

decodeHash: #/dblab#next

hashHistory: initial_value

this is wrong. because hashHistory has not changed. but it is not useState problem. because hashHistory that i see with
{hashHistory}
 in screen is #/dblab#next which is the right hash.
how can i get the right hashHistory inside of useCallback?.
ps. i must have to use useCallback.

A: useEffect(() => {
    const startFunc = () => {
        if(!didAuthMountRef.current) {
            set();
            didAuthMountRef.current = true;
        }
        window.addEventListener('hashchange', set);
    }
    startFunc();
    return ()=> {
        window.removeEventListener('hashchange', set);
    }
}, [set]);

Logic problem


text:
Q: PyMongo: how to get all objects that match any of possible filters? I have a list of "usernames" as an array, and a list of posts in a mongodb collection with an "author" variable. I want to get all objects from the collection whose author is one of the usernames in the array.
so if:
Collection:
{
"author": "tim"
},
{
"author": "bob"
},
{
"author": "jon"
}
following = ["tim", "jon"]
then i only want to get the posts by tim and jon

A: I got the answer; it should be:
following = ["tim", "jon"]
mongo.db.posts.find({"author": {"$in": following}})

This will only get posts where the author is tim or jon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to lookup multiple cells based on multiple criteria in VBA I'm extremely new to VBA and have tried Googling to find what I need, but have fallen short.
I have a sheet (Sheet1) containing a list of companies that currently have, or at some point have had, a subscription. The list contains the City (Col A), the Company (Col B), the Category (Col C) and a Cancellation Date (Col D) (if applicable). What I want to do is fill in the current company for that city/category on a different sheet. I want those headers to be City (Col D), Category 1 (Col E), Category 2 (Col F), and Category 3 (Col G).
Here are images of the two sheets of test data:
Sheet 1

Sheet 2

There can only be one company per category per city. For example: in my test data, company D was under Category 1 in San Antonio, but cancelled on 11/12/2021. Then, company N took that spot in San Antonio. So, in my table on Sheet 2, I want company N to be populated. The data set I'm using this for is very large and constantly changing, so I would like an automated way to do this.
Here is a copy of the code I pieced together:
Sub CompanyLookup()

    With Application
        .Calculation = xlCalculationManual
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Dim lastRowInCity, lastRowOutCity, i, k, m As Long
    Dim lookFor, j, inArray, outArray, findArray As Variant
    Dim inWks, outWks As Worksheet

    Set inWks = ThisWorkbook.Sheets(1)
    Set outWks = ThisWorkbook.Sheets(2)

    lastRowInCity = inWks.Cells(Rows.Count, "A").End(xlUp).Row
    lastRowOutCity = outWks.Cells(Rows.Count, "D").End(xlUp).Row
    lastRowCategory = inWks.Cells(Rows.Count, "C").End(xlUp).Row
    lastRowDate = inWks.Cells(Rows.Count, "D").End(xlUp).Row
    lastColCategory = outWks.Cells(Columns.Count, "D").End(xlToLeft).Column

    inArray = Range(inWks.Cells(1, 1), inWks.Cells(lastRowInCity, 3))

    findArray = Range(outWks.Cells(1, 4), outWks.Cells(lastRowOutCity, 4))

    outArray = Range(outWks.Cells(1, 5), outWks.Cells(lastRowOutCity, 5))

    On Error Resume Next

    For i = 2 To lastRowOutCity

        For j = 2 To lastRowInCity

            For k = 2 To lastRowCategory

                For m = 2 To lastRowDate

                     lookFor = findArray(i, 1)

                     If inArray(j, 1) = lookFor And inArray(m, 4) < 1 And inArray(k, 3) = outArray(lastColCategory, 1) Then
                                    outArray(i, 1) = inArray(j, 2)
                                    Exit For
                     End If

                Next j

            Next m

        Next k

    Next i

    Range(outWks.Cells(1, 5), outWks.Cells(lastRowOutCity, 5)) = outArray

    With Application
        .Calculation = xlCalculationAutomatic
        .EnableEvents = True
        .ScreenUpdating = True
    End With

End Sub

A: I had exact same issue this week, and from what i read online, the fact that you cannot use vlookup or find function for multiple criteria. Mostly people prefer using .find fuction and when you find it, you can use loop to find second criteria. It was what i used.

A: Assuming your data looks exactly as your screenshots:
Sub CompanyLookup()

    Dim sourceData, resultData, rngSource As Range, rngResult As Range
    Dim r As Long, c As Long, city As String, cat As String, rSrc As Long

    Set rngSource = ThisWorkbook.Sheets(1).Range("A1").CurrentRegion
    Set rngResult = ThisWorkbook.Sheets(2).Range("D1").CurrentRegion

    sourceData = rngSource.Value
    resultData = rngResult.Value

    'scan through the results array
    For r = 2 To UBound(resultData, 1)
        city = resultData(r, 1)             'city
        For c = 2 To UBound(resultData, 2)
            cat = resultData(1, c)          'category

            'Scan the source data for a city+category match,
            '  ignoring lines with a cancellation date
            For rSrc = 2 To UBound(sourceData, 1)
                If Len(sourceData(rSrc, 4)) = 0 Then           'no cancellation date
                    If sourceData(rSrc, 1) = city And sourceData(rSrc, 3) = cat Then
                        resultData(r, c) = sourceData(rSrc, 2) 'populate the company
                        Exit For                               'done searching
                    End If
                End If
            Next rSrc
        Next c
    Next r

    rngResult.Value = resultData   'populate the results

End Sub


text:
Q: Re-Symbolizing Proportional Symbols by calling a function in leaflet I'm trying to re-symbolize normalized proportional symbols to raw proportional symbols on an interactive map (Leaflet)
//Step 2: Import GeoJSON data
function getData(map){
    //load the data
    $.ajax("data/PropRaw2001_2013.geojson", {
        dataType: "json",
        success: function(response){

             //create an attributes array
            var attributes = processData(response);
            var rawAttributes = processRawData(response);

function processData(data){
    //empty array to hold attributes
    var attributes = [];

    //properties of the first feature in the dataset
    var properties = data.features[0].properties;

    //push each attribute name into attributes array
    for (var attribute in properties){
        //only take attributes with population values
        if (attribute.indexOf("Prop") > -1){
            attributes.push(attribute);
        };
    };

    //check result
    console.log("these are the attributes")
    console.log(attributes);

    return attributes;
};

function processRawData(data){
    console.log("Raw data")
    //empty array to hold attributes
    var rawAttributes = [];
    console.log(rawAttributes)
    //properties of the first feature in the dataset
    var properties = data.features[0].properties;

    //push each attribute name into attributes array
    for (var rawAttribute in properties){
        //only take attributes with population values
        if (rawAttribute.indexOf("Raw") > -1){
            rawAttributes.push(rawAttribute);
            console.log(rawAttributes)
        };
    };

Here, is the function that will update my proportional symbol size:
function updatePropSymbols(map, attribute){
    map.eachLayer(function(layer){
      //Example 3.16 line 4
        if (layer.feature && layer.feature.properties[attribute]){
            //access feature properties
            var props = layer.feature.properties;

            //update each feature's radius based on new attribute values
            var radius = calcPropRadius(props[attribute]);
            layer.setRadius(radius);

            //add city to popup content string
            var popupContent = "
City: " + props.City + "
";

            //add formatted attribute to panel content string
            var year = attribute.split("_")[1];
            popupContent += "
Population in " + year + ": " + props[attribute] + " million
";

            //replace the layer popup
            layer.bindPopup(popupContent, {
                offset: new L.Point(0,-radius)
            });
        };
    });
};

I added two buttons as divs, "normalized" and "raw" which I want the user to be able to use to toggle between normalized raw, using the following function:
$("#Normalized").click(function(attribute){
            console.log("normalize function")
            //normalize = true
            //if (normalize = true) {

                updatePropSymbols(map, attribute);
            //}
         });
//
 $("#Raw").click(function(rawAttribute){
            //normalize = false
            //if (normalize = false){
                updatePropSymbols(map, rawAttribute);
            //}
     });

However- it's not passing the attribute data through.  It seems like I'm not able to call updatePropSymbols with rawAttribute or attribute (this is normalized).

A: By using attribute and rawAttribute as arguments for your click handler functions, you are actually creating new local variables (in this case, they are jQuery eventObjects describing the click event) that will be used instead of the original attribute and rawAttribute variables. Assuming that you have defined these variables elsewhere, what you want is this:
$("#Normalized").click(function(){
  updatePropSymbols(map, attribute);
});

$("#Raw").click(function(){
  updatePropSymbols(map, rawAttribute);
});

Here is a simple example illustrating this: http://jsfiddle.net/nathansnider/zhLLydcr/


text:
Q: Can an Entity Framework Context return a class that inherits a Entity I have an Entity Framework 5 Code First DbContext
public class ProductContext : DbContext
{
    public DbSet<Product> Products {get;set;}
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
}

Now I have to implement an interface but don't want to pollute my model so I create a
public class ProductEx : Product, ISomeInterface
{
    public bool ISomeInterface.SomeMethod() { return false; }
}

I know I could do:
var query = from p in context.Products
            select new ProductEx { p.ProductId, p.Name };

But since the DbContext already returns a dynamic proxy (because of change tracking / lazy loading) maybe there is a better approach. I am thinking about something like this:
var query = from p in context.Products.As<ProductEx>()
            select p;

the entities should be a dynamic proxy inherited from ProductEx.
Is there a way to achive this?

A: One way is to You can create a wrapper for product:
public class Product
{
    public virtual int ProductId { get; set; }
    public virtual string Name { get; set; }
}

public class ProductEx : Product, ISomeInterface
{
    private readonly Product _product;

    public ProductEx(Product product) {
        this._product = product;
    }

    public bool ISomeInterface.SomeMethod() { return false; }

    public override int ProductId
    {
        get { return this._product.ProductId; }
        set { this._product.ProductId = value; }
    }

    public override string Name
    {
        get { return this._product.Name; }
        set { this._product.Name = value; }
    }
}

Then you can query liko so:
var query = from p in context.Products
        select new ProductEx(p);


text:
Q: To show Ajax call value on same controller while using front controller I wanted to send ajax data to controller page and display ajax data on template file in prestashop 1.6 .
I am using this method but not able to get any results -
tpl file :
<input type="button" class="btn btn-primary" id="test" onclick = "testing()" value="test" />
function testing() {
        url = '{$link->getModuleLink("hotelapi", "filter")|escape:"html"}';
        $.ajax({
            url: url,
            type : 'GET',
            cache : false,
            data : {
                ajax: 1,
                action: 'fetchTPL',
            },
            success: function(html){
                alert("SUCCESS:");
            },
            error: function() {
                alert("ERROR:");
            }
        });

    }

Front Controller file - File name is - filter.php
<?php
/*require (dirname(__FILE__) . '/../../../../config/config.inc.php');
require (dirname(__FILE__) . '/../../../../init.php');*/

class hotelapiFilterModuleFrontController extends ModuleFrontController
{
    public function displayAjaxFetchTPL()
    {
        echo 'hello';
        //after processing all data just assign it to smarty of content
        /*$this->context->smarty->assign(array(
            'youContentData' => $_POST['room'])
        );

        // to fetch a tpl file use fetch method and use die function to return the response to ajax
        die($this->context->smarty->fetch('a1.tpl'));*/

    }

}

My ajax url is executing successfully but I am not able to print anything written inside displayAjaxFetchTPL action.
Please anyone help me with this problem.
Thanks and regards,
Ridhi Bhutani

A: Instead of using the "onclick" event on your button, why not use a JQuery event lsitener?
Your HTML would be something like this:
<input type="button" class="btn btn-primary" id="test" value="test" />
And your JS like this:
$("#test").on("click", function () {
    url = '{$link->getModuleLink("hotelapi", "filter")|escape:"html"}';
    $.ajax({
        url: url,
        type: 'GET',
        cache: false,
        data: {
            ajax: 1,
            action: 'fetchTPL',
        },
        success: function (html) {
            alert("SUCCESS:"+html);
        },
        error: function () {
            alert("ERROR:");
        }
    });
});

A: php:
public function displayAjaxFetchTPL()
{
    $data = ['mYtxt' => 'hello'];
    die(Tools::jsonEncode($data));
}

jquery:
success: function (html) {
        alert(html.mYtxt);
    },


text:
Q: Docker buildx is not using cache when building image from arm platform I am building arm64 image on my x86_64 amd machine using docker buildx everything is working fine except whenever I try to build arm image it start building it from scratch.
Steps to reproduce

*

*Create a docker builder
export DOCKER_CLI_EXPERIMENTAL=enabled
docker buildx create --name buildkit
docker buildx use buildkit
docker buildx inspect --bootstrap

*Build docker image using command
docker buildx build . --platform linux/arm64 -t test-image:p-arm64 -f ./arm64.Dockerfile

When I build it multiple time all the steps are executing which takes around 20-30 min for every build. I want to minimize this time by caching.
This is what my dockerfile looks like
FROM python:3.7-slim

USER root

RUN apt-get update && \
    apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common \
    gnupg \
    g++ \
    && rm -rf /var/lib/apt/lists/*

RUN curl -fsSL https://download.docker.com/linux/debian/gpg |  gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg && \
    echo "deb [arch=arm64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian \
    $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

RUN apt-get update && \
    apt-get install -y docker-ce-cli \
    && rm -rf /var/lib/apt/lists/*

RUN python3 -m pip install --no-cache-dir \
    ruamel.yaml==0.16.12 \
    pyyaml==5.4.1 \
    requests==2.27.1

RUN apt-get remove -y g++ && apt-get purge g++

ENTRYPOINT ["/bin/bash"]

Any suggestion is appretiated.


text:
Q: download a file periodically from FTP in linux I wish to write a cron or setup a software to periodically download a file every specific day of a week from a FTP server.
I need a software like IDM which opens multi thread connections and increase the download speed significantly.
Because of that I prefer to use an application.
I already tried uGet and flareget on Ubuntu but they don't contain any feature to run the same download every day of a week.

A: You should use a console application like axel to get this work.
If you have to rename the download you should write a little bash script to complete the task.
Finally call the script every ... by cron.
Hennes

A: Actually you can do that in Flareget. In scheduler you have two options one time and periodic. In periodic you can set week day and time. But file needs to be added to custom queue again after each download.


text:
Q: ng-token-auth ui-router resolver causes blank screen I am following the docs for ng-token-auth here trying to add a resolver for auth, which calls validateUser.  When I add this block of code from the documentation I render a blank screen.  I get no errors on my rails server console and none in the javascript console in Chrome.  Any idea why this would be happening?
Here's my app.js file where the code in question is the resolve block for the "home" state.
sparkleApp = angular.module("sparkleApp",
            ['templates',
                         'validation.match',
                         'ui.bootstrap',
                         'ngSanitize',
                         'ui.router',
                         'LocalStorageModule',
                         'pippTimelineDirectives',
             'ng-token-auth',
                         'sparkleControllers',
             'sparkleServices']);

/* Controllers */
var sparkleControllers = angular.module('sparkleControllers', []);

/* Services */
var sparkleServices = angular.module('sparkleServices', []);

sparkleApp.config(['$stateProvider', '$urlRouterProvider',
                   function($stateProvider, $urlRouterProvider) {
                       $urlRouterProvider.otherwise('/');

                       // HOME STATES AND NESTED VIEWS ========================================
                       $stateProvider.state('home', {
                         url: '/',
                         views: {
                           // the main template will be placed here (relatively named)
                           '': {
                             templateUrl: 'tplHomeView.html',
                             controller: 'HomeCtrl'
                           },

                           'homeJumbotron@home': {
                             templateUrl: '_tplJumbotron.html'
                           },
                           'sparkleForm@home': {
                             templateUrl: '_tplMessageForm.html'
                           },
                           'sparkleFeatured@home': {
                             templateUrl: '_tplSparkleQuotes.html'
                           }
                         },
             resolve: {
               auth: function($auth) {
                 return $auth.validateUser();
               }
             }
                       })
                   }])
  .config(function($authProvider) {
    $authProvider.configure({
      apiUrl: '/api/v1'
    });
  });

A: I wasn't catching the $stateChangeError code and handling that correctly.  It was throwing an unauthorized and I redirected to the login page.
The docs helped and another stack overflow question did too.
https://github.com/angular-ui/ui-router/wiki#state-change-events
$state transition after rejected promise Angular ui-router


text:
Q: When is initialize invoked in smalltalk? I have a class with instance variable 'a'.
When i create a new instance of the class using new, what is the order of the methods that are called?
How will the object know that it should call the initialize method?
If I create a class method to assign values to my instance variables, will the initialize still be called for other instance variables that are not invoked by my class method?

A: initialize is usually called by the new method itself.
I believe the standard implementation is:
new
    ^self basicNew initialize

#basicNew is a primitive that just creates the object, but does no initialization.  All instance variables will be nil after basicNew.
Note that the initialize method isn't called automatically in all implementations of Smalltalk (but I don't know which ones don't do it) so if you want to be properly portable, you should override #new in your classes to explicitly call it.

A: Stuart answered it perfectly. But if you have still doubt about your second question:

If I create a class method to assign values to my instance variables, will the initialize still be called for other instance variables that are not invoked by my class method?

If you use something like Kent Beck's Constructor Parameter Method idiom for example in Pharo, where #initialize is sent from #new (as described by Stuart's answer):
Point class>>x: xNumber y: yNumber
    ^self new
        setX: xNumber
        y: yNumber

Point>>setX: xNumber y: yNumber
    x := xNumber.
    y := yNumber.
    ^self

Then first your initialize method will be called and only afterwards your Constructor Parameter Method will be called.


text:
Q: Understanding ground when using a USB vs a benchtop oscilloscope I am trying to understand how a USB oscilloscope can furnish a proper ground from which to take measurements.
If I'm not mistaken, my benchtop scope which is powered by my wall outlet at AC 120V, has access to actual earth ground through its power supply.
If so, how can a USB scope connected to a battery-powered laptop furnish a ground to the probes? I have a limited understanding of 'virtual-ground' in an electronic device as opposed to actual earth-ground - maybe that applies here.

A: The ground wire of the probe on a regular oscilloscope is connected to the outlet ground.
Connecting the two grounds together is not about the signal, though.
The oscilloscope ground is connected to the outlet ground as a safety feature.  The point of it is to keep any uninsulated parts of the scope from killing you.
You can (but should not) disconnect the ground pin of the oscilloscope power lead, and the scope will work properly.  The metal housing and any exposed metal parts will be at the same potential as your circuit though.  If you connect the probe ground clip from the scope to a high voltage source in your circuit, then the high voltage will be on the housing or other metal parts - just waiting for you to touch them so they can kill you.
A scope without a grounded power lead (USB or battery poweted) must be double insulated so that you cannot possibly touch anything that may have high voltage on it.
When you connect the ground clip from the scope to the device, you are providing all the ground that the signal requires.
All an oscilloscope does is to show you the voltage  difference between the probe tip and the probe clip.   An ungrounded scope can measure the voltage between any two points in a circuit.  A grounded scope can only measure voltage between the ground (connected to the power lead ground) and the signal.
All you need to measure a voltage is two points connected to the circuit.  To safely measure potentially high voltages, you need either a grounded scope or an insulated and isolated scope.


text:
Q: Split string of varying length using regex I don't know if this is possible using regex. I'm just asking in case someone knows the answer.
I have a string ="hellohowareyou??". I need to split it like this
[h, el, loh, owar, eyou?, ?].
The splitting is done such that the first string will have length 1, second length 2 and so on. The last string will have the remaining characters. I can do it easily without regex using a function like this.
public ArrayList<String> splitString(String s)
    {
        int cnt=0,i;
        ArrayList<String> sList=new ArrayList<String>();
        for(i=0;i+cnt<s.length();i=i+cnt)
        {
         cnt++;
         sList.add(s.substring(i,i+cnt));
        }
        sList.add(s.substring(i,s.length()));
        return sList;
    }

I was just curious whether such a thing can be done using regex.

A: Solution
The following snippet generates the pattern that does the job (see it run on ideone.com):
// splits at indices that are triangular numbers
class TriangularSplitter {

  // asserts that the prefix of the string matches pattern
  static String assertPrefix(String pattern) {
    return "(?<=(?=^pattern).*)".replace("pattern", pattern);
  }
  // asserts that the entirety of the string matches pattern
  static String assertEntirety(String pattern) {
    return "(?<=(?=^pattern$).*)".replace("pattern", pattern);
  }
  // repeats an assertion as many times as there are dots behind current position
  static String forEachDotBehind(String assertion) {
    return "(?<=^(?:.assertion)*?)".replace("assertion", assertion);
  }

  public static void main(String[] args) {
    final String TRIANGULAR_SPLITTER =
      "(?x) (?<=^.) | measure (?=(.*)) check"
        .replace("measure", assertPrefix("(?: notGyet . +NBefore +1After)*"))
        .replace("notGyet", assertPrefix("(?! \\1 \\G)"))
        .replace("+NBefore", forEachDotBehind(assertPrefix("(\\1? .)")))
        .replace("+1After", assertPrefix(".* \\G (\\2?+ .)"))
        .replace("check", assertEntirety("\\1 \\G \\2 . \\3"))
        ;
    String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    System.out.println(
        java.util.Arrays.toString(text.split(TRIANGULAR_SPLITTER))
    );
    // [a, bc, def, ghij, klmno, pqrstu, vwxyzAB, CDEFGHIJ, KLMNOPQRS, TUVWXYZ]
  }
}

Note that this solution uses techniques already covered in my regex article series. The only new thing here is \G and forward references.
References
This is a brief description of the basic regex constructs used:

*

*(?x) is the embedded flag modifier to enable the free-spacing mode, where unescaped whitespaces are ignored (and # can be used for comments).

*^ and $ are the beginning and end-of-the-line anchors. \G is the end-of-previous match anchor.

*| denotes alternation (i.e. "or").

*? as a repetition specifier denotes optional (i.e. zero-or-one of). As a repetition quantifier in e.g. .*? it denotes that the * (i.e. zero-or-more of) repetition is reluctant/non-greedy.

*(…) are used for grouping. (?:…) is a non-capturing group. A capturing group saves the string it matches; it allows, among other things, matching on back/forward/nested references (e.g. \1).

*(?=…) is a positive lookahead; it looks to the right to assert that there's a match of the given pattern.(?<=…) is a positive lookbehind; it looks to the left.

*(?!…) is a negative lookahead; it looks to the right to assert that there isn't a match of a pattern.

Related questions

*

*Articles in the [nested-reference] series:

*

*How does this regex find triangular numbers?

*How can we match a^n b^n with Java regex?

*How does this Java regex detect palindromes?

*How does the regular expression (?<=#)[^#]+(?=#) work?

Explanation
The pattern matches on zero-width assertions. A rather complex algorithm is used to assert that the current position is a triangular number. There are 2 main alternatives:

*

*(?<=^.), i.e. we can lookbehind and see the beginning of the string one dot away

*

*This matches at index 1, and is a crucial starting point to the rest of the process

*Otherwise, we measure to reconstruct how the last match was made (using \G as reference point), storing the result of the measurement in "before" \G and "after" \G capturing groups. We then check if the current position is the one prescribed by the measurement to find where the next match should be made.

Thus the first alternative is the trivial "base case", and the second alternative sets up how to make all subsequent matches after that. Java doesn't have custom-named groups, but here are the semantics for the 3 capturing groups:

*

*\1 captures the string "before" \G

*\2 captures some string "after" \G

*If the length of \1 is e.g. 1+2+3+...+k, then the length of \2 needs to be k.

*

*Hence \2 . has length k+1 and should be the next part in our split!

*\3 captures the string to the right of our current position

*

*Hence when we can assertEntirety on \1 \G \2 . \3, we match and set the new \G
You can use mathematical induction to rigorously prove the correctness of this algorithm.
To help illustrate how this works, let's work through an example. Let's take abcdefghijklm as input, and say that we've already partially splitted off [a, bc, def].
          \G     we now need to match here!
           ↓       ↓
a b c d e f g h i j k l m n
\____1____/ \_2_/ . \__3__/   <--- \1 G \2 . \3
  L=1+2+3    L=3

Remember that \G marks the end of the last match, and it occurs at triangular number indices. If \G occured at 1+2+3+...+k, then the next match needs to be k+1 positions after \G to be a triangular number index.
Thus in our example, given where \G is where we just splitted off def, we measured that k=3, and the next match will split off ghij as expected.
To have \1 and \2 be built according to the above specification, we basically do a while "loop": for as long as it's notGyet, we count up to k as follows:

*

*+NBefore, i.e. we extend \1 by one forEachDotBehind

*+1After, i.e. we extend \2 by just one

Note that notGyet contains a forward reference to group 1 which is defined later in the pattern. Essentially we do the loop until \1 "hits" \G.

Conclusion
Needless to say, this particular solution has a terrible performance. The regex engine only remembers WHERE the last match was made (with \G), and forgets HOW (i.e. all capturing groups are reset when the next attempt to match is made). Our pattern must then reconstruct the HOW (an unnecessary step in traditional solutions, where variables aren't so "forgetful"), by painstakingly building strings by appending one character at a time (which is O(N^2)). Each simple measurement is linear instead of constant time (since it's done as a string matching where length is a factor), and on top of that we make many measurements which are redundant (i.e. to extend by one, we need to first re-match what we already have).
There are probably many "better" regex solutions than this one. Nonetheless, the complexity and inefficiency of this particular solution should rightfully suggest that regex is not the designed for this kind of pattern matching.
That said, for learning purposes, this is an absolutely wonderful problem, for there is a wealth of knowledge in researching and formulating its solutions. Hopefully this particular solution and its explanation has been instructive.

A: Regex purpose is to recognize patterns. Here you doesn't search for patterns but for a length split. So regex are not appropriate.
It is propably possible, but not with a single regex : to find the first n characters using a regex, you use: "^(.{n}).*"
So, you can search with that regex for the 1st character.
Then, you make a substring, and you search for the 2 next characters.
Etc.
Like @splash said, it will make the code more complicated, and unefficient, since you use regex for something outside of their purpose.

A: String a = "hellohowareyou??";
int i = 1;

    while(true) {

        if(i >= a.length()) {
            System.out.println(a);
            break;
        }

        else {
            String b = a.substring(i++);
            String[] out = a.split(Pattern.quote(b) + "$");
            System.out.println(out[0]);
            a = b;
            if(b.isEmpty())
                break;
        }

    }


text:
Q: How wide-columns databases achieve dynamic columns on the storage layout? As known, in relational databases, when adding a new column, data must be reallocated (ALTER TABLE without locking the table?) to maintain a single row contiguous on disk.

I would like to understand how this is achieved on wide-columns storages such as Cassandra, which are sparses and can handle lots of dynamic columns insertions (http://www.datastax.com/dev/blog/thrift-to-cql3 (Dynamic Column family))
Thanks!

A: In Cassandra adding a Column is adding a bit like adding row in relational database. You can even delete a column for a specific row:
delete first_name from user where user_id='abcd';

In CQL, alter table doesn't modify all rows, in short it just modifies the schema dictionary which describe tables (look at tables prefixed schema_ in the system keyspace). This changes only CQL parsing (the new column is now recognized) and interpretation (select * from user meaning is changed).
When you drop a column, data doesn't appear anymore in query results yet it is still present in SSTables. The data will be removed (and space freed) during a future compaction (like tombstones).


text:
Q: probability going outside 1 (due to optimization violation of constraint) I am working on an optimization, which involves the following density:
K = 5
probs = Table[
  Binomial[K, j]*(w*p^j*(1 - p)^(K - j) + (1 - w)*
      Beta[alpha + j, K - j + beta]/Beta[alpha, beta]), {j, 0, K}]

With
(* alpha>0,beta>0,0<p<1,0<w<1 *)

as constraints for optimization.
The values in 'probs' should all be between 0 and 1, and most importantly they sum to 1!
test1 = {alpha -> 2.3, beta -> 3.2, p -> 0.9999, w -> 0.4};
test2 = {alpha -> 0.9, beta -> 0.1, p -> 0.8, w -> 0.4};
test3 = {alpha -> 120, beta -> 250, p -> 0.7, w -> 0.4};
test4 = {alpha -> 0.003, beta -> 0.0001, p -> 0.001, w -> 0.4};
test5 = {alpha -> 0.0001, beta -> 0.0001, p -> 0.1, w -> 0.4};
probs /. test1
Sum[%[[i]], {i, 1, 6}]
probs /. test2
Sum[%[[i]], {i, 1, 6}]
probs /. test3
Sum[%[[i]], {i, 1, 6}]
probs /. test4
Sum[%[[i]], {i, 1, 6}]
probs /. test5
Sum[%[[i]], {i, 1, 6}]

ALL GOOD!
Test for some extreme values near the boundary,
test6 = {alpha -> 10^(-10), beta -> 30, p -> 0.9999, w -> 0.0001};
test7 = {alpha -> 10^(-11), beta -> 300, p -> 0.8, w -> 0.0001};
test8 = {alpha -> 10^(-12), beta -> 3000, p -> 0.7, w -> 0.0001};
test9 = {alpha -> 10^(-13), beta -> 30000, p -> 0.001, w -> 0.0001};
test10 = {alpha -> 10^(-14), beta -> 300000, p -> 0.1, w -> 0.0001};

probs /. test6
Sum[%[[i]], {i, 1, 6}]
probs /. test7
Sum[%[[i]], {i, 1, 6}]
probs /. test8
Sum[%[[i]], {i, 1, 6}]
probs /. test9
Sum[%[[i]], {i, 1, 6}]
(* Take a lot of time to run!!! Dont know why *)
probs /. test10
Sum[%[[i]], {i, 1, 6}]

Apart from the last one, taking a long time to run, all summation return to 1.
Now, the problematic one!
badset = {alpha -> 10^(-14), beta -> 1.14*10^(26), p -> 0, w -> 0}
probs /. badset

The probabilities are MORE than 1.

These certainly sum to more than 1.
We know that the parameters are at the boundary, but I would expect something like Indeterminate, like this

This had cost me three days trying to locate the problem from a large piece of code, where the log-likelihood value is more than 0 (usually a negative number).
Is there a way to work around with it?
Thanks!!

A: You need higher precision to finish these calculations
badset = N[{alpha -> 10^(-14), beta -> (114/100)*10^(26), p -> 0,
   w -> 0}, 30];

probs /. badset

{1.0, 4.*10^-40, 8.*10^-66, 1.3*10^-91, 1.8*10^-117, 1.2*10^-143}

And
Sum[%[[i]], {i, 1, 6}]

1.0


text:
Q: Chrome remote device debugger interface corrupted I have a strange problem with the remote device debugger tool of Chrome.
I use it for cordova app testing, essentially for the console.log messages in the console tab. The developer tools works.
With some Android smartphone all works well, but when I use Meizu MX6 smartphone, the developer tools interface appears corrupter: tabs are positioned in the wrong location, console has no scrollbars so I can't scroll, if I click a tab all disappears and the debugger window becames white, and so on.
Has anyone esperienced this anomaly?
Thanx,
Steven

A: Meizu MX6 use Android 6.0 (Marshmallow) which is old enough to cause this problem.
To deal with it I use old Chromium builds as described here


text:
Q: How is reading an InputStream object from a local file different than from the network (via Amazon S3)? I didn't think there was a difference between an inputstream object read from a local file vs one from a network source (Amazon S3 in this case) so hopefully someone can enlighten me.
These programs were run on a VM running Centos 6.3.
The test file in both cases are 10MB.
Local file code:
    InputStream is = new FileInputStream("/home/anyuser/test.jpg");

    int read = 0;
    int buf_size = 1024 * 1024 * 2;
    byte[] buf = new byte[buf_size];

    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf_size);

    long t3 = System.currentTimeMillis();
    int i = 0;
    while ((read = is.read(buf)) != -1) {
        baos.write(buf,0,read);
        System.out.println("reading for the " + i + "th time");
        i++;
    }
    long t4 = System.currentTimeMillis();
    System.out.println("Time to read = " + (t4-t3) + "ms");

The output of this code is this: it reads 5 times, which makes sense since the buffer size read in is 2MB and the file is 10MB.
reading for the 0th time
reading for the 1th time
reading for the 2th time
reading for the 3th time
reading for the 4th time
Time to read = 103ms

Now, we have the same code run with the same 10MB test file, except this time, the source is from Amazon S3.  We don't start reading until we finish getting the stream from S3.  However, this time, the read loop is running through thousands of times, when it should only read it 5 times.
    InputStream is;
    long t1 = System.currentTimeMillis();
    is = getS3().getFileFromBucket(S3Path,input);
    long t2 = System.currentTimeMillis();

    System.out.print("Time to get file " + input + " from S3: ");
    System.out.println((t2-t1) + "ms");

    int read = 0;
    int buf_size = 1024*1024*2;
    byte[] buf = new byte[buf_size];

    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf_size);
    long t3 = System.currentTimeMillis();
    int i = 0;

    while ((read = is.read(buf)) != -1) {
        baos.write(buf,0,read);
        if ((i % 100) == 0)
        System.out.println("reading for the " + i + "th time");
        i++;
    }
    long t4 = System.currentTimeMillis();

    System.out.println("Time to read = " + (t4-t3) + "ms");

The output is as follows:
Time to get file test.jpg from S3: 2456ms
reading for the 0th time
reading for the 100th time
reading for the 200th time
reading for the 300th time
reading for the 400th time
reading for the 500th time
reading for the 600th time
reading for the 700th time
reading for the 800th time
reading for the 900th time
reading for the 1000th time
reading for the 1100th time
reading for the 1200th time
reading for the 1300th time
reading for the 1400th time
Time to read = 14471ms

The amount of time taken to read the stream changes from run to run.  Sometimes it takes 60 seconds, sometimes 15 seconds.  It doesn't get faster than 15 sec.  The read loop still loops through 1400+ times on each test run of the program, even though I think it should only be 5 times, like the local file example.
Is this how inputstream works when the source is through the network, even though we had finished getting the file from the network source?  Thanks in advance for your help.

A: I don't think it's specific to java. When you read from the network, the actual read call to the operating system will return a packet of data at a time, no matter how big is the buffer you allocated. If you check the size of the read data (your read variable), it should show the size of the network packet used.
This is one of the reason why people use a separate thread to read from network and avoid blocking by using async i/o technique.

A: As @imel96 points out, there is nothing in the documentation that guarantees the behaviour you are expecting. You will never read 2MB at a time from a socket, because the socket receive buffer isn't normally that large, quite apart from other factors such as bandwidth.


text:
Q: Disable auto-intend or/and save project config can me some answer how can I disable the auto-intend in vsc?
I work with different teams and some of them have different intend configurations and if I push my code in git we got everytime a lot of merge conflicts.
Or is there a possibility to save different configs in a projectfolder?
Cheers


text:
Q: how sabre sd boots directly from uboot without SPL sabre sd is based on imx-6 which has around 150Kb max internal RAM. however the uboot is large enough to fit in this space. How things work in this scenerio ?
https://community.freescale.com/docs/DOC-95015
In this freescale documentation only uboot is used to create an SD card for sabre sd boot.

A: Short answer: it doesn't matter how small SRAM is since U-Boot itself apparently doesn't go anywhere near it.
The major giveaway is that the mx6qsabresd config sets an entry point of 0x17800000, which according to the memory map in the the reference manual is a DRAM address. Now, I don't "know" i.MX6 per se, but I can certainly summarise what the "System Boot" chapter of that manual says (hey, it was interesting...)
The internal ROM loader reads the first 4K of the image from offset 0x400 of the SD card into internal RAM to look at the header. This header (in the u-boot.imx Image) contains the size and DRAM load address of the U-Boot image, along with a load of configuration register data - from building mx6qsabresd_config I see this comes from board/freescale/mx6sabresd/mx6q_4x_mt41j128.cfg and, briefly cross-checking the addresses there with the peripheral map, appears to be mostly setting up the IOMUX and DRAM controller. The ROM code writes to configuration values to their relevant registers, DMA's the whole image from the SD card straight into DRAM, and jumps to it.


text:
Q: I can't figure out why double digits are not recognized I am trying to create a program where you could enter player's number and it will return his name. Everything is good with players whose jersey number is single digit, however it doesn't return anything for a player whose jersey number is double digits. How can I fix this issue?
Thank you for the helps in advance.
    cimbom = input( "Player's Number: ")
players = {"10": "Belhanda",
             "89": "Feghouili",
             "20": "Emre",
             "7": "Onyekuru",
             "6": "Taylan"}
out = ""
for player in cimbom:
    out += players.get(player," ")
print(out)

A: Inputs from console are taken as strings. So, if you input 20, then cimbom is equal to the string "20".
Which means, when looping over cimbom using for player in cimbom:, the loop will loop over each character of "20" individually, namely, "2", then "0".


text:
Q: Logback - filtering stack trace I'm using logback for logging and i found some problem with filtering stack trace.
I hava a structure like this:
public class Main {
    static final Logger logger = (Logger) LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        logger.debug("Start");

        MyObject1 loggingElement = new MyObject1();
        loggingElement.logg();

        logger.debug("End");
    }
}

public class MyObject1 {

    public MyObject2 obj;
    static final Logger logger = (Logger) LoggerFactory.getLogger(MyObject1.class);

    public MyObject1() {
        obj = new MyObject2();
    }
    public void logg() {
        obj.loggError();
    }
}
public class MyObject2 {
    static final Logger logger = (Logger) LoggerFactory.getLogger(MyObject2.class);

    public void loggError() {
        logger.error("Error info", new Throwable("Error"));
    }
}

and configuration xml like this:

<property name="mask"
            value="MyObject2"/>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss} | %level | %-4thread | %-21logger | %m%n
        </pattern>
    </encoder>
</appender>

<root level="${root.level:-TRACE}">
    <appender-ref ref="STDOUT" />
</root>

When i run the main method i get output like this:
12:29:35 | DEBUG | main | com.logging.Main      | Start
12:29:35 | ERROR | main | com.logging.MyObject2 | Error info
java.lang.Throwable: Error
    at com.logging.MyObject2.loggError(MyObject2.java:11) [bin/:na]
    at com.logging.MyObject1.logg(MyObject1.java:17) [bin/:na]
    at com.logging.Main.main(Main.java:14) [bin/:na]
12:29:35 | DEBUG | main | com.logging.Main      | End

i would like to remove line with 'MyObject1' in it and leave rest of stack trace untouched just like int this example:
http://java.dzone.com/articles/filtering-stack-trace-hell
i tried to change configuration of logback
<pattern>%d{HH:mm:ss} | %level | %-4thread | %-21logger | %m%n%ex{full,${mask}}
</pattern>

doesn't work at all
<pattern>%d{HH:mm:ss} | %level | %-4thread | %-21logger | %m%n%eXe{full,${mask}}
            </pattern>

removes whole stack trace(not solution for me)
Anyone knows anything that could help?

A: This capability has been included in Logback Classic as of version 1.1.3. It seems to apply to the following Conversion Words of PatternLayout:

*

*ex / exception / throwable

*rEx / rootException

*xEx / xException / xThrowable

A: On my case I used a ThrowableConverter for the stacktrace.
You can add that to your logback.xml where you have your consoleApender, inside your encoder:
    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">

            <!-- your other encoder configurations -->

            <stackTrace>
                <fieldName>stacktrace</fieldName>
                <throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
                    <pattern>[%thread] - %msg%n%stack{1,1024,10,rootFirst}</pattern>
                </throwableConverter>
            </stackTrace>

        </encoder>
    </appender>

It will add a field name "stack_trace" with the stack trace. And it does the job for me.
Inside stack you have the parameters:

*

*maxDepthPerThrowable: Limits the number of stackTraceElements per throwable

*maxLength: Limits the total length in characters of the trace.

*shortenedClassNameLength: Abbreviates class names based on the shortenedClassName

*rootCauseFirst: Outputs in either 'normal' order (root-cause-last), or root-cause-first


text:
Q: How to convert deep query parameters into Perl data structure? I learn using Datatables to draw dynamic tables on my site, using server-side data as source for tables. Datatables uses complicated parameters in queries, which I'd like to convert into proper Perl datastructure. So, query string like this (wrapped into lines for clarity):
columns[0][data]=status&
columns[0][name]=&
columns[0][searchable]=true&
columns[0][orderable]=true&
columns[0][search][value]=&
columns[0][search][regex]=false&
columns[1][data]=some&
columns[1][name]=&
columns[1][searchable]=true&
columns[1][orderable]=true&
columns[1][search][value]=&
columns[1][search][regex]=false&
columns[2][data]=title&
columns[2][name]=&
columns[2][searchable]=true&
columns[2][orderable]=true&
columns[2][search][value]=&
columns[2][search][regex]=false

would become like:
@columns = ( {
    data => 'status',
    name => '',
    searchable => 1,
    orderable => 1,
    search => {
      value => '',
      regex => 0,
    }
  },
  {
    data => 'true',
    name => '',
    searchable => 1,
    orderable => 1,
    search => {
      value => '',
      regex => 0,
    }
  },
  {
    data => 'title',
    name => '',
    searchable => 1,
    orderable => 1,
    search => {
      value => '',
      regex => 0,
    }
  },
);

What is the best way to achieve it?
EDIT.
Additionally, in this particular case I use CGI.pm to retrive query params, this gives me flat data structure.

A: use Data::Diver 'DiveVal';

my @columns;
my %translate = ( 'true' => 1, 'false' => 0 );
for my $param ( $query->param() ) {
    if ( $param =~ /^columns/ ) {
        my $value = $query->param($param);
        DiveVal( \@columns, $param =~ /\[(.*?)\]/g )
            = $translate{$value} // $value;
    }
}

A: Assuming you pulled the params from the CGI object, then the following could work:
use strict;
use warnings;

my %params = (
    'columns[0][data]'          => 'status',
    'columns[0][name]'          => '',
    'columns[0][searchable]'    => 'true',
    'columns[0][orderable]'     => 'true',
    'columns[0][search][value]' => '',
    'columns[0][search][regex]' => 'false',
    'columns[1][data]'          => 'some',
    'columns[1][name]'          => '',
    'columns[1][searchable]'    => 'true',
    'columns[1][orderable]'     => 'true',
    'columns[1][search][value]' => '',
    'columns[1][search][regex]' => 'false',
    'columns[2][data]'          => 'title',
    'columns[2][name]'          => '',
    'columns[2][searchable]'    => 'true',
    'columns[2][orderable]'     => 'true',
    'columns[2][search][value]' => '',
    'columns[2][search][regex]' => 'false',
);

my @columns;
while (my ($key, $val) = each %params) {
    next if $key !~ /^columns/;
    my @keys = $key =~ /\[(.*?)\]/g;
    my $ref = $columns[shift @keys] ||= {};
    $ref = $ref->{shift @keys} ||= {} while @keys > 1;
    $ref->{$keys[0]} = $val;
}

use Data::Dump;
dd @columns;

Outputs:
(
  {
    data => "status",
    name => "",
    orderable => "true",
    search => { regex => "false", value => "" },
    searchable => "true",
  },
  {
    data => "some",
    name => "",
    orderable => "true",
    search => { regex => "false", value => "" },
    searchable => "true",
  },
  {
    data => "title",
    name => "",
    orderable => "true",
    search => { regex => "false", value => "" },
    searchable => "true",
  },
)

A: You could try something like:
#! /usr/bin/perl

use warnings;
use strict;

my $qs="columns[0][data]=status&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=some&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=title&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false";

my @data=split ("&",$qs);

my @col;

for (@data) {
   my ($val)=/=(.*)$/;
   $_=~s/=.*//;
   my @b=split(/\[(.*?)\]/);
   my @c=@b[grep {$_% 2} 0..$#b];
   if (@c==2) {
      $col[$c[0]]->{$c[1]}=$val;
   } else {
      $col[$c[0]]->{$c[1]}{$c[2]}=$val;
   }
}

or using eval for a more general solution:
for (@data) {
   my ($val)=/=(.*)$/;
   $_=~s/=.*//;
   my @b=split(/\[(.*?)\]/);
   my @c=@b[grep {$_% 2} 0..$#b];
   my $cmd='$col[$c[0]]->';
   for my $i (1..$#c) {
      $cmd.='{$c['.$i.']}';
   }
   $cmd.='=$val';
   eval ($cmd);
}


text:
Q: RabbitMQ Sequential Publish with ACK and NACKs(Reject & Nack handling) Synchronous Console.WriteLine($"Publishing to Default EXG & queue: {result.QueueName}");

Todo : BUILD Retries, Republish and Acknowledgement Workflow.
                    IBasicProperties messageProps = _channel.CreateBasicProperties();
                    messageProps.Persistent = true;

//Handle Acks

                    _channel.BasicAcks += _channel_BasicAcks;
                    _channel.ConfirmSelect();
//Publish

                    byte[] body = Encoding.UTF8.GetBytes(messageToPublish);

                    _channel.QueueBind(
                        queueName,
                        exchangeName,
                        routingKey,
                        null
                        );
                    _channel.BasicPublish
                    (   exchange: exchangeName,
                        routingKey: routingKey,
                        basicProperties: messageProps,
                        body: body);

//Wait for the Confirmations

                    _channel.ConfirmSelect();
                    _channel.WaitForConfirmsOrDie(10000);

The Event

_channel_BasicAcks (Object Sender, EventArgs e)

which is being called now externally from the scope of the publish method(async) instead of Synchronously getting response.
For a hardbound requirement of retrying individual messages immediately after a nack in a bulk publish how do I make this strictly synchronous.
Sync Wrapper to Async Publish method is the Solution I came up with, it works though it is not the best there is! Is there a better performing solution instead of having to trial and error with timeouts!

A:
For a hardbound requirement of retrying individual messages
  immediately after a nack in a bulk publish how do I make this strictly
  synchronous.

Don't wait for acks synchronously!
Save messages client-side until you receive an asynchronous ack / nack for it, then do something based on that response. Specify a certain number of "outstanding" acknowledgements that are acceptable and do not publish if that limit is reached. Specify a time limit that is acceptable for receiving an ack/nack and if that limit is exceeded, do something in your application to deal with it.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: Combine the SQL queries into one I am trying to combine two queries into one.
First query:
select SaleID
from Sales
where InvoiceStatusID = 'OR';

Second query:
select ItemSaleLines.Quantity, Items.CustomField2
from ItemSaleLines
inner join Items on ItemSaleLines.ItemID = Items.ItemID
inner join Sales on ItemSaleLines.SaleID = Sales.SaleID
where (ItemSaleLines.SaleID = {keyProductID}
  and (ItemSaleLines.Quantity > 0)
  and (Items.ItemNumber not like '%tnt%')
  and (Items.ItemNumber not like '%contact%')
  and (Items.ItemNumber <> '')
  and (Items.ItemNumber <> '-' ) )

where keyProductID is the SaleID which I am getting from query 1.
I am doing this by storing SaleID first from query 1 and passing to the query 2, but it is not efficient and have too many calls.
Whats the better way to do it?

A: You can try something like this,
select ItemSaleLines.Quantity,Items.CustomField2 from ItemSaleLines
inner join Items on ItemSaleLines.ItemID=Items.ItemID
inner join Sales on ItemSaleLines.SaleID=Sales.SaleID
where (ItemSaleLines.SaleID=(select SaleID from Sales where InvoiceStatusID='OR')
AND (ItemSaleLines.Quantity > 0) AND (Items.ItemNumber not
like '%tnt%') AND (Items.ItemNumber not like '%contact%') AND (Items.ItemNumber <> '') AND (Items.ItemNumber <> '-' ) )


text:
Q: TortoiseGit - как убрать из-под контроля версий файлы в папке? Есть папка с файлами, файлы помечены красными крестами. Цитата из руководства:

This icon shows you that some files or folders inside the current folder have  been scheduled to be deleted from version control or a file under version control  is missing in a folder.

Что означает "запланированы к удалению"? Когда они удалятся из-под контроля? На следущем коммите? Коммит сделал, иконка не поменялась. Как их удалить из-под контроля вручную?

A: Из комментария KoVadim:
Это значит, что файлы Вы удалили, и Git хочет, чтобы ему об этом явно сказали. Когда будете коммитить, нужно добавить данные файлы (как бы странно это не звучало). Если работаете в консоли, то нужно ввести git add -u && git commit -m "message".


text:
Q: Unexpected output while executing string methods #include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  static char s1[]="Good";
  static char s2[20];
  static char s3[20]="Day";

  int i = strcmp(strcat(s3,strcpy(s2,s1)),strcat(s3,"good"));

  printf("%d\n",i);

  return 0;
}

Here the output is 0, which implies that the two strings passed as arguments to strcmp are equal.  But for strcmp the first argument is "DaygoodGood" and second is "Daygood"...
Why is this happening?

A: You are comparing s3 with s3, no matter how you look at it.  You'll always get equal doing that.  Just break it down - changing:
    i=strcmp(strcat(s3,strcpy(s2,s1)),strcat(s3,"good"));

into:
    char *s4 = strcpy(s2,s1);     // s4 == s2 -> "Good"
    char *s5 = strcat(s3,s4);     // s5 == s3 -> "DayGood"
    char *s6 = strcat(s3,"good"); // s6 == s3 -> "DayGoodgood"

    i = strcmp(s5, s6);           // same as strcmp(s3, s3)

Now whether it really happens this way, or if it's:
    char *s4 = strcpy(s2,s1);     // s4 == s4 -> "Good"
    char *s6 = strcat(s3,"good"); // s6 == s3 -> "Daygood"
    char *s5 = strcat(s3,s4);     // s5 == s3 -> "DaygoodGood"

    i = strcmp(s5, s6);           // same as strcmp(s3, s3)

Instead, is unspecified by the standard.  Regardless, you're comparing identical strings, whichever order the concatenations happen in.  You're either comparing "DayGoodgood" to "DayGoodgood" or "DaygoodGood" to "DaygoodGood", but you should expect 0 as a result either way.

A: The result of strcat(t, s) is always equal to t.  If you find this confusing, remember that strings in C are character pointers, so we are talking about the two pointers being equal, not about the (previous or current) contents of string t.
Therefore, the two strings compared are s3 and s3, no matter what s3 contains at that time.  Of course they are equal.

A: This is because first strcat returns s3, just as the second. First invocation appends something to s3's content, second appends more, but both return the same pointer.

A: First of all, thank-you for this question.  It is actually more complicated than one might believe at first glance.
The first concept to understand is that of "side-effects".  That is, when a parameter invokes a function then that function might modify data such that how the parameter is evaluated is modified.
For example, when evaluating strcmp(A,B) which parameter is evaluated first, A or B?  If A and B are just variables then it does NOT matter.  However, if they are themselves functions, it can matter: strcmp(A(1), B(2)) it might/maybe make a difference if A(1) is evaluated first or B(2).
Let's look specifically at your code:
 strcmp(strcat(s3,strcpy(s2,s1)),strcat(s3,"good"));

It can be evaluated internally by the compiler as:
 A)
    strcat(s3,strcpy(s2,s1));  //s3 = "DayGood'
    strcat(s3,"good");         //s3 = "DayGoodgood"
    strcmp(s3, s3);

or it can be evaluated as:
 B)
    strcat(s3,"good");         // s3 = "Daygood"
    strcat(s3,strcpy(s2,s1));  // s3 = "DaygoodGood"
    strcmp(s3, s3);

So, s3 has two possible values, depending on how a compiler evaluates parameters, and the difference is evidence of "side-effects".
Finally, to see exactly how your compiler works, then modify your printf statement:
  printf("\n%d, %s\n\n", i, s3);

Hope this helps.


text:
Q: Evaluating $\int\frac{4x^3-3x^2+6x-27}{x^4+9x^2}dx$ $$\int\frac{4x^3-3x^2+6x-27}{x^4+9x^2}dx$$
this integral get very messy. Can I get a step by step breakdown of solving?

A:
No Step by step solution, but just a hint

By reducing to partial fractions we get
$$\frac{4x^3-3x^2+6x-27}{x^4+9x^2}=\frac{Ax+ B}{x^2+9}+\frac{C}{x^2}+\frac Dx$$
$$Ax^3+Bx^2+Cx^2+9C+Dx^3+9Dx=4x^3-3x^2+6x-27$$
$$9C=-27\implies C=-3$$
$$9D=6\implies D=\frac23$$
$$A+D=4\implies A=-\frac{10}{3}$$
$$B+C=-3\implies B=0$$

$$\frac{4x^3-3x^2+6x-27}{x^4+9x^2} =\frac{10x}{3(x^2+9)}-\frac{3}{x^2}+\frac{2}{3x}$$

A: Doing long division, I get $$\int{\frac{4}{x}-\frac{3}{x^2}-\frac{30}{x^3+9x}dx}$$ We can rewrite as $$\int{4x^{-1}-3x^{-2}-30(x^3+9x)^{-1}}$$


text:
Q: Get parallel edges and give them color I want to get list of all parallel edges within a collection and give them seperate color
My code is
cy.elements().parallelEdges().animate({ 'style':{'line-color':'coral', 'width': '10px'} }, {duration: 1000 })

But it end up in coloring all edges....

A: You call the function on all elements in cytoscape, the documentation implys, that you have to callthe function on edges.
cy.edges().parallelEdges().animate();

Edit:
cy.edges() wont work, the funciton is designed to give you the parallel edges to a set collection of edges, so if you want to achieve this, I think you have to:

*

*Iterate through all nodes via cy.nodes() and a for loop

*Get the edges of the current node with cy.edges("[source = theRightId]")

*Check for every edge (Just one edge for the following function!!) if it has a parallel edge via cy.$('#idOfEdge').parallelEdges()

*Put those with a parallel edge in a cy.collection() [add elements in a collection with: yourCollection = yourCollection.add(theParallelEdges)]


text: Q: apache server hides header.php I am trying to create a file called headers.php in my apache server.But each time I enter the server`s file directory I see that header is not seeming. Is there any restrictions from apache on this "headers.php" nomination? And hozw to solve this problem?


text:
Q: Using @font-face with Rails 3.1 app? I'm having trouble using the following @font-face declaration to work with my Rails 3.1 app.  I put the fonts in the Asset Pipeline in its own folder called "Fonts" alongside images and stylesheets and javascripts
Here is the declaration I used (generated by Font Squirrel.)
@font-face {
  font-family: 'ChunkFiveRegular';
  src: url('Chunkfive-webfont.eot');
  src: url('Chunkfive-webfont.eot?#iefix') format('embedded-opentype'),
     url('Chunkfive-webfont.woff') format('woff'),
     url('Chunkfive-webfont.ttf') format('truetype'),
     url('Chunkfive-webfont.svg#ChunkFiveRegular') format('svg');
  font-weight: normal;
  font-style: normal;
}

Anyone successfully utilize @font-face on their Rails 3.1 app?
Update
I just read this thread http://spin.atomicobject.com/2011/09/26/serving-fonts-in-rails-3-1/ that said to change url to font-url in the declarations.  That didn't seem to work either unfortunately.

A: Using Rails 4.0 (don't know if this is specific to 4, but anyway), I was only able to make it work with url(font_path('font-name.ttf')). Adding the fonts path to the assets path was not necessary either (config.assets.paths << "#{Rails.root}/app/assets/fonts").
So, to me this is what worked:
@font-face {
  font-family: 'ChunkFiveRegular';
  src: url(font_path('Chunkfive-webfont.eot'));
  src: url(font_path('Chunkfive-webfont.eot?#iefix')) format('embedded-opentype'),
     url(font_path('Chunkfive-webfont.woff')) format('woff'),
     url(font_path('Chunkfive-webfont.ttf')) format('truetype'),
     url(font_path('Chunkfive-webfont.svg#ChunkFiveRegular')) format('svg');
  font-weight: normal;
  font-style: normal;
}

A: You have to add the folder to the assets path (to file config/application.rb), see Rails Guides
config.assets.paths << "#{Rails.root}/app/assets/fonts"

And you should use the asset_path helper:
src: url('<%= asset_path('Chunkfive-webfont.eot') %>');

A: I know this is an old question, but I just stumbled across this issue with rails 3.2, and after reading the link to the documentation posted previously, there was no need to edit the application.rb. All I needed to do was do the following in my stylesheet (using sass)
@font-face {
    font: {
       family: 'Junction';
       weight: 'normal';
       style: 'normal';
    }
    src: asset-url('Junction-webfont.eot', font);
    src: asset-url('Junction-webfont.eot', font) format('embedded-opentype'),
         asset-url('Junction-webfont.woff', font) format('woff'),
         asset-url('Junction-webfont.ttf', font) format('truetype'),
         asset-url('Junction-webfont.svg#JunctionRegular', font) format('svg')
}

So instead of using url, I used the generic asset-url, which takes 2 arguments, the file and the asset class, in this case 'font'.

A: From Rails 3.1 and above you can call font-url directly. Like this:
@font-face {
  font-family: 'ChunkFiveRegular';
  src: font-url('Chunkfive-webfont.eot');
  src: font-url('Chunkfive-webfont.eot?#iefix') format('embedded-opentype'),
     font-url('Chunkfive-webfont.woff') format('woff'),
     font-url('Chunkfive-webfont.ttf') format('truetype'),
     font-url('Chunkfive-webfont.svg#ChunkFiveRegular') format('svg');
  font-weight: normal;
  font-style: normal;
}

Expect your final css to look like that:
@font-face {
  font-family: 'ChunkFiveRegular';
  src: url(/assets/Chunkfive-webfont.eot);
  src: url(/assets/Chunkfive-webfont.eot?#iefix) format('embedded-opentype'),
     url(/assets/Chunkfive-webfont.woff) format('woff'),
     url(/assets/Chunkfive-webfont.ttf) format('truetype'),
     url(/assets/Chunkfive-webfont.svg#ChunkFiveRegular) format('svg');
  font-weight: normal;
  font-style: normal;
}

Usually works :)

A: I just updated that article on Atomic Object's Spin blog. Here is the CSS converted (You were looking at the Sass syntax)
@font-face {
  font-family: "Merriweather";
  src: url(/assets/merriweather-black-webfont.eot);
  src: local("Merriweather Heavy"), local("Merriweather-Heavy"), url(/assets/merriweather-black-webfont.eot?#iefix) format("embedded-opentype"), url(/assets/merriweather-black-webfont.woff) format("woff"), url(/assets/merriweather-black-webfont.ttf) format("truetype"), url(/assets/merriweather-black-webfont.svg#MerriweatherHeavy) format("svg");
  font-weight: 900;
  font-style: normal;
}

A: I'm using 3.1.1 and have my fonts under vendor/assets/store (Spree implementation).  The solutions given here did not work for me and I eventually just tried what ended up being my solution - there was no need for
Here's an example of my src attribute for EOT:
src: url('1617A5_4.eot');

I'm a little bit confused by this but it seems like once assets are compiled the assets are all copied in to their parent folder (assets/store/) at which point the stylesheet can just pick them up.

A: While this is late, you could use Compass's +font-face mix-in to avoid all this trouble. The mixin helps your life easier by

*

*Not remember the awful caveats of the traditional font-face decleration

*It internally handles url_helper and format declarations for you

*It's far easier to remember
It is declared the following way madams and gentlemen:
+font-face("#{$font-name}",
  font-files("#{$font-name}.woff", woff,
  "#{$fontFileName}.ttf", ttf,
  "#{$fontFileName}.svg", svg), "#{$fontFileName}.eot", normal, normal);


text:
Q: Redux Saga & Redux Toolkit watcher problem hope you have a nice day!
I am newbie to redux and redux saga and i wanted to ask you all help.
This is the sandbox https://codesandbox.io/s/staging-wave-3ewyr?file=/src/store.js
The problem is that when i click on increment button the value of "counter" inside the store become 0 then it will be incremented by 1. Clicking on Decremenet and Sum works because they are not using sagas.
Example:
Click on decrement: counter become -1
Click on increment: counter become 0 then 1 (it should be 0 cause we expect to be: -1 + 1)
Anyone can explain me where is the problem?
Thank you all!

A: The problem is in the final part of your reducer:
default:
  return 0;

Since there is no case for the INCREMENT action, the code execution goes to default and resets the counter to zero.
The solution is to return the current state instead:
default:
  return state;


text:
Q: Suming a value for Fiscal Year when YY, MM and DD are are stored separately in SQL Ok, I need some help with this. I think I may have been looking at this too long and its messing with my brain. I have a table, we'll call it Goals. In this table I have the following 4 columns:
StaffID example (123)
Syear example (2011)
Smonth example (7)
SGoal  example (104.2)
What I need is to sum the SGoal column for Fiscal Year, ie months 7-12 of one year and 1-6 of the next. Problem is I need this to be looping and by that I mean it cant be year specific. I will be using this query to run a report in BIZ for years to come. So I think it may be able to be done 2 ways, either through a query or modifying the table somehow. Either way, any help would be greatly appreciated.

A: It's probably best to put the fiscal year calculation into a View but here's one way to do it in a query
SELECT staffid, syear+(((smonth+1)&8)/8) as fiscalyear, sum(sgoal) AS 'sum'
FROM goals
GROUP BY staffid, syear+(((smonth+1)&8)/8)

A: Something like this would work, although storing the fiscal year would be a better and more elegant solution.
select staffId, fiscal_year, sum(sGoal) from (
select staffid, sGoal, if (sMonth > 6, sYear, sYear-1) as fiscal_year
  from goals ) as fiscal
group by staffId, fiscal_year

SQL Fiddle


text:
Q: Tensorflow: what's the SplitByWorker exactly done in distributed version? In Tensorflow, there's a placement algorithm (which named as placer.cc in master branch) used for mapping node (op) to devices.
Supposed that in distributed TF, there's

*

*1 client graph and 2 workers(or maybe more)

*Without specifying node operations to specified workers or devices on workers such as with tf.device("/job:worker/task:7"):

*Without using tf.train.replica_device_setter() for model replication on workers.

Question:

*

*What's the SplitByWorker actually done?
I've read the SplitByDevice and it seems to retrive by node->device_name() if user explicitly specified a device and placement algo places the whole worker0 subgraph to /job:worker0/gpu:0

*Is there any API or tf source code that actually make partition of client graph to different subgraphs, and send to different workers?
I know that tf.train.replica_device_setter() is used to create replicas on workers and for place parameters to ps. But without using this, can tensorflow partition model for me if there's more than 1 workers? (Obviously 1 worker get the whole client graph as its "subgraph")

*What's the default option for tensorflow if the client doesn't partition the graph all all?
If the ans of 2 is NO, then I must partition by myself through explicit specifying. But how would tf do to if the client doesn't partition the graph all? Like placement algorithms default option is put all nodes on GPU:0, would it place the whole client graph to worker0 without partition and let worker1 be idle?
Please give me some insight for this, any answers or source code references are appriciated (:


text:
Q: How to duplicate SVGSurface in Cairo (Python) Say I have a surface and draw something on it.
surface = cairo.SVGSurface("foo.svg", 360, 240)

ctx = cairo.Context(surface)
ctx.move_to(0, 0)
ctx.line_to(0, 80)
ctx.line_to(80, 80)
ctx.fill()

How do I duplicate this surface so I can draw different shapes from where I left off?
surface_1 = [copy surface]
surface_2 = [copy surface]

# Draw something on surface_1
# Draw something different on surface_2

A: My suggestion: Create a new surface and draw your existing one to it.
surface2 = cairo.SVGSurface("foo2.svg", 360, 240)
ctx2 = cairo.Context(surface2)
ctx2.save()
ctx2.set_source_surface(surface)
ctx2.set_operator("SOURCE")
ctx2.paint()
ctx2.restore()

(Note that I have no idea how PyCairo maps the C API to Python, so the above is a guess that might not work)


text:
Q: how to implement search for 2 different table data? Using mysql and PHP
I am using MATCH AGAINST clauses already.
It is working fine against individual tables. Like if i want to search in shops table. No problem.
What i want is to be able to search and DISPLAY results from different tables in a single result page.
Eg if i type "chocolate clothes"
i may get 4 results as follows:
Shop1 result
ShopItem1 result
ShopItem2 result
Shop2 result
and of course the most relevant results should be ranked first.
i have quite a few questions. design wise as well as implementation wise
1) should i change my design?  i am thinking of having a separate table called search results that will contain data from both SHOPS and SHOPPRODUCTS table. however that means i have some data duplication.
2) should i keep my current design? if so, then how on earth can i get the search results sorted by relevancy across 2 different tables?
i saw that rottentomatoes organised their search results in different groups. however, we prefer the search results not to be restricted by different types especially when we have paging that is going to be even more difficult to navigate UI wise.
http://www.rottentomatoes.com/search/full_search.php?search=girl
OR that is actually the best way out?
I hope that someone can give me guidance on this kind of thing esp if you have experience in generating search results across what would seem like multiple tables.
since by demand, i will put the table structures here
CREATE TABLE `shopitems` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `ShopID` int(10) unsigned NOT NULL,
  `ImageID` int(10) unsigned NOT NULL,
  `name` varchar(100) NOT NULL,
  `description` varchar(255) NOT NULL,
  `pricing` varchar(45) NOT NULL,
  `datetime_created` datetime NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

/*Table structure for table `shops` */

DROP TABLE IF EXISTS `shops`;

CREATE TABLE `shops` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(100) default NULL,
  `description` text,
  `keywords` text,
  `url` varchar(255) default '',

  `owner_id` varchar(255) default NULL,
  `datetime_created` datetime default NULL,
  `created_by` varchar(255) default NULL,
  `datetime_modified` datetime default NULL,
  `modified_by` varchar(255) default NULL,

  `overall_rating_avg` decimal(4,2) default '0.00',

  PRIMARY KEY  (`id`),
  FULLTEXT KEY `url` (`url`),
  FULLTEXT KEY `TitleDescFullText` (`keywords`,`title`,`description`,`url`)
) ENGINE=MyISAM AUTO_INCREMENT=3051 DEFAULT CHARSET=utf8;

i intend to search through the description and the name columns of the shopproducts table.
but as you can see it has not been implemented yet.
although the search for the shops is already up and running.

A: Here are a few "rules of the game" that you must keep in mind for solving this problem.  You probably know these already, but stating them clearly may help confirm for other readers.

*

*All indexes in MySQL can reference only columns in a single base table.  You can't make a fulltext index that indexes across multiple tables.

*You can't define indexes for views, only base tables.

*A MATCH() query against a fulltext index must match against all the columns in the fulltext index, in the order declared in the index.

I would create a third table to store the content you want to index.  No need to store this content redundantly -- store it solely in the third table.  This borrows a concept of a "common superclass" from object-oriented design (insofar as we can apply it to RDBMS design).
CREATE TABLE Searchable (
  `id` SERIAL PRIMARY KEY,
  `title` varchar(100) default NULL,
  `description` text,
  `keywords` text,
  `url` varchar(255) default '',
  FULLTEXT KEY `TitleDescFullText` (`keywords`,`title`,`description`,`url`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `shopitems` (
  `id` INT UNSIGNED NOT NULL,
  `ShopID` INT UNSIGNED NOT NULL,
  `ImageID` INT UNSIGNED NOT NULL,
  `pricing` varchar(45) NOT NULL,
  `datetime_created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`id`) REFERENCES Searchable (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `shops` (
  `id` INT UNSIGNED NOT NULL,
  `owner_id` varchar(255) default NULL,
  `datetime_created` datetime default NULL,
  `created_by` varchar(255) default NULL,
  `datetime_modified` datetime default NULL,
  `modified_by` varchar(255) default NULL,
  `overall_rating_avg` decimal(4,2) default '0.00',
  PRIMARY KEY (`id`),
  FOREIGN KEY (`id`) REFERENCES Searchable (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Notice the only table with an auto-increment key is now Searchable.  The tables shops and shopitems use a key with a compatible data type, but not auto-increment.  So you must create a row in Searchable to generate the id value, before you can create the corresponding row in either shops or shopitems.
I've added FOREIGN KEY declarations for illustration purposes, even though MyISAM will silently ignore these constraints (and you already know that you must use MyISAM to have support for fulltext indexing).
Now you can search the textual content of both shops and shopitems in a single query, using a single fulltext index:
SELECT S.*, sh.*, si.*,
  MATCH(keywords, title, description, url) AGAINST('dummy') As score
FROM Searchable S
LEFT OUTER JOIN shops sh ON (S.id = sh.id)
LEFT OUTER JOIN shopitems si ON (S.id = si.id)
WHERE MATCH(keywords, title, description, url) AGAINST('dummy')
ORDER BY score DESC;

Of course, for a given row in Searchable only one table should match, either shops or shopitems, and these tables have different columns.  So either sh.* or si.* will be NULL in the result.  It's up to you to format the output in your application.

A couple of other answers have suggested using Sphinx Search.  This is another technology that complements MySQL and adds more sophisticated full-text search capability.  It has great performance for queries, so some people have gotten pretty enchanted with it.
But creating indexes and especially adding to an index incrementally is expensive.  In fact, updating a Sphinx Search index is so costly that the recommended solution is to create one index for older, archived data, and another smaller index for recent data that is more likely to be updated.   Then every search has to run two queries, against the two separate indexes.  And if your data doesn't naturally lend itself to the pattern of older data being unchanging, then you may not be able to take advantage of this trick anyway.

Re your comment:  Here's an excerpt from the Sphinx Search documentation about live updates to an index:

There's a frequent situation when the
  total dataset is too big to be
  reindexed from scratch often, but the
  amount of new records is rather small.
  Example: a forum with a 1,000,000
  archived posts, but only 1,000 new
  posts per day.
In this case, "live" (almost real
  time) index updates could be
  implemented using so called
  "main+delta" scheme.

The idea is that since it's costly to update a Sphinx Search index, their solution is to make the index you update as small as possible.  So that only the most recent forum posts (in their example), whereas the larger history of archived forum posts never changes, so you build a second, larger index for that collection once.  Of course if you want to do a search, you have to query both indexes.
Periodically, say once a week, the "recent" forum messages would become considered "archived" and you'd have to merge the current index for recent posts to the archived index, and start the smaller index over.  They do make the point that merging two Sphinx Search indexes is more efficient than reindexing after an update to the data.
But my point is that not every data set naturally falls into the pattern of having an archived set of data that never changes, versus recent data that updates frequently.
Take your database for example:  You have shops and shopitems.  How can you separate these into rows that never change, versus new rows?  Any shops or products in the catalog should be permitted to update their description.  But since that'd require rebuilding the entire Sphinx Search index every time you make a change, it becomes a very expensive operation.  Perhaps you'd queue up changes and apply them in a batch, rebuilding the index once a week. But try explaining to the shop vendors why a minor change to their shop description won't take effect until Sunday night.

A: I am not sure I understood correctly, but here are my 2 cents.
From what I can see, the problem is that you have 2 tables with very different layouts, so I will assume that you want to base the fulltext search on these fields:

*

*for shops: title, description and keywords

*for shopitems: name and description

Solution 1: Layout consistency -- does not use index...
If you could somehow change the name of your columns for shopitems, it would immediately get much simpler.
Select id From
(Select id, text1, text2, text3 From table1
 UNION
 Select id, text1, text2, text3 From table2)
Where MATCH(id, text1, text2, text3) AGAINST('keyword1 keyword2 keyword3')

However I can understand that it would be impractical to change everything that already exists. Note that with aliasing, adding a third (dummy) text column to shopitems could do the trick though.
Solution 2: Post-treatment
I should remark that the value computed can actually be returned (and thus used). Therefore you can create a temporary table with this value! Note that if you wish to return the 'title' and 'description' both columns should have the same type to be dealt with in an unifrom manner...
Select id, title, description From
(
 Select id, title, description, MATCH(id, title, description, keywords) AGAINST('dummy') As score
        From shops
        Where MATCH(id, title, description, keywords) AGAINST('dummy')
 UNION
 Select id, name As title, description, MATCH(id, name, description) AGAINST('dummy') As score
        From shopitems
        Where MATCH(id, name, description) AGAINST('dummy')
)
ORDER BY score DESC

I have no idea of the performance of this query though, I wonder if mysql will optimize away the double call to MATCH / AGAINST in each of the Selects (I hope it does).
The catch is that my query is merely a demonstration. The downside of using aliasing is that now you don't know from which table they come from any longer.
Anyway, I hope it helped you.

A: I suggest you the first option. Redundancy isn't always evil.
So I would make a table like this:
CREATE TABLE search_results
(
   ...
   `searchable_shop_info` VARCHAR(32),
   `searchable_shopitem_info` TEXT
   FULLTEXT KEY `searchable` (`searchable_shop_info`, `searchable_shopitem_info`)
) Engine=MyISAM;

Then you can still use SELECT * FROM search_results WHERE MATCH (searchable_shop_info,searchable_shopitime_info) AGAINST ('search query string');

A: hmm maybe u can use union? like

create table search1 (
    title varchar(12),
    relavency tinyint unsigned
);

create table search2 (
    title varchar(12),
    relavency tinyint unsigned
);

insert into search1 values (substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100));

insert into search2 values (substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100)),
(substring(md5(rand()), 1, 12), (rand()*100));

(select *, 'search1' as source from search1)
union (select *, 'search2' as source from search2)
order by relevancy desc;
select your rows and calculate relevancy as per normal then union the results. i dunno if i understood u way wrong because no one seem to think of union?

UPDATE 1:
ok i re-read ur question and comment already ... i think

1) should i change my design? i am
  thinking of having a separate table
  called search results that will
  contain data from both SHOPS and
  SHOPPRODUCTS table. however that means
  i have some data duplication.

i think u shld use a view instead, to contain data from both tables as a view will automatically "update" when ur data changes. if u use a table, u will probably need to update it urself.
CREATE VIEW viewSearch (Title, Relavency, SourceTable) AS
(SELECT title, relavency, 'search1' as source FROM search1
ORDER BY relavency DESC
LIMIT 10)
UNION
(SELECT title, relavency, 'search2' as source FROM search2
ORDER BY relavency DESC
LIMIT 10)
ORDER BY relavency DESC
LIMIT 10;

2) should i keep my current design? if
  so, then how on earth can i get the
  search results sorted by relevancy
  across 2 different tables?

by the SQL/View above you can. basically by placing
...
ORDER BY relavency DESC
LIMIT 10

i am curious. that means i need to run
  that query EVERYTIME for any search
  input. because different input would
  have different relevancy scores.

i dont really get what u mean? if u were to search between 2 tables now, wont u do 2 separate SQL Queries (1 for each table)? or if u were to select results into 1 table its still ... in fact 3 queries (2 to select into results table then 1 to query).
i have also added ORDER BY & LIMIT into the each SELECT to speed up the process by getting less records. then ORDER BY & LIMIT once more as a whole.
in this example, i dont know how you would calculate relevancy, so i have used random numbers for that.

Maybe
  i am a bit lacking in understanding. i
  am suspicious whether your method is
  resource intensive. Please enlighten
  me. I am willing to consider all
  possibilities.

i am not really sure to be honest, but will like to know the answer to this... i am guessing it will still be better than multiple queries.
oh and i am also not really familiar with full text search so i dunno if this method will affect anything

A: If I understand your questions right, the answer is very simple:

*

*Don't change the design. It's perfectly fine. That's how it's supposed to be.

*Do a joined query like this:

SELECT * FROM shops
LEFT OUTER JOIN shopitems ON (shopitems.shopid = shops.id)
WHERE
    MATCH (shops.title, shops.description, shops.keywords,
           shopitems.name, shopitems.description)
    AGAINST ('whatever text')

A: I would go for the UNION. That is thepurpose of the statement.

A: I would go with your first alternative, creating  a seperate search table.
We have done this once when we needed to search for data across several SOA systems.
The benefits of this approach are:

*

*faster response to search requests

*more control over organizing of search results

The drawbacks are:

*

*slower time to save data, since it must be written two places

*extra space used to store data


text:
Q: how do I apply bootstrap styles only for django-crispy-forms not for other tags in the html template Upto know I used Bootstrap for the total project. But now I wanted to use my own styling for my Whole project. And I want to use crispy form tags for some forms like registration and login form.But when I tried it bootstrap styles are applying to my whole project.I don't want that I just want styling for only forms from crispy_forms. How can I achieve this. Thanks in advance.
{% extends '../base.html' %}
{% load crispy_forms_tags %}
{% block extra_head %}
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
            integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
{% endblock extra_head %}
{% block content %}

<form method="post">
    {{ form|crispy }}
    <button class="btn btn-outline-primary" type="submit">SignUp</button>  #styles applying for this button also
</form>
{% endblock content %}

A: I think you should be loading your crispy form tags before the form itself. I am sorry if this didn't work I am not that into bootstrap and i rarely use it.


text:
Q: load multiple versions of the class file to the JVM Is it possible to load multiple versions of the same class into the JVM. I have a version of the class "XYZ" loaded in the main thread and I have multiple children threads doing some work. I want to load different versions of class "XYZ" in to children threads.
Is this doable? I was thinking of creating a new context class loader for each of the children threads and use this context class loader to load a different version of the class. For now I am using URLClassLoader for context class loaders but that does not seem to work. Do I have to create a custom class loader to the do the job?
Here is the code I have so far.
    final Thread builderThread = new Thread("Child Thread " + buildToken) {
        @Override
        public void run() {
            futureTask.run();
        }
    };

    try {
        URL url  = new URL("file:///path to the jar file");
        URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
        classLoader.loadClass("XYZ");
        builderThread.setContextClassLoader(classLoader);
    }

The reason why I want to have different versions of the class is because I want to have different values for the static fields in the class "XYZ".

A: Yes, it is possible, and you're on the right track with URLClassLoader.  The scope of your classloaders will be determined by the scope you want the static fields to have.  For example, if each task or thread should have its own copy of those fields, then each task or thread must have its own classloader.
There are a couple other issues to be aware of.  First, the class you want to load multiple times must not be found on the system classpath.  This is because classloaders exist in a hierarchy, and delegate to their parent before attempting to load a class themselves.  If the system classloader finds the class, it will load it only once, and other classloaders will use the class loaded by the system classloader.
Second, the JVM will treat each loading of the class as a distinct class, despite the fact that they're all identical.  This means that instances of the dynamically loaded class must be confined to the scope of their classloader.  If each task has its own classloader, then instances cannot be passed between tasks.  And obviously you cannot publish instances to the rest of the app, because the rest of the app uses the system classloader, which must not know about the class.  (You can get around this somewhat if the dynamically loaded class has a superclass or superinterface that the system classloader does know about.  Then you can publish the instance as that type.)

A:
The reason why I want to have different versions of the class is because I want to have different values for the static fields in the class "XYZ".

This really seems like a hack to me.  Do you really have no other way to inject different values into this class?
How about passing some sort of Context instance for each thread and convert your class to use the settings from the Context instead of from static fields.  You could also use a ThreadLocal so each thread would get the static field information from there instead.
Loading different versions of the class is going to be extremely hard (if not impossible) to debug.  The only time I've ever heard of folks using multiple class loaders is when you have security concerns (often in a web server environment) and there is a deliberate point to having separation between the web classes and the outer admin classes.


text:
Q: cant run test in vs2012 i am using visual studio 2012. i installed test driven personal beta 2. then i installed gallio bundle 3.2.
however, when i am running a test, it fails. the output says this:
  It looks like you're trying to execute a Gallio/MbUnit unit test.

  For Gallio v3.0.6 build 787 / Gallio v3.1 build 313 or above (recommended):
  Please ensure that the directory containing your 'MbUnit.dll' reference also contains     Gallio's
  test runner files ('MbUnit.dll.tdnet', 'TDNet\Gallio.TDNetRunner.dll', 'Gallio.dll' etc.)

  For earlier versions:
  You need to install Gallio (after TestDriven.Net) using its MSI installer.

  You can find Gallio downloads and support here:
  http://www.gallio.org/

i am not sure what is the problem. for those who are using visual studio 2012, which versions of testdriven and gallio you are using?
UPDATE:
I checked the said dlls if it is in the same folder with MbUnit.dll and they are. what is the problem?? T T


text:
Q: Nette Framework - Route a signal I'm using the kdyby/facebook extension for Facebook authentication, which uses a link to open signal in fbLogin component.
<a n:href="fbLogin-open!">Login using facebook</a>

This results into /?do=fbLogin-open! How could route this link to /login/facebook?

A: In your router (commonly in /app/RouterFactory.php) make a new route.
$router[] = new Route('login/<do>', [
  'presenter' => 'Login',
  'action' => 'fbLogin',
  'do' => array(
    Route::FILTER_TABLE => array(
      'facebook' => 'fbLogin-open'
    )
  )
]);

Now you can use /login/facebook route.


text:
Q: Save and share an image created on website I'm working on this fun tool on a website I'm working on that allows the user to drag images around (using jQuery UI) to create their own character.
You can see the basics of this working here: http://goo.gl/JVXM0
What I'm after, however, is the ability for the user to then share their creation via Facebook and Twitter. Whether once created, it takes a screenshot of an area then they can share their creation... I'm unsure.
Having a look at this, is there any steps or directions I can take to making this happen?
Any help would be so appreciated.
Thanks,
Richard

A: So you're trying to generate an image of the DOM on a page? If so, this would be a good question to start with:
Generate image from DOM elements
Hope this helps!
Cheers, Robin


text:
Q: How can i import a func from another script in odoo? I am trying to import a function from another script in odoo but when i run the odoo its returning me a error. After i refresh website its working okay. But when i run the odoo every time i have this error.
this is error
assert module.startswith('odoo.addons.'), \
AssertionError: Invalid import of custom_addons.invoice_integration.models.model.InheritAccountMove, it should start with 'odoo.addons'. - - -

-- coding: utf-8 --
from .xml_generator import start
from .bifatura_methods import send_invoice
from .numeric_to_string_price import numeric_to_string_price

from odoo import models, fields, api, SUPERUSER_ID, _
from odoo.exceptions import UserError, ValidationError, QWebException
from odoo.addons import decimal_precision as dp

this is how i am using the imports.


text:
Q: Yii ошибка 400, при обращении к внешнему Action Не могу подключить экшн. при обращении к /post/image выдает ошибку 400.
Контроллер:
public function actions()
{
    return array(
        'image' => 'application.controllers.Actions.imAction',
    );
}

сам экшн
class imAction extends CAction
{
    public function run($id)
    {
        echo $id;
    }
}

Делал по документации.

A: В вашем методе run() для этого action значение $id по умолчанию не указано. Из URL вида /post/image ID не извлекается. Поэтому два решения проблемы:

*

*Используйте URL вида /post/image/1 где 1 это ID изображения, например.

*Используете код вида:

   class imAction extends CAction
    {
        public function run($id = null)
        {
            if (is_null($id)){
                // Находим изображение по умолчанию, например первое.
                $image = Image::model()->find();
            } else {
                $image = Image::model()->findByPk($id);
            }
            $this->render('view', compact('image'));
        }
    }

Ну и на вторую версию Yii переходить уже можно свободно.


text:
Q: Stop a request programmatically At work we have every now and then requests that that so long to return that by the time they finish, the frontend (nginx) already killed the connection, so the user will not see the output (either if it's good or bad).
Worst is that the balancer (haproxy) will also kill the connection and then assume that the server is free to handle another request, which means that while the server is still handling the old request a new one comes in and fight for the resources.
Ideally servers should handle only one request at a time to reuse as much as possible the connection thread with the ZEO database, so having two requests running at the same time makes the server even slower and then one of our monitoring systems rightfully restarts plone all together because the dummy prove it sends times out.
So given some logic (maybe reusing Products.LongRequestLogger which we already use) is there a way to tell a thread processing a request to stop doing it?

A: IMHO this is a bad idea to abort a request manually. You somehow interfere with the conflict resolution, which is IMHO not a really good behavior.
I'm running some large plone sites with 200 - 400 authors publishing/modifying 1000 - 3000 objects a day. Usually the load is spread across the day, so also longer request are going to be processed in a reasonable amount time.
For example in the evening, als long requests (30s - 60s) are doing well. no reason to abort them.
In Plone we have some classic long requests, like rename/move a large tree, change permissions, copy a lot of objects. Then usually conflicts happens somewhere in the catalog and aborts the transaction after 3 retries.
By aborting long request you simply remove some features from Plone. You may consider adding a condition to the rename/move/copy actions, so they're no longer there, if you have for example 1000 objects in a container.
What I tried/did so far:

*

*Make long requests shorter (Haha, I now simply said but hard to achieve :-)) --> For example checkout this package's copy/move patch: It does no longer doing a uncatalog/catalog for renaming and moving, instead it updates just the necessary indexes. We achieved a lot with this one.

*Queues: I used for example redis to queue and handle known long actions. Of course you need to know in advance, which is a potential long request, but I guess you already know this in your environment. You may contact the user by email, or some kind of flash message if the request is done.

*Keep catalog as small as possible, delegate everything to solr/elasticsearch (Removing the SearchableText gives you a lot...)

*Hardware: I know sounds silly, but this is often a quick-win. Try to load at least all catalog objects in the RAM. invest a few $ in a fast cpu/ssd (general I/O). This is not the way I like, but it happens and in the year 2016 it can give you some time to solve the long requests problem.
The Future:

*

*You probably saw Jim Fultons "The ZODB" talk at the ploneconf 2016. If you can handle the conflict resolution on the zeoclient and you got the object instead only the state, it's may be possible to implement a better conflict resolution.

Ehhh... First I only made a comment, but I exceeded the characters limit ;-)