text:
Q: Google Compiler not assigning empty arrays to variables? So I am pretty new to using Google Compiler and am running into a few issues. The first is that in my preprocessed code I am setting an empty array to a variable which will be populated later on, but when compiling it removes the variable altogether so that it becomes undefined when trying to use it later on.
Here is the code I have slightly modified. Line 19 ends up being removed so therefore rowDivs is showing up as undefined on line 44:
/**
 * Equal Heights
 *
 * @see https://css-tricks.com/equal-height-blocks-in-rows/
 */
goog.provide('EqualHeights');

(function($) {

    // =  Equalize columns on load and resize
    equal_heights();

    $(window).resize(function() {
        equal_heights();
    })

    var currentTallest = 0;
    var currentRowStart = 0;
    var rowDivs = new Array();

    function setConformingHeight(el, newHeight) {

        // set the height to something new, but remember the original height in case things change
        el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")));
        el.height(newHeight);
    }

    function getOriginalHeight(el) {

        // if the height has changed, send the originalHeight
        return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"));
    }

    function equal_heights() {

        // find the tallest DIV in the row, and set the heights of all of the DIVs to match it.
        $('[data-equalizer-watch]').each(function() {

            // "caching"
            var $el = $(this);
            var topPosition = $el.position().top;

            if (currentRowStart != topPosition) {

                // we just came to a new row. Set all the heights on the completed row
                for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);

                // set the variables for the new row
                rowDivs.length = 0;

                // empty the array
                currentRowStart = topPosition;
                currentTallest = getOriginalHeight($el);
                rowDivs.push($el);
            }
            else {

                // another div on the current row. Add it to the list and check if it's taller
                rowDivs.push($el);
                currentTallest = (currentTallest < getOriginalHeight($el)) ? (getOriginalHeight($el)) : (currentTallest);
            }
        });

        // do the last row
        for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
            setConformingHeight(rowDivs[currentDiv], currentTallest);

        }
    }

})(jQuery);

For the compiler settings, I am using the following flags. Note that I am not even using the advanced optimizations complication level:
--closure_entry_point main.js
--externs node_modules/google-closure-compiler/contrib/externs/jquery-1.9.js
--language_in ECMASCRIPTS5
--warning_level: VERBOSE

I am probably missing something obvious, but just want to get on the right track. Thanks.

A: With simple-compile mode local variables are minimized and potentially removed if not used. Probably what's happening is: based on the entry point you specified, closure compiler determines that rowDivs can never used.
To fix you need to tell closure compiler more information.
(Disclaimer: I've never used jquery so I might be way off track in what follows.  I've also never used node or modules, and there are special ways to write for those which I'm not familiar with.)
One thing to try is the special flag for jquery: --process_jquery_primitives see
https://github.com/google/closure-compiler/wiki/jQuery-Expansions
The jquery-1.9 extern defines $ as a global variable, so you don't need to pass it in to your function.
You might need to tell closure-compiler to export the functions you define. See "Export the Symbols You Want to Keep" in
https://developers.google.com/closure/compiler/docs/api-tutorial3
If you are open to using "object-oriented style", here are some ideas.
There is probably a way to write your code without changing to an object-oriented style, but I'm not familiar enough with that style to help you.
(I don't know how to get jquery to be activated when your program starts, but I assume this happens in your startup code somewhere.)
It looks like you designed this code to be a self-executing function that happens whenever you say goog.require('EqualHeights'). But you don't actually define anything for the EqualHeights namespace. Maybe this instead:
goog.provide('EqualHeights');

/**
* @constructor
*/
EqualHeights = function() {
    this.currentTallest = 0;
    this.currentRowStart = 0;
    this.rowDivs = new Array();
};

/**
* @param {!Element} el
* @param {number} newHeight
*/
EqualHeights.prototype.setConformingHeight = function(el, newHeight) {

    // set the height to something new, but remember the original height in case things change
    el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")));
    el.height(newHeight);
};

/**
* @param {!Element} el
* @return {number}
*/
EqualHeights.prototype.getOriginalHeight = function(el) {

    // if the height has changed, send the originalHeight
    return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"));
}

/**
* @return {undefined}
*/
EqualHeights.prototype.equal_heights = function() {

    // find the tallest DIV in the row, and set the heights of all of the DIVs to match it.
    $('[data-equalizer-watch]').each(function() {

        // "caching"
        var $el = $(this);
        var topPosition = $el.position().top;

        if (this.currentRowStart != topPosition) {

            // we just came to a new row. Set all the heights on the completed row
            for(currentDiv = 0 ; currentDiv < this.rowDivs.length ; currentDiv++)
              setConformingHeight(this.rowDivs[currentDiv], this.currentTallest);

            // set the variables for the new row
            this.rowDivs.length = 0;

            // empty the array
            this.currentRowStart = topPosition;
            this.currentTallest = getOriginalHeight($el);
            this.rowDivs.push($el);
        }
        else {

            // another div on the current row. Add it to the list and check if it's taller
            this.rowDivs.push($el);
            this.currentTallest = (this.currentTallest < getOriginalHeight($el)) ? (getOriginalHeight($el)) : (this.currentTallest);
        }
    });

    // do the last row
    for (currentDiv = 0 ; currentDiv < this.rowDivs.length ; currentDiv++) {
        setConformingHeight(this.rowDivs[currentDiv], this.currentTallest);

    }
}

Then in your startup code have this:
goog.require('EqualHeights');

var eh = new EqualHeights();

// =  Equalize columns on load and resize
eh.equal_heights();

$(window).resize(function(){eh.equal_heights();});

I'm unclear what this line is doing:
var $el = $(this);

The value of this should be the EqualHeights object inside each method. You can use the goog.bind function (if it's available for you) to ensure that this is what you want it to be for that function.


text:
Q: Deserialize using a function of the tag An API with this internally tagged field structure, with "topic" being the tag:
{
    "topic": "Car"
    "name": "BMW"
    "HP": 250
}

This can be deserialized with
#[derive(Serialize, Deserialize)]
#[serde(tag = "topic")]
pub enum catalog {
    CarEntry(Car),
    ... (other types)
}

#[derive(Serialize, Deserialize)]
pub struct Car {
    pub name: String
    pub HP: i32
}

It turns out that instead of reporting the topic as just Car, the API actually sends Car.product1 or Car.product2 etc.
This breaks the deserialization, because the deserializer doesn't know what the type is based on the string. Is there a way to supply a function to chop off the type string so that the correct model is found?

A: I don't think serde provides a way to mangle the tag before using it (at least I don't see anything relevant). And the generated serializers for tagged enums are relatively complex, with internal caching if the tag isn't the first field, and whatnot, so I wouldn't want to reproduce that in a custom deserializer.
The cheapest (but not necessarily most efficient) shot at this is to deserialize to serde_json::Value first, manually process the tag, and then deserialize the serde_json::Values to whatever struct you want.
Do that in a custom deserializer, and it starts looking reasonable:
impl<'de> Deserialize<'de> for Catalog {
    fn deserialize<D>(d: D) -> Result<Self, <D as Deserializer<'de>>::Error>
    where
        D: Deserializer<'de>,
    {
        use serde_json::{Map, Value};
        #[derive(Deserialize)]
        struct Pre {
            topic: String,
            #[serde(flatten)]
            data: Map<String, Value>,
        }
        let v = Pre::deserialize(d)?;
        // Now you can mangle Pre any way you want to get your final structs.
        match v.topic.as_bytes() {
            [b'C', b'a', b'r', b'.', _rest @ ..] => Ok(Catalog::CarEntry(
                serde_json::from_value(v.data.into()).map_err(de::Error::custom)?,
            )),
            [b'B', b'a', b'r', b'.', _rest @ ..] => Ok(Catalog::BarEntry(
                serde_json::from_value(v.data.into()).map_err(de::Error::custom)?,
            )),
            _ => return Err(de::Error::unknown_variant(&v.topic, &["Car.…", "Bar.…"])),
        }
    }
}

Playground
Btw, what do you want to do with the suffix of topic? Throw it away? How do you plan on handling serialization if you do throw it away?

A: You can directly use enum instead of defining extra struct type.
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "topic")]
pub enum Catalog {
    Car { name: String, hp: i32 }
}

fn main() {
    let car = Catalog::Car { name: String::from("BMW"), hp: 2000 };

    // Convert the Car to a JSON string.
    let serialized = serde_json::to_string(&car).unwrap();

    // Prints serialized = {"topic":"Car","name":"BMW","hp":2000}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Car.
    let deserialized: Catalog = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Car { name: "BMW", hp: 2000 }
    println!("deserialized = {:?}", deserialized);
}

Playground

You can use #[serde(rename()] to rename type in output
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "topic")]
pub enum Catalog {
    #[serde(rename(serialize = "Car", deserialize = "CarEntry"))]
    CarEntry(Car),
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Car {
    pub name: String,
    pub hp: i32
}

fn main() {
    let car = Car { name: String::from("BMW"), hp: 2000 };
    let catalog = Catalog::CarEntry(car);
    // Convert the Car to a JSON string.
    let serialized = serde_json::to_string(&catalog).unwrap();

    // Prints serialized = {"topic":"Car","name":"BMW","hp":2000}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Car.
    let deserialized: Car = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Car { name: "BMW", hp: 2000 }
    println!("deserialized = {:?}", deserialized);
}

Playground

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a service that allows to access multiple API's using unified interface and one login? Some time ago I was browsing the web, when I found a service that allowed to access multiple API's using single, unified interface and single login.
I remember that I browsed the catalog of API's and check OCR services to see what features they offer.
I don't remember if it was a free service or paid one. I didn't bookmark it and now I can't find it. I have found only API's catalog on Programmable Web.
Is anyone knows the name of this service?

A: Well, after getting one vote down I decided to google more. No results. I reviewed bookmarks and... bingo!
It's called mashape.com and what I have had in mind was this catalogue.
Disclaimer: I have no connection to this service. I just liked the idea.
Edit:
I have just found API search:
{API}Search.
It does not allow to access mutiple API's using single credentials, but might be usefull for API's discovery.


text:
Q: prepositional pattern with choice of prepositions ("to" vs. "for") Now I am learning about prepositional patterns, but I have questions about when to use proper prepositions.
Here's question sentences

*

*I gave a book to John.

*I gave a book for John.

*He brought a chair to her.

*He brought a chair for her.

*send a letter to Steve.

*send a letter for Steve. (wrong)

in these two sentences, my teacher told me that to John in sentence 1 means goal, whereas for John in sentence 2 refers to Benefactive or proxy.
sentence 1 and 2 seems okay to me, however, sentences 3 and 4 confused me.
I think meaning of sentence 3 and sentence 4 which interpreted as Benefactive are same..
I don't get difference of underlying meaning.
Also, I don't know the reason why my teacher just said sentence 6 is wrong..

A: Prepositions are tricky. Each preposition typically has several meanings (sometimes more than a dozen), and the meaning often changes depending on the verb.

1) I gave a book to John.
  2) I gave a book for John.
  2a) I bought a book for John.

If the verb were bought instead of give, the second sentence would work. However, the expression gave something for someone sounds awkward. I wouldn't use #2 unless, say, John couldn't make it to a baby shower, and I gave the mother-to-be a book, saying the book was from John instead of from me. When dealing with gift-giving, we typically buy something for someone, and we give something to someone.

3) He brought a chair to her.
  4) He brought a chair for her.

Both of these are fine, and mean pretty much the same thing. The first emphasizes the action; the other emphasizes the intent. The version with to could be further explained as: He brought a chair to where she was standing, while the version with for could be paraphrased as: He brought a chair for her to sit in. Put another way, the first tells us where he brought the chair, the second tells us why he brought the chair.

5) I sent a letter to Steve.
  6) I sent a letter for Steve.

Sentence #5 is a normal, idiomatic way to explain that Steve's name and address were on the envelope, and we mailed the letter to him. Sentence #6 is more unusual, but it isn't incorrect. Let's say Steve and I are roommates, and he wrote a letter to his mom last night. He wants to send this letter today, but the post office is five miles in the wrong direction during his daily commute – yet he knows I drive right by the post office on my way to work. He asks, "Would you mail this for me this morning?" Naturally, I agree. When I get to work later that day, a co-worker might say, "As I was driving into work, I thought I saw you getting out of your car at the post office," and I might answer, "Yes, I was sending a letter for my roommate Steve," meaning I was doing him a favor.
This isn't the only interpretation for Sentence #6. We might say:

We sent a card for Steve.

meaning that we mailed a card for Steve to receive. (Perhaps Steve is in the hospital recovering from surgery, and we sent him a get-well-soon card.) Much like the chair example discussed earlier, using to emphasizes where the card was mailed (to Steve), while using for emphasizes why the card was sent (to cheer him up). The version with for may sound a little awkward by itself, but, with the right surrounding context, it could work. We need to be careful when we say something is "wrong." Wrong doesn't always mean grammatically wrong, sometimes it just means not idiomatic, or unusual, or it doesn't mean what you are trying to say.


text:
Q: C format specifier "%n" in Java so I'm starting to learn java and I was wondering if I could use the "%n" parameter (from C printf()), which should write the number of bytes written up to the "%n" parameter:
this is it's use in C:
#include <stdio.h>

int main()
{
  int val;

  printf("ciao %n ciao\n", &val);

  printf("val = %d\n", val);

  return 0;

}

prints:
ciao  ciao
val = 5

But when I try to use it in java:
public class CharTest
{
   public static void main(String[] argv)
   {
      int  value;

      System.out.printf("\nNumber of bytes written up to now: %n\n", &value);
      System.out.println(value);
   }
}

The java compiler gives me this message:
CharTest.java:20: error: illegal start of expression

System.out.printf("\nNumber of bytes written up to now: %n\n", &value);
                                                               ^
1 error

How do I solve this?

A: In C you can pass parameters by reference or change the value of variables passed to functions by passing a pointer to them, the %n specifier stores the number of characters written so far in value and in order to do that you had to pass the pointer to value with &value.
In Java it's not possible to pass parameters by reference or to pass pointers of variables and the same syntax is not possible, & operator is bitwise and. The printf %n specifier in Java prints a platform specific line separator.

A: You can't do it in Java at all. There is no conversion that would correspond to %n of the printf C. Instead, you can use the String.format to format the string
String s = String.format("\nNumber of *%s* written up to now: ", "characters");

then check the number of characters in s, and format that separately:
int len = s.length()
String result = String.format("%s%d\n", s, len);

Lastly, do note that unlike in C where char is exact synonym of byte, in Java the strings do not even consist of bytes, but Unicode/UTF-16 codepoints. Asking how many bytes are written by a string formatting operation is meaningless.


text:
Q: expected method to read dictionary element not found on object of type 'nsstring *' I am trying to use a text field to type in some numbers and then have the Parse server look for images tagged with whatever number was typed in the field, but I am getting this big red error (in the subject header) when trying to build the app for testing.  Here's my code:
-(IBAction)Submit:(id)sender {

PFFile *people = TicketNumberBox.text[@"ticketNumber"];
[people getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
         UIImageView TicketImage = [UIImage imageWithData:imageData];
    }
}];

}
Here's an image to help you further:

A: TicketNumberBox.text[@"ticketNumber"]; doesn't make any sense as text variable from UITextField is type of NSString, not dictionary, so You can't just take ticketNumber value like that. You can divide your code to something like this to understand:
NSString *text = TicketNumberBox.text;
PFFile *people = text[@"ticketNumber"];

Is that still makes sense to You?
More believable would be:
NSString *text = TicketNumberBox.text;
PFFile *people = [PFFile alloc] init];
people.ticketNumber = text;

A: The syntax in someString[@"this is the string I want to set"] is how you request a value-for-key @"this is the string I want to set" in NSDictionary, which is why you're getting the specific error you got. However, a string isn't a dictionary, so the compiler is complaining that you're trying to address a string as a dictionary key. The element of confusion is that dictionaries can use a string as a key. So to reference a the dictionary: NSDictionary *dictionary = @{@"key":"@"value"}; you use the syntax NSString *string = dictionary[@"key"] which returns @"value", making "string" equal to @"value".


text:
Q: Force ServicePointManager.SecurityProtocol to TLS 1.2 on all connections I have a WCF service which sends an outgoing request. Currently it is using SSL 3.0 or TLS 1.0.
The service I am sending the request to now only accepts TLS 1.2.
I can set the SecurityProtocolType just before the request (and for each request), but I would like it to use TLS 1.2 for all outgoing requests without having to specify it for each request.
This code sets it correctly for the request:
<OperationContract(), WebGet(UriTemplate:="...")>
Public Function SomeService()

    System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) 3072; // 3072 is TLS 1.2

    // Do request

End Function

But I cannot see how to set WCF to use TLS 1.2 for all requests. I have tried placing the above statement into Application_Start and Application_BeginRequest in Global.asax, but by the time it comes to doing the request, SecurityProtocol is back to SSL3/TLS1.0

A: If you have access to the registry you can apply the following key:
registry key
This enforces TLS 1.2 at the Windows level of the Transport Layer so you don't need to change any code.
These are the keys changed in the above file:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

A: Add this line in the Startup.Auth.cs file.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

This worked for us.


text:
Q: User don't have access to the secret even after enabling the access though policy I have created a policy so that a developer can access the secret but when I try to access the secret as a developer it shows that I don't have permission to access it.
I tried changing the value and adding new secret but nothing helped
 path "kv/*" {
     capabilities = ["list"]
     }
 path "kv/dev01"{
   capabilities = ["read", "list"]
   }
 path "kv/dev_01_cred" {
   capabilities = ["read", "list"]
 }

the developer should be able to read the secret in dev01 and dev_01_cred.
Currently, the developer can only see the list of secrets in kv.


text:
Q: How to fix this UnicodeDecodeError that says "invalid continuation byte"? I'm following along with a sentiment analysis tutorial (https://pythonprogramming.net/sentiment-analysis-python-textblob-vader/). How would I go about fixing this error?
I tried changing how to go line by line but I don't think that is the problem. Somehow I have to convert the way the text is encoded?

pos_count = 0
pos_correct = 0

with open("positive.txt","r") as f:
    for line in f.read().split('\n'):
        analysis = TextBlob(line)
        if analysis.sentiment.polarity > 0:
            pos_correct += 1
        pos_count +=1

neg_count = 0
neg_correct = 0

with open("negative.txt","r") as f:
    for line in f.read().split('\n'):
        analysis = TextBlob(line)
        if analysis.sentiment.polarity <= 0:
            neg_correct += 1
        neg_count +=1

print("Positive accuracy = {}% via {} samples".format(pos_correct/pos_count*100.0, pos_count))
print("Negative accuracy = {}% via {} samples".format(neg_correct/neg_count*100.0, neg_count))

  File "/Users/adixit/PycharmProjects/sentiment_analysis/Tutorial.py", line 15, in <module>
    for line in f.read().split('\n'):
  File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 4645: invalid continuation byte

A: Per https://docs.python.org/3.7/library/functions.html#open

In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding

On your system the default encoding is utf-8, while Firefox detects the encoding of https://pythonprogramming.net/static/downloads/short_reviews/positive.txt as "Western".
You need to specify the correct encoding, like:
with open("positive.txt", "r", encoding="windows-1252") as f:


text:
Q: Plugin with id 'kotlin-android' not found on OnboardingScreens I am new to react native and was trying to create a Onboarding Screen for an app. After adding the code for onboarding screen and importing it into App.js file. I tried to run the application.
However, the app failed to install on my emulator.
The error:

*

*What went wrong:
A problem occurred evaluating project ':react-native-navigation'.

Plugin with id 'kotlin-android' not found.

*

*

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
2: Task failed with an exception.

*

*What went wrong:
A problem occurred configuring project ':react-native-navigation'.

compileSdkVersion is not specified. Please add it to build.gradle

My build.gradle file looks like this:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "29.0.2"
        minSdkVersion = 16
        compileSdkVersion = 29
        targetSdkVersion = 29
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:4.1.1')
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

This is my App.js file
import React, { Component } from 'react';
import SplashScreen from 'react-native-splash-screen';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

//import Screens
import onboardingScreen from './screens/onboardingScreen';

import {
  Platform,
  StyleSheet,
  Text,
  View,
  StatusBar
} from 'react-native';

const AppStack = createStackNavigator();

export default class App extends Component {

  componentDidMount() {
    SplashScreen.hide()
  }
  render() {
    return (
      <NavigationContainer>
        <AppStack.Navigator
          headermode="none">

          <AppStack.Screen name="onboardingScreen" Component={onboardingScreen} />

        </AppStack.Navigator>
      </NavigationContainer>
    );
  }
}

package.json:
{
  "name": "Reactnative",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-navigation/native": "^5.8.10",
    "@react-navigation/stack": "^5.12.8",
    "react": "16.13.1",
    "react-native": "0.63.4",
    "react-native-app-intro-slider": "^4.0.4",
    "react-native-navigation": "^7.6.0",
    "react-native-onboarding-swiper": "^1.1.4",
    "react-native-splash-screen": "^3.2.0",
    "react-navigation-stack": "^2.10.2"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4",
    "@react-native-community/eslint-config": "^1.1.0",
    "babel-jest": "^25.1.0",
    "eslint": "^6.5.1",
    "jest": "^25.1.0",
    "metro-react-native-babel-preset": "^0.59.0",
    "react-test-renderer": "16.13.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

onboardingScreen.js:
import React from 'react';
import { view, Button, Text, Image, StyleSheet} from 'react-native';

import Onboarding from 'react-native-onboarding-swiper';

const Dots = ({selected}) => {
    let backgroundColor;

    backgroundColor = selected ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.3)';

    return (
        <View
            style={{
                width:6,
                height: 6,
                marginHorizontal: 3,
                backgroundColor
            }}
        />
    );
}

const Skip = ({...props}) => (
    <TouchableOpacity
        style={{marginHorizontal:10}}
        {...props}
    >
        <Text style={{fontSize:16}}>Skip</Text>
    </TouchableOpacity>
);

const Next = ({...props}) => (
    <TouchableOpacity
        style={{marginHorizontal:10}}
        {...props}
    >
        <Text style={{fontSize:16}}>Next</Text>
    </TouchableOpacity>
);

const Done = ({...props}) => (
    <TouchableOpacity
        style={{marginHorizontal:10}}
        {...props}
    >
        <Text style={{fontSize:16}}>Done</Text>
    </TouchableOpacity>
);

<Onboarding
   SkipButtonComponent={Skip}
        NextButtonComponent={Next}
        DoneButtonComponent={Done}
        DotComponent={Dots}
        onSkip={() => navigation.replace("Login")}
        onDone={() => navigation.navigate("Login")}
  pages={[
    {
      backgroundColor: '#fff',
      image: <Image source={require('../assets/img/slider1.png')} />,
      title: 'Enabling Collaboration',
      subtitle: 'We connect local shoppers to online buyers',
    },
      {
      backgroundColor: '#fff',
      image: <Image source={require('../assets/img/slider2.png')} />,
      title: 'Peer Up',
      subtitle: 'Going home? Ready to help? Drop Orders Get Compensated',
    },
      {
      backgroundColor: '#fff',
      image: <Image source={require('../assets/img/slider3.png')} />,
      title: 'Enabling Collaboration',
      subtitle: 'Busy at home? Need groceries quickly? Want low service fees 0% Mark-up as well? Just make a list',
    },
  ]}
/>

export default onboardingScreen;

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

I tried googling the error as well, but couldn't find anything related to react-native-onboarding-swiper.

A: I thought another library produced the error. Try this

android/build.gradle

buildscript {
ext {
    minSdkVersion = 21
    // kotlinVersion = "1.3.72"
    kotlinVersion = "1.6.0"
}

dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" // add this line
}
}

A: Your App, js import package react-navigation
https://reactnavigation.org/
But, your error shows package resct-native-navigation
https://github.com/wix/react-native-navigation
Be sure about your packages and follow installation guide
Edit:
According to your source code in github

*

*You don't need react-navigation-stack package

*You must add some package required
According to doc of react-navigation version 5.x
When you using @react-navigation/stack, you must ensure that you have installed the @react-navigation/native
https://reactnavigation.org/docs/stack-navigator/
Then, when you using @react-navigation/stack, you must install some react-native packages
https://reactnavigation.org/docs/getting-started/#installation

*Splash screen freeze because onboardingScreen not found
There are some mistakes when import and export file
So, you can fix it like this:
Number 1 and 2:
package.json
change the package.json, then delete node_modules folder and $ npm install
Number 3:
On screens/onboardingScreen.js you must fix the export
screens/onboardingScreen.js
On App.js you must fix the import
App.js


text:
Q: Droppable not working I'm trying to get draggable and droppable working and the drop part of this is not working.
$(function(){
    $(".draggable").draggable();
    $("#dashboard").droppable({
        drop: function(){
            alert("HEY!");
        }
    });
});

Where am I making the mistake?
HTML-

    LeftSide

         Dashboard

   Center

      DraggableTest

This could also be an issue with version compatibility-

OTHER CODE THAT IS THERE-
$(dashboard).click(function(){
    console.log("HELLO");
    if($(dashboard).hasClass("dashBoardIn")){
        $(dashboard).removeClass("dashBoardIn");
    $(dashboard).addClass("dashBoardOut");
    $(".dashboard").stop().animate({'marginLeft':'-2px'},200);
} else{
    if($(dashboard).hasClass("dashBoardOut")){
        $(dashboard).removeClass("dashBoardOut");
        $(dashboard).addClass("dashBoardIn");
    $(".dashboard").stop().animate({'marginLeft':'-85px'},200);
    }
}
});

ANSWER-
Ok, so turns out I needed to add in an "accept" - like this
    $("#favouritesDashboard").droppable({
    accept:".draggable",
    drop: function() {
        console.log("HEY!");
    }
});

A: You're using id instead of class - change that:
$("#dashboard").droppable({

to that (or use #favouritesDashboard id instead of just #dashboard):
$(".dashboard").droppable({

Working demo: http://jsbin.com/ovamaf/1/
If it still doesn't work it has to be something wrong with your setup (for example you didn't embed jquery or jquery ui correctly. Check your console for errors.

A: There is no id #dashboard and I assume #favouritesDashboard should be droppable
I think it should be,
$(function(){
    $(".draggable").draggable();
    $("#favouritesDashboard").droppable({
        drop: function(){
            alert("HEY!");
        }
    });
});

A: Ok so I needed to add an accept-
$("#favouritesDashboard").droppable({
    accept:".draggable",
    drop: function() {
        console.log("HEY!");
    }
});

That works.


text:
Q: Can't host a winsock server I am using simple msdn TCP sockets example from here. When my friends run the server, or when I am using it through my local network everything is fine. But there is no way to connect to server running on my computer through the internet. I opened the port binded by server in my router, disabled Windows firewall, turned off antivirus, but it doesn't work!
Here is what I got in Wireshark, but I don't know what it means:

192.168.1.2 is my local IP, 17000 is the port, binded by server. I am running both server and client on the same computer here.

A: Run the server on your machine and have it bind() to IP 192.168.1.2 (or to INADDR_ANY aka 0.0.0.0 to bind to all of the machine's available IPs) on port 17000, and configure your router to forward all inbound traffic on port 17000 to IP 192.168.1.2.  Your friends can then connect to your router's public IP on port 17000.  If your router does not have a static IP assigned by your ISP, you will have to look up the current IP using an external service, such as http://www.whatismyip.com.


text:
Q: left join with Hibernate by @OneToOne and FetchType.EAGER I have two tables with @OneToOne by a id.
So if the second id refer to a not present row of the table
can I say to Hibernate to skyp this row.
Instead I have an error.
@Entity
@Table(name="user")
public class User implements Serializable {

private Long idUser;
private Area area;

//...other get and setter

@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="idarea")
public Area getArea() {
return area;
}
}

now if I have an row of user with non-existent idarea , how can I skip the user,
or can I make a LEFT JOIN?

A: This situation should not happen in a well-defined schema, with foreign key constraint. If the user has a non-null idarea, then this ID should refer to an existing ID in the Area table. I would fiw the data, and add a foreign key constraint to make sure this never happens.
If for extremely good reasons, it's impossible, then you can use the @NotFound(NotFoundAction.IGNORE) annotation. But it will have a performance cost, because Hibernate will have to check i the ID is a real ID or a non-existing ID each time it loads a user.


text:
Q: calender tag in jsf with date & time restriction I have a jsf page named as page.xhtml like following:
<p:calendar id="start_date_time_label" widgetVar="myCalendar1"
    value="#{bean.startDateTime}" pattern="dd/MM/yy"
    style="width: 359px; " required="true"
    requiredMessage="Start Date is mandatory" />

Here I have added one javascript function like following to restrict the minimum date value:
<script type="text/javascript">
        jQuery(document).ready(function(){
            myCalendar1.jqEl.datepicker("option", "minDate", -365);//set minDate to 1 year back
        });
</script>

Till now the script is working fine.
Now as per requirement I have to change the pattern of p:calender tag to pattern="dd/MM/yy HH:mm:ss". But then the script is not working. Please help me to make it work with the time value.

A: Why not use primefaces' mindate attribute?
<p:calendar id="start_date" mindate="#{of:addMonths(now, -12)}" value="#{bean.startDateTime}" pattern="dd/MM/yy HH:mm:ss" />

The 1 year back minimum date is set via a combination of omnifaces' now bean and their el date functions, but you could replace it with a bean method that returns the same thing.


text:
Q: having issues displaying objects from state I am having an issue with getting the data from my state I need the information from the employee state to display the pages in referring to are Employee.js and EmployeeItem.js in my repo.
I can map through the state and display a number of blank objects based on how many entries are in the state but I am having trouble displaying and information for the individual objects
How the page currently renders

How I need the page to render

Employee.js
import React, {Fragment, useEffect} from 'react'
import {Link} from 'react-router-dom'
import {connect} from 'react-redux'
import Spinner from '../../layout/Spinner'
import {getEmployees} from '../../../actions/employee'
import EmployeeItem from './EmployeeItem'
import PropTypes from 'prop-types'

const Employees = ({ getEmployees, employee: {employees, loading}}) => {
    useEffect(() => {
        getEmployees()
    }, [])

    return (
        <Fragment>
            {loading ? <Spinner/> :
                <Fragment>

Employees

                                <Link to="/employees/new"></Link>

                                {employees.length > 0 ? (
                                    employees.map(employee => (
                                        <EmployeeItem key={employee._id} profile={employee} />
                                    ))
                                ) :
No Employees Found....
}

                </Fragment>
            }
        </Fragment>
    )
}

Employees.propTypes = {
    getEmployees: PropTypes.func.isRequired,
    employee: PropTypes.object.isRequired,
}

const mapStateToProps = state => ({
    employee: state.employee
})

export default connect(mapStateToProps, {getEmployees})(Employees)

EmployeeItem.js
import React from 'react'
import {Link} from 'react-router-dom'
import PropTypes from 'prop-types'

const EmployeeItem = ({employee: name, employement, _id}) => {
    return (

            <Link to={`/employees/${_id}`}>

J D

{name}

            </Link>

    )
}

EmployeeItem.propTypes = {
    employee: PropTypes.object.isRequired,
}

export default EmployeeItem

[What is in the state:

Any help on fixing this would be much appreciated.

A: If you look at the EmployeeItem. You are assigning employee value to profile prop.
<EmployeeItem key={employee._id} profile={employee} />

and you are trying to access the value wrongly.
const EmployeeItem = ({employee: name, employement, _id}) => {
}

You could have done either this way
<EmployeeItem key={employee._id} profile={employee} />

and  in EmployeeItem
const EmployeeItem = ({ profile: { name, _id } }) => {
}

or
<EmployeeItem key={employee._id} {...employee} />

and  in EmployeeItem
const EmployeeItem = ({ name, _id }) => {
}


text:
Q: Reduce join table with performing pagination, order by? Sorry this may be a noob question, but I don't know how to search about this.
User case
A full-site Search function : when the user input keyword and submit the form, the system should be search in both title & content of forum, blog, products. The search result of all those type of page should display in one single list with pagination. The user can also chose to ordering the result by relevance or recency.
What I did
I am using LMAP. I have data tables for those three page type , and I have make the title & content column as index Key.
I knew that join table is a very bad idea, so I make three separate query for searching the forum, blog, and products. I get all the data into PHP, make them into array, write a function for making a relevance value for every row of search result. For recency, there is "updateDate" column in all those table, so it is ok.
Now I have three nice array. I can implode() them and sort() them easily. I can also render pagination by array_slice().
What make me Frown
 Unnecessary performance waste. Yes, what I did is able to do all the things in user case , but --- I don't know how to do (I am a beginner), --- but I am sure the performance can be a lot better.

*

*after the first time query, all the data we need has already get from database. but with my solution, whenever user click to another page of search result, or change the "sort by", the php will start over again, and do the [sql query, relevance function, implode()] again. can I someHow store the result array in someWhere , so the system can save some energy for next user action ?

*most of the user will not click on all page of search result. I will guess 90% of user will not keep looking after 10th page, which mean (may be) the first 200 recorded. So, can I do any thing to stop the sql query somewhere instead of all result ?

*furthermore, while the traffic grow, there may be some keywords be come common and repeated searching lots of time, what can I do reduce the repeat of those search ? (pls slap me if you think i am thinking too much)

Thank you for reading these, Please correct me if my concept is incorrect, or tell me if I miss something to notice in this user case. Thank you and may God's love be with you.
Edit : I am not using any php framework.

A: To get you the full story is probably like writing a book. Here are some extracted thoughts:

*

*fully blown page indicators cost you extra data set counts - just present "Next" buttons which can be made up by select ... limit [nr_of_items_per_page+1] and then if(isset($result[nr_of_items_per_page+1])) output next button

*these days net traffic costs are not as high as ten years ago and users demand for more. Increase your nr_of_items_per_page to 100, 200, 500 (depending on the data size per record)

*Zitty Yams comments work out - I have loaded >10000 records in one go to a client and presented those piece by piece - it just rocks - eg. a list of 10000 names with 10 characters avg makes just 100000 Bytes. Most of the images you get in the net are bigger then that. Of cause there are limits...

*php caching via $SESSION works as well - however keep in mind that each Byte to be reserved for php cannot be dedicated to the database (at least not on a shared server). As long as not all data in the database fit into memory, in most cases it is more efficient to extend database memory rather than increasing php caches or os caches.


text:
Q: How do I redirect Weblogic logging to database? Is there a way to send or redirect Weblogic (or Fusion Middleware) logging output to a database, without having to write a custom application? All the documentation I've read seem to deal exclusively with files.

A: Weblogic is not actually my field, but according to Oracle's documentation, you should be able to send WLS logs to syslog using Log4j Logger, from where it is again possible to forward them to MySQL (and some other) databases.
See here for rsyslog instructions and here for syslog-ng.
This syslog-approach has its benefits, since it is rather trivial to send syslogs from several servers to one central repository and then store them to a database there. Additionally there are front ends available (this to promote one I have used) to ease up analysing.
However this solution probably will not qualify as "without having to write a custom application". Perhaps someone else has better ideas.

A: Since Weblogic is capable of utilizing generic Log4j logger facility, it is possible to configure it to send the logs to database.
See here about configuring WLS to use Log4j and here and here about configuring Log4j to direct logs to a database.
This again may not qualify as "without having to write a custom application", but I'm afraid this is as much as out of the box as it gets.

A: There are 3 types of log sources that an WebLogic application can generate:

*

*STDOUT, WebLogic server, HTTP access, transaction and audit logging are using java.util.logging.Logger and can be configured to use log4j easily.

*application logs - use server logging bridge See: http://docs.oracle.com/cd/E21764_01/web.1111/e13739/logging_services.htm#CHDBBEIJ

*JVM STDOUT (like JVM out of memory errors, thread dumps), that can not be managed by log4j nor WebLogic. Those will always go to a file. (Or I could not find out a way to redirect them)

See also: http://docs.oracle.com/cd/E21764_01/web.1111/e13739/logging_services.htm
Any solution you will chose, you will need to take some time to understand it. Logging can be a very complex task.


text:
Q: Error in implementation of a stack with O(1) find-max/find-min? I have implemented several functions for the Stack ADT. I am trying to find the max and min values in O(1) time and I have augmented my stack structure to serve this purpose. This is my code:
 void mms_push(MMStack mms, int i) {

struct llnode *new = malloc(sizeof(struct llnode));
new->item = i;
if(mms->len!=0)
{
 new->next = mms->topnode;
 mms->topnode = new;
}
else
{
 new->next = NULL;
 mms->topnode = new;
}

if (mms->len == 0)
{
mms->topnode->minc = i;
mms->topnode->maxc = i;}
else
{
  if(mms->topnode->maxc < i)
  {
      mms->topnode->maxc = i;
  }

  if(i<mms->topnode->minc)
  {
      mms->topnode->minc = i;
  }

mms->len++;}

int mms_pop(MMStack mms) {
  assert(mms);
  int ret = mms->topnode->item;
  struct llnode *backup = mms->topnode;
  mms->topnode = mms->topnode->next;
  mms->len--;

  free(backup);
  return ret;
}

My structures used are as below:
struct llnode
{

  int item;
  struct llnode *next;
  int minc;
  int maxc;
};

struct mmstack
{
  int len ;
  struct llnode *topnode;

};

typedef struct mmstack *MMStack;

I am not getting the correct value of max and min values. How do I correct the code so that I get the right value of max and min element in the stack?
Thanks in advance!

A: Take a look at this code:
if (mms->len == 0)
{
  mms->topnode->minc = i;
  mms->topnode->maxc = i;
}
else
{
  if(mms->topnode->maxc < i)
  {
      mms->topnode->maxc = i;
  }

  if(i<mms->topnode->minc)
  {
      mms->topnode->minc = i;
  }
}

Notice that in the else branch, you're reading the values of mms->topnode->minc and mms->topnode->maxc before you've initialized them. I think you meant to look at the values of mms->topnode->minc/maxc before you reassigned mms->topnode. To fix this, try doing something like this:
else
{
  mms->topnode->maxc = mms->topnode->next->maxc;
  mms->topnode->minc = mms->topnode->next->minc;

  if(mms->topnode->maxc < i)
  {
      mms->topnode->maxc = i;
  }

  if(i<mms->topnode->minc)
  {
      mms->topnode->minc = i;
  }
}

These extra two lines initialize the min and max values to the old max values before comparing against i, which should ensure that they get a value.
Hope this helps!

A: You're doing things a bit backwards — comparing i to the values in the new, uninitialised node after you have inserted it in the stack.
It's easier to first prepare the new node completely, and then link it into the stack.
Assuming that an empty stack has a NULL topnode:
void mms_push(MMStack mms, int i) {
   struct llnode *new = malloc(sizeof(struct llnode));
   new->item = i;
   new->next = mms->topnode;
   if (!mms->topnode)
   {
       new->minc = i;
       new->maxc = i;
   }
   else
   {
      new->minc = min(mms->topnode->minc, i);
      new->maxc = max(mms->topnode->maxc, i);
   }
   mms->topnode = new;
   mms->len++;
}

I'm not sure if min and max are C99, but they're trivial to define.


text:
Q: Can't set target worksheet from macro I have this sub which processed macros that I added into 2 excel files and everything worked.
Now I've learned that the files that are to be processed won't have these macros and I should store them elsewhere. I put them in an empty workbook and I can call the macro.
The problem is, it's target is itself (an empty workbook).
I need to to work on the Excel I have opened (x1)
It was originally
xl.Run macroName

the macro and target worksheets were contained here
Now I have this but I need it to run on the worksheets of x1, not itself.
myMacro.Run macroName
'runs but no worksheets here

Here is the full code of the sub
Sub prepareReport(macroName As String)

Dim myMacro As Object
Dim xl As Object

Dim filePath As String
Dim fileName As String

fileName = determineFileNameAuto(macroName)
filePath = CurrentProject.Path + "\source_files\" + fileName

'load macro-excel files
Set myMacro = CreateObject("Excel.Application")
myMacro.Workbooks.Open (myMacroFilePath)

'Load Excel file, then open the target workbook.
Set xl = CreateObject("Excel.Application")
xl.Workbooks.Open (filePath)

'Run the  macros

 'originally was
 'xl.Run macroName
 'macros were contained within file

'this will run but the target should be the x1 workbook
myMacro.Run macroName

' Close and save the workbook, then close Excel
echoBackToForm ("Closing Workbook")
   xl.ActiveWorkbook.Close (True)
   xl.Quit

'Step 5:  Memory Clean up.
Set xl = Nothing

End Sub


text:
Q: R: Solve for variable for all rows, and output answer to new column I have the formula: f=b*(1-exp((-t)/x))
f, b, and t all correspond to columns in my data frame, and I am trying to solve for x. I want to solve for x for each row in the data frame and output the answer into a new column.
I have tried doing something like this:
f <- df$value
t <- df$time
b <- df$initial

formula <- function(x){
     f=b*(1-exp((-t)/x))
}

df$answer <- solve(formula(x))

I've also tried things like:
apply(df[,c("answer", 1, FUN=formula)

I've also tried doing a Vectorize function.
But I cannot seem to get anything right.


text:
Q: Change image when clicked via javascript I'm building a website for home automation, I'm trying to get the image to change when I click it but what happens is it disappears into nothing and doesn't change back! I've tried multiple online scripts but same result.
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Raspberry Pi Home Automation</title>
<link href="css/singlePageTemplate.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

A: I'm not sure what is happening for you but your script seems to be working fine as you can see below.
Are you sure the image paths/file names are correct? If the second image doesn't exist it will just be an empty tag with no src image and therefore have no width or height for you to click it again to change it back.
Check the console also and let us know if there are any errors there.

function changeImage() {
  if (document.getElementById("imgClickAndChange").src == "https://via.placeholder.com/150/0000ff"){
    document.getElementById("imgClickAndChange").src = "https://via.placeholder.com/150/ff0000";
  }else{
    document.getElementById("imgClickAndChange").src = "https://via.placeholder.com/150/0000ff";
  }
}


text:
Q: Tweepy: How can I look up more than 100 user screen names You can only retrieve 100 user objects per request with the
api.lookup_users() method. Is there an easy way to retrieve more than 100 using Tweepy and Python? I have read this post: User ID to Username tweepy but it does not help with the more than 100 problem. I am pretty novice in Python so I cannot come up with a solution myself. What I have tried is this:
users = []
i = 0
num_pages = 2
while i < num_pages:
    try:
        # Look up a collection of ids
        users.append(api.lookup_users(user_ids=ids[100*i:100*(i+1)-1]))
    except tweepy.TweepError:
        # We get a tweep error
        print('Something went wrong, quitting...')
    i = i + 1

where ids is a list containing the ids, but I get IndexError: list index out of range when I try to get a user with index higher than 100. If it helps I am only interested in getting the screen names from the user ids.

A: I haven't tested it since I don't have access to the API.
But if you have a collection of user ids in any range, this should fetch all of them.
It fetches any remainder first, meaning if you have a list of 250 ids, it will fetch 50 users with the last 50 ids in the list.
Then it will fetch the remaining 200 users in batches of hundreds.
from tweepy import api, TweepError

users = []
user_ids = []  # collection of user ids
count_100 = int(len(user_ids) / 100)  # amount of hundred user ids

if len(user_ids) % 100 > 0:
    for i in range(0, count_100 + 1):
        try:
            if i == 0:
                remainder = len(user_ids) % 100
                users.append(api.lookup_users(user_ids=user_ids[:-remainder]))
            else:
                end_at = i * 100
                start_at = end_at - 100
                users.append(api.lookup_users(user_ids=user_ids[start_at:end_at]))

         except TweepError:
             print('Something went wrong, quitting...')

A: You're right that you need to send the tweets to the API in batches of 100, but you're ignoring the fact that you might not have an exact multiple of 100 tweets. Try the following:
import tweepy

def lookup_user_list(user_id_list, api):
    full_users = []
    users_count = len(user_id_list)
    try:
        for i in range((users_count / 100) + 1):
            full_users.extend(api.lookup_users(user_ids=user_id_list[i*100:min((i+1)*100, users_count)]))
        return full_users
    except tweepy.TweepError:
        print 'Something went wrong, quitting...'

results = lookup_user_list(ids, api)

By taking the minimum of results = lookup_user_list(user_ids, main_api) we ensure the final loop only gets the users left over. results will be a list of the looked-up users.
You may also hit rate limits - when setting up your API, you should take care to let tweepy catch these gracefully and remove some of the hard work, like so:
consumer_key = 'X'
consumer_secret = 'X'
access_token = 'X'
access_token_secret = 'X'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)


text:
Q: Dojo datagrid filtering by "ANY COLUMN" broken by IE's max URL length limit Internet Explorer cannot handle URLs longer than 2083 characters (ref: What is the maximum length of a URL in different browsers?)
Using a Dojo EnhancedGrid with the Filter plugin, it is possible for a user to apply a filter to "ANY COLUMN". With serverside filtering enabled, the resulting URL is the same as if the user applied the same filter individually to every column, producing a GET request to a very long URL.
Is there a way around this?
var myStore = new JsonRest({target:"duck/", sortParam: "sortBy"});
grid = new EnhancedGrid({
    store: dataStore = new ObjectStore({objectStore: myStore}),
    id: "colId",
    query: { colId: "*"},
    structure: [
    //whole bunch of columns
    ],
    plugins:{
        filter:{
            isServerSide: true,
            itemsName: "ducks",
            setupFilterQuery: function(commands, request){
                request.query.filter =  JSON.stringify(commands.filter)
            }
        }
    }

A: The two options I see are:
1) Modify or switch the objectstore to be able to POST the filter parameters.
2) (chosen) Compress the URL using a simple search/replace dictionary. This works very well if you target large chunks of frequently recurring JSON.


text:
Q: Covariance of two random vectors IF I have $X,Y_1,...,Y_n$ iid then how do I calculate:
cov  $\left [\begin{pmatrix}X\\.\\.\\.\\X \end{pmatrix}, \begin{pmatrix}Y_1\\.\\.\\.\\Y_n \end{pmatrix}\right]$?

A: This is known as the cross-covariance between vectors, and is defined by
$$
\text{cov}[\boldsymbol{X},\boldsymbol{Y}] = \text{E}[(\boldsymbol{X}-\boldsymbol{\mu_X})(\boldsymbol{Y}-\boldsymbol{\mu_Y})^\text{T}]
$$
where
$$
\boldsymbol{\mu_X} = \text{E}[\boldsymbol{X}]\\
\boldsymbol{\mu_Y} = \text{E}[\boldsymbol{Y}]
$$
In your case, because all the components of $\boldsymbol{X}$ are the same, things simplify greatly.
$$
\boldsymbol{X} = X
\left[
\begin{array}{c}1\\1\\\vdots\\1\end{array}
\right], \;\;
\boldsymbol{\mu_X} = \mu_X
\left[
\begin{array}{c}1\\1\\\vdots\\1\end{array}
\right]
$$
Where $\mu_X=\text{E}[X]$. Then
$$
\boldsymbol{X}-\boldsymbol{\mu_X} = (X-\mu_X)
\left[
\begin{array}{c}1\\1\\\vdots\\1\end{array}
\right]
$$
Now
$$
(\boldsymbol{X}-\boldsymbol{\mu_X})(\boldsymbol{Y}-\boldsymbol{\mu_Y})^\text{T} =
(X-\mu_X)
\left[
\begin{array}{c}1\\1\\\vdots\\1\end{array}
\right]\left[
\begin{array}{cccc}Y_1-\mu_1&Y_2-\mu_2&\cdots&Y_n-\mu_n\end{array}
\right]
$$
where $\mu_m=\text{E}[Y_m]$ for $m\in[1,2,\cdots,n]$. Expanding out that matrix product we have
$$
(\boldsymbol{X}-\boldsymbol{\mu_X})(\boldsymbol{Y}-\boldsymbol{\mu_Y})^\text{T} =
(X-\mu_X)\left[
\begin{array}{cccc}
Y_1-\mu_1&Y_2-\mu_2&\cdots&Y_n-\mu_n\\
Y_1-\mu_1&Y_2-\mu_2&\cdots&Y_n-\mu_n\\
\vdots&\vdots&\ddots&\vdots\\
Y_1-\mu_1&Y_2-\mu_2&\cdots&Y_n-\mu_n
\end{array}
\right]
$$
Taking that scalar inside the matrix, we see it multiplies each entry in the matrix. Then taking the expectation of the result finally gives
$$
\text{E}[(\boldsymbol{X}-\boldsymbol{\mu_X})(\boldsymbol{Y}-\boldsymbol{\mu_Y})^\text{T}] =
\left[
\begin{array}{cccc}
\text{E}[(X-\mu_X)(Y_1-\mu_1)]&\text{E}[(X-\mu_X)(Y_2-\mu_2)]&\cdots&\text{E}[(X-\mu_X)(Y_n-\mu_n)]\\
\text{E}[(X-\mu_X)(Y_1-\mu_1)]&\text{E}[(X-\mu_X)(Y_2-\mu_2)]&\cdots&\text{E}[(X-\mu_X)(Y_n-\mu_n)]\\
\vdots&\vdots&\ddots&\vdots\\
\text{E}[(X-\mu_X)(Y_1-\mu_1)]&\text{E}[(X-\mu_X)(Y_2-\mu_2)]&\cdots&\text{E}[(X-\mu_X)(Y_n-\mu_n)]
\end{array}
\right]
$$
$$
=
\left[
\begin{array}{cccc}
\text{cov}(X,Y_1)&\text{cov}(X,Y_2)&\cdots&\text{cov}(X,Y_n)\\
\text{cov}(X,Y_1)&\text{cov}(X,Y_2)&\cdots&\text{cov}(X,Y_n)\\
\vdots&\vdots&\ddots&\vdots\\
\text{cov}(X,Y_1)&\text{cov}(X,Y_2)&\cdots&\text{cov}(X,Y_n)
\end{array}
\right]
$$
Now we are at the answer: you specified all the variables to be identically distributed and independent. Independent variables have covariance $0$. SO, you get the all zeros matrix for your answer
$$
\text{cov}(\boldsymbol{X},\boldsymbol{Y})=\text{E}[(\boldsymbol{X}-\boldsymbol{\mu_X})(\boldsymbol{Y}-\boldsymbol{\mu_Y})^\text{T}] =
\left[
\begin{array}{cccc}
0&0&\cdots&0\\
0&0&\cdots&0\\
\vdots&\vdots&\ddots&\vdots\\
0&0&\cdots&0\\
\end{array}
\right]
$$

A: Covariance of $2$ vectors is basically what is called a variance-covariance matrix $(\Sigma)$ defined as
$$((\Sigma_{ij}))=Cov(X_i,Y_j)$$ where $Cov(A,B)=E(AB)-E(A)E(B)$
For more details, just Google Variance Covariance matrix.
Specifically, because of the iid character of your variables, $Cov$ will be $0$ for all.


text:
Q: failed to run springboot. getting dependency injection error in service layer when I inject DAO, it fails to run the server. tried clean cache and .gradle and clean build. jpa repository and kotlin reflect are also added as a gradle dependencies.
error log
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-08-06 01:03:04.625 ERROR 92784 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'businessController' defined in file [/Users/hadi/Documents/house/code/backend-kotlin-rest/api/build/classes/kotlin/main/com/house/api/controller/BusinessController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'businessServiceImpl': Resolution of declared constructors on bean Class [com.house.api.service.BusinessServiceImpl] from ClassLoader [org.springframework.boot.devtools.restart.classloader.RestartClassLoader@5598bc99] failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/repository/CrudRepository
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) [spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) [spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) [spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) [spring-boot-2.6.6.jar:2.6.6]
    at com.house.api.ApiApplicationKt.main(ApiApplication.kt:20) [main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_322]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_322]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_322]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_322]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.7.1.jar:2.7.1]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'businessServiceImpl': Resolution of declared constructors on bean Class [com.house.api.service.BusinessServiceImpl] from ClassLoader [org.springframework.boot.devtools.restart.classloader.RestartClassLoader@5598bc99] failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/repository/CrudRepository
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:309) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1302) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1219) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.18.jar:5.3.18]
    ... 23 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/repository/CrudRepository
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_322]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756) ~[na:1.8.0_322]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_322]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:473) ~[na:1.8.0_322]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74) ~[na:1.8.0_322]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369) ~[na:1.8.0_322]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363) ~[na:1.8.0_322]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_322]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362) ~[na:1.8.0_322]
    at org.springframework.boot.devtools.restart.classloader.RestartClassLoader.findClass(RestartClassLoader.java:160) ~[spring-boot-devtools-2.7.1.jar:2.7.1]
    at org.springframework.boot.devtools.restart.classloader.RestartClassLoader.loadClass(RestartClassLoader.java:142) ~[spring-boot-devtools-2.7.1.jar:2.7.1]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_322]
    at java.lang.Class.getDeclaredConstructors0(Native Method) ~[na:1.8.0_322]
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671) ~[na:1.8.0_322]
    at java.lang.Class.getDeclaredConstructors(Class.java:2020) ~[na:1.8.0_322]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:304) ~[spring-beans-5.3.18.jar:5.3.18]
    ... 36 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.data.repository.CrudRepository
    at java.net.URLClassLoader.findClass(URLClassLoader.java:387) ~[na:1.8.0_322]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_322]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352) ~[na:1.8.0_322]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_322]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_322]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_322]
    at org.springframework.boot.devtools.restart.classloader.RestartClassLoader.loadClass(RestartClassLoader.java:145) ~[spring-boot-devtools-2.7.1.jar:2.7.1]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_322]
    ... 52 common frames omitted

Process finished with exit code 0

domain
@Entity
class Business(
    @Id
    @Column(columnDefinition = "uuid")
    override val id: UUID = UUID.randomUUID()
    )

service
@Service
class BusinessServiceImpl(
    @Autowired private val businessDAO: BusinessDAO // when I inject dependency it fails to run the server.
) : BusinessService {
    override fun save(addBusinessRequest: AddBusinessRequest): Business? {
        return businessDAO.save(addBusinessRequest.toBusiness())
    }
    fun AddBusinessRequest.toBusiness(): Business {
        return Business(
            name = name)
    }
    fun UpdateBusinessRequest.toBusiness(): Business {
    return Business(
        id = id,
        name = name)
    }
}

dao
@Repository
interface BusinessDAO :
    CrudRepository<Business, UUID>,
    JpaRepository<Business, UUID>,
    JpaSpecificationExecutor<Business>

dto
data class AddBusinessRequest(
    val name: String? = null)
data class UpdateBusinessRequest(
    val id: UUID,
    val name: String? = null)

#Application
@EntityScan // not helping
@EnableJpaRepositories // not helping
@SpringBootApplication
@RestController // not helping
class ApiApplication
fun main(args: Array<String>) {
    runApplication<ApiApplication>(*args)
}

A: First "BusinessDAO" is a repository. As far in your code I saw dependency injection process is not implemented in a right way. Try this and let me know.
#Add this compiler plugin in maven dependency
<compilerPlugins>
    <plugin>jpa</plugin>
</compilerPlugins>

#Application class
@SpringBootApplication
class ApiApplication

fun main(args: Array<String>) {
    runApplication<ApiApplication>(*args)
}

#Domain class
@Entity
class Business(
        @Id
        @Column(columnDefinition = "uuid")
        val id: UUID,
        @Column
        val name: String
)

#Service class
@Service
class BusinessServiceImpl @Autowired constructor(val businessDAO: BusinessDAO) : BusinessService {
    override
    fun save(addBusinessRequest: AddBusinessRequest): Business? {
        return businessDAO.save(addBusinessRequest.toBusiness())
    }

    fun AddBusinessRequest.toBusiness(): Business {
        return Business(UUID.randomUUID(), name = "Name of business")
    }

    fun UpdateBusinessRequest.toBusiness(): Business {
        return Business(
                id = UUID.randomUUID(),
                name = "Updated business")
    }
}

#Business Service class
interface BusinessService {
    open fun save(addBusinessRequest: AddBusinessRequest): Business?
}

Or check the link : https://tedblob.com/kotlin-spring-dependency-injection/


text:
Q: Ember not posting date attribute I have a date attribute on my Ember model:
// models/foo.js
export default DS.Model.extend({
  name: attr('string'),
  startDate: attr('date')
});

My component is setting the date in the ISO 8601 format as is convention:
// components/date-picker.js
export default Ember.Component.extend({
...
picker.on({
  set: function(timestamp) {
    // timestamp.select is a unix timestamp
    var date = new Date(timestamp.select);
    var iso = date.toISOString();
    self.set('property', iso);
  }
});
...

And I can see this reflected in the Ember inspector:

However when Ember posts the data to my backend, the startDate is null.
Does anyone have an idea why this might be?

A: The date transform expects your property to be a date object client side, not a string.  It checks when serializing it that it's an instance of Date.
serialize: function(date) {
  if (date instanceof Date) {
    return toISOString.call(date);
  } else {
    return null;
  }
}

You are better off setting the property to the date object, and letting it call toISOString when it serializes it to send off to the server.


text:
Q: Why did Harry tell Snape's secret to everyone? In the climax of the Battle of Hogwarts, when he duels the Dark Lord for the last time, Harry Potter explains to the Dark Lord that Professor Snape was in love with Lily Potter.

 'Snape's Patronus was a doe,' said Harry, 'the same as my mother's, because he loved her for nearly all his life, from the time when they were children. […]'

(Harry addresses the Dark Lord here, but it seems that everyone in the hall can hear his speech.)
Why would Harry do that, if he knows that Professor Snape specifically wanted to keep that a secret?  This seems very disrespectful towards Professor Snape to me.

A: One thing to consider is that Harry is in a fight for his life.  I think he would have grabbed any tool that was available to him.  He was thinking on his feet.
There is another thing to consider relating to whether his revealing of this (somewhat open, arguably) secret was respectful of Snape or not.  Harry's entire picture of Snape had just been radically rewritten--inconceivably rewritten, probably--and, for all we know, Harry was honoring Snape's memory, recognizing that his incredible courage was sourced, fundamentally, from the greatest of all possible motivations.
It seems likely to me that he is throwing Snape at Voldemort as an example of greatness in the same way that he just previously threw Dumbledore at him.  He is presenting Dumbledore as someone who had the capability to do what Voldemort did, but the wisdom not to.  And he is presenting Snape as someone that would go to incredible lengths to be loyal to someone that he loved, at great personal sacrifice.  Snape and Dumbledore both laid down their lives to save Harry;  Harry could, in his mind, be paying the highest honor he could to that memory.

A: (Too long for a comment, hence posted as an answer.)
On what basis do you rest the claim that "Professor Snape specifically wanted to keep [his love for Harry's mother] a secret"? As far as I can tell, (a) Snape's love for Lily was never a secret and (b) at no point did Snape make Harry promise to keep this (non-)secret.
When Snape, Lily Evans, James Potter, Sirius Black, Remus Lupin etc attended Hogwarts, it was widely known that Snape admired and loved Lily. Voldemort too knew that Snape had been in love with Lily. Not much of a secret, this piece of knowledge... It is probably true that not many people knew the reason for why Snape's Patronus was a doe -- that Lily's Patronus was a doe too. However, that's just one -- admittedly very tangible -- proof of the strong feelings Snape felt for Lily, not a revelation of the underlying secret.
For sure, Snape made Dumbledore promise -- immediately following the deaths of Harry's parents -- that he (Dumbledore) would never let Harry know that Snape was committed to helping Harry survive and succeed. Importantly, though, Snape extracted no such promise before giving Harry his memories as he was dying from Nagini's bites. Harry was thus free to make use of the memories as he saw fit.
The two preceding paragraphs are based on the very end of Chapter 32, "The Elder Wand", and on Chapter 33, "The Prince's Tale", in HP7.

A: Speculation:
He's using it as further evidence that Snape had turned against Voldemort and had been playing him the entire time.
He's calling out to Voldemort that not only was his attack on Harry and his family part of his original undoing - but it will ultimately serve to be part of his final undoing and Snape will have had a hand in that, all because of love. He's telling Voldemort that he (Voldemort) had miscalculated entirely on the front of how powerful a motivator and magical power love can be.
Harry is in a battle for his life with the most powerful dark wizard ever. He isn't going to say "hey - I've got some news for you, but, it's kind of a secret from a former pal of yours and he may not be terribly comfortable with me telling everyone standing around here listening. Would you mind leaning in so I can whisper it to you? Be cool though, no attacking."
Additionally, Harry probably on some level did want to redeem Snape in the eyes of everyone, just in case Harry died. They all spent years not trusting and hating Snape and Harry had a chance to correct some perceptions about Snape and Snape's motivations. But, on the other hand, while he eventually came to respect and admire Snape, Harry probably still had 7 years of harassment to outweigh any concerns over Snape's feelings over being potentially embarrassed.
Also - Snape didn't care anymore :\

A: Harry knew that he could not let Voldemort win at any cost, as it was not just a battle for Hogwarts but a battle for the whole Wizarding and Muggle communities. This is not the first time they had come face to face, and it was not just because of Harry's own wizarding might that he managed to stay alive in their previous encounters.

*

*He survived as a baby after taking a direct hit from the Killing Curse of Voldemort at his forehead; the curse was not only ineffective but managed to send Voldemort into hiding in a highly weakened state. Harry, as a baby, of course did not control this win.

*In Goblet of Fire, the power of their Wands prevented Voldemort from making the strike, and then the memories of Harry's parents took shape and delayed Voldemort from taking a second strike as the Wand connection broke away. Harry was on the retreat, quickly disappearing with Cedric's body as another Killing Curse narrowly missed him. Again Harry did not fully control this win.

*In The Deathly Hallows, Voldemort made the strike in the Forbidden forest at point blank range, but Harry survived that Killing Curse too, where he offered no visible resisting spells back at Voldemort. Harry walked into Forbidden forest not armed with an attack plan to win, he offered no fight, and was giving himself up for the sake of the rest of the world.

But in the final battle Harry would have realized the meaning of his past wins with Voldemort. Harry now would be a fool to not realize that he cannot defeat the mighty Voldemort in a head-on duel with the handful of spells he knows, as compared to Voldemort's huge arsenal of destructive spells. In all the three instances mentioned above, the common factor was the invisible protection of his parents, binding to his body, especially Lily's. He knew that if there is one thing Voldemort couldn't comprehend fully with all his wizarding might, it was the unknown, invisible protection of Love, the white divine magic that could resist all destructive dark spells. And again it was this concoction of Love and emotions inside Harry that prevented Voldemort from possessing Harry for too long at the battle at the Department of Mysteries in the Order of the Phoenix.
He walked to the final battle knowing that Snape who was Voldemort's right-hand man was in fact Dumbledore's man through and through. And that Snape had an undying Love towards his mother and caring for Harry that remained till his last breath. He knew that by letting Voldemort know about his trusted man's true credentials and its underlying tale of Love, he would be reminding Voldemort again about the power of Love, the magic he never was able to fathom, one which he not only despised but perhaps even feared, and by re-confirming its existence to him using Snape's case was perhaps one of the most powerful weapons he could unleash against him.


text:
Q: How can I dynamically load two (or more) different versions of a class in VB.Net? I have multiple classes generated from xsd files (given to me by a third party), that conflict with each other, in terms of the class name and individual properties within the class.  I was thinking if I could load only one class at a time, I could use all these classes within one project.
Is there a relatively simple way to do this?

A: You cannot.
What you can do however is put them in different namespaces. Now you can have them all in your program even at the same time.

A: I found that xsd.exe also has a parameter /N for namespace - that inserts the namespace correctly - so I can follow that syntax for adding the namespace manually (or rerun xsd.exe)


text:
Q: VB.net chart controls and sql server Problem: I am currently using a vb application(Visual Studio 2012) to query my database (SQL Server 2012) and display the information using the chart control feature in vb.net
Additional information: I want the x axis to display location name and y axis to display the count of the location
I have complied the code and cannot seem to find the error in the line of code. Please find the code below!
Code:
My code is as follows:
    Dim cnn3 As New SqlConnection
    Dim cmd3 As New SqlCommand

    cnn3.ConnectionString = ("Data Source=SARAHSCOMPUTER;Initial Catalog=FYPDB1;Integrated Security=True")
    cmd3.Connection = cnn3

    Dim tblFields As String = "SELECT * from tblTagInfo"
    Dim oData As New SqlDataAdapter(tblFields, cnn3)
    Dim ds As New DataSet
    Dim oCmd As New SqlCommand(tblFields, cnn3)

    cnn3.Open()
    oData.Fill(ds, "tblTagInfo")
    cnn3.Close()

    Chart1.DataSource = ds.Tables("tblTagInfo")
    Dim Series1 As Series = Chart1.Series("Series1")
    Series1.Name = "Location"
    Chart1.Series(Series1.Name).XValueMember = "Location"
    Chart1.Series(Series1.Name).YValueMembers = "SELECT COUNT (Area) FROM tblLocation group by Location"

    Chart1.Size = New System.Drawing.Size(780, 350)
End Sub

A: Please try this code:
Dim cnn3 As New SqlConnection
Dim cmd3 As New SqlCommand

cnn3.ConnectionString = ("Data Source=SARAHSCOMPUTER;Initial Catalog=FYPDB1;Integrated Security=True")
cmd3.Connection = cnn3

Dim tblFields As String = "SELECT COUNT(Location) AS LocationCount, Location AS LocationName FROM tblTagInfo group by Location"
Dim oData As New SqlDataAdapter(tblFields, cnn3)
Dim ds As New DataSet
Dim oCmd As New SqlCommand(tblFields, cnn3)

cnn3.Open()
oData.Fill(ds, "tblTagInfo")
cnn3.Close()

Chart1.DataSource = ds.Tables("tblTagInfo")
Dim Series1 As Series = Chart1.Series("Series1")
Series1.Name = "Sales"
Chart1.Series(Series1.Name).XValueMember = "LocationName"
Chart1.Series(Series1.Name).YValueMembers = "LocationCount"

Chart1.Size = New System.Drawing.Size(780, 350)


text:
Q: ¿Cómo hago para pasar variables entre funciones? en Python Digamos que yo, tengo cierta función llamada name, con una variable dentro que sea una lista, digamos que la lista num[1,2], y nosotros queremos dar esta lista  a otra función, como hacemos ¿Cómo para pasarla como parámetro?
Este es el codigo en python (bastante sencillo), pero es una duda que como principiante, aún teniendo varios meses de experiencia no me queda totalmente claro:
def main():

    lista = [1,2]

    sum(suma)

def sum():

    suma = 0

    for i in lista:

        suma  += i

    return(suma)

main()

En este pequeño programa vemos la lista que ha sido declarada en la función main, pero tengo absoluto desconocimiento de como usar esta variable en otra función, seguramente sea una tontería, pero me aclararí el paso de parámtros entre funciones. Muchas gracias por su atención!

A: En Python, por defecto cuando una variable se crea fuera de una función, se considera global por lo que puede usarse en cualquier parte del código:
x = "mundo"

def myfunc():
  print("Hola " + x)

myfunc()

Cuando se crea dentro de una función, se considera local y solo puede usarse dentro de esa función. Por ejemplo, el siguiente código te dará error porque x no existe como variable global, solo como local:
def myfunc():
  x = "mundo"
  print("Hola " + x)

myfunc()

print("Hola " + x)

Pero existe otra opción, que es definir una variable local como global. Es decir, la creas dentro de una función pero especificas que va a ser de tipo global con la instrucción global:
def myfunc():
  global x
  x = "mundo"
  print("Hola " + x)

myfunc()

print("Hola " + x)

Este último código, aunque x se haya creado como variable local dentro de una función, se ha especificado que va a ser global, con lo que puede usarse en cualquier parte del código de ahora en adelante.

Global
variables

Entonces, con todo esto en mente, prueba tu código así:
def main():
    global lista
    lista = [1,2]
    sum(suma)

def sum():
    suma = 0
    for i in lista:
        suma  += i
    return(suma)

main()

Y ya por último, entiendo que como estás aprendiendo Python estás haciendo códigos sencillos (y eso está fenomenal, yo hago lo mismo) pero que sepas que puedes sumar todos los valores de una lista sin necesidad de hacer un bucle:
sum(lista) te devolverá la suma de la lista entera:

Función sum()

A: Basicamente para pasar variables entre funciones, vamos a asignar a un parámetro a una función, por ejemplo, si tenemos la función de suma(numbers), el parámetro numbers equivaldrá a lo que nosotros le pasemos como parámetro más tarde a la función. El ejemplo aquí:
def main():

    lista = [1,2,3,4]

    print(suma(lista))

def suma(numbers):

    suma = 0

    for i in numbers:

        suma += i

    return suma

main()

Nosotros en la función main tenemos la variable de lista que contiene en si, los numeros [1,2,3,4], entonces podemos decir que lista equivale a [1,2,3,4].
Y en la funcion de suma, debemos crear un parámetro que pueda ser equivalente a la lista de nuestra función main.
Entonces para generar esta equivalencia necesitaremos introducir el parametro que queremos que equivalga a otro, que en nuestro caso es numbers, y lo introducimos también como parámtro en nuestra función suma entre los parentesis, para entendernos mejor, main(#Variable a ser equivalente a otra#), en este caso nosotros generaremos equivalencia entre lista y numbers, por lo tanto nuestra función de suma deberá quedar así suma(numbers); con esto le estamos diciendo a suma, que cuando llamemos a la función suma desde cualquier otro lugar, e introduzcamos un numero, variable o demás en forma de parámetro, por ejemplo suma(parámetro), nuestro parámetro introducido va a hacer equivalencia con numbers.
Basicamente suma(#Parámetro introducido por ejemplo con valor 1#) hace que numbers sea igual que parámetro introducido.