text:
Q: Simple React Native Image Game is Lagging.How do i optimize? I am trying to implement a simple img tapping game with react native for learning purposes.I am using this librarys https://github.com/bberak/react-native-game-engine game loop component as a game loop.
What I am trying to do is render some imgs with random locations on screen with small radius then increase it up to a value, after decrease it and finally remove the img from screen (or when tapped) - just like in this game: http://mouseaccuracy.com/
import React, { Component } from "react";
import { AppRegistry, StyleSheet, Dimensions, View,ToastAndroid,TouchableOpacity,Image,Text } from "react-native";

    const { width: WIDTH, height: HEIGHT } = Dimensions.get("window");
    import { GameLoop } from "react-native-game-engine";
    import { Fonts } from '../utils/Fonts';
    import FastImage from 'react-native-fast-image'
    import * as Progress from 'react-native-progress';
    import SwordImage from "../assets/tapfight/sword.png";
    import ShieldImage from "../assets/tapfight/shield.png";

          this.renderSwordOrCircle(circle)
        )

            })

    )

    }

       }

     renderHealth = () =>{
    return(
      <View>
        <View style={{ alignItems:'center' ,position: "absolute", top: 0, left: 0}}>
        <Text style={{fontFamily:Fonts.MainFont,color:'white',fontSize:25}}>{this.playerHealth}</Text>
        <Progress.Bar color='red' progress={this.playerHealth/100} width={100} height={18} />

        </View>
        <View style={{ alignItems:'center',position: "absolute", top: 0, right: 0}}>
        <Text style={{fontFamily:Fonts.MainFont,color:'white',fontSize:25}}>{this.enemyHealth}</Text>
        <Progress.Bar  color='red' progress={this.enemyHealth/100} width={100} height={18} />
         <FastImage resizeMode="contain" style={{width:100,height:100}} source={require('../assets/tapfight/guard_2_head.png')}></FastImage>
        </View>

      </View>

    )

     }

      render() {
        if(this.state.fight==true){
          return (
            <View style={{flex:1,backgroundColor:'transparent'}} >
             <GameLoop style={{flex:1}} onUpdate={this.updateCircle}>
             {this.renderHealth()}
             {this.renderCircles()}
             </GameLoop>
             </View>

          );

        }else{

    return(
      null
    )

        }

      }
    }

    const styles = StyleSheet.create({
      container: {
        flex: 1,
      }
    });

What i am doing is i am generating images every 600 ms on screen and player tries to tap them.The problem is when there is more than 2 images on screen fps drops significantly.Tested in android actual device.I am updating state once at the end of updateCircle function.
Game loop is updateCircle component

A: Your problem is that you're trying to animate a component that is not made for being animated.
I dont know well the FastImage component, but I understand that it purpose is to pre-load images, not animate.
You shoud use Animated.Image for the image, and Animated.timing for managing the animations of Animated.Image


text:
Q: Module not fould Error in angular while making build using AOT? Could you please tell me  why i am getting this error while making build using aot .Build is working fine in without aot .
C:\projects\Books>npm run build --prod

> books@0.0.0 build C:\projects\Books
> ng build --aot

Date: 2018-08-10T06:31:50.446Z
Hash: e0734627de059fdafc90
Time: 15810ms
chunk {main} main.js, main.js.map (main) 113 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 535 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 75.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.54 MB [initial] [rendered]

ERROR in multi ./src/polyfillngs.ts
Module not found: Error: Can't resolve 'C:\projects\Books\src\polyfillngs.ts' in 'C:\projects\Books'
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! books@0.0.0 build: `ng build --aot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the books@0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

any update

redpajama_set_name: RedPajamaStackExchange


text:
Q: Program terminated with signal SIGSEGV, Segmentation fault I got a code snippet  https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/397542/C-solution
I submit it online, and it passed the test. Yet when I want to test on my local machine, I met a problem "Program terminated with signal SIGSEGV, Segmentation fault. " when it reach the next line of breakpoint - return result.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void catRes(char **result, char **phone, char *digits, char *tmp, int nowIndex,
             int *resLen) {

    if (nowIndex == strlen(digits)) {
        tmp[nowIndex] = 0;
        result[(*resLen)] = (char *)malloc(strlen(tmp) + 1);
        strcpy(result[(*resLen)], tmp);
        (*resLen)++;
        return;

    }
    char *phoneData = phone[digits[nowIndex] - '0' - 2];
    for (int i = 0; i < strlen(phoneData); i++) {
        tmp[nowIndex] = phoneData[i];
        catRes(result, phone, digits, tmp, nowIndex + 1, resLen);
    }
}

char ** letterCombinations(char * digits, int* returnSize){
    char *phone[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    char **result = (char **)malloc(sizeof(char *) * 40);
    char tmp[strlen(digits) + 1];
    int resLen = 0;
    if (strlen(digits) == 0) {
        *returnSize = resLen;
        return result;
    }
    catRes(result, phone, digits, tmp, 0, &resLen);
    *returnSize = resLen;// set breakpoint here
    return result;
}

int main(){
    char s[] = {'2', '3'};
    char * digits = s;
    int * returnSize = NULL;
    char ** outcome = letterCombinations(digits, returnSize);
    ...
    return 0;

I check the value of result at the line just before return result, it seems okay. I need some help to show me where the problem is.

A:
"Program terminated with signal SIGSEGV, Segmentation fault. " when it reach the next line of breakpoint - return result.

this is because main call letterCombinations with NULL for returnSize so in :

*returnSize = resLen;// set breakpoint here

you write at the address 0.

Anyway before you have a lot of undefined behaviors accessing non initialized values. For instance in main the array s only contains the characters '2' and '3' and is not terminated by the null character, so strlen(digits) has an undefined behavior reading after s, just do char s[] = "23"; to avoid that.
The result executing your program under valgrind :
pi@raspberrypi:/tmp $ valgrind ./a.out
==6789== Memcheck, a memory error detector
==6789== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6789== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==6789== Command: ./a.out
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x4866210: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x48662D4: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x106B8: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x10498: catRes (c.c:8)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x10570: catRes (c.c:18)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x10498: catRes (c.c:8)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x10570: catRes (c.c:18)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x10498: catRes (c.c:8)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x10540: catRes (c.c:16)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Invalid read of size 4
==6789==    at 0x10540: catRes (c.c:16)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==  Address 0xbd9670d0 is on thread 1's stack
==6789==  24 bytes below stack pointer
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x10570: catRes (c.c:18)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x10498: catRes (c.c:8)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x104AC: catRes (c.c:9)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x48661D8: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x48661DC: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem-v7l.so)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x484762C: malloc (vg_replace_malloc.c:309)
==6789==    by 0x104DB: catRes (c.c:10)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x484BA2C: strcpy (vg_replace_strmem.c:513)
==6789==    by 0x10507: catRes (c.c:11)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Use of uninitialised value of size 4
==6789==    at 0x484BA48: strcpy (vg_replace_strmem.c:513)
==6789==    by 0x10507: catRes (c.c:11)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x484BA80: is_overlap (vg_replace_strmem.c:131)
==6789==    by 0x484BA80: strcpy (vg_replace_strmem.c:513)
==6789==    by 0x10507: catRes (c.c:11)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x484BA88: is_overlap (vg_replace_strmem.c:140)
==6789==    by 0x484BA88: is_overlap (vg_replace_strmem.c:127)
==6789==    by 0x484BA88: strcpy (vg_replace_strmem.c:513)
==6789==    by 0x10507: catRes (c.c:11)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x484BA8C: is_overlap (vg_replace_strmem.c:143)
==6789==    by 0x484BA8C: is_overlap (vg_replace_strmem.c:127)
==6789==    by 0x484BA8C: strcpy (vg_replace_strmem.c:513)
==6789==    by 0x10507: catRes (c.c:11)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Conditional jump or move depends on uninitialised value(s)
==6789==    at 0x484BAA8: strcpy (vg_replace_strmem.c:513)
==6789==    by 0x10507: catRes (c.c:11)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x1059B: catRes (c.c:19)
==6789==    by 0x106D3: letterCombinations (c.c:32)
==6789==    by 0x1072B: main (c.c:42)
==6789==
==6789== Invalid write of size 4
==6789==    at 0x106DC: letterCombinations (c.c:33)
==6789==    by 0x1072B: main (c.c:42)
==6789==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6789==
==6789==
==6789== Process terminating with default action of signal 11 (SIGSEGV)
==6789==  Access not within mapped region at address 0x0
==6789==    at 0x106DC: letterCombinations (c.c:33)
==6789==    by 0x1072B: main (c.c:42)
==6789==  If you believe this happened as a result of a stack
==6789==  overflow in your program's main thread (unlikely but
==6789==  possible), you can try to increase the size of the
==6789==  main thread stack using the --main-stacksize= flag.
==6789==  The main thread stack size used in this run was 8388608.
==6789==
==6789== HEAP SUMMARY:
==6789==     in use at exit: 304 bytes in 37 blocks
==6789==   total heap usage: 37 allocs, 0 frees, 304 bytes allocated
==6789==
==6789== LEAK SUMMARY:
==6789==    definitely lost: 0 bytes in 0 blocks
==6789==    indirectly lost: 0 bytes in 0 blocks
==6789==      possibly lost: 0 bytes in 0 blocks
==6789==    still reachable: 304 bytes in 37 blocks
==6789==         suppressed: 0 bytes in 0 blocks
==6789== Rerun with --leak-check=full to see details of leaked memory
==6789==
==6789== Use --track-origins=yes to see where uninitialised values come from
==6789== For lists of detected and suppressed errors, rerun with: -s
==6789== ERROR SUMMARY: 649 errors from 23 contexts (suppressed: 0 from 0)
Erreur de segmentation
pi@raspberrypi:/tmp $

A: I added the missing } at the end of the main function and started fiddling with your code for a while. At the line
    char ** outcome = letterCombinations(digits, returnSize);

in your main function, you pass returnSize as a NULL. Now shortly before returning from you letterCombinations function, you try to dereference said NULL and this is what causes a SEGFAULT.
Now it seems like you are trying to propagate a value from inside of your letterCombinations function to the outside. One would do this by passing the pointer to a valid variable to the function like so:
int main(){
    char s[] = {'2', '3'};
    char * digits = s;
    int returnSize;
    char ** outcome = letterCombinations(digits, &returnSize);
    return 0;
}

Regarding why it passed the online-test, I cannot answer this as fast as your main question.


text:
Q: Facebook C# SDK Post Image more than once I am uploading or Posting Image to Facebook using Facebook C# SDK but I call this function one time but it uploads the same Image three times or more. It should only upload the Image one time but it does at least three times, I am using 5.4.1 SDK.
Code is:
public void AddCover(string accessToken, string imageName, string folder, string loggedinuserId)
{
    FacebookClient facebookClient = new FacebookClient(accessToken);
    var fbUpl = new Facebook.FacebookMediaObject
    {
        FileName = imageName,
        ContentType = "image/jpg"
    };

    var bytes = System.IO.File.ReadAllBytes(@"F:\Websites\Covers\" + folder + "\\" + imageName);
    fbUpl.SetValue(bytes);

    var photoDetails = new Dictionary<string, object>();
    photoDetails.Add("message", "Facebook Covers");
    photoDetails.Add("image", fbUpl);
    var response = facebookClient.Post(@"/" + loggedinuserId + "/photos", photoDetails);
    var result = (IDictionary<string, object>)response;
    var postedcoverId = result["id"];

}

Am I missing something here? Please see the code and tell me what I am doing wrong.
Thanks


text:
Q: oozie : file and archive tag usage and differences? in oozie schema there are two tags for a java action , File and Archive .
<xs:element name="file" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="archive" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
I am trying to understand usage of them ? I also noticed the both tags are also applied to a MR/pig action .

A: Quick description about File and archive tags :

The file & archive elements make available, to map-reduce jobs, files and archives. If the specified path is relative, it is assumed the file or archiver are within the application directory, in the corresponding sub-path. If the path is absolute, the file or archive it is expected in the given absolute path.
Files specified with the <file> element, will be symbolic links in the home directory of the task.
If a file is a native library (an '.so' or a '.so.#' file), it will be symlinked as and '.so' file in the task running directory, thus available to the task JVM.
To force a symlink for a file on the task running directory, use a '#' followed by the symlink name. For example 'mycat.sh#cat'.

For more information about any oozie related documentation click on link     https://oozie.apache.org/docs/3.3.1/WorkflowFunctionalSpec.html#a3.2_Workflow_Action_Nodes


text:
Q: Fetch vs FetchAll with mysql_query | PHP I am aware that using mysql_query is terrible and the much better / preferred way of doing this is like so:
PREFERRED
$dbquery->fetch(PDO::FETCH_ASSOC))

BUT I HAVE TO
However, working with a legacy system that uses mysql_query ... running into a PHP Fatal error:  Allowed memory size of 536870912 bytes exhausted error when calling mysql_fetch_assoc.
QUESTION
Does msyql_query / mysql_fetch_ have functionality that acts as fetch vs fetchAll?

A: Two things:

*

*Use a loop in PHP and read one row at a time. (not needed if you use #2)

*Use the LIMIT {start row},{number of rows} clause in your SQL statement for pagination.


text:
Q: Image in one section of website takes up the entire page I am redesigning a website for fun and I was messing around with some JQuery and some CSS effects. When you click on an arrow, everything on the page gets pushed down and a video comes up. The issues is I'm trying to create a section for an image. However, changing the background-size of the image to cover ends up making the entire image take up the screen. If I manually change the size of the image then the image is distorted.
Here is the HTML:

Click the arrow to view Kai Greene's Scar Story

 <button = class="btn btn-danger">Sign up for our News Letter</button>

View other products

Here is the CSS:
.stuff{
  margin-top: 100px;
  background-soze: cover;
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 0;
}

You can view the entire code on codepen: http://codepen.io/sibraza/pen/wWgqBO

A: You would probably have to change the size of the image manually. Setting the width to a certain value and setting height to auto or visa versa should not distort the image. So setting either width or height to auto shouldn't distort the image.
http://www.w3schools.com/css/css_rwd_images.asp is a helpful resource for image sizing in CSS

A: Instead of background-size, use width or height to set your desired image size. You can also use object-fit: cover to keep the image aspect ratio no matter what size you set. Its like doing a "cropping" effect.


text:
Q: puppet and array loop Hi I'd like some help on how to code this in erb in puppet, basically I have
server::actionhost { 'details':
    servername[ 'felix', 'washington', ],
    ipa [ '192.168.43.5', '192.168.43.11', ],
    enviro [ 'prod', 'uat', ],
}

I now want to print this out to a file with each respective element from each array in one line, i.e the output from the template file in my class should be like:
felix 192.168.43.5 prod
washington 192.168.43.11 uat

When I attempted this I wrote the following code in my template file:
<% servername.each do |name| -%>
    <% ipa.each do |ip| -%>
        <% enviro.each do |env| -%>
            <%= name %> <%= ip %> <%= env %>
        <% end -%>
    <% end -%>
<% end -%>

but what I get is multiple recursive prints instead of a print from each array and then move to the next array element.
I'm thinking of a for loop but unsure how to get the array length as the argument to the for loop, Would appreciate some guidance on how to accomplish the correct output?
I tried doing something like this but it fails with errors on the puppet run?
<% for id in servername.length %>
    <%= servername[id] %> <%= ipa[id] %> <%= enviro[id] %>
<% end -%>

Thanks Dan

A: Any particular reason you need to use that data structure?  That will get unreadable very quickly, and would be very easy to break things by accidentally adding or removing an element from one of the arrays and not the others.  How about something like this instead?
$servers = [
  {
    name => 'felix',
    ip   => '192.168.43.5',
    env  => 'prod',
  },
  {
    name => 'washington',
    ip   => '192.168.43.11',
    env  => 'uat',
  },
]

Then it's much simpler to work with in the erb:
<% servers.each do |server| -%>
  <%= server['name'] %> <%= server['ip'] %> <%= server['env'] %>
<% end -%>

But, if you're stuck with your current data structure, then this should do it..
<% (1..servername.length).each do |i| -%>

A: Shane Madden's answer is great but for I think there is a '@' missing:
instead of
<% servers.each do |server| -%>

one should use
<% @servers.each do |server| -%>

can someone with higher reputation please comment that in the original answer and/or acknowledge that so my "answer" could be deleted
This is also how it is documented on puppet cookbook third edition
Thanks,
Matt


text:
Q: Why my query return repeating records? I have 3 tables.
Complaints, Categories, SubCategories

Primary keys of Categories is foreign in Complaints table i.e. Cat_ID
Primary key of Categories table is foreign in SubCategories i.e. Category_ID
When I join Complaints with Categories then it works fine i.e. unique rows but when I join with SubCategories then it repeats each record. I have tried LEFT, RIGHT, INNER but nothing works.
Select *
        From dbo.Complaints Comp
        inner Join Categories Cat
        ON cat.CategoryID= Comp.Cat_ID
        inner join SubCategories scat
        ON scat.Category_ID= cat.CategoryID

SubCategories:

Categories:

Output:

Complaints table:

A: Did you tried to check if the rows are really unique? I've worked once with tables with several rows and I've got something similar to your issue because the rows were not unique. It was a column that was different

A: I think you want a left join to subcategory and to use the subcategory information contained in the complaints table:
SELECT *
FROM dbo.Complaints Comp
INNER JOIN Categories Cat
    ON cat.CategoryID = Comp.Cat_ID
LEFT JOIN SubCategories scat
    ON scat.Category_ID = cat.CategoryID
        AND scat.SubCategoryID = Comp.SubCat_ID

(I'd also recommend using nulls rather than 0s to represent no subcategory, which is what I assume the 0s stand for)

A: you need to insert SubCategoryId in Complaints table then it will work as your desire out put. And base on this you need to change your query
Select *
        From dbo.Complaints Comp
        inner join SubCategories scat
        ON scat.SubCategoryId= Comp.SubCategoryId
        inner Join Categories Cat
        ON cat.CategoryID= scat.CategoryID

A: If you don't have subcategory ID in the Complaints table then there is no any way to identify which subcategory should be used. So you get all subcategories for each category. And it is the source of duplicates.
Add SubCat_Id to the Complaints table and join it with Subcategories on this field.

A: The reason is that you have 8 subcategories related  to category = 1  so when you join the category obtained  by  Complaints  (value = 1) to subcategories  you join all the 8  possible values
in this case  if you don't any columns form subcategories in select  the simplest solution is the use of distinct clause   eg:
Select DISTINCT Comp.*, Cat.*
    From dbo.Complaints Comp
    inner Join Categories Cat
    ON cat.CategoryID= Comp.Cat_ID
    inner join SubCategories scat
    ON scat.Category_ID= cat.CategoryID

Otherwsie you use also column for subcategories  as with select *  .. the row are not exactly repated  because you have (at least) the different subcategory related  to join with category 1
try using explicit column name (and not *)
Select DISTINCT Comp.complainID
   , Comp.Mode_ID
   , Comp.Cat_Id
   , ...
   , Cat.CategoryID
   , Cat.Name
    From dbo.Complaints Comp
    inner Join Categories Cat
    ON cat.CategoryID= Comp.Cat_ID
    inner join SubCategories scat
    ON scat.Category_ID= cat.CategoryID


text:
Q: In PostgreSQL can trigger know which function invoked it? I have a trigger as follows:
CREATE TRIGGER A
  AFTER INSERT OR UPDATE OR DELETE
  ON TableA
  FOR EACH ROW
  EXECUTE PROCEDURE func1();

and the trigger function:
CREATE OR REPLACE FUNCTION func1()
  RETURNS trigger AS
$BODY$
begin
    insert into tableinfo values(...);
    return new;
end ;
$BODY$
  LANGUAGE plpgsql VOLATILE

Now I have many functions that insert/update/delete from TableA.
Is there a way in the trigger to know which function invoke it?
something like:
CREATE OR REPLACE FUNCTION func1()
  RETURNS trigger AS
$BODY$
begin
    if functionname='insertnewrecord' or functionname='deleterecord'  then
        insert into tableinfo values(...);
         return new;
    else
       return NULL;
    end if;
end ;
$BODY$
  LANGUAGE plpgsql VOLATILE

is it doable? can I limit the trigger to do something based on which function invoke it?

A: You can get information from call stack using get diagnostics as described here.
Something like that:
CREATE OR REPLACE FUNCTION func1()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
declare
  stack text;
begin
  get diagnostics stack = pg_context;
  raise notice E'--- Call Stack ---\n%',stack;
  ...
return new;
end;
$function$;

Test function:
CREATE OR REPLACE FUNCTION insertnewrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  insert into TableA values(...);
end;
$function$

And result:
select insertnewrecord();
NOTICE:  --- Call Stack ---
PL/pgSQL function func1() line 6 at GET DIAGNOSTICS
SQL statement "insert into tbl values(10)"
PL/pgSQL function insertnewrecord() line 3 at SQL statement
CONTEXT:  SQL statement "insert into tbl values(10)"
PL/pgSQL function insertnewrecord() line 3 at SQL statement
 insertnewrecord
-----------------

(1 row)

So you can analyze stack in func1() and make decisions based on it, though it's not very handy.


text:
Q: Is there a standard way to create dynamic formsets in Django? I have created formsets in Django, and am able to render them in templates. The issue is that there does not seem to be a "standard" way to Add/Delete forms from formsets in the templates.
I have tried "Django-dynamic-formsets" but this seems like a hack of a way to achieve something that is built into the Django admin.
So is there a Django way to have an "Add" and "Delete" button on a template for adding and deleting forms from a formset? If it matters, I'm using inline formsets Django 2.2


text:
Q: How to update a separate variable and add it to another variable during each loop iteration? (running calculator iteration problem) I am trying to build a running calculator. After every loop, lap should be updated with "extra" and summed together with what I have ran already.

ran = 2.45 lap = .45 extra = 0.05

The formula is this:

2.45 + .45 = first loop.
2.90 + .5 = second loop.
3.4 + .55 = third loop.
3.95 + .60 = fourth loop.
4.55 + .65 = fifth loop.

During each iteration of the for loop, the "ran" variable should add lap and extra.
lap should update lap + extra.
extra should remain constant.
this is the code I have so far:
ran = 2.45;
let lap = .45
const extra = .05;

var arra = [];
var sum = 0;

 for (let i = 1; i <=5; i++) {

   ran+= lap;

   arra.push(Math.round(ran*100)/100)

   };

console.log(arra)

All I can manage to do so far is add ran to lap. What I need to do instead, is update lap during each loop, while maintaining extra as a constant and summing this up with ran.

loop 1 lap = .45 loop2 lap = .5 loop3 lap = .55 loop4 lap = .6
loop5 lap = .65

A: You could increment the loop value with extra for each loop.

let
    ran = 2.45,
    lap = .45,
    extra = 0.5;

for (let i = 0; i < 5; i++) {
    ran += lap;
    lap += extra;
    console.log(ran.toFixed(2));
}


text:
Q: Integral with Convolution and Homomorphism Let $\gamma \colon (\mathbb{R}_+,+) \to (\mathbb{C}^\times,\cdot) $ a continous Homomorphism such that $\|\gamma\|_\infty \le 1$. I want to prove that for $ f,g \in L^1(\mathbb{R}_+) $:
$$  \int_{\mathbb{R}_+} (f \ast g ) (x) \gamma(x) \mathrm{d}x = \int_{0}^{\infty} g(y) \gamma(y) \mathrm{d}x \int_{0}^{\infty} f(x) \gamma(x) \mathrm{d}y $$.
My try:
\begin{align}
 \int_{\mathbb{R}_+} ( f \ast g ) (x) \gamma(x) \mathrm{d}x
 &= \int_{0}^{\infty} \gamma(x) \int_{0}^{x} f(x-y)g(y) \mathrm{d}y \mathrm{d}x \\
 &= \int_{0}^{\infty} \gamma(y) \int_{0}^{x} f(x-y)g(y) \gamma(x-y) \mathrm{d}y \mathrm{d}x \\
 &= \int_{0}^{\infty} \int_{0}^{\infty } f(x-y) g(y) \gamma(x-y) \gamma(y) 1_{ [ 0,x ] } (y) \mathrm{d}y \mathrm{d}x \\
 &= \int_{0}^{\infty} \int_{0}^{\infty } f(x-y) g(y) \gamma(x-y) \gamma(y) 1_{ [ 0,x ] } (y) \mathrm{d}x \mathrm{d}y \\
 &= \int_{0}^{\infty} \int_{0}^{\infty } f(x-y) g(y) \gamma(x-y) \gamma(y) \mathrm{d}x \mathrm{d}y \\
 &= \int_{0}^{\infty}  g(y) \gamma(y) \int_{0}^{\infty } f(x-y) \gamma(x-y)  \mathrm{d}x \mathrm{d}y \\
 &= \int_{0}^{\infty} g(y) \gamma(y) \left[ \int_{0}^{\infty} f(x-y) \gamma(x-y) \mathrm{d}x \right] \mathrm{d}y \\
 &= \int_{0}^{\infty} g(y) \gamma(y) \left[ \int_{0}^{\infty} f(x) \gamma(x) \mathrm{d}x \right] \mathrm{d}y \\
 &= \int_{0}^{\infty} g(y) \gamma(y) \mathrm{d}x \int_{0}^{\infty} f(x) \gamma(x) \mathrm{d}y
 \end{align}
Explanation where needed:
Line 2: $\gamma(x-y)\gamma(y) = \gamma(x)$ if $x-y \ge 0$
Line 3: Transform integral limits into characteristic function
Line 4: Fubini
Line 5: The Integral over this function results into $1_{[0,\infty)}(x)$. This is a step where i do not know any rigor way to prove this.
Line 8: Extending $f $ and $\gamma$ by zero on $(-\infty,0)$ and due to the translation invariance of the lebesgue measure this holds.

A: I now know how to better prove the step in line 5:
It is $1_{[0,x]}(y)$ with $0 \le y \le \infty$ and $x \ge 0$. This is equivalent to $1_{[0,\infty)}(x-y)$ and $0 \le y < \infty$. So the step 5 should look like in the following calculation:
\begin{align}
 \int_{\mathbb{R}_+} ( f \ast g ) (x) \gamma(x) \mathrm{d}x
 &= \int_{0}^{\infty} \gamma(x) \int_{0}^{x} f(x-y)g(y) \mathrm{d}y \mathrm{d}x \\
 &= \int_{0}^{\infty} \gamma(y) \int_{0}^{x} f(x-y)g(y) \gamma(x-y) \mathrm{d}y \mathrm{d}x \\
 &= \int_{0}^{\infty} \int_{0}^{\infty } f(x-y) g(y) \gamma(x-y) \gamma(y) 1_{ [ 0,x ] } (y) \mathrm{d}y \mathrm{d}x \\
 &= \int_{0}^{\infty} \int_{0}^{\infty } f(x-y) g(y) \gamma(x-y) \gamma(y) 1_{ [ 0,x ] } (y) \mathrm{d}x \mathrm{d}y \\
 &= \int_{0}^{\infty} \int_{0}^{\infty } f(x-y) g(y) \gamma(x-y) \gamma(y) 1_{[0,\infty)}(x-y) \mathrm{d}x \mathrm{d}y \\
 &= \int_{0}^{\infty}  g(y) \gamma(y) \int_{0}^{\infty } f(x-y) \gamma(x-y) 1_{[0,\infty)}(x-y)  \mathrm{d}x \mathrm{d}y \\
 &= \int_{0}^{\infty} g(y) \gamma(y) \left[ \int_{0}^{\infty} f(x-y) \gamma(x-y)  \mathrm{d}x \right] \mathrm{d}y \\
 &= \int_{0}^{\infty} g(y) \gamma(y) \left[ \int_{0}^{\infty} f(x) \gamma(x) \mathrm{d}x \right] \mathrm{d}y \\
 &= \int_{0}^{\infty} g(y) \gamma(y) \mathrm{d}x \int_{0}^{\infty} f(x) \gamma(x) \mathrm{d}y
 \end{align}
Where in line 7 i can remove $1_{[0,\infty)}(x-y)$ due to the fact that it already holds $f(x-y) = 0 $ for $x-y<0$.


text:
Q: Fast exponentiation when only first k digits are required? This is actually for a programming contest, but I've tried really hard and haven't got even the faintest clue how to do this.
Find the first and last k digits of nm where n and m can be very large ~ 10^9.
For the last k digits I implemented modular exponentiation.
For the first k I thought of using the binomial theorem upto certain powers but that involves quite a lot of computation for factorials and I'm not sure how to find an optimal point at which n^m can be expanded as (x+y)m.
So is there any known method to find the first k digits without performing the entire calculation?
Update 1 <= k <= 9 and k will always be <= digits in nm

A: not sure, but the identity nm = exp10(m log10(n)) = exp(q (m log(n)/q)) where q = log(10) comes to mind, along with the fact that the first K digits of exp10(x) = the first K digits of exp10(frac(x)) where frac(x) = the fractional part of x = x - floor(x).
To be more explicit: the first K digits of nm are the first K digits of its mantissa = exp(frac(m log(n)/q) * q), where q = log(10).
Or you could even go further in this accounting exercise, and use exp((frac(m log(n)/q)-0.5) * q) * sqrt(10), which also has the same mantissa (+ hence same first K digits) so that the argument of the exp() function is centered around 0 (and between +/- 0.5 log 10 = 1.151) for speedy convergence.
(Some examples: suppose you wanted the first 5 digits of 2100. This equals the first 5 digits of exp((frac(100 log(2)/q)-0.5)*q)*sqrt(10) = 1.267650600228226. The actual value of 2100 is 1.267650600228229e+030 according to MATLAB, I don't have a bignum library handy. For the mantissa of 21,000,000,000 I get 4.612976044195602 but I don't really have a way of checking.... There's a page on Mersenne primes where someone's already done the hard work; 220996011-1 = 125,976,895,450... and my formula gives 1.259768950493908 calculated in MATLAB which fails after the 9th digit.)
I might use Taylor series (for exp and log, not for nm) along with their error bounds, and keep adding terms until the error bounds drop below the first K digits. (normally I don't use Taylor series for function approximation -- their error is optimized to be most accurate around a single point, rather than over a desired interval -- but they do have the advantage that they're mathematically simple, and you can increased accuracy to arbitrary precision simply by adding additional terms)
For logarithms I'd use whatever your favorite approximation is.

A: Well. We want to calculate  and to  get only n first digits.
Calculate  by the following iterations:

You have .
Calcluate each  not exactly.
The thing is that the relative error of  is less
than n times relative error of a.
You want to get final relative error  less than .
Thus relative error on each step may be .
Remove last digits at each step.
For example, a=2, b=16, n=1. Final relative error is 10^{-n} = 0,1.
Relative error on each step is 0,1/16 > 0,001.
Thus 3 digits is important on each step.
If n = 2, you must save 4 digits.
2 (1), 4 (2), 8 (3), 16 (4), 32 (5), 64 (6), 128 (7), 256 (8), 512 (9), 1024 (10) --> 102,
204 (11), 408 (12), 816 (13), 1632 (14) -> 163, 326 (15), 652 (16).
Answer: 6.
This algorithm has a compexity of O(b). But it is easy to change it to get
O(log b)

A: Suppose you truncate at each step? Not sure how accurate this would be, but, e.g., take
n=11
m=some large number
and you want the first 2 digits.
recursively:

*

*11 x 11 -> 121, truncate -> 12 (1 truncation or rounding)
then take truncated value and raise again

*12 x 11 -> 132  truncate -> 13
repeat,

*(132 truncated ) x 11 -> 143.
...
and finally add #0's equivalent to the number of truncations you've done.

A: Have you taken a look at exponentiation by squaring? You might be able to modify one of the methods such that you only compute what's necessary.
In my last algorithms class we had to implement something similar to what you're doing and I vaguely remember that page being useful.


text:
Q: What does pre-damped mean in the pre-damped switched-inductor piezoelectric energy-harvesting charger There is a paper from the IEEE,title:Optimally Pre-Damped Switched-Inductor Piezoelectric Energy-Harvesting Charger,and the author show two kind of pre-damped: symmetry and asymmetry,shown as fig 1 and fig 2.

And now i want to ask what does "pre-damped" mean in his pre-damped switched-inductor piezoelectric energy-harvesting charger?i know the damp  means that any vibration system in vibration, due to external effects or the system itself is inherently caused by the gradual decrease in vibration amplitude characteristics,but what is "pre"-damp ?

A: Simple answer:
It means adding electrical alternating LC tuned DC switched voltage capacitance to a mechanical induced capacitor (piezo) oscillating square wave current pump that generates only 33uW and boost it > 700% in power.
A really long answer
This is an electro-mechanical dynamic impedance matching scheme. It boosts the energy harvesting from 33uW by 780% from gains in efficent energy conversion with 1 Ω ESR at V<20V. THe voltage gain <10 is stored energy but the impedance matching improves coupling efficiency. This matching is performed by the switched partly resonant LC capacitive DC voltage applied returned as current from the end-stop cantelever "jerk" on the crystal. (Jerk is a unit of measure for rate of change of acceleration)
REF

This PZT piezo-electric energy harvesting chip that is a switched charge current source in a vibration mode with end stops that applies small square waves.  By synchronously applying a pre-charge voltage, the PZT can dump  more power thru the action of stepped current.
Essentially it means a precharged capacitance voltage is applied to the piezo cantelever transducer so that greater mechanical piezo energy transfer efficiency can be performed.  This is based on matching the impedance of a switched discrete capacitance voltage ( and some inductive current) to a mechanically excited alternating Norton current source and thus mechanical energy is absorbed by the dwitched electrical capacitance.
When this occurs,  pre-charging the crystal C(pz) to some applied Vpd(pre-damp v) between half cycles allows both end stops of the cantelever mounting to have higher DC voltage charges switched.  In other words Vpd raises the damping force against which motion supplies power, which in turn allows more energy to be harvested.
Basically it is improving energy transfer by matching the impedance of the mechanical alternating step force with an electrical alternating step load impedance to maximize the rms P(pzt) = current * square wave voltage by synchronous impedance matching to a square wave mechanical-to electrical current source.
So a switched Vpd cap load collects more energy from a "pico-bang-bang" ( my terminology) alternating cantelever PZT current source.  THis must be matched and optimized as component ESR*I^2 losses rise exponentially with gains from pre-dampening voltages applied.
What I'm not sure about yet is the optimal LC resonant frequency vs the mechanical vibration range of frequencies and the ratio of Cpc/Cpz.  THe other thing not stated is how this affects the longevity or reliablity of the crystal.
Anecdotal
As I know from previous car experience, if replacement shock absorbers are too stiff, the McPherson strut popped thru the hood (bonnet) of my Audi CD5000 Turbo on a washboard road.  Exceptionally "smooth" but self-destructive.

A: The harder  i press the PZT,the stronger electrical damping forece PZT produce,that is , the current source produce the stronger current ,and before we want to know what is predamp,we have to know there are a equivalent current source and  capacitor in the PZT equivalent circuit.
"No predamp" means the current source charge the equivalent capacitor,just simple!
"predamp" means the outside circuit charge this equivalent capacitor first,then the current source charge the equivalent capacitor to the higher or lower voltage.


text:
Q: Angular custom filtering by condition in HTML doesn't work I'm pretty new in angular, so my question may looks simple or stupid, but I didn't found any solution.
I have a collection in my controller (for example, a collection of integers) and I want to filter it and take items for which condition is true.
At first I tried this:

{{myCollection.find(item => item === 2)}}

and it didn't work.
Then I found another approach (which one I don't like because I will always have only single element to show and there is no need in peretition):

{{item}}

And it also doesn't work.
Here is JSBin with my efforts: http://jsbin.com/govovocace/1/edit?html,js,output
Is there any possible solution of my problem? Calculating the required field in controller and passing it to the view doesn't suit me (unfortunately).

A: You can define a filter function in your controller like so:
$scope.filterFn = function(val){
    return val === 2;
};

And then use it in your template like so:

{{item}}

Tha said, this is equivalent to just filtering the array to begin with, so i'm not sure if this meets your needs or not. If you have a particular use case this doesn't suit let me know in the comments.

A: You had syntactical mistake. You should not be mentioning any object inside filter as you're directly filtering actual object which you are looping on. The last option true is because we are going to perform exact check.
HTML

{{item}}

Demo Plunkr

A: i would have done something like this
.controller('SomeController',function($scope){

 // get the list from somewhere
  $scope.list  = [] // some array for instance

  $scope.dataList = list.filter(function(i){
     return i.someVal==list.someVal; // condition that satisfy your req
  });

});

and now use it in view as

   {{item}}

if your condition will return only one result then you can do
$scope.dataList = list.filter(function(i){
         return i.someVal==list.someVal; // condition that satisfy your req
      })[0];


text:
Q: Javax: ListView: load controllers by selecting item in ListView I have view and there is a ListView and a Pane. I want to add Controllers as items of the ListView, and when I click on one of the listView's element, set the Pane's content to its the controllers content,
For example I have FruitsController and VegetablesController and of course the corresponding .fxml for each controller, and when I click on the first element set the Panes element a tableView of fruits, otherwise a tableview with vegetables. I tried whith <fx:include source=Fruits.fxml> and so on but I don't know how to switch the content, and how to display a custom name as element name in the ListView. So do you have any idea?
Edit:
I found partial solutions here How can I Populate a ListView in JavaFX using Custom Objects? and here JavaFX - ListView Item with an Image Button
But the problem is still there I don't know how and where put the <fx:include> tag, to load it when I click on an item.

A: You can just register a listener with the list view's selection model, and load the corresponding view when the selection changes.
E.g., supposing you have
public class View {

    private final String name ;
    private final Class<?> controllerType ;

    // You could assume that the resource is name+".fxml" if you want to rely on conventions like that
    // That would eliminate the need for another field here, but would prevent
    // e.g. names with whitespace etc.
    private final String resource ;

    public View(String name, Class<?> controllerType, String resource) {
        this.name = name ;
        this.controllerType = controllerType ;
        this.resource = resource ;
    }

    public String getName() {
        return name ;
    }

    public Class<?> getControllerType() {
        return controllerType ;
    }

    public String getResource() {
        return resource ;
    }

    @Override
    public String toString() {
        return name ;
    }
}

Then in FXML:
<!-- imports, namespaces omitted -->

<BorderPane fx:id="root" fx:controller="app.MainController" ... >
    <left>
        <ListView fx:id="selector"/>
    </left>
</BorderPane>

and in the controller:
package app ;

public class MainController {

    @FXML
    private BorderPane root ;

    @FXML
    private ListView<View> selector ;

    public void initialize() {
        selector.getSelectionModel().selectedItemProperty().addListener((obs, oldView, newView) -> {
            if (newView == null) {
                root.setCenter(null);
            } else {
                // assumes each FXML is in the same package as its controller
                // (which I think is a nice way to organize things)
                FXMLLoader loader = new FXMLLoader(newView.getControllerType().getResource(newView.getResource()));
                try {
                    root.setCenter(loader.load());
                } catch (IOException exc) {
                    // unrecoverable...
                    throw new UncheckedIOException(exc);
                }
            }
        });

        selector.getItems().addAll(
            new View("Fruits", FruitsController.class, "Fruits.fxml"),
            new View("Vegetables", VegetablesController.class, "Vegetables.fxml")
        );
    }
}

If all the controllers have common functionality, you can make them implement a common interface (ProductsController, for example), and retrieve the current controller from the loader with ProductsController currentController = loader.getController(); after loading the new FXML. (You can also change the type of controllerType in View to Class<? extends ProductsController> in this case.)


text:
Q: Regex to match pattern only if a string is not present in pattern Stuck with finding a regex for a typical scenario. Not sure how this can be achieved in regex.
Regex ---> (?is)[^:]\/\/
Payload ---> Regexp,test//check//last://
Matches ---> t// and k//

Issue : I need to modify the above regex to ignore match for // only if the test string starts with "data:image"(as in below payload).
Payload ---> data:image/png;base64,test//check//last://

In this above case it should not match for my criteria (match for //) since the test string starts with "data:image"
Suggest a way to modify the above regex, so that we can handle this case.

A: If I understood your question correctly, you want the regex to match your pattern // and the preceding character which shouldn't be :. And the matches should only be done if the test string does not start with data:image.
/(?!data:image)(?:.*?)([^:]\/\/)/giy

*

*(?!data:image) ensures that the string doesn't start with data:image

*(?:.*?) non-capturing non-greedy match

*([^:]\/\/) your match // and the preceding character which shouldn't be :

*/y to denote a sticky match so that it matches only from where a previous match ended. That way, for strings starting with data:image it won't match anything

var regex = /(?!data:image)(?:.*?)([^:]\/\/)/giy

// This shouldn't match since test string starts with data:image
var payload = "data:image/png;base64,test//check//last://";
var match = regex.exec(payload);
console.log(match);

// This should find matches since payload doesn't start with data:image
var anotherpayload = "Regexp,test//check//last://";
match = regex.exec(anotherpayload);
while (match != null) {
  // Accessing group 1
  console.log(match[1])
  match = regex.exec(anotherpayload);
}


text:
Q: WebAPI service design I'm pretty comfortable with how Asp.NET MVC controllers worked when designing services.
However the new WebAPI controllers. how am I supposed to design my services here?
Lets say we have 3 different ways to list e.g. Users.
Get 10 latest , Get all, Get inactive or whatever.
none of these might need parameters. so how would you solve this in WebAPI
IEnumerable<User> Get10Latest()
IEnumerable<User> GetAll()
IEnumerable<User> GetInactive()

That won't work since they have the same param signature.
So what is the correct way to design this here?

A: You can support multiple methods in one controller for a single HTTP method by using the action parameter.
E.g.
public class UsersController : ApiController
{

    [ActionName("All")]
    public HttpResponseMessage GetAll()
    {
        return new HttpResponseMessage();
    }

    [ActionName("MostIQ")]
    public HttpResponseMessage GetMostIQ()
    {
        return new HttpResponseMessage();
    }

    [ActionName("TenLatest")]
    public HttpResponseMessage GetTenLatest()
    {
        return new HttpResponseMessage();
    }

}

Unfortunately, I have not found a way to get a single controller to handle both with and without the action at the same time.
e.g.
public class UsersController : ApiController
{

    [ActionName("")]  // Removing this attribute doesn't help
    public HttpResponseMessage Get()
    {
        return new HttpResponseMessage();
    }

    [ActionName("All")]
    public HttpResponseMessage GetAll()
    {
        return new HttpResponseMessage();
    }

    [ActionName("MostIQ")]
    public HttpResponseMessage GetMostIQ()
    {
        return new HttpResponseMessage();
    }

    [ActionName("TenLatest")]
    public HttpResponseMessage GetTenLatest()
    {
        return new HttpResponseMessage();
    }

}

Being able to use a single controller for a collection resource and all of its subsets would be nice.

A: Someone will probably be along and wrap me on the knuckles for this, but you need to configure your routing to handle the Gets. This is how I got it working with the above operations:
config.Routes.MapHttpRoute(
            name: "CustomApi",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { id = RouteParameter.Optional }
        );

So now your requests are mapped to the correct controller -> action via the route template. Note that the new route needs to be registered first in WebApiConfig.cs. If you keep the old, default one.
EDIT
Having re-read the question I realize I wasn't quite answering the design question. I would think that one way to go about it, from a REST perspective, would be to use a separate resource to expose the proper collections (Get10Latest for example) since I assume that there is a business reason for exposing that exact subset of data through the service. In that case you'd expose that resource though a single Get in its own Controller (if that is the desired behaviour).

A: Well why not have urls like this:
GET /users
GET /users/latest
GET /users/inactive

Using routing you could route them to
public classs UserController : ApiController
{
    public IEnumerable<User> Get(string mode)
    {
        // mode is in routing restricted to be either empty, latest, or inactive
     }
 }

Otherwise use multiple controllers. The use of action names in Web API is kind of a wrong way to about it.


text:
Q: AngularJS: triggering a controller function when a variable changes into a directive I have a directive to do 2 things: (i) it manages the visualization of some tabs in HTML, (ii) it $watches the value of the object myObj in session storage and saves this object in a variable called myData. Here there is the code:
.directive('panelManager', function(){
    return {
        restrict: 'E',
        templateUrl: 'foo.html',

        controller: ['$scope', '$window',  function($scope, $window) {
            pn = this;
            pn.tab = 1; // init

            this.selectTab = function(setTab) {
                pn.tab = setTab;
            };

            this.isSelected = function(checkTab) {
                return pn.tab === checkTab;
            };

            $scope.$watch(function () {
                return $window.sessionStorage.getItem('myObj');
            }, function (value) {
                pn.myData = JSON.parse(value);
            });
        }],
        controllerAs: 'panels'
    };
})

I have a controller to call a WS passing a property foo of the aforementioned myData, every time it changes. Here it is:
.controller('MyDataController', ['$http', function($http) {

    pdc = this;
    pdc.myResultset = [];

    pdc.getDetails = function(val) {
        return $http.get("myUrl"+val+"/").then(function(response){
              pdc.myResultset= response.data;
        });
    };
}]);

Is there a way to trigger getDetails in that controller and to pass val = MyData.foo to it every time myData changes value?
In this way, I could store in myResultset the current resultset of the WS and assign it to local scope.

A: You can emit from your directive, but you need the $rootScope in the associated controller. So the declaration becomes:
controller: ['$rootScope', '$scope', '$window',  function($rootScope, $scope, $window) {

Then, you could do something like this:
$scope.$watch(function () {
    return $window.sessionStorage.getItem('myObj');
}, function (value) {
    pn.myData = JSON.parse(value);
    $rootScope.$broadcast('valueChanged', pn.myData);
});

And in your controller:
.controller('MyDataController', ['$http', '$scope', function($http, $scope) {

    pdc = this;
    pdc.myResultset = [];

    pdc.getDetails = function(val) {
        return $http.get("myUrl"+val+"/").then(function(response){
            pdc.myResultset= response.data;
        });
    };

    $scope.$on('valueChanged', function(event, data) {
        pdc.getDetails(data.foo); //pass data.foo to the function
    });
}]);


text:
Q: Synchronous NSURLConnection Threading on iPhone I started out using asynchronism but to get the returned data became a hassle. I then began using class methods which, I believe, ruled out the possibility of using the delegate methods. So I kept with the synchronous, knowing that this would be an issue but didn't think I would have this much difficulty with a solution. What is the best way to retrieve data whilst keeping the UI interact-able?

A: The NSURLConnection synchronous call should be able to be stuck in a background thread, but I strongly recommend you deal with the 'hassle', and do it The Right Way™. The best way to retrieve data whilst keeping the UI interactive is to use NSURLConnection's asynchronous methods.

A: Synchronous NSURLConnections work great inside of an NSOperation - and because you are using them synchronously, an NSOperationQueue handed the NSOperations will automatically use a background thread to run them (you have to do extra work otherwise).
Having URL connections operate in a background thread is the key to keeping the UI responsive, something that an asynchronous NSURLOperation does not do by default (look at what thread the data callbacks all come in on).
Sometimes you want to handle data incoming (like if you have a progress bar) and in those cases asynchronous URL connections are better, they can still be in an NSOperation.
Because this is frustrating you, you may well want to take a look at the alternative ASIHTTPRequest library, also based on NSOperation but it seems like it may make some of this less painful for you (they have good example code):
http://allseeing-i.com/ASIHTTPRequest/

A: Out of interest what issues where you having with getting the data? I found using async NSURLConnection and a NSNotificaion when it had finished to be quite a handy solution.
In the class where you need the data (I normally put it in the init method)
-(id)init{
    ... object setup ...
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView) name:@"ScanCompleted" object:nil];
}

updateView is the method to be called when the connection has finished receiving data
in the NSURLConnection
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

//Notify that we are finished
[[NSNotificationCenter defaultCenter] postNotificationName:soapAction object:self];

}

This works for me quite nicely - the NSURLConnection is threaded so the UI doesn't lock up and it gets updated when the data has finished downloading.


text:
Q: Python curses window flickering when resizing terminal This is my first post on stack overflow so I hope I'm doing it properly.
I am currently working on a Terminal User Interface for python applications. I know that there are many ready-to-use libraries such as npyscreen out there, but I wantend to create one as programming excercice. In particular, I wanted to to play with some architectural patterns to learn them.
All that said, I'm currently facing several problems with python curses library, that I'm using as low level interface to the terminal.
The problems arise when I try to resize my terminal. As you can see from the code (see below), I handle the terminal resizing in the main loop, invoking the getmaxyx()() method of my curses window and redrawing what is on the screen accordingly.
The problem is that the screen seems to flicker when I try to resize the terminal.
Moreover, my "curses application" works fine on MacOS but totally crashes on windows (even after installing windows curses).
To handle that I tried to re-write the low-level interfice by using the blessed library. It solved the windows crashing problem, but the flickering still remains.
I can not figure out what the problem is.
Fore those wishing to help me, here follows the github page of the project: Terminal GUI on GitHub
Thank you in advance.

A: With curses, there's (at least) 3 things to look for:

*

*ncurses can handle SIGWINCH (PDCurses may not)

*some Python configurations interfere with ncurses receiving SIGWINCH.  If your program never receives KEY_RESIZE (which it's not checking for...), then it's time to file a bug report for Python to get that fixed.

*some programs don't actively read keyboard input (and if KEY_RESIZE isn't read, ncurses won't update the screensize.  That would make the program crash.


text:
Q: Does Gigabit degrade all ports to 100 megabit if there is a 100 megabit device attached? Our company is buying some HP Procurve managed gigabit switches to replace some of our core switches.  However, we aren't able to upgrade all of our switches from 100Mb to Gigabit switches.  I think I know the answer but I'm not exactly sure.  If we plug those 100Mb switches (or even a 100Mb device) into those Gigabit switches, will the performance of the entire switch drop to 100Mb or will just that one port work at 100Mb?

A: Just that port.

A: If you can avoid cascading switches, I'd strongly encourage it.  The downsides are easily exampled with two people on the same cascaded switch copying a large file to a fileserver.  Having a single user under normal usage being able to cause usage issues for multiple other users is obviously bad.
Implications are even worse with servers.


text:
Q: Selecting rows in geopandas or pandas based on latitude/longitude and radius I have a dataframe (pd) where each row contains a bunch of measures, as well as latitude and longitude values. I can convert those into geopandas points if needed.
From this dataframe, I would like to select only rows that fall within a certain (let's say 1km) radius from a new given lat/long.
Is there a wise way to go about this problem?
Here's a data sample from the df:
id .  lat  .  long  . polution . label
----------------------------------------
3  . 45.467. -79.51 .    7     . 'nice'
7  . 45.312. -79.56 .    8     . 'mediocre'

a sample lat/long would be lat = 45.4 and long = -79.5.

A: Here's an example of working code. First make a function to calculate your distance. I implemented a simple distance calculation, but I would recommending which ever you feel most useful. Next you can subset the DataFrame to be within your desired distance.
#Initialize DataFrame
df=pd.DataFrame(columns=['location','lat','lon'])
df['location']=['LA','NY','LV']
df['lat']=[34.05,40.71,36.16]
df['lon']=[-118.24,-74.00,-115.14]

#New point Reno 39.53,-119.81
newlat=39.53
newlon=-119.81

#Import trig stuff from math
from math import sin, cos, sqrt, atan2,radians

#Distance function between two lat/lon
def getDist(lat1,lon1,lat2,lon2):
  R = 6373.0

  lat1 = radians(lat1)
  lon1 = radians(lon1)
  lat2 = radians(lat2)
  lon2 = radians(lon2)

  dlon = lon2 - lon1
  dlat = lat2 - lat1

  a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
  c = 2 * atan2(sqrt(a), sqrt(1 - a))

  return R * c

#Apply distance function to dataframe
df['dist']=list(map(lambda k: getDist(df.loc[k]['lat'],df.loc[k]['lon'],newlat,newlon), df.index))

#This will give all locations within radius of 600 km
df[df['dist']<600]

A: You can use the following algorithm:

*

*Create a geodataframe (gdfdata) from the input data (pd dataframe)

*Create another geodataframe (gdfsel) with the center point for the selection

*Create a buffer around the center point (make gdfselbuff from gdfsel) for the selection

*Use the within method of geopandas to find the points within.  E.g. gdf_within =
gdfdata.loc[gdfdata.geometry.within(gdfselbuff.unary_union)]
For making the buffer, you can use GeoSeries.buffer(distance, resolution)).  See these links for reference.
http://geopandas.org/geometric_manipulations.html
https://gis.stackexchange.com/questions/253224/geopandas-buffer-using-geodataframe-while-maintaining-the-dataframe

A: On top of Sharder's solution, I found convenient to apply a filter function. It also seems to execute faster
def filter(row,lat2,lon2,max):
    if getDist(row['lat'],row['lon'],lat2,lon2) < max:
        return True
    else:
        return False

df[df.apply(filter, args = (newlat,newlon,600), axis=1)]


text:
Q: Convert String to Date in T-SQL I try to convert a string into a date in t-sql. However get results that I can't explain.
DECLARE @String as char(11)
DECLARE @TString as char(11)

SELECT @String = SUBSTRING([Flat File Source Error Output Column],1,CHARINDEX(',',[Flat File Source Error Output Column])-6)
FROM [ERROR].[Import_V2X]

SELECT @TString = '12/18/2009'

-- Check content before conversion
SELECT @TString as 'CheckTString'
SELECT @String as 'CheckString'

-- Convert the strings to date
SELECT CONVERT(date,@TString,101) as 'ConvertSuccess'

SELECT CONVERT(date,@String,101) as 'ConvertFails'

[Flat File Source Error Output Column] is defined as text in the table
This gives me the following result:
CheckTString
------------
12/18/2009

(1 row(s) affected)

CheckString
-----------

12/18/2009

(1 row(s) affected)

ConvertSuccess
--------------
2009-12-18

(1 row(s) affected)

ConvertFails
------------
Msg 241, Level 16, State 1, Line 16
Conversion failed when converting date and/or time from character string.

Anybody can explain me where the problem is or comes from ?
For me the strings look exactly the same :(

A: If I had to guess it's because you're imported string has a non-visible character at the end of the string that doesn't allow it to convert.  Your variable is char(11) but the string '12/18/2009' is only 10 characters long so that leaves room for 1 more character at the end.

A: By the look of your output you have a line feed in the checkstring variable.  If this is not just a copy and paste error in the question, that will cause the error that you are describing.  See below
DECLARE @TString as char(11)

SELECT @TString = '
12/18/2009'

-- Check content before conversion
SELECT @TString as 'CheckTString'

-- Convert the strings to date
SELECT CONVERT(date,@TString,101) as 'ConvertFails'

Gives the following results.
(1 row(s) affected)
Msg 241, Level 16, State 1, Line 13
Conversion failed when converting date and/or time from character string.

A: Looks like @CheckString potentially has a newline character at the beginning.


text:
Q: Did Aida have her Inhuman powers inside the Framework? Aida's Inhuman powers are attributed by Fitz and May to experiments on transferring Inhuman DNA done within the Framework, suggesting that the transfer was done there:

COULSON: No, no, no! She has Inhuman powers now? Can we get a break,
please? Can we get one break?
MAY: Guess they weren't assessing powers at Hydra as much as
collecting them.
Agents of S.H.I.E.L.D., "The Return"

Her body was said to have been transferred from the Framework to real flesh, which would also tend to suggest that the powers were transferred to her there: if the Darkhold could (or would) do it, there wouldn't have been any need for the experiments there.
It might seem that Aida didn't have her powers within the Framework, since she didn't heal from the injuries she suffered. However, her healing ability is strongly implied to be because she's made of the same substance as the Darkhold: according to the Superior, Robby Reyes could harm her because the Ghost Rider came from the same dimension as the Darkhold and her body. As such, she wouldn't have had it even had the Inhuman powers been transferred over.
Is there any evidence that Aida had her Inhuman powers in the Framework?

A: Short answer, no.
She never shows any Inhuman abilities in the Framework, even when it would've helped her a lot or saved her

 like when she were falling from the Triskelion after Daisy kicked her butt

Also, the Framework replicates reality at a point where Inhuman powers works exactly like in the real MCU, so she would've needed the Inhuman gene to be able to get ONE power.
More importantly, this is never addressed in the show, so no, she didn't have any Inhuman powers in the Framework.
My understanding is that they were collecting Inhuman powers (or data on them, more likely) to replicate them on Aida's human body through Project Looking Glass. It's safe to say that the Darkhold allows its reader to perform genetic manipulations on an artificially created human body, even if it means introducing the Inhuman gene and multiple selected powers.
So Aida added Inhuman powers (that she analysed into the Framework) to her human body.


text:
Q: How can I make deployed resources editable with Maven 2? I have a project where I create a JAR which contains a bunch of classes with main() plus a set of scripts which set the environment to invoke them. Most of those are long running processes which log a lot (~10-20GB).
This means I have a pretty complex log4j.xml file which, being in src/main/resources/, goes into the JAR. When something breaks in the production system, I'd like to modify the logging on the fly for a single run.
So I came up with the idea to have a conf/ directory on the production and put that into the classpath, first. Then, I thought that it would be great if M2 would put the config files in there (instead of the JAR). But that would overwrite any manual changes during an automated deployment which I strongly dislike. I'm also not fond of timestamps and things like that.
So my next ideas was this: M2 should leave the config files in the JAR but create copies of the files with the name *.tpl in the conf/ directory. The admin could then copy a template to the basename to override the files in the JARs. .tpl-Files would be overwritten but that wouldn't hurt. Admins would have full control over which version of the log was active and they could run a diff to see whether any important changes were made.
Now the question: Has someone seen a plugin which automates this process? That is which creates a conf/ directory with all or a selected subset of everything in src/main/resources/ and which renames the files?

A: *

*Best practice in Maven handling config files is to place them in a separate conf directory, and pack them in a binary assembly using the assembly plugin. Placing configuration files, like log4j.xml in the src/main/resources doesn't make sense, since it is not a true application resource, but more of a configuration file.

*We cope with the overwriting, by packing the configuration files with the posfix .def. For example: myapp.properties is packed into the assembly as myapp.properties.def. When the person who uses the assembly unpacks it, it will not overwrite his original files. After unpacking he simply merges them by an external tool (we use meld in Fedora Core).

A: I may be missing something and this doesn't answer directly the question but did you consider producing a zip assembly of the exploded content of required artifacts (to be unzipped on the target environment)?

A: Sounds like you're attacking the problem the wrong way.  Why not just run the application with -Dlog4j.configuration=/some/where/my-log4j.properties?  If you want, you can add a command line flag to main() which invokes the PropertyConfigurator directly.


text:
Q: Twilio Flex - How Do I View My Call Logs / Records? I have an IVR application built on top of Twilio Studio / Flex.  At the end of my Studio flow, I send the user to a Flex agent.
How would I get a log of all calls that were sent to Flex?  I am looking for the start time (when a call was answered by an agent in Flex), the end time (when an answered call ends), the number the call came from, and the attributes that were passed to Flex for that call from Studio.
Also, is there a way to make a request to a webhook after each call to pass this info to an endpoint that I control?


text:
Q: How can I give "Japanese/Chinese" data? Context: Japanese sample data, does not get displayed (cout) as is taken in sample. Why so?
Below is the code:
std::setlocale(LC_ALL,"");
wchar_t *pStrAddr = L"日本語";
wcout <<"pStrAddr:: "<< pStrAddr << std::endl;

Output is observed as:
pStrAddr:: �,�

A: Please see the code below for answers, it works well now.

Locale setting Code 1:

setenv("LANG","en_US.utf8",1);              //"en_GB.utf8" or "ja_JP.utf8" etc.
cout << "GET ENV .... " << getenv("LANG");
setlocale(LC_ALL,"");

Locale setting Code 2:

setlocale(LC_ALL,"en_US.utf8");

Also I had to use the wcstombs together with the setlocale. Here goes my revised code that works.
setlocale(LC_ALL,"en_US.utf8");
wchar_t *pStrAddr = L"日本語";
wcout <<"pStrAddr:: "<< pStrAddr << std::endl;
cout << "HARDCODED : 日本語" << endl;

char strBuffer[11];                 //char []
int retStrAddr = wcstombs ( strBuffer, pStrAddr, sizeof(strBuffer) );
if (retStrAddr==11)
    strBuffer[11-1]='\0';   //since, not NULL terminated
//to string, as per converter support
std::cout << "multibyte strBuffer: " << strBuffer << '\n';

Output::
pStrAddr:: �,�
HARDCODED : 日本語
multibyte strBuffer: 日本語


text:
Q: Why can't I use more than levels in a select linq statement? I have three tables in my database:

What I want is to get items from the table wedstrijden like this:
int id = 3;
var wedstrijden = from w in db.wedstrijden
                  where w.teams.teamleden.gebruikersid == id
                  select w;

Unfortunately i get the following error:

Compiler Error Message: CS1593: Delegate
  'System.Func' does not take 1
  arguments

Does anyone have a clue what's causing the error or where i can find the answer to my question?

A: The property wedstrijden.teams.teamleden is an enumerable so you have to check each item individually:
int id = 3;
var wedstrijden = from w in db.wedstrijden
                  where w.teams.teamleden.Any(t => t.gebruikersid == id)
                  select w;

A: Your names are quite misleading because of plural/singular form misuse.
The problem isw.teams.teamleden.gebruikersid makes no sense with this diagram.
It looks like wedstrijden.teams means "teams" when in fact it is a single team.
Again, it looks like teams.teamleden is a single entity when in fact the relationship is one-to-many.
Because many teamleden entities match a single teams entity, you can't put a dot, it's just as meaningless as this:
from p in db.Products
where p.Owner.Orders.ID == id // what would you expect this to mean?
select p


text:
Q: using jquery and kohana well I havn't really ever using jquery to grab data from a server.. and well my jquery skills are pretty limited anyway so maybe im doing the jquery wrong ...im not sure
heres my controller to handle the json requests
class Controller_Json extends Controller_Template{

public function get_chat_entries(){
    echo json_encode($this->db->get('chat_entries')->result());
}}

and heres my view that is meant to test it

A: I can't really tell cause you don't provide any details about the error itself but I'd guess this might solve your problem:
http://de2.php.net/manual/en/function.json-encode.php#95667

If you are planning on using this function to serve a json file, it's important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add ";" to the end.

Cheers,
aefxx

A: I think you are missing out on the document ready wrapper. I would wrap my jquery code inside a document.ready method like this :`

I would also test the 'ajax/test.json' url from my browser to check if the server is returning a proper json string. Also make sure that the data object obtained inside your ajax callback function has a text property.

A: I tried your code in my test base kohana. your js code is ok.
problem is mysql_resoure to json conversion.
i.e. "echo json_encode($this->db->get('chat_entries')->result());"
result method returns mysql_resoure which needs to be converted into array.
it works when if i put like this
...
echo json_encode($this->db->get('emails')->current());

...
only one email is displayed inside of #chats ul list.
PS: emails is my table contains multiple email address


text:
Q: ggvis, error in function( ) : attempt to apply non-function : post sessionInfo() library("dplyr")
library("ggvis")
mtcars %>% ggvis(~wt,~mpg) %>% layer_points()
sessionInfo()

I posted sessionInfo() because I have an Error in (function ()  : attempt to apply non-function.
When I use R markdown and run, it works. It has error all the time, when I run it in R.

A: I had a similar issue to this.
I updated Rstudio from ver  0.98.1102 to ver  0.98.1103 and it's working now
Test to see if you can get ggvis to work in vanilla R to see if it's Rstudio behind your problem
Good Luck


text:
Q: Call a member function with bare function pointer What's the best way to call a member function if you have an object and a bare function pointer pointing to the member? Essentially I want to call the function pointer with thiscall calling convention.
Background: I'm looking up symbols in a shared library dynamically, obtaining a factory function pointer and a pointer to a certain member function I want to call. The member function itself is not virtual. I have no control over the shared library, I just have the binary.
Example:
typedef void * (*GenericFptr)();
GenericFptr lookup(const char *);

class CFoo;

GenericFptr factoryfn(lookup("CFoo factory function"));
CFoo *foo = reinterpret_cast<CFoo *>(factoryfn());

GenericFptr memberfn(lookup("CFoo member function"));

// now invoke memberfn on foo

Currently I'm using an union to convert the function pointer to a pointer to member function. It's ugly and creates dependencies to compiler implementation details:
class CFoo {
  public:
  void *dummy() { return 0; }
};
typedef void * (CFoo::*FooMemberPtr)();

union {
  struct {
    // compiler-specific layout for pointer-to-member
    void *x, *y;
    GenericFptr ptr;
  } fnptr;
  FooMemberPtr memberfn;
} f;

f.memberfn = &CFoo::dummy; // init pointer-to-member
f.fnptr.ptr = memberfn;    // rewrite pointer

void *result = (foo->*f.memberfn)();

A: A pointer to member function can't be stored in a pointer to function because it needs more information (for instance in case of multiple inheritance an offset may have to be applied to this before the call).  So you can't do without knowledge of implementation details.
If you want to be portable, the easiest is for your library to provide wrapper functions doing the member call.

A: Unfortunately a member function pointer has more information than a standard function pointer, and when you get the standard function pointer, converting it to a member function pointer would effectively be trying to generate extra data out of thin air.
I don't think there's any portable way to do what you're attempting, although if the union appears to work you could probably get away with that. Again, you would need to know the representation and calling convention for these methods for each compiler you wish to use to build the bode.
If you know the member function's name, why can't you just do foo->dummy() for example? Otherwise either the lookup function needs to provide a full member function pointer or the library would have to provided a C wrapper interface with normal functions to which a this pointer can be passed.

A: The following two links provide insight and possibly a solution. Note that calling a member function pointer with a this argument usually don't work, since you must take into account virtual methods, multiple and virtual inheritance.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx

A: According to the answer below it is doable in GCC, but not portable:
https://stackoverflow.com/a/5067992/705086


text:
Q: Counterexample to an implication Denote $\bar{A}$ a complement of $A$ in a set $\Omega$ and $A \Delta B = A/B \cup B/A$ the symmetric difference of $A, B$. It is claimed that for a map $\phi := \Omega \rightarrow \lbrace 0, 1 \rbrace, \; \phi(\emptyset) = 0$:
$$
\begin{array}{|c|c|}
\hline
\phi(A) & \phi(\bar{A}) \\
\hline
0 & 1 \\
1 & 0 \\
\hline
\end{array}, \, A \in \Omega  \implies \phi(A \Delta B) = \phi(A) + \phi(B),  \text{  and } \phi(\Omega) = 1
$$
I know of a counterexample to this. Let $\mathcal{P}(\alpha)$ be a set of all subsets (a power set) of set $\alpha$. Consider $\phi: \Omega \rightarrow \lbrace 0,1 \rbrace$, $\Omega = \mathcal{P}({\lbrace a, b, c \rbrace})$:
$$
\begin{align*}
\phi(a) &= 0 &
\phi(b) &= 1 &
\phi(c) &= 1 &
\phi(\emptyset) &= 0 \\
\phi(b \cup c ) &= 1 &
\phi(a \cup c) &= 0 &
\phi(a \cup b) &= 0 &
\phi(a \cup b \cup c) &= 1
\end{align*}
$$
which satisfies the truth table, but breaks linearity ($\phi(a \Delta c) = \phi(a \cup b) = 0 \neq \phi(a) + \phi(c) = 1$).
I am interested if the following could be also implied by the LHS and also lead to a valid counter:
$$
\phi(A \Delta B) = \phi(A) + \phi(B) + \phi(A)\phi(B), \, \text{ and } \phi(\Omega)  =1
$$
Choosing $\phi(A) = 0$ implies that:
$$
\phi(A \Delta \bar{A}) = \phi(\Omega) = 1 = \phi(A) + \phi(\bar{A})(1 + \phi(A)) = \phi(\bar{A})$$
and hence: $\phi(A) = 0 \implies\phi(\bar{A}) = 1$ and $\phi(\bar{A}) = 0 \implies \phi(A) = 1$.
Choosing $\phi(A) = 1$ however leads to:
$$
1 = 1 + \phi(\bar{A})\cdot 0 = 1
$$
no matter what $\phi(\bar{A})$ is, so the opposite implication is not simply shown to hold. Is there any way out of this to finish the counter?
Note: If you can think of a better title for the question, please let me know.


text:
Q: Shifting temperature signal in time has no effect I'm trying to cross correlate a temperature signal with a strain signal.
I want to get the time delay between the two signals then I want to shift the temperature signal in time so that I can use it further for PCA.
The problem is I did the cross correlation and everything but the shifted temperature signal has no effect at all, it's the same as the correrlated signal.
You can download a data set here :
http://www.mediafire.com/file/r7dg7i9dacvpl2j/curve_fitting_ahmed.xlsx/file
You can look at the figures

The first signal is the shifted signal I suppose
The last ACF is the cross correlated signal
df = pd.read_excel(file_path, skip_blank_lines=False, skiprows=1)

def process_data_time_delay(temperature, strain, df):
    from scipy import signal

    # normalization before ACF
    def normalize(data):
        return (data - np.mean(data, axis=0).reshape((1, -11))) / (np.std(data, axis=0).reshape((1, -1)))

    # select subset of columns, seems relevant as a group
    SCOLS = ['T1', 'W_A1']

    # just to see the data
    f = plt.figure()
    ax = f.add_subplot(111)
    df[SCOLS[:2]].iloc[::10].plot(ax=ax)
    ax.set_title('Raw data')

    # normalization
    normalized = normalize(df[SCOLS].values)
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.plot(np.arange(normalized.shape[0]), normalized[:, 0], label='TW_A1')
    ax.plot(np.arange(normalized.shape[0]), normalized[:, 1], label='W_A1')
    ax.set_title('Normalized')

    # ACF between two components
    x1x2 = np.correlate(normalized[:, 0], normalized[:, 1], 'full')

    # see the results
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.plot(x1x2)
    ax.set_title('ACF')
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    peaks_indices = signal.find_peaks_cwt(array(x1x2).flatten(), np.arange(1,10))
    print(peaks_indices)
    delta_index = np.argmax(peaks_indices);
    print(delta_index)
    delta_time = df['TIMESTAMP'][delta_index] - df['TIMESTAMP'][0]
    # assuming timestamps is a datetime64 numpy array that can be easily obtained from pandas;
    shifted_signal = x1x2[delta_index:]

    f = plt.figure()
    ax = f.add_subplot(111)
    ax.plot(shifted_signal)

    # mainloop
    plt.show()

    return x1x2

A: The signal should be similar in shape but with shift in the time scale.


text:
Q: How did drinking from the Mortal Cup give Simon back his memories? I can't remember if this was ever spelled out in the books, but why does drinking from the Mortal Cup give Simon back his memories? It seemed to me that it was just taken for granted that it would help, but why? What power does the Mortal Cup have to give back memories taken away by a demon?

A: Simon needed to ascend, as it would counteract the spell that Asmodeus did, and return his memories. It also would ensure that they would be able to remain together, as Shadowhunters cannot marry Mundanes.


text:
Q: The equation $ax+bu+cs=ayz+bvw+crt$ also has no integers solutions for any integers $a,b,c$ Assuming that the system of equations:
$$x=yz$$
$$u=vw$$
$$s=rt$$
has no integers solutions. How I can prove that the equation $$ax+bu+cs=ayz+bvw+crt$$ also has no integers solutions for any integers $a,b,c$

A: $$ax+bu+cs=ayz+bvw+crt\\
a(x-yz)+b(u-vw)+c(s-rt)=0$$
Plugging in any specific integers for $x,y,z,u,v,w,r,s,t$ yields specific integer values $x-yz,u-vw,s-rt$.  It really doesn't matter what these values are, they just become coefficients for $ae+bf+cg=0$ which is always solvable in integers (e.g., $a=b=c=0$).  So the implication in the question is false as a starting point (i.e., solutions need not exist for the original "system" in order for the equation to have solutions).
After that, note that the original "system" is somewhat meaningless as there are no constraints given on the listed variables aside from "this system doesn't have solutions".


text:
Q: Get logical path from treeview which has HierarchicalDataTemplate I have a structure of geography objects:
Country
Areas,
Provinces,
Cities
and Hotels

Country has areas, areas has provinces, provinces has cities, and cities has hotels.
 Whne I'll click City node I wanna to get logical path eg: France,Provanse,SomeProvince,Montpellier,Grand Hotel.
Each class has fields: name, code nad listOf...
Treeview works great, but this method not:
 private void structureTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
if (structureTree.SelectedItem is Hotel)
            {
                objectCode = ((Hotel)structureTree.SelectedItem).Code;
                TreeViewItem item = e.OriginalSource as TreeViewItem;
                DependencyObject parent = VisualTreeHelper.GetParent(item);
                dlgEditHotel(objectCode, structureTree.Parent.ToString());
            }
          }

`**structureTree.SelectedItem as TreeViewItem **`

gives me null, when I'll click at some area, province,city or hotel

A: you could store names of tree items in their Tag or somewhere,
and at SelectedItemChanged recursively traverse the tree up to the topmost item and build up the pathstring.

A: you can read DataContext property of each TreeviewItem and will get the item(Country, Areas, Provinces, Cities, etc.). Read the Name(for example) and append into the path string recursively while traversing through the tree.

A: I have created a treeview as follows:
<TreeView Name="tree">
            <TreeViewItem Header="Country" Selected="GetName">
                <TreeViewItem Header="Areas" Selected="GetName">
                    <TreeViewItem Header="Provinces" Selected="GetName">
                        <TreeViewItem Header="Cities" Selected="GetName">
                            <TreeViewItem Header="Hotels" Selected="GetName">
                            </TreeViewItem>
                        </TreeViewItem>
                    </TreeViewItem>
                </TreeViewItem>

            </TreeViewItem>

        </TreeView>

Now GetName method would do something like this:
private void GetName(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)sender;
            name = item.Header + "." + name;
            if (!(item.Parent is TreeViewItem))
            {
                MessageBox.Show(name);
            }

        }

In the end the MessageBox would Show name as

Country.Areas.Provinces.Cities.Hotels.

I hope this is what you wanted.


text:
Q: How to cancel ChangeDetectorRef in ngOnDestroy   ngOnInit() {
    this.detectChangeInterval = setInterval(
      () => {
        this.detectRef.detectChanges(); // detectRef is type ChangeDetectorRef
      }, 2000);
  }

  // After leaving this page, I got: error_handler.js:47 EXCEPTION: Attempt to use a destroyed view: detectChanges
  ngOnDestroy() {
    if(this.detectChangeInterval) {
      clearInterval(this.detectChangeInterval);
    }
  }

I assume the exception means clearInterval(this.detectChangeInterval); did not cancel the recursive calling of this.detectRef.detectChanges();
Any suggestion will be appreciated.

A: My suggestion is to use different life cycle events than the default angular2 ones. Ionic2 has its own Page life cycle events which you can use. You can see those here (scroll a bit).
ionViewDidLoad() {
   this.detectChangeInterval = setInterval(() => {
      this.detectRef.detectChanges(); // detectRef is type ChangeDetectorRef
   }, 2000);
}

ionViewWillLeave() {
   if(this.detectChangeInterval) {
     clearInterval(this.detectChangeInterval);
   }
}


text:
Q: Getting the bigram probability (python) I am trying to write a function that calculates the bigram probability.
So, I basically have to calculate the occurence of two consective words (e.d. I am) in a corpus and divide that by the first word of those two words.
In formula it is:
P(W_n-1, W_n) / P(W_n-1)
So in my code I am trying to do something like:
def prob(self, prevWord, word):
    word = word.strip()
    prevWord = prevWord.strip()
    for sen in corpus:
        for word in sen:
            if(word occurs after prevWord): #Pseudocode here
                  counter++
    numerator = counter / self.total
    prevWordProb = self.counts[prevWord]/self.total
    return numerator / prevWordProb

First of all, is my approach valid? If so, I am not sure how to code the
if(word occurs after prevWord): #Pseudocode here

part of the code. How will it look like?

A: There are a few other issues with the code, but if resolved, the loop and conditional should look something like:
for sen in corpus:
    for i, w in enumerate(sen):
        if w == prevWord and sen[i+1] == word:
            counter++


text:
Q: Debugging win32 application entry I have a win32 application which was developed in VS C++ 2005. I converted this using VS 2010 C++. Now I have added a new library which I developed in again VS 2010 and linked them. However when I start debugging, I get the following error:

The program '[26432] Test.exe: Native' has exited with code -1073741701 (0xc000007b).

I have a breakpoint in _tWinMain. But the code crashes out even before reaching this point. How do I put/ Where do I put a breakpoint to understand why it is crashing? Any suggestions?


text:
Q: wpf datagrid select first cell programmatically my datagrid SelectionMode="Single", I need to switch the cell focus on the first cell whenever I click a cell in the Description column or any other column.
this is my code that I attempted to
private void dgvConfig_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;
        // iteratively traverse the visual tree
        while ((dep != null) &&
                !(dep is DataGridCell) &&
                !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridColumnHeader)
        {
            string columnHead = "";
            DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
            columnHead = columnHeader.Column.Header.ToString();
            LoadGridview(columnHead);
            //MessageBox.Show(columnHeader.Column.DisplayIndex.ToString());
        }

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;
            string cellName = cell.Column.Header.ToString();

            if (cellName.Equals("Description"))
            {

                cell.Focus();
                string datagridselect;
                //datagridselect = DataGrid.SelectedIndexProperty[]
                //var cellInfo = dgvConfig.SelectedCells[0];
                //var xt = dgvConfig.CurrentCell.Column.

                // the prob is I cant seem to access an array to move the focus to the first column of that selected row

            }

        }

    }

A: Have a try:
 private void dgShow_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach(DataGridCellInfo info in dgShow.SelectedCells)
        {
           if( info.Column.Header.ToString()=="Name")
           {
               dgShow.CurrentCell = info;
               break;
           }
        }
    }


text:
Q: Database project in Visual studio showing errors when creating users I am creating a database project in VS 2022. It is a fresh database that I have created.  After importing a database when I build I get the following error

error: SQL71501: User: Tim_Admin@work.com has an unresolved reference to Login [Tim_admin@work.com].

object:
CREATE USER [Tim_admin@Work.com] FOR LOGIN [Tim_admin@Work.com];

In the below image note that I unchecked all login and permission settings.


text:
Q: Saving file under /Download gives name /storage/emulated/0/Download. Sometimes the file is not accessable On my Samsung devices I put a file in the /Download folder. When I select the file within my app (via a file browser), the file is called /storage/emulated/0/Download/myfile.db. This name is stored in my app settings.
At the start of the app the file should be opened. First the app checks if the file exists. In some cases, say once every 2 weeks, the file is said to be not existing! This happens also at my friends mobile since half a year.
Why is that happening? For years everything ran smoothly.
This code runs for 6 years. Of course I added the permissions stuff.
Your help is much appreciated!

A: You can't use the Download as an guaranteed storage place for your files. You should use the Internal storage for the app. This is what Google has written about the download folder:

This space is called external because it's not guaranteed to be accessible—it is a storage space that users can mount to a computer as an external storage device, and it might even be physically removable.

Here you can read more about the Internal storage and the External storage in Android.
Here is some more information about the Download folder from Google.

Caution: The external storage might become unavailable if the user removes the SD card or connects the device to a computer. And the files are still visible to the user and other apps that have the READ_EXTERNAL_STORAGE permission. So if your app's functionality depends on these files or you need to completely restrict access, you should instead write your files to the internal storage.


text:
Q: Google smart home action : where to trigger a requestSync? I created a smart home action and I have to implement the requestSync feature for certification.
But I don't understand from where to call it : from my backend fulfillment ? or from elsewhere ?.
In the documentation, I saw :
You must trigger a SYNC request:

- If the user adds a new device.
- If the user removes an existing device.
- If the user renames an existing device.
- If you implement a new device type, trait, or add a new device feature.

But all these user interactions are from the Google side (in the Google Home app), so I don't understand why Google doesn't trigger the sync itself, and how could my backend know that the user changed something ?
Can someone help me with this feature ?
Thank you !

A:
But I don't understand from where to call it : from my backend fulfillment ? or from elsewhere ?

It definitely should come from backend.

But all these user interactions are from the Google side (in the Google Home app), so I don't understand why Google doesn't trigger the sync itself, and how could my backend know that the user changed something ?

This isn't a case to use the "requestSync". And your backend doesn't need to know about it if your users operate their devices from Google Home app
Here I will explain some example use case for you.
Imagine that you have your own application for controlling your devices. Then you develop the smarthome action project to make your device be able to controlled over voice. When your devices are linked with HomeGraph and you change your device's name, add or remove it from your own application. This is the time that your backend system should make "requestSync".
Even if your system doesn't allow user to make such of those changes on the device unless using Google Home app, google requires your system to be able to send them the "requestSync" for the case that when you "Implement a new device type, trait, or add a new device feature". This is the way that allows you(as developer) to update your users' devices without them(your users) unlinking and relinking their account.
And if you are not clear about "Implement a new device type, trait, or add a new device feature". Just thinking of case that you want to add more traits for your devices and you want to make update on all devices that has been linked before to be able to use a functionality from your new trait. You will need "rquestSync"
Hope this help. Goodluck :)


text:
Q: Teradata table creation and select statements fail when using LPAD and RPAD Background: The application I'm working on is not using any character delimiters. Fields are fixed length. Alphanumeric fields have to be left justified and space filled to the right, and numeric fields are right justified and zero-filled to the left.
I've been trying to accomplish this by using the RPAD and LPAD functions. The problem I'm running into is the error Teradata is displaying, "Response Row size or Constant Row size overflow". Each record if 4000 Bytes, and (from what I've read) the maximum size for each record in Teradata is 64KB, so I'm well under the maximum Teradata-allowed length.
Here is a small sample of the code that is generating an error;
SELECT
    RPAD(t1.MemberNbr, 20, ' ') AS MemberNbr
    ,RPAD(t1.LastName, 35, ' ') AS LastName
    ,RPAD(t1.FirstName, 25, ' ') AS FirstName
,CAST(t1.B_Day AS DATE FORMAT 'YYYYMMDD') (char(8)) AS BirthDay
FROM someTable AS t1

Can anyone explain to me why this isn't working? Thanks

A: When you check the resulting data type (SELECT TYPE(RPAD(t1.MemberNbr, 20, ' '))) you will notice it's either a VARCHAR(32000) CHARACTER SET UNICODE or VARCHAR(64000) CHARACTER SET LATIN, you need to decrease it using a cast:
CAST(RPAD(t1.MemberNbr, 20, ' ') AS CHAR(20))

I know it's stupid, but RPAD & LPAD are no built-in functions but FastPath UDFs, thus the parser/optimizer doesn't seem to know about the actual result size (Otherwise it's ok for other UDFs, e.g. LTRIM/RTRIM)


text:
Q: SQL Server 2008 Full text search stopwords I have row values like "shop.it", "shop.com" for a column
When I do full text search by shop, I can get "shop.com" but not "shop.it".
I am using SQL Server 2008.
Please help me on the same


text: Q: Is there a way to create a layer with view over UICollectionView I have a UICollectionView with some elements. I want to create a sublayer over that collection view, that will be scrolled according to the position of collection view and will cover only some elements of that. My point of creating sublayer is that, that will be dragable, so will be have ability to move despite of collection view position. How can I achieve that?


text:
Q: Javascript currying vs method chaining From what I have understood:
Currying - functions returning functions
string.capitalize(1)('character')('at the end')

Method chaining - methods returning objects
string.lowercase.capitalize.uppercase

Is this understanding correct?
If so, are there cases one of them is better than the other?
Cause it seems to me that method chaining is better and more readable. You also have autocompletion showing what methods you can use if you hit "dot" and it will show all the arguments you can pass.

A: A better equivalent of currying would be the Builder design pattern.
Ergo, you would do something like:
myObject.setIndexRangeToEffect(1,1).setTextTransformation(UPPERCASE).execute();
At any point before calling execute, you essentially have a "curried" action object.


text:
Q: How can I group by the country in column two and then sort by the resulting sum? I have the file like:
1   UA
2   GB
3   UA
3   UA
2   US
1   UA
4   US

How can I group by the second column and sum by the first one? So the output should be like:
8 UA
6 US
2 GB

A: With GNU awk:
$ awk 'BEGIN{PROCINFO["sorted_in"] = "@val_num_desc"}
       {a[$2]+=$1} END{for(k in a) print a[k], k}' ip.txt
8 UA
6 US
2 GB

See gawk manual: Using Predefined Array Scanning Orders for details about the sorting options.

With perl:
perl -lane '$h{$F[1]}+=$F[0]; END{print "$h{$_} $_" for
            sort {$h{$b} <=> $h{$a}} keys %h}' ip.txt

A: Using GNU datamash:
$ datamash -W -s -g 2 sum 1 <file
GB      2
UA      8
US      6

This treats whitespaces as field delimiters, sorts the input on the second field, groups it on this field and sums the first field for each group.
Pipe the output through awk '{ print $2, $1 }' if you want to swap the columns (datamash always writes the grouping column first in its output), and sort -nr if you want to sort that output in decreasing order as in your example:
$ datamash -W -s -g 2 sum 1 <file | awk '{ print $2, $1 }' | sort -nr
8 UA
6 US
2 GB

Using awk for the summation:
$ awk '{ sum[$2] += $1 } END { for (i in sum) print sum[i], i }' file
8 UA
2 GB
6 US

Pass this through sort -nr to sort, as above.