text:
Q: Using shader for calculations Is it possible to use shader for calculating some values and then return them back for further use?
For example I send mesh down to GPU, with some parameters about how it should be modified(change position of vertices), and take back resulting mesh? I see that rather impossible because I haven't seen any variable for comunication from shaders to CPU. I'm using GLSL so there are just uniform, atributes and varying. Should I use atribute or uniform, would they be still valid after rendering? Can I change values of those variables and read them back in CPU? There are methods for mapping data in GPU but would those be changed and valid?
This is the way I'm thinking about this, though there could be other way, which is unknow to me. I would be glad if someone could explain me this, as I've just read some books about GLSL and now I would like to program more complex shaders, and I wouldn't like to relieve on methods that are impossible at this time.
Thanks

A: Great question! Welcome to the brave new world of General-Purpose Computing on Graphics Processing Units (GPGPU).
What you want to do is possible with pixel shaders. You load a texture (that is: data), apply a shader (to do the desired computation) and then use Render to Texture to pass the resulting data from the GPU to the main memory (RAM).
There are tools created for this purpose, most notably OpenCL and CUDA. They greatly aid GPGPU so that this sort of programming looks almost as CPU programming.
They do not require any 3D graphics experience (although still preferred :) ). You don't need to do tricks with textures, you just load arrays into the GPU memory. Processing algorithms are written in a slightly modified version of C. The latest version of CUDA supports C++.
I recommend to start with CUDA, since it is the most mature one: http://www.nvidia.com/object/cuda_home_new.html

A: This is easily possible on modern graphics cards using either Open CL, Microsoft Direct Compute (part of DirectX 11) or CUDA. The normal shader languages are utilized (GLSL, HLSL for example).  The first two work on both Nvidia and ATI graphics cards, cuda is nvidia exclusive.
These are special libaries for computing stuff on the graphics card. I wouldn't use a normal 3D API for this, althought it is possible with some workarounds.

A: Now you can use shader buffer objects in OpenGL to write values in shaders that can be read in host.

A: My best guess would be to send you to BehaveRT which is a library created to harness GPUs for behavorial models. I think that if you can formulate your modifications in the library, you could benefit from its abstraction
About the data passing back and forth between your cpu and gpu, i'll let you browse the documentation, i'm not sure about it


text:
Q: Buddypress user registration validation not working with custom select query I have created a phone number as Buddypress Profile field. I need to check that no two or more user accounts share the same phone number. My query below is not enforcing the restriction.
I need help to resolve this.
function bp_phone_number_validate() {
   global $bp;
   global $wpdb;

  // check if phone number is in use
  $result=$bp->get_var("SELECT COUNT(*) FROM {$bp->profile->wp_bp_xprofile_data} WHERE value = '{$_POST['field_2']}' GROUP BY id;");

  if($result > 0){
    $bp->signup->errors['field_2'] = __( 'Phone number is already in use.', 'buddypress' );
  }
}
add_action( 'bp_signup_validate', 'bp_phone_number_validate');

A: There is no such thing as $bp->get_var.  Try using $wpdb->get_var.
Or try this:
function validate_user_signup($result) {
   global $wpdb;

   $result = $wpdb->get_var("SELECT user_id FROM wp_bp_xprofile_data WHERE value = '{$_POST['field_2']}'");

   if( $result != NULL ){

      $new_error = new WP_Error();

      $new_error->add( 'field_2', __( 'Phone number is already in use.', 'buddypress' ) );

      $result['errors'] = $new_error;
   }

   return $result;
}
add_filter('bp_core_validate_user_signup', 'validate_user_signup', 10, 1);

redpajama_set_name: RedPajamaStackExchange


text:
Q: UBER iOS SDK - 401 error I am following the UBER iOS SDK documentation to integrate uber into my app.
https://github.com/uber/rides-ios-sdk
I am trying to integrate "Ride Request Button" into my app and I copy pasted the example code from the documentation
UBSDKRideRequestButton *button = [[UBSDKRideRequestButton alloc] init];
[self view] addSubview:button];
UBSDKRidesClient *ridesClient = [[UBSDKRidesClient alloc] init];
CLLocation *pickupLocation = [[CLLocation alloc] initWithLatitude: 37.787654 longitude: -122.402760];
CLLocation *dropoffLocation = [[CLLocation alloc] initWithLatitude: 37.775200 longitude: -122.417587];
__block UBSDKRideParametersBuilder *builder = [[UBSDKRideParametersBuilder alloc] init];
builder = [builder setPickupLocation: pickupLocation];
builder = [builder setDropoffLocation: dropoffLocation];
[ridesClient fetchCheapestProductWithPickupLocation: pickupLocation completion:^(UBSDKUberProduct* _Nullable product, UBSDKResponse* _Nullable response) {
    if (product) {
        builder = [builder setProductID: product.productID];
        button.rideParameters = [builder build];
        [button loadRideInformation];
    }
}];

The block UBSDKResponse (response.response) looks as below
<NSHTTPURLResponse: 0x15c6c1eb0> { URL: https://sandbox-api.uber.com/v1/products?latitude=37.787654&longitude=-122.40276 } { status code: 401, headers {
    Connection = "keep-alive";
    "Content-Length" = 63;
    "Content-Type" = "application/json";
    Date = "Thu, 01 Sep 2016 21:39:12 GMT";
    Server = nginx;
    "Strict-Transport-Security" = "max-age=0";
    "X-Content-Type-Options" = nosniff;
    "X-Uber-App" = "uberex-sandbox, migrator-uberex-sandbox-optimus";
    "X-XSS-Protection" = "1; mode=block";
} }

I have configured the UberClient ID in my app in info.plist file. Not sure what I am missing to get a 401 response.
Thanks

A: You just need to add the server token to your Info.plist.
Copy this snippet into your Info.plist (right click and select Open As > Source Code) and replace [Your Server Token] with the Server Token from your dashboard (make sure you use the server token corresponding to your client ID).
<key>UberServerToken</key>
<string>[Your Server Token]</string>

Hope this helps!


text:
Q: COALESCE in MySQL returning conversion failed I am trying to execute coalesce as nvl in oracle.
SELECT COALESCE('SYSTEM ADMIN',10)

ideally it should return "SYSTEM ADMIN" AS OUTPUT.
SELECT COALESCE(NULL,10)

And this should return 10.
but this syntax is returning....
SELECT COALESCE('SYSTEM ADMIN',10)

Conversion failed when converting the varchar value 'SYSTEM ADMIN' to data type int.
plz help what's wrong here

A: You should also return a string alternative, (must have the same data type)
SELECT COALESCE('SYSTEM ADMIN', '10') FROM ....


text:
Q: Laravel relationships, return boolean Did anybody figure out if you can return true or false from relationships?
For example i have status and i want to check if current user liked it. But i want to return only true or false, not the whole object with hasOne, because i don't want to return whole object back in JSON response.
I have already tried with
public function isLiked()
{
    return count($this->likes()) > 0;
}

public function likes()
{
    return $this->hasOne("\App\Model\Users\Users","id");
}

But i always get
Call to a member function addEagerConstraints() on boolean
Thanks

A: Use like this
public function isLikedAttribute()//use model mutators
{
    if ( ! array_key_exists('likes', $this->relations)) $this->load('likes');
    $likes = $this->getRelation('likes');
    return count($likes) > 0;
}

public function likes()
{
    return $this->hasOne("\App\Model\Users\Users","id");
}

& from your controller or from other places you just access like
$YOUR_MODEL_OBJECT->isLiked;//replace $YOUR_MODEL_OBJECT with your model object

ref: https://laravel.com/docs/master/eloquent-mutators#accessors-and-mutators


text:
Q: Looking for a prototype slider/carousel I'm looking for a slider/carousel which uses PrototypeJs / script.aculo.us
I've found this:
http://www.protoshow.net/
But I'm looking for functionality which has the ability to display multiple "slides" at once, i.e. more of a carousel effect.
I'd also like the ability to define how many slides are skipped by pressing next.
Please do not recommend: https://code.google.com/p/prototype-carousel/
That code is not fully functional and has been split into multiple branches on github, none of which can functionally skip more than a single slide at a time, or follow proper continuous or "circular" movement, i.e. slide 1 - 2 - 3 - 4 - 1 - 2 - 3 - 4 etc.
Appreciate it.

A: I ported the Bootstrap (2.3.2) components to PrototypeJS/Script.aculo.us, which does a very nice carousel
repo https://github.com/jwestbrook/bootstrap-prototype
examples http://cwaadmin.com/bootstrap/


text:
Q: Prove that a self-complementary graph has radius $2$ and diameter $2$ or $3$
Prove that a self-complementary graph has radius $2$ and diameter $2$ or $3$.

I think that is one of the well-known properties of self-complementary graphs, but I am having some troubles trying to prove it. The facts that, if $G\cong \bar G$, then both graphs $G$ and $\bar G$ are connected, and that, for any graph, if $rad(G)\geq3$ then $rad(\bar G)\leq 2$, and that if $diam(G)\geq3$ then $diam(\bar G)\leq3$, should make the proof quite easier, but I don't know how to develop it. Could you help me? Thanks in advance!

A: The properties you list directly imply that a self-complementary graph cannot have radius $3$ or higher, and it cannot have diameter $4$ or higher.
The only thing that remains to show is that it can't have radius $1$ (the fact that the diameter can't be $1$ follows as a corollary). And (excluding the trivial example of a singleton), that can't happen either, as radius $1$ means there is a node which is connected to all other nodes, meaning the complement is not connected.


text:
Q: Calling fragment activity form main project app to the module project app on kotlin android studio I just want to ask how can I get /call / transfer data from main app to module app in android studio Kotlin?
I have 2 modules project inside of my main project
example: main [App] then Module [Chatapp]
I just want to call class or fragment activity on main project to moudule project chatapp. I can only call it in my module now, not in my main project app
I've search on Google but nothing found.


text:
Q: subdomain redirection using htaccess I need to redirect the url  http://testing.domain.com/ to http://testing.domain.com/admin/index.php

A: I think you are trying to secure your home page.   Put this php code in your index.php.
header("Location: http://testing.domain.com/admin/index.php")
exit;

If you got everything in admin folder, then you can use this one
Options -Indexes
RewriteEngine on
RewriteCond $1 !^(admin)
RewriteRule ^(.*)$ admin/index.php [L]

A: Put the following into your .htaccess file
Redirect 301 http://testing.domain.com/ http://testing.domain.com/admin/index.php


text:
Q: Java: How do I Put a Canvas in a Canvas? Lets say I Have a Canvas, like the one below -
Canvas canvas1 = new Canvas();
canvas1.setBounds(0,0,100,100);
panel.add(canvas1);

Now I have canvas1. Lets say I want to make another Canvas, Like the one below -
Canvas canvas2 = new Canvas();
canvas2.setBounds(0,0,50,50);
panel.add(canvas2);

As you can see, I have added canvas2 inside canvas1, But when I try to use canvas2, it doesn't work because it's inside canvas1. Is There anyway to make canvas1 and canvas2 work at the Same time without changing any of my code?

A: We need allot more detail from you if you want help. What doesn't work? Painting? Location?
The way you setup your canvases looks fine, are you overriding paint correctly like this:
java.awt.Canvas canvas2 = new CanvasTest();
public class CanvasTest extends Canvas
{
    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        //paint to your canvas here
        g.drawRect(5,5, 10, 10);
    }
}

Note:
You have not put canvas2 inside canvas1, you have added them both to "panel": panel.add(canvas1);, panel.add(canvas2);
please be careful how you word your questions


text:
Q: Integer partitions and dice result probabilities This is a Project Euler question, so no spoilers :]
I was going to try to solve it by first finding how many ways a certain sum can be acquired from a number of dice using IntegerPartitions . For example, using two 6-sided dice, there is only one way to get a sum of 2.
IntegerPartitions[2, {2}, {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6}]
I expected the answer to be {1,1}, but the output was {{1,1},{1,1},{1,1}}. I'm really confused now. Am I not using the function properly? If so, is there some other way that I could achieve the required result?
Bam XD

s = 0;
For[i = 9, i <= 36, i++,
 n1 = Length@
   Flatten[(Permutations /@ IntegerPartitions[i, {9}, Range[4]]), 1];
 For[j = 6, j < i, j++,
  n2 = Length@
    Flatten[(Permutations /@ IntegerPartitions[j, {6}, Range[6]]), 1];
  p = n1/4^9*n2/6^6;
  s = s + p]];
N[s]

A: I like this puzzle:
peter = Total /@ Tuples[Range[4], 9];
colin = Total /@ Tuples[Range[6], 6];
{sp, wp} = Transpose[Tally[peter]];
{sc, wc} = Transpose[Tally[colin]];
edp = EmpiricalDistribution[wp -> sp];
edc = EmpiricalDistribution[wc -> sc];

Counting the answer:
r = Tuples[{sp, sc}];
p = Pick[r, First@# > Last@# & /@ r];
probp = MapThread[#1 -> N[#2/Total[wp]] &, {sp, wp}];
probc = MapThread[#1 -> N[#2/Total[wc]] &, {sc, wc}];
NumberForm[Total[(#1 /. probp) (#2 /. probc) & @@@ p], 7]

Using probability functionality:
N[Probability[s > u, {s \[Distributed] edp, u \[Distributed] edc}]]

Or simulation:
pt = DiscreteUniformDistribution[{1, 4}];
cl = DiscreteUniformDistribution[{1, 6}];
fun[n_] :=
 N[Total[Table[
     Boole[Total@RandomVariate[pt, 9] >
       Total@RandomVariate[cl, 6]], {n}]]/n]

and evaluate,e.g. fun[1000000]
Some visualization:
DiscretePlot[{PDF[edp, x], PDF[edc, x]}, {x, 2, 40},
 PlotStyle -> {Red, Black},
 PlotLegends -> {"Pyramidal Peter", " Cubic Colin"}]

I have not put my answer deliberately.


text:
Q: Get Image name from full image path using PHP I am trying to display an image with a caption and thumbnails. I am able to display the picture but I am finding difficult to display the image file name as caption.
Below is my code:
<?php
$files = glob("images/Friends/*.*");
for ($i=0; $i<count($files); $i++)
{
    $num = $files[$i];
    echo '
';
    echo '
';
    echo '
';
    echo '
';
    echo ''."  ";
    echo '
';
    echo '
';
    echo '❮';
    echo '❯';
    echo '
';
    echo '
';
}
?>

A: To show caption set title attribute. And set name of image in tile attribute.
To get Image name from fullpath of Image use basename($num)
Please replace your php code with below.
echo ''."  ";

To get filename without extension for every image place below code in loop. And place $filename variable where you want to display image name.
$filenamewithextension = basename($num);
$fileextenstion = pathinfo($filenamewithextension, PATHINFO_EXTENSION);
$filename = basename($num,$fileextenstion);
$filename = trim(preg_replace('/[0-9]+/', '', $filename));


text:
Q: Get top 10 unique vendor data based on sub query which return vendor id I have two tables FileMaster and VendorMaster.
In VendorMaster i have vendor id and other stuff. in FileMaster i have file related data where 'Vendorid' is foreign key in FileMaster. Now I want to fetch top 10 data from FileMaster for Each 'Vendor' (One record for one vendor).
I have tried below query, but it returns me 10 records with duplicate vendorID
select top 10 * from FileMaster where VendorId in (select  top 10 VendorId from VendorMaster)

A: You can use ROW_NUMBER. I assumed FileID column for the identity of File Master. By the way, you don't need any subquery
SELECT TOP 10 * FROM (
    select  *,
        ROW_NUMBER() OVER(PARTITION BY VendorID ORDER BY FileID) AS RN
    FROM FileMaster ) AS T
WHERE RN = 1
ORDER BY FileID

A: Here you can use simple way instead of subquery
Or Anther way you can use CTE click this Link
SELECT DISTINCT FM.*
FROM FileMaster FM WITH(NOLOCK)
INNER JOIN [dbo].[VendorMaster] VM WITH(NOLOCK)
ON FM.VendorId  = VM.VendorId
ORDER BY FM.VendorId ASC
OFFSET 0 ROWS
FETCH NEXT 10 ROWS ONLY

For more details OFFSET related check this Link


text:
Q: Apollo GraphQL appends duplicates to component state I have a page that contains a component that renders a list from the results of a query. When I load the page the first time, the list renders fine. But whenever I go to another page and navigate back, an additional set of the result is appended to the list, creating duplicates in the DOM.
I'm not sure what I'm doing wrong here, but I don't want a new set items to be appended to the list every time I load the page.
apolloClient (https://github.com/vercel/next.js/tree/canary/examples/with-apollo)
let apolloClient;

const createApolloClient = () =>
  new ApolloClient({
    ssrMode: typeof window === "undefined",
    link: new HttpLink({
      uri: DB_URI,
      credentials: "same-origin",
    }),
    cache: new InMemoryCache(),
  });

export function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient();

  if (initialState) {
    const existingCache = _apolloClient.extract();
    const data = merge(initialState, existingCache);

    _apolloClient.cache.restore(data);
  }

  if (typeof window === "undefined") return _apolloClient;
  if (!apolloClient) apolloClient = _apolloClient;
  return _apolloClient;
}

export function addApolloState(client, pageProps) {
  if (pageProps?.props) {
    pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract();
  }
  return pageProps;
}

export function useApollo(pageProps) {
  const state = pageProps[APOLLO_STATE_PROP_NAME];
  return useMemo(() => initializeApollo(state), [state]);
}

On my page I use getStaticProps as follows
export async function getStaticProps() {
  const apolloClient = initializeApollo();

  await apolloClient.query({
    query: GET_THINGS,
  });

  return addApolloState(apolloClient, {
    props: {},
    revalidate: 1,
  });
}

My list component looks as follows:
const ItemsList: React.FunctionComponent<Props> = (props) => {
  const { loading, error, data } = useQuery(GET_THINGS, {});

  const { items} = data;
  const { filters } = props;

  const [filteredItems, setFilteredItems] = useState(items);

  useEffect(() => {
    setFilteredItems(filterItems(items, filters));
  }, [filters, items]);

  const renderItems = (filteredItems: Array<Item>) =>
    filteredItems.map((item) => (

        <Link href={`/items/${item.id}`}>{item.name}</Link>

    ));

  if (loading) return
"Loading...";
;
  if (error) return
`Error! ${error.message}`;
;

  return (

      {filteredItems?.length > 0 ? (

{renderItems(filteredItems)}

      ) : (
        No items matched the criteria
      )}

  );
};

export default ItemsList;


text:
Q: How does the power-series expansion of the spectral phase describe chromatic dispersion? I don't understand how the spectral phase (the phase in the frequency domain) describes dispersion.

A: For example, if you measure the amplitude of a wave in point A you can find that the signal there has the form:
$s_a(t) = sin(\omega t)+sin(2\omega t)+sin(3\omega t)$
If you do the same measurement in point B you can get:
$s_b(t) = sin(\omega t)+sin(2\omega t+2\pi/8)+sin(3\omega t+3\pi/8)$
The last two sinus are shifted with $2\pi/8$ and $3\pi/8$. This shift with various phases is called dispersion.


text:
Q: Running Process in background in PHP Some Php Process took long time to complete, like several hours.
So users cannot wait for loading the php file.
Please help to find the way how i could run php in background.
It should be processing in the background(could be hosting background or something else)
although after we closed that php.

A: Have you ever tried microtime()..?Timing How Long Code Takes to Execute
This little technique is really useful if you want to time exactly long it too to, say, load a page, or run a block of code. It takes advantage of PHP's microtime() function.
$start = microtime(true);
//Do stuff in here
sleep(1);
//Stop doing stuff
$end = microtime(true);
$time = $end - $start;
echo $time;


text:
Q: meaning of 'would have to'
I would have to believe that the only logical way for my life to
  go after the riots in 2001 was to dream-up a non-profit called
  InkTank, to encourage anybody who ever wanted to set things on fire to
  write down the deepest, most hidden part of their hearts. (Kathy
  Holwadel)

Is would have to the back-shifted form of will have to, or the non-past modal remoteness?

A: The sentence before the one you quoted is necessary to understand the usage:

Because if that were true, that there's a plan, it would mean there's a reason I live in Cincinnati, Ohio and my son robs banks. I would have to believe that ...

Removing the intervening text, the important parts are "Because if that were true, ... I would have to believe ..."
I'm probably going to mess up the grammatical terms, but I think this is just the normal subjunctive mood, expressing the consequences of a contrafactual supposition.
Edit: On further reading, I think this usage is not subjunctive. Instead, it's called a conditional, specifically the "second conditional", according to the Wiki article.


text:
Q: React js use Abort controller outside useEffect I have a component where an abort controller is declared outside a useEffect. controller.abort() is called inside a useEffect when the component is unmounted.
When the component is unmounted this error below is thrown
Unhandled Rejection (AbortError): The operation was aborted.
 const controller = new AbortController()
    function MyComponent() {

      useEffect(() => {
        return () => controller.abort()
      }, [])

    const fetchData = async () => {
         try {
         const data = await fetchMyData(controller)
    } catch(error) {
    if (error.name === "AbortError") return
      console.log("Error ", error)
    }
  }
}

What am I doing wrong?
stacktrace images

A: Check your index.js in root. If you are using StrictMode, that is exactly the problem. Checkout document: https://reactjs.org/docs/strict-mode.html.
I think what you should do here is call request and abort in the same one.


text:
Q: c++ weird result from showing lettters from cout I'm new to programming and I started reading some c/c++ books to understand better. So i'm not very newbie and i will go straight to the subject. I want to make a program that show all the letters from a to z, so i made 2 programs. One in C and other in C++.
The one in C works as expected, here is the code:
#include <stdio.h>

void alfa(){
char c;
    for(c='A'; c<='Z'; ++c)
       printf("%c ",c);
}

int main()
{
    alfa();
    getchar();
    return 0;
}

but the other in C++ is showing an "[" or numbers..
#include <iostream>
using namespace std;

void alphabet(){
    char abc;
    for(abc='A'; abc<='Z'; abc++);
    cout<<abc;
}

int main(){
    cout<<"This will show letters from a to z"<<endl;
    alphabet();
    cin.ignore();
    return 0;
}

PS: If I made the c++ program in one function it works... but I still learning and I want it to be called. Thanks

A: You have a column ; after the for loop. As stated by tadman, the for loop runs nothing because of this.
for(abc='A'; abc<='Z'; abc++)
    cout<<abc;

You can also put some brackets to make sure you are not doing any mistake when writing your first pieces of code.
for(abc='A'; abc<='Z'; abc++) {
    cout<<abc;
}


text:
Q: Removing a space from the start of a array to use strcmp Hello I am doing a looping on my code with fgets and I want that when user introduces the word "bye" the program ends, so I have a do while like this:
char buf[1000]

do{

    fgets(buf, 1000, stdin);

    //More code here

while(strcmp(buf, "bye")!=0);

But I have a problem that it is, when user made a space or a tab or multiple spaces before write bye the strcmp doesnt recognize him as bye, so the program only exits when users only type bye without any previous space or tab.
I want to know how can I prevent the spaces or tabs before the by word to exits if user type for example:
'     bye'

A: fgets reads in a complete line, including any starting white spaces and also including the new line character at the end of the line. Even if a user does not enter preceding white spaces, the content of buf is likely to be "bye\n", such that buf will hardly compare equal to "bye" when using strcmp.
I'd suggest to scan the buffer for a single word using sscanf and compare this word to "bye" then. Note that scanf("%s"...) skips white space characters at the beginning of a word and stops before the first white space after the word.
   char isStopWord[20];
   isStopWord[0] = '\0';
   sscanf(buf,"%19s",isStopWord);
}
while(strcmp(isStopWord, "bye")!=0);

A: It a very strange requirement to use strcmp to remove characters from the array but everything is possible :)
char *removeSpacesAndTabsBeginning(char *str)
{
    size_t len;
    char savedc;
    if(str && *str)
    {
        len = strlen(str);
        savedc = str[1];
        str[1] = 0;
        while(!strcmp(str, " "))
        {
            str[1] = savedc;
            memmove(str, str + 1, len);
            savedc = str[1];
            str[1] = 0;
        }
        str[1] = savedc;
    }
    return str;
}

int main(void)
{
    char z[] = "  \t\tHello World.";
    printf("`%s`\n", removeSpacesAndTabsBeginning(z));
}

If you want to know if the string contains "bye" use strstr.
int isBye(const char *str)
{
    return !!strstr(str, "bye");
}

A: There are 2 problems in your code:

*

*you should test the return value of fgets() to detect unexpected end of file.

*you should ignore whitespace in the comparison. You should just trim the string read by fgets() as the other code probably does not handle these either.

#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main() {
    char buf[1000];
    while (fgets(buf, sizeof buf, stdin)) {
        size_t i = 0, length = strlen(buf);
        /* trim trailing white space */
        while (length > 0 && isspace((unsigned char)buf[length - 1])) {
            buf[--length] = '\0';
        }
        /* trim leading white space */
        while (isspace((unsigned char)buf[i]) {
            i++;
        }
        if (i > 0) {
            memmove(buf, buf + i, length - i + 1);
        }
        // check for end command
        if (!strcmp(buf, "bye"))
            break;

        //More code here: handle other commands
        //...
    }
    return 0;
}


text:
Q: Calculating possible values of complex integral I need to find all possible values of:
$$\int _C \frac{e^zdz}{z(z^2-1)}$$
when $C$ is a circle that doesn't pass through $0,1,-1$.
Can you please help?

A: Note that $f(z)=\dfrac{e^z}{z(z+1)(z-1)}$ has simple poles at $0,\pm 1$. Recall that at a simple pole $c$, the residue of $f$ is given by
$$
\operatorname{Res}(f,c)=\lim_{z\to c}(z-c)f(z).
$$
So in this case, one can calulate that $\operatorname{Res}(f,0)=-1$, $\operatorname{Res}(f,1)=\frac{e}{2}$, and $\operatorname{Res}(f,-1)=\frac{1}{2e}$.
There are $8$ possible subsets of $\{0,1,-1\}$ that such a circle $C$ as described in the problem may contain. Then use the fact that the value of the integral is $2\pi i$ times the sum of the residues of the poles $C$ encloses to find the  possible values of the integral.

A: Hint: Use the Cauchy's Integral Formula or the Residue theorem as you see fit.
Here is an example: If $0,1,-1$ are not in the region bounded by the contour then by the Residue theorem (or the Integral theorem if you prefer), your integral is $0$.


text:
Q: Creating a pivot table to apply dynamically to any file name Every week I pull the same report for multiple clients and I need to extract a pivot table from it.
I've created a macro that combines full name and auto fills to last row in range. It then creates a pivot table on a new sheet inside the work book. I need this macro to be applicable to whatever the file name is. Thank you so much!
Sub Pivot()
'
' Pivot Macro
'

'
    Columns("M:M").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Columns("L:L").ColumnWidth = 16.57
    Range("M1").Select
    Columns("M:M").ColumnWidth = 24.57
    Range("M1").Select
    ActiveCell.FormulaR1C1 = "Full Name"
    Range("M2").Select
    ActiveCell.FormulaR1C1 = "=RC[-1]&"", ""&RC[-2]"
    Range("M2").Select
    Dim lastrow As Long
    lastrow = Cells.Find(What:="*", After:=[A1], _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlPrevious).Row
    Selection.AutoFill Destination:=Range("M2:M" & lastrow)
    Range(Selection, Selection.End(xlDown)).Select
    Cells.Select
    Sheets.Add
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "American Trans!R1C1:R1048576C31", Version:=7).CreatePivotTable _
        TableDestination:="Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion _
        :=7
    Sheets("Sheet1").Select
    Cells(3, 1).Select
    With ActiveSheet.PivotTables("PivotTable1")
        .ColumnGrand = True
        .HasAutoFormat = True
        .DisplayErrorString = False
        .DisplayNullString = True
        .EnableDrilldown = True
        .ErrorString = ""
        .MergeLabels = False
        .NullString = ""
        .PageFieldOrder = 2
        .PageFieldWrapCount = 0
        .PreserveFormatting = True
        .RowGrand = True
        .SaveData = True
        .PrintTitles = False
        .RepeatItemsOnEachPrintedPage = True
        .TotalsAnnotation = False
        .CompactRowIndent = 1
        .InGridDropZones = False
        .DisplayFieldCaptions = True
        .DisplayMemberPropertyTooltips = False
        .DisplayContextTooltips = True
        .ShowDrillIndicators = True
        .PrintDrillIndicators = False
        .AllowMultipleFilters = False
        .SortUsingCustomLists = True
        .FieldListSortAscending = False
        .ShowValuesRow = False
        .CalculatedMembersInFilters = False
        .RowAxisLayout xlCompactRow
    End With
    With ActiveSheet.PivotTables("PivotTable1").PivotCache
        .RefreshOnFileOpen = False
        .MissingItemsLimit = xlMissingItemsDefault
    End With
    ActiveSheet.PivotTables("PivotTable1").RepeatAllLabels xlRepeatLabels
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Full Name")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Pay Total"), "Sum of Pay Total", xlSum
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Bill Total"), "Sum of Bill Total", xlSum
End Sub


text:
Q: border around outside of page but on top of header image I'm trying to add a border around the outside of my page but it needs to be on top of the header image.. I'm not sure how to achieve something like this.
I thought maybe something like
body {

    border:solid 1px brown
    padding: 5px;

}

But something like this obviously pushing everything in.. Is this even possible to do?
Here's what I'm trying to make: https://imgur.com/a/gZAJ5Gy
The brown border just continues around the entire page.

A: This can be achieved by using a pseudo element purely for stylistic purposes.
Here's some CSS you can try:

body {
    position: relative;
}

body::after {
    border: solid 1px brown;
    padding: 5px;
    content: '';
    height: 100%;
    width: 100%;
    pointer-events: none;
    position: absolute;
    top: 0;
    left: 0;
}

This should be by default overtop of your body being an "after", you can play around with z-index to achieve your desired effect if not. Hope this helps!


text:
Q: Firebase Realtime Database Overrides my Data at a location even when I use .push() method Firebase Realtime Database Overrides my Data at a location even when I use .push() method. The little-concrete knowledge I have about writing to Firebase Realtime database is that writing to Firebase real time database can be done in few several ways. Two of the most prominent are the

*

*set() and 2. push() method.

The long story short, push() is used to create a new key for a data to be written and it adds data to the node.
So fine, firebase has being co-operating with me in my previous projects but in this, I have no idea what is going on. I have tried different blends of push and set to achieve my goal but no progress so far.
In the code below, what I want to achieve is 2 things, write to a location chatUID, message and time only once, but write severally '-MqBBXPzUup7czdG2xCI' all under the same node "firebaseGeneratedId1" ->
A better structure is below.

Help with code. Thanks.
UPDATE
Here is my code
The writers reference
_listeningMsgRef = _msgDatabase
.reference()
    .child('users')
    .child(userId)
    .child('chats')
    .child(chatUIDConcat);

When a user hits sendMessage, here is the function called
void sendMessage() {
    _messageController.clear();
    var timeSent = DateTime.now().toString();

    //Send
    Map msgMap = {
        'message': msg,
        'sender': userId,
        'time': timeSent,
        'chatUID': chatUIDConcat
    };

    //String _key = _listeningMsgRef.push().key;

    _listeningMsgRef.child(chatUIDConcat).set().whenComplete(() {
        SnackBar snackBar = const SnackBar(content: Text('Message sent'));
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
        DatabaseReference push = _listeningMsgRef.child(chatUIDConcat).push().set(msgMap);
    });
}

The idea about the sendMessage function, is to write
chatUID:"L8pacdUOOohuTlifrNYC3JALQgh2+q5D38xPXVBTwmwb5Hq..."
message: "I'm coming"
newMessage: "true"
sender: "L8pacdUOOohuTlifrNYC3JALQgh2"

When it is complete, then push new nodes under the user nodes.
EDIT:
I later figured out the issue. I wasn't able to achieve my goal because I was a bit tensed while doing that project. The issue was I was wanted to write new data into the '-MqBBXPzUup7czdG2xCI' node without overwriting the old data in it.
The solution is straight forward. I just needed to ensure I wrote data in that node as new nodes under it. Nothing much, thanks
Frank van Puffelen for your assistance.

A: Paths in Firebase Realtime Database are automatically created when you write any data under then, and deleted when you remove the last data under them.
So you don't need to first create the node for the chat room. Instead, it gets auto-created when you write the first message into it with _listeningMsgRef.child(chatUIDConcat).push().set(msgMap)


text:
Q: Swift Firebase retrieve data into tableview My database tree

Hello,
I am trying to retrieve data to to tableview but although I can read data from firebase database, I cannot display them in table view. My code is below, I hope you can help me.
class Calls {

var callType: String?
var callHospital: String?

init(callType: String?, callHospital: String?) {
    self.callType = callType
    self.callHospital = callHospital
}
}

class myCallsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var ref:DatabaseReference!
var myCallList = [Calls]()

@IBOutlet weak var callListTableView: UITableView!

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myCallList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! myCallsViewControllerTableViewCell

    let test = myCallList[indexPath.row]
    cell.callType?.text = test.callType
    cell.callHospital?.text = test.callHospital

    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()

     callListTableView.dataSource = self
     callListTableView.delegate = self
   LoadCalls()
}

func LoadCalls() {
    ref = Database.database().reference()
    let userID = Auth.auth().currentUser?.uid
    ref.child("calls").queryOrdered(byChild: "userID").queryEqual(toValue: userID!).observe(.childAdded, with: { (snapshot) in
        if snapshot.childrenCount > 0{
        self.myCallList.removeAll()
            for result in snapshot.children.allObjects as! [DataSnapshot]{
                let results = result.value as? [String : AnyObject]
                let type = results?["calltype"]
                let hospital = results?["hospital"]
                let myCalls = Calls(callType: type as! String?, callHospital: hospital as! String?)
                self.myCallList.append(myCalls)
        }
                 self.callListTableView.reloadData()
        }
        })
}

A: I solved the problem, thank you guys,Blake and Siyavash, so much. I registered the cell and put dispatch main queue and it worked. Here is the latest code:
class Calls {
var callType: String?
var callHospital: String?

init(callType: String?, callHospital: String?) {
    self.callType = callType
    self.callHospital = callHospital
}

}
class myCallsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var ref:DatabaseReference!
var myCallList = [Calls]()

@IBOutlet weak var callListTableView: UITableView!

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myCallList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! myCallsViewControllerTableViewCell

    let test = myCallList[indexPath.row]
    cell.callType?.text = test.callType
    cell.callHospital?.text = test.callHospital

    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()

     callListTableView.dataSource = self
     callListTableView.delegate = self
   LoadCalls()
}

func LoadCalls() {
    ref = Database.database().reference()
    let userID = Auth.auth().currentUser?.uid
    ref.child("calls").queryOrdered(byChild: "userID").queryEqual(toValue: userID!).observe(.childAdded, with: { (snapshot) in
                let results = snapshot.value as? [String : AnyObject]
                let type = results?["calltype"]
                let hospital = results?["hospital"]
                let myCalls = Calls(callType: type as! String?, callHospital: hospital as! String?)
                self.myCallList.append(myCalls)
                DispatchQueue.main.async {
                    self.callListTableView.reloadData()
                }
        })
}

A: Your issue probably has to do with the fact that you're calling reloadData() from a closure, which means you're updating the UI from a background thread.  Check out this answer:
Swift UITableView reloadData in a closure


text:
Q: Is it possible to get // to work locally? I do a lot of small-scale front-end projects so I don't want to spend to much time setting up dev enviroments. When I develop locally, I usually just write html and open the files in a browser. This usually works fine. At some times however I wish to use // instead of a protocol when referencing a file, like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

This is good cause it will work for both http and https, however if the protocol is file:// it won't work. Is there some way to solve this? I would prefer to not having to run a local server and setting up domains for each project.


text:
Q: Не могу перегрузить оператор "<" для класса #include "stdafx.h"
#include "iostream"
#include "string"
#include <set>
#include <algorithm>

using namespace std;

class student {
public:
bool operator< (student &ob2) {
        return true;
    }
    student() {
        a = 0;
        fio = "Kolesnikov Vadim Sergeevich";
        vuz = "PSU";
        fac = "Facultet";
        kaf = "Kafedra";
        f_o = "Ochka\Zaochka";
    }
    student(char *fio1, int a1) {
        a = a1;
        fio = fio1;
        vuz = "VUZ";
        fac = "Facultet";
        kaf = "Kafedra";
        f_o = "Ochka\Zaochka";
    }
    ~student() {};
    void output() {
        cout << fio.c_str() << endl;
        cout << vuz.c_str() << endl;
        cout << fac.c_str() << endl;
        cout << kaf.c_str() << endl;
        cout << f_o.c_str() << endl << endl;
    }
    void input() {
        cout << "FIO:";
        cin >> fio;
        cout << "vuz:";
        cin >> vuz;
        cout << "fac:";
        cin >> fac;
        cout << "kaf:";
        cin >> kaf;
        cout << "f_o:";
        cin >> f_o;
        cout << endl;
    }
protected:
    string kaf;
    string f_o;
    int a;
private:
    string fio;
    string vuz;
    string fac;
};

void main(void)
{
    char str0[] = "Potogin Nikita";
    char str1[] = "Sidelnikov Maxim";
    char str2[] = "Kolesnikov Vadim";
    char str3[] = "Fedoseev Gena";
    student ob0(str0,1);
    student ob1(str1,2);
    student ob2(str2,3);
    student ob3(str3,4);
    ob0.output();

    multiset<student> list;
    multiset<student>::iterator it;
    list.insert(ob0);
    list.insert(ob1);
    list.insert(ob2);
    list.insert(ob3);

    system("pause");
}

A: Основная ошибка
operator< должен принимать константные ссылки
bool operator< (const student &ob1, const student &ob2)

И, само собой, он не должен быть тривиальным.
По мелочи
f_o = "Ochka\\Zaochka";

Бекслеши в строковых константах надо удваивать
int main(void)

main () надо декларировать с int, а не void и возвращать 0.

A: нужны константные ссылки
bool operator< (const student &ob1, const student &ob2) {
    return true;
}

или использовать lamda:
int main(void)
{
    char str0[] = "Potogin Nikita";
    char str1[] = "Sidelnikov Maxim";
    char str2[] = "Kolesnikov Vadim";
    char str3[] = "Fedoseev Gena";
    student ob0(str0,1);
    student ob1(str1,2);
    student ob2(str2,3);
    student ob3(str3,4);
    ob0.output();

    // вместо просто возврата true, наверное должно возвращаться что-то осмысленное
    auto comp = [](const student& lst, const student& rst){ return true; };

    typedef multiset<student, decltype(comp)> myset;

    myset list(comp);
    myset::iterator it;
    list.insert(ob0);
    list.insert(ob1);
    list.insert(ob2);
    list.insert(ob3);

    system("pause");
}

A: *

*Необходимости засовывать оператор в класс не было. Наоборот, правильнее перегружать такой оператор отдельной функцией.
В любом случае, оба параметра оператора сравнения должны быть константными
bool operator< (const student &ob2) const {
     return true;
}

*Оператор сравнения, который всегда return true; - грубое нарушение требований, накладываемых на оператор сравнения. Работать не будет.

*Что такое
#include "iostream"
#include "string"

? При включении стандартных заголовков, скобки должны быть только треугольными.

*int main, а не void main.


text:
Q: Clean Com components when host the asp.net website in IIS I have a website hosted in IIS.
My application is all about writing and reading data to/from Excel document.
When I run the application from VS,i'm seeing only one EXCEL.exe all the time
But When I host the same application in IIS ,for every writing its creating one excel object and showing in Task-manager,Hence sometimes my website stops responding.
Below is my code
    try
            {
                xlApp = new app.Application();
                xlWorkBooks = xlApp.Workbooks;
                xlWorkBook = xlWorkBooks.Open(FilePath, missing, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing);
                xlWorkSheet = xlWorkBook.Worksheets.get_Item(index);
//code …………………………….
                xlApp.DisplayAlerts = false;
                xlWorkBook.Save();
                boolWriteSuccess = true;
                xlApp.DisplayAlerts = true;
            }
Catch()
{
}
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                Marshal.FinalReleaseComObject(xlWorkSheet);
                Marshal.FinalReleaseComObject(xlWorkSheets);
                xlWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
                Marshal.FinalReleaseComObject(xlWorkBook);
                xlWorkBooks.Close();
                Marshal.FinalReleaseComObject(xlWorkBooks);
                if (xlApp != null)
                    xlApp.Quit();
                Marshal.FinalReleaseComObject(xlApp);
            }

Here is the screen shot of Task Manager when website hosted in IIS

I want to clean the excel.exe from task manager always but some how I'm unable to clean.
Please help me in this regard.

A: after saving the excel you should close the workbook. as each time you are creating nea app.application it will create new excel.exe
after saving excel use below code
    try {
foreach (Process proc in Process.GetProcessesByName("Excel"))
        {
            proc.Kill();
        }}catch(Exception ex){
MessageBox.Show(ex.Message);}


text:
Q: How can I access a parameter in a constructor new window? I want to pass a variable as a parameter from my main window to a new one.
Actually, I can access parameter in an event handler of the new window, but not in the constructor.
mainwindow.xaml.cs :
                string selectedKey = "test";
                EditTri editTri = new EditTri();
                editTri.key = selectedKey;
                editTri.ShowDialog();

EditTri.xaml.cs:
public partial class EditTri : Window
    {

        public string key;

        public EditTri()
        {
            InitializeComponent();

         MessageBox.Show(key);  //key = null ...

        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {

            MessageBox.Show(key);   //key = test

            this.Close();
        }

    }

I just need to access the parameter key in constructor EditTri(). How can I do this?

A: Just add a parameter to your constructor:
public partial class EditTri : Window
{

    private string _key;

    public EditTri(string key)
    {
        _key = key;
        InitializeComponent();

        MessageBox.Show(key);
    }

    ...

Usage
string selectedKey = "test";
EditTri editTri = new EditTri(selectedKey);
editTri.ShowDialog();

Warning, showing a MessageBox in a constructor is not ideal.
Best do it somewhere like on Loaded event, etc.


text:
Q: Need help in debugging NullPointerException in Android I have a about class in my app to show some button and when the user click on the button it jump to a webview activity to view some webpage so I defined urls in the about class, then set onlick method to deliver them to the same webview activity to open the web page, but I keep getting a curious NullPointerException when running this activity and my logcat print nothing but

12-02 09:03:11.815: WARN/ActivityManager(51): Activity idle timeout
  for HistoryRecord{44d68ea0 com.appkon.hdtvs/.About} 12-02
  09:03:17.026: WARN/ActivityManager(51): Activity destroy timeout for
  HistoryRecord{44e37518 com.appkon.hdtvs/.HDtvs}

Here are my code.Any help would be appreciated, thank you
About.java
public class About extends Activity{

    private Button backbutton;
    private Button likebutton;
    private ImageView versionlogo;
    private ImageButton faq;
    private ImageButton forum;
    private ImageButton feedback;
    private ImageButton rate;
    private String likepath ="http://appkon.com/hdtvs/share.html";
    private String likename = "分享";
    private String lpath="" ;
    private String lname="" ;
    private String faqpath ="http://appkon.com/hdtvs/faq.html";
    private String faqname ="常见问题";
    private String forumpath= "http://appkon.com/forum/" ;
    private String forumname = "APP论坛";
    private String fqpath="";
    private String fqname="";
    private String frpath="";
    private String frname="";
    private String ratepath ="http://appkon.com/hdtvs/";
    private String ratename="评价";
    private String rpath="";
    private String rname="";
    private String feedbackpath ="http://appkon.com/hdtvs/feedback.html";
    private String feedbackname="反馈问题";
    private String fdname="";
    private String fdpath="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        backbutton=(Button) findViewById(R.id.back);
        likebutton=(Button) findViewById(R.id.share);
        faq =(ImageButton)findViewById(R.id.faqbutton);
        forum =(ImageButton)findViewById(R.id.forumbutton);
        feedback =(ImageButton)findViewById(R.id.feedbackbutton);
        rate =(ImageButton)findViewById(R.id.ratebutton);

        backbutton.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setClass(About.this, HDtvs.class);
            startActivity(intent);
            About.this.finish();

          }
        });

        likebutton.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setClass(About.this, Renrenframe.class);
            startActivity(intent);
            About.this.finish();

          }
        });

        faq.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setClass(About.this, Aboutframe.class);
            Bundle bundle = new Bundle();
            bundle.putString("fqpath",faqpath);
            bundle.putString("fqname",faqname);
            intent.putExtras(bundle);
            startActivity(intent);
            About.this.finish();

          }
        });

        feedback.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setClass(About.this, Aboutframe.class);
            Bundle bundle = new Bundle();
            bundle.putString("fdpath",feedbackpath);
            bundle.putString("fdname",feedbackname);
            intent.putExtras(bundle);
            startActivity(intent);
            About.this.finish();

          }
        });

        rate.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setClass(About.this, Aboutframe.class);
            Bundle bundle = new Bundle();
            bundle.putString("rpath",ratepath);
            bundle.putString("rname",ratename);
            intent.putExtras(bundle);
            startActivity(intent);
            About.this.finish();

          }
        });

        forum.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setClass(About.this, Aboutframe.class);
            Bundle bundle = new Bundle();
            bundle.putString("frpath",forumpath);
            bundle.putString("frname",forumname);
            intent.putExtras(bundle);
            startActivity(intent);
            About.this.finish();

          }
        });

        }
}

Aboutframe.java
public class Aboutframe extends Activity{

      private TextView namebar;
      private ImageButton likebutton;
      private ImageButton backbutton;
      private WebView aboutframe;
      private String lpath ;
      private String lname ;
      private String fqpath;
      private String fqname;
      private String frpath;
      private String frname;
      private String rpath;
      private String rname;
      private String fdname;
      private String fdpath;

      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.aboutframe);
          this.requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar

          backbutton=(ImageButton) findViewById(R.id.back);
          likebutton=(ImageButton) findViewById(R.id.share);
          aboutframe =(WebView)findViewById(R.id.aboutframe);

          Intent intent=this.getIntent();
          Bundle bunde = intent.getExtras();

          lname = bunde.getString("lname");
          lpath = bunde.getString("lpath");
          fqname = bunde.getString("fqname");
          fqpath = bunde.getString("fqpath");
          frname = bunde.getString("frname");
          frpath = bunde.getString("frpath");
          rname = bunde.getString("rname");
          rpath = bunde.getString("rpath");
          fdname = bunde.getString("fdname");
          fdpath = bunde.getString("fdpath");

          if(lname != null&lpath!= null){
              namebar.setText(lname);
              aboutframe.setWebViewClient(new WebViewClient(){
                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
                      view.loadUrl(lpath);
                      return true;
                  }
                  });
          }
          if(fqname != null&fqpath!= null){
              namebar.setText(fqname);
              aboutframe.setWebViewClient(new WebViewClient(){
                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
                      view.loadUrl(fqpath);
                      return true;
                  }
                  });
          }
          if(frname != null&frpath!= null){
              namebar.setText(frname);
              aboutframe.setWebViewClient(new WebViewClient(){
                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
                      view.loadUrl(frpath);
                      return true;
                  }
                  });
          }
          if(rname != null&rpath!= null){
              namebar.setText(rname);
              aboutframe.setWebViewClient(new WebViewClient(){
                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
                      view.loadUrl(rpath);
                      return true;
                  }
                  });
          }
          if(fdname != null&fdpath!= null){
              namebar.setText(fdname);
              aboutframe.setWebViewClient(new WebViewClient(){
                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
                      view.loadUrl(fdpath);
                      return true;
                  }
                  });

              backbutton.setOnClickListener(new View.OnClickListener()
              {
                public void onClick(View v)
                {
                  Intent intent = new Intent();
                  intent.setClass(Aboutframe.this, About.class);
                  startActivity(intent);
                  Aboutframe.this.finish();

                }
              });

              likebutton.setOnClickListener(new View.OnClickListener()
              {
                public void onClick(View v)
                {
                  Intent intent = new Intent();
                  intent.setClass(Aboutframe.this, Renrenframe.class);
                  startActivity(intent);
                  Aboutframe.this.finish();

                }
              });
          }

}
}

A: That error means your activity timed out.
I don't understand why you call:
aboutframe.setWebViewClient

multiple times. You can try to replace if's with if else's:
/*...*/
else if(frname != null&frpath!= null){
/*...*/
else if(rname != null&rpath!= null){
/*...*/

A: put all your code between
try
{
your Code here...
}
catch(NullPointerException e)
{
e.printStackTrace();
}

A: You better use && instead of &. The latter is "binary and", you want to use "logical and".


text:
Q: Отображение password, MVC Подскажите, пожалуйста, допустим есть модель с учетными данными
public class UserModel
{
    public string Login{get;set;}
    public string Password {get;set;}
}

И есть контроллер, и например мне надо вывести просто список в json учётных записей, но надо чтобы Password отображался в виде звездочек...есть какой-то атрибут для такого варианта?
То есть мне надо атрибут не для проверки вводимого значения, а для отображения...или тут надо мне руками писать в get;set; или на подобии этого?


text:
Q: CRM 2011 Timezone in OnChange Event I'm in the process of customizing our CRM solution. Due to different timezone, sometimes due dates in Cases or Tasks are not consistent because the time defaults to midnight 12 am. So to different timezone the due date could be one day later or earlier.
In order to fix this we're setting the default time of the due date field (logical name = "followupby" ) to 7 PM. We're creating an OnChange event for the Due date field with Java script function as follow. In "Handler Properties" dialogue to set up the Library and Function name, I check the option to "Pass execution context as first parameter". Therefore in my function below it's receiving the 'context' parameter:
setCaseDueDate: function (context) {

    var oField = context.getEventSource().getValue();
    var sTmp = oField;

    var hours =19;
    var minutes = 0;
    var seconds = 0;

    if (typeof (oField) != "undefined" && oField != null) {

        var newTime = new Date(sTmp.getFullYear(), sTmp.getMonth(), sTmp.getDate(), hours, minutes, seconds);
        context.getEventSource().setValue(newTime);
    }
},

However I keep getting an error that says "There was an error with this field's customized event. Error 'setCaseDueDate' is undefined."
Could it be that certain values in my function is undefined or is it probably not getting the 'context' parameter correctly?
Thanks, greatly appreciate your help.
***UPDATE**********
Nevermind this... I was putting my function with existing collection of Javascript functions and then I decided to put into a separate new webresource and it's working now... weird but works.
Thanks.

A: Your code to define a JavaScript function is wrong, try with
function setCaseDueDate(context) {
// rest of the code
}

and to change the date, it's not necessary the context, for example:
function setCaseDueDate() {
   var fieldName = "followupby";
   var sTmp = Xrm.Page.getAttribute(fieldName).getValue();
   if (currentDate != null) {
      var newTime = new Date(sTmp.getFullYear(), sTmp.getMonth(), sTmp.getDate(), 19, 0, 0);
      Xrm.Page.getAttribute(fieldName).setValue(newTime);
   }
}


text:
Q: Getting a java.lang.ClassNotFoundException even though i've specified the correct jar with -cp java.lang.ClassNotFoundException: com.hazelcast.core.Hazelcast
This bit is strange though, because i've added hazelcast-1.8.5.jar to the classpath when i'm running java:
java -cp hazelcast-1.8.5.jar -jar myapp.jar

So i cannot understand why i'm getting the ClassNotFoundException, when the hazelcast jar is well and truly present, and specified in the command line. Any ideas please?
By the way, hazelcast is pretty fricking sweet!

A: From the -jar option docs:
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A: You need to set ClassPath in the JAR manifest.


text:
Q: How to Split number with comma after two digit and store into two variables in javascript? I have a variable var Number = 2425;
I want to break it into two parts and store into into two different variables.
var data = 24;
var month = 25;

How can I get this in javaScript.

A: Coerce the number to a string, and then use substring to get the relevant characters.

const number = 2425;

const str = String(number);

const data = str.substring(0, 2);
const month = str.substring(2);

console.log(data, month);

A: You need to substring the number at target position and after that you can add comma and join the rest of the number . Then split it with comma and get as array. Then you can use the array at position . Check the below solution
function splitNumber(number, index) {
    var commaAdded = number.substring(0, index) + ',' + number.substring(index);
    return commaAdded.split(',');
}

console.log(splitNumber('2425', 2));
// ["24", "25"]

Now you can use the array index in your variable.

A: One was would be to convert it into a string and do a slice on it.

let num = 2524;
let strNum = String(num);
let midIndex = Math.floor(strNum.length/2);
let firstHalf = Number(strNum.slice(0,midIndex));
let secondHalf = Number(strNum.slice(midIndex));
console.log(firstHalf);
console.log(secondHalf);

A: Or just math via treating "Number" as an arithmetic progression on order of 100:

var number = 2425
var data = Math.floor(number / 100)
var month = number - (data * 100)

console.log(number)
console.log(data)
console.log(month)

/* Output
2425
24
25
*/

But don't really understand how "month" can be more than 12, let alone 11 if base(0).


text:
Q: Touch feedback during swipe left and right My app has a master-detail structure, where the user can tap on a master item to go to the detail view and then swipe left or right to navigate to other details items.
I'm using on-swipe-left and on-swipe-right to let users swipe between the detail views, however, when the user swipes, there is no visual feedback that there is a swipe happening. Only after the user has fully swiped does anything happen. I thought I could use the slide box, because the slidebox does provide visual feedback as soon as you start swiping, however, my views have vertical scroll and that conflicts with the left and right swipe actions due to the swipe sensitivity. In other words, when the user touches the screen to begin scrolling down, the swipe action takes over and it tries to swipe left or right instead of scrolling down.
So, what are my options? Is there any way I can provide some kind of an animation with on-swipe-left and on-swipe-right so that there is some kind of visual feedback (may be an ink trail on the screen) I can show the user? Or is there any way I can make the slidebox approach work so that the horizontal swipe and vertical scroll can function harmoniously? I have seen other apps that have scroll and swipe functions working harmoniously--gmail and pinterest are examples. Just not able to get it working with ionic.
Or is there another UI pattern that I am not thinking of? Worst case, I could provide buttons for next and previous, but this is a mobile app, so I really shouldn't have to resort to that.
Thanks!


text:
Q: R No Mode and Exclude NA I'm looking for a mode function in R which I can use for dplyr. The two posts I have seen treats "ties" very differently. This post (Ken Williams) treats ties by selecting the first-appearing value of the set of modes. This post treats ties by noting both values in the same cell.
I'm looking a mode function that treat ties as NA AND excludes missing values. I used Gregor's post to treat ties as NA, but I can't seem to exclude the missing values.
The variable DF$Color is a character type.
Here's an example DF
Category<-c("A","B","B","C","A","A","A","B","C","B","C","C", "D", "D")
Color<-c("Red","Blue","Yellow","Blue","Green","Blue","Green","Yellow","Blue","Red","Red","Red","Yellow", NA)
DF<-data.frame(Category,Color)
DF <- arrange(DF, Category)
DF
DF$Color <- as.character(DF$Color)

With NA included, the code looks like:
 mode <- function(x) {
  ux <- unique(x)
  tx <- tabulate(match(x, ux))
  if(length(unique(tx)) == 1) {
    return(NA)
  }
  max_tx <- tx == max(tx)
  return(ux[max_tx])
}

    DF %>%
      group_by(Category) %>%
      summarise(Mode = mode(Color))

I'm trying to figure out the code that excludes the NA. The df would look like:
  Category Mode
  <fct>    <fct>
1 A        Green
2 B        Yellow
3 C        NA
4 D        Yellow

A: The following changes to the function ensure that the correct type of NA value is returned depending on the input and that it works with vectors of length 1.
mode <- function(x) {
  ux <- unique(na.omit(x))
  tx <- tabulate(match(x, ux))
  if(length(ux) != 1 & sum(max(tx) == tx) > 1) {
    if (is.character(ux)) return(NA_character_) else return(NA_real_)
  }
  max_tx <- tx == max(tx)
  return(ux[max_tx])
}

DF %>%
  group_by(Category) %>%
  summarise(Mode = mode(Color))

# A tibble: 4 x 2
  Category Mode
  <fct>    <chr>
1 A        Green
2 B        Yellow
3 C        NA
4 D        Yellow


text:
Q: Laravel collection issue I have to get the quantity of supplies for each supply by a certain supplier. I know that sounds weird but let me explain:
I have a Supplier model which has many supplies and each supply has many stocks which have a quantity. So now I'm building a view in which I want to represent each Supply with their quantity on a certain supplier.
So that's what I came up with in my controller:
foreach ($suppliers as $supplier) {

        foreach($supplier->supplies as $supply){

            if(!$comp_supplies->contains('name', $supply->name)){

                $comp_supplies->push(['name'=>$supply->name, 'supplier'=>[['name'=> $supplier->name, 'quantity' => $supply->stocks->first()->quantity]]]);

            }elseif($comp_supplies->contains('name', $supply->name)){

                $array = (['name'=> $supplier->name, 'quantity' => $supply->stocks->first()->quantity]);
                $array2 = $comp_supplies->where('name', $supply->name)->first()['supplier'];

                array_push($array2, $array);

                //dd($array2);
                $comp_supplies->where('name', $supply->name)->first()['supplier'] = $array2;
                dd($comp_supplies->where('name', $supply->name)->first()['supplier']);
            }
        }

    }

So I'm iterating over my suppliers and iterate again over the supplies from each of them. Now I want to fill the collection I want as a result.
If this collection not contains a supply with the name of "$supply->name", I push an array with the supply-name and create an array "suppliers" in which I also set the first entry with the current supplier information.
Now we are getting close to my problem.
If comp_supply already contains a supply with the current supply-name, if have to push the new supplier into the already existing "supplier" array we created in the first "if".
Therefore I created $array, which holds the new supplier-informations, and $array2, which holds the supplier-array ($comp_supplies->where('name', $supply->name)->first()['supplier']) we already made.
Now, if I push $array onto $array2 and dd(array2) everything works as i want it to.
But if I now set
$comp_supplies->where('name', $supply->name)->first()['supplier'] = $array2

and then
dd($comp_supplies->where('name', $supply->name)->first()['supplier']);

it didn't change.
I'm stuck on this Problem for nearly 2h and getting really frustrated.
Please if anyone has an idea what I could do to solve this, or knows where I can look next, let me know.
Here are also the migrations:
Supplier:
public function up()
{
    Schema::create('suppliers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->unsignedInteger('coordinates_id')->index()->nullable();
        $table->timestamps();
    });
}

Supplies:
public function up()
{
    Schema::create('supplies', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->unsignedInteger('supplier_id');
        $table->foreign('supplier_id')
              ->references('id')
              ->on('suppliers')
              ->onDelete('cascade');
        $table->timestamps();
    });
}

Stocks:
    public function up()
{
    Schema::create('stocks', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('supplies_id');
        $table->foreign('supplies_id')
              ->references('id')
              ->on('supplies')
              ->onDelete('cascade');
        $table->integer('quantity');
        $table->timestamps();
    });
}

A: Your problem is related to how PHP deals with arrays. Arrays are passed by value, not by reference, so when you call $comp_supplies->where('name', $supply->name)->first(), you actually get a copy of the array, and therefore modifying the value at the index 'supplier' modifies only the value of the copy, not the value of the original array.
You can verify this behavior with this example code:
class TestList
{
    protected $values;

    public function push($value)
    {
        $this->values[] = $value;
    }

    public function get($index)
    {
        return $this->values[$index];
    }
}

$list = new TestList();
$list->push(['test' => 1]);

var_dump($list->get(0)['test']); // int(1)

$list->get(0)['test'] = 2;
var_dump($list->get(0)['test']); // still int(1)...

You can overcome this issue by using objects instead of arrays, cause objects are passed by reference (notice the (object) cast):
$list = new TestList();
$list->push((object)['test' => 1]);

var_dump($list->get(0)->test); // int(1)

$list->get(0)->test = 2;
var_dump($list->get(0)->test); // int(2)!

A: Try this
$comp_supplies->where('name', $supply->name)->first()->update($array2)

Instead of
$comp_supplies->where('name', $supply->name)->first()['supplier'] = $array2

A: Instead of
$comp_supplies->where('name', $supply->name)->first()['supplier'] = $array2;

You should use:
$key = $comp_supplies->where('name', $supply->name)->get()->keys()->first();
$comp_supplies[$key]['supplier'] = $array2;

because you push into collection arrays, so first you need to find valid key of collection so later you can update this array for this key


text:
Q: MVC5 reading Config values without using System.Web I keep reading that the new MVC avoids using System.Web by default as that used to add lots of extra stuff automatically.
Does that mean that in order to read the config file now in MVC5,
one should use from System.Net instead?
Thanks...

A: I read somewhere in a Microsoft example where they imported
using System.Configuration;

and then use the standard
ConfigurationManager.AppSettings["MyKey"]

Just thought to post this in case somebody has the same question/problem

A: It should be:
string key = System.Configuration.ConfigurationManager.AppSettings.Get("AppKey");

OR
string key = System.Configuration.ConfigurationManager.AppSettings["AppKey"];


text:
Q: Processing results of getifaddrs() function causes segmentation fault I tried to use example from official getifaddrs page on Ubuntu 18.04.5 LTS bionic (Odroid-N2 board ARM64) while got the segmentation fault.
Further  analysis showed that struct ifaddrs which is filled by getifaddrs() contains invalid pointers.
Here is my code:
#include <stdint.h>
#include <unistd.h>
#include <ifaddrs.h>

int main(int argc, char** argv) {
    struct ifaddrs *ifaddr;
    int family;

    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        return -1;
    }

    for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr == NULL)
            continue;

        printf("IF: %s\n",ifa->ifa_name);
        printf("\tThis: %p\n", ifa);
        printf("\tNext: %p\n", ifa->ifa_next);
        printf("\tFlags: %x\n",ifa->ifa_flags);
        printf("\tAddr: %p\n", ifa->ifa_addr);
        printf("\tMask: %p\n", ifa->ifa_netmask);
        printf("\tDst: %p\n", ifa->ifa_dstaddr);
        printf("\tData: %p\n", ifa->ifa_data);

        family = ifa->ifa_addr->sa_family;
    }

    return 0;
}

And valgrind prints this:
==18313== Memcheck, a memory error detector
==18313== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18313== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==18313== Command: ./main.bin
==18313== IF: lo
        This: 0x49f8380
        Next: 0x49f8438
        Flags: 10049
        Addr: 0x49f83b800000000
        Mask: (nil)
        Dst: 0x49f840000000000
        Data: 0x49f89f800000000
==18313== Invalid read of size 2
==18313==    at 0x10899C: main (main.c:28)
==18313==  Address 0x49f83b800000000 is not stack'd, malloc'd or (recently) free'd
==18313==
==18313==
==18313== Process terminating with default action of signal 11 (SIGSEGV)
==18313==  Access not within mapped region at address 0x49F83B800000000
==18313==    at 0x10899C: main (main.c:28)
==18313==  If you believe this happened as a result of a stack
==18313==  overflow in your program's main thread (unlikely but
==18313==  possible), you can try to increase the size of the
==18313==  main thread stack using the --main-stacksize= flag.
==18313==  The main thread stack size used in this run was 8388608.
==18313==
==18313== HEAP SUMMARY:
==18313==     in use at exit: 1,944 bytes in 1 blocks
==18313==   total heap usage: 8 allocs, 7 frees, 7,476 bytes allocated
==18313==
==18313== LEAK SUMMARY:
==18313==    definitely lost: 0 bytes in 0 blocks
==18313==    indirectly lost: 0 bytes in 0 blocks
==18313==      possibly lost: 0 bytes in 0 blocks
==18313==    still reachable: 1,944 bytes in 1 blocks
==18313==         suppressed: 0 bytes in 0 blocks
==18313== Rerun with --leak-check=full to see details of leaked memory
==18313==
==18313== For counts of detected and suppressed errors, rerun with: -v
==18313== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) Segmentation fault

You may see that ifa_addr's pointer is 0x49f83b800000000 which is reported as "not stack'd, malloc'd or (recently) free'd"
Does anybody faced same problem?
Thanks

A: Apparently passing -fpack-struct=2 to gcc caused this issue


text:
Q: Get Hard Disk Size dynamically in Cocoa I'm trying to get the the size of the main HD. Here's the code I'm using:
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:@"/" error:nil];

But this code doesn't give me the correct size of the HD. If my HD has a capacity of 320gb that will return 290GB. I think there are other volumes but I don't know how to calculate them.
What I want to know is a way to get the total size of my hard drive.

A: It sounds like you're getting the correct answer, actually. People who sell hard drives like to use the power-of-10 gigabyte to describe the capacity of the disk, while the computer itself cares about how many multiples of 2 are available, and displays the gibibytes. A gibibyte is bigger than a gigabyte. The SI prefix "giga-" means 109; the so-called binary prefix "gibi-" was chosen to be the closest power of two, 230, which is 1,073,741,824.
The true number of bytes is the same in either case, it's just reported differently depending on whether you divide by 1,000,000,000 or 1,073,741,824. For example, 320,000,000,000 ÷ 1,073,741,824 = 298.023, and you might lose a bit more to area the disk reserves for itself.


text:
Q: get error on "buildozer android debug deploy run" get this error
Command failed: ./distribute.sh -m "kivy"
when trying to
$ buildozer android debug deploy run
How to fix it?
thanks

A: That means something went wrong in the python-for-android build step, but there are tons of problems that would give that error.
Could you set the buildozer token log_level = 2 in your buildozer.spec and try it again (by default it will be 1). This will get buildozer to print much more information about the build process, including hopefully more about the error. Then, could you include that error information here?


text:
Q: Rspec 2 and Rails 3 stubbing / mocking I am currently in the process of migration to rails 3 from rails 2 in a large application. In our functional specs, we have alot of stuff like this:
@model = Factory :model
@child = Factory :child
Model.stub!(:find).and_return(@model)
Child.stub!(:find).and_return(@child)

...

@child.should_receive(:method).twice

The main issue is that if I let it hit DB and get actual instance of child, real :method makes tests too complex (need two big factories) and slow.
In code we use various ways to get items: find, dynamic finders, etc
@model = Model.find(1)
@child = @model.children.find_by_name(name)

How would you advice to move this logic to rails 3? Any advice on another stubbing/mocking library maybe?

A: Normally you would mock the model inside controller specs:
Model.stub!(:find).and_return(mock_model('Model'))
Child.stub!(:find).and_return(mock_model('Child'))

However, when you've got gem "rspec-rails", "~> 2.0" in your rails 3 app's Gemfile, then the standard rails scaffold generator will use rspec to generate specs for you, so running rails generate scaffold MyResource will generate some example specs for you.
The following is a lightly annotated version of what rails/rspec will generate for controller specs, so I suppose this should be considered "The RSpec Way".
describe AccountsController do

  # Helper method that returns a mocked version of the account model.
  def mock_account(stubs={})
    (@mock_account ||= mock_model(Account).as_null_object).tap do |account|
      account.stub(stubs) unless stubs.empty?
    end
  end

  describe "GET index" do
    it "assigns all accounts as @accounts" do
      # Pass a block to stub to specify the return value
      Account.stub(:all) { [mock_account] }
      get :index
      # Assertions are also made against the mock
      assigns(:accounts).should eq([mock_account])
    end
  end

  describe "GET show" do
    it "assigns the requested account as @account" do
      Account.stub(:find).with("37") { mock_account }
      get :show, :id => "37"
      assigns(:account).should be(mock_account)
    end
  end

  describe "GET new" do
    it "assigns a new account as @account" do
      Account.stub(:new) { mock_account }
      get :new
      assigns(:account).should be(mock_account)
    end
  end
end


text:
Q: Images Randomly Disappearing in WordPress I have been having a strange issue happen that started suddenly. My images in my posts are randomly disappearing. I have changed themes, turned off plugins and checked the error logs. I called my hosting company and they can't figure it out either. I've been debugging this issue for almost two weeks now. They disappear from the media library, and the server. It's like the images were never uploaded at all. I even did a fresh install on another site to see if it still happened, and it is happening on that site too. But most of the plugins are different. This is very frustrating!
Here's a list of the plugins I have:
ACF Pro
ACF Frontend Forms
Advanced Database Cleaner PRO: Not active for debugging
Advanced Editor Tools (previously TinyMCE Advanced)
Advanced Post Queries
BuddyPress
Classic Widgets
Code Snippets: no snippets added that affect the media library
Elementor
Elementor Pro
Enlighter - Customizable Syntax Highlighter
Happy Elementor Addons
JetEngine
JetSmart Filters
JetTabs
User Role Editor
WP Mail SMTP
wpDiscuz
Youzify

THEME: Kava was the original, but I changed to Customify to further debug, so that's what's active right now.
Does anyone know how to trace what is calling for the deletion of these images? Or at least have a clue as to what could be causing it?

A: I actually figured it out! It was a cron job setting in wpDiscuz plugin! It was set to delete any images not attached to a post. Once I deleted the cron job, the issue stopped. I NEVER would have guessed that a comment plugin would do that! It took a long time to figure it out. But at least I know what it is now.


text:
Q: WPF : Passing Custom data to between Custom Control and parent I am total newbie to WPF. I am creating my custom user control which will display the employee data structure which is as follows I have implemented INotifyPropertyChanged also:
Here's code snippet
public class Employee : INotifyPropertyChanged
    {
        private int id;
        private string name;
        private double salary;
        private EmployeeDesignation designation;
        public int ID
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ID"));
                //PropertyChanged(ID, new PropertyChangedEventArgs("ID"));
            }
        }
...
     public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }
    }
}

And user control code is as follows :
<UserControl x:Class="Assignment5.EmployeeUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://scenter code herehemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" DataContext="{Binding RelativeSource={RelativeSource Self}, Path=.}"
             d:DesignHeight="196" d:DesignWidth="300">
    <Grid Height="182">
        <Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="26,57,0,0" Name="label1" VerticalAlignment="Top" Width="76" />
        <Label Content="Salary" Height="28" HorizontalAlignment="Left" Margin="26,91,0,0" Name="label2" VerticalAlignment="Top" />
        <Label Content="ID" Height="28" HorizontalAlignment="Left" Margin="26,23,0,0" Name="label3" VerticalAlignment="Top" />
        <Label Content="Designation" Height="28" HorizontalAlignment="Left" Margin="26,125,0,0" Name="label4" VerticalAlignment="Top" />
        <TextBox Text="{Binding ElementName=Employee, Path=ID}" Height="23" HorizontalAlignment="Left" Margin="134,28,0,0" Name="IdTextBox" VerticalAlignment="Top" Width="120" />
        <TextBox Text="{Binding ElementName=Employee, Path=Name}" Height="23" HorizontalAlignment="Left" Margin="134,59,0,0" Name="NameTextBox" VerticalAlignment="Top" Width="120" />
        <TextBox Text="{Binding ElementName=Employee, Path=Salary}" Height="23" HorizontalAlignment="Left" Margin="134,91,0,0" Name="SalaryTextBox" VerticalAlignment="Top" Width="120" LostFocus="SalaryTextBoxLostFocus" />
        <TextBox Text="{Binding ElementName=Employee, Path=designation}" Height="23" HorizontalAlignment="Left" Margin="134,125,0,0" Name="DesignationTextBox" VerticalAlignment="Top" Width="120" />
    </Grid>
</UserControl>

Here's code behind file
namespace Assignment5
{
    public partial class EmployeeUserControl : UserControl, INotifyPropertyChanged
    {
        public static readonly DependencyProperty EmpDependancyProperty =
                            DependencyProperty.Register("Employee", typeof(Employee), typeof(EmployeeUserControl)
                            , new PropertyMetadata(
                                new PropertyChangedCallback(
                                            EmployeeUserControl.EmployeeDataChanged)));
        public Employee Employee
        {
            get
            {
                return (Employee)GetValue(EmpDependancyProperty);
            }
            set
            {
                SetValue(EmpDependancyProperty, value);
            }
        }

        public EmployeeUserControl()
        {
            InitializeComponent();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void SalaryTextBoxLostFocus(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(Employee.Name);
        }
        private static void EmployeeDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            EmployeeUserControl userControl = d as EmployeeUserControl;
            userControl.OnPropertyChanged("Employee");
        }
    }
}

Here's my parent control...
<Window x:Class="Assignment5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:Assignment5"
        DataContext="{Binding RelativeSource={RelativeSource Self}, Path=.}">
    <Grid>
        <my:EmployeeUserControl  Employee="{Binding Path=emp, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" HorizontalAlignment="Left" Margin="130,56,0,0" x:Name="employeeUserControl1" VerticalAlignment="Top" Width="285" />
    </Grid>
</Window>

and a code behind :
namespace Assignment5
{

    public partial class MainWindow : Window
    {
        public static readonly DependencyProperty EmpDependancyProperty =
                        DependencyProperty.Register("Employee", typeof(Employee), typeof(EmployeeUserControl)
                        , new PropertyMetadata(
                            new PropertyChangedCallback(
                                        EmployeeUserControl.EmployeeDataChanged)));
    public Employee Employee
    {
        get
        {
            return (Employee)GetValue(EmpDependancyProperty);
        }
        set
        {
            SetValue(EmpDependancyProperty, value);
        }
    }
        public MainWindow()
        {
            emp = new Employee(203,"AAA",23232);
            InitializeComponent();
        }
    }
}

When I run this code. I came to know that Employee object in parent control is getting initialized but in the user control it is not getting initialized. What I am doing wrong here?

A: Two issues

*

*In your UserControl change the Bindings to
<TextBox Text="{Binding Path=Employee.ID}" Height="23" HorizontalAlignment="Left" Margin="134,28,0,0" Name="IdTextBox" VerticalAlignment="Top" Width="120" />
<TextBox Text="{Binding Employee.Name}" Height="23" HorizontalAlignment="Left" Margin="134,59,0,0" Name="NameTextBox" VerticalAlignment="Top" Width="120" />
<TextBox Text="{Binding Employee.Salary}" Height="23" HorizontalAlignment="Left" Margin="134,91,0,0" Name="SalaryTextBox" VerticalAlignment="Top" Width="120" LostFocus="SalaryTextBoxLostFocus" />
<TextBox Text="{Binding Employee.designation}" Height="23" HorizontalAlignment="Left" Margin="134,125,0,0" Name="DesignationTextBox" VerticalAlignment="Top" Width="120" />

*In your Window:
<my:EmployeeUserControl  Employee="{Binding Employee, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" HorizontalAlignment="Left" Margin="130,56,0,0" x:Name="employeeUserControl1" VerticalAlignment="Top" Width="285" />

In your constructor   emp = new Employee(203,"AAA",23232); does not make any sense. Instead do this.Employee = new Employee(203,"AAA",23232);


text:
Q: Redefining \section outputs the equivalent of an additional \section{*} before the TOC When I redefine the \section command, an additional section with title "*" is created before the table of contents, as if I had inserted a \section{*} before the table of content, which I never did. Here is the minimum working example:
\documentclass[12pt]{article}

\usepackage{parskip,lipsum}
\let\oldsection\section
\def\section#1{\oldsection{#1}} % CREATES ADDITIONAL GHOST SECTION???

\begin{document}
\tableofcontents
\section{I am a section}
\lipsum[1]
\end{document}

Screenshot of what I am getting at the bottom.
What I have tried:

*

*Using \renewcommand{\section}[1]{\oldsection{#1}} gives exactly the same problem.

*Omitting the argument as in \def\section{\oldsection} does not create the same problem, but I need to pass the argument for what I need to do.

(What I need to do in the grander scheme of things: I want to redefine \def\section#1{\clearevenpage\twocolumn[\oldsection{#1}]} so that sections start on even pages and span the whole page in a twocolumn document. However, the unexpected behaviour seems wholly unrelated to what I am trying to achieve here.)

EDIT: For anyone wondering,  \clearevenpage mentioned above is defined as
\documentclass[twoside]{article}

\makeatletter
\def\clearevenpage{\clearpage\if@twoside \ifodd\c@page
    \hbox{}\newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}
\makeatother

A: A couple of things:

*

*Within the article document class, \tableofcontents issues \section*{\contentsname}. Note the *.

*\section is defined not to take any arguments by default. Whaaa?! In fact, it passes the argument capturing and star checking over to other macros.
So your (re)definition of \section to take a singular argument is bound to take whatever is passed as the first argument as its only argument... and as you've seen, this is a problem when that first argument is a * (like with \tableofcontents).
Instead of your simple redefinition, you would have to either intervene in a different location (not \section but somewhere deeper in the bowels of subsidiary macros called by \section) or condition on the choices offered by the default \section from the start. This latter option is easier and more comprehensible.
\documentclass[twocolumn]{article}

\usepackage{lipsum}
%\usepackage{xparse}% Use this if your LaTeX distribution is not up-to-date.

\newcommand{\clearevenpage}{\clearpage}% Or whatever you have \clearevenpage defined as.

\let\oldsection\section
\RenewDocumentCommand{\section}{s o m}{%
  \clearevenpage
  \twocolumn[%
    \IfBooleanTF{#1}
      {\oldsection*{#3}}% \section*[.]{..}
      {\IfValueTF{#2}
        {\oldsection[#2]{#3}}% \section[.]{..}
        {\oldsection{#3}}% \section{..}
      }%
  ]
}

\begin{document}

\tableofcontents

\section{I am a section}

\lipsum[1]

\end{document}


text:
Q: what is com.google.android.gms.providerinstaller mean? I build an app using flutter. I am fetching data from firebase to my build app but some problem occur again and again.
 W/DynamiteModule(11085): Local module descriptor class for com.google.android.gms.providerinstaller
 not found.
 I/DynamiteModule(11085): Considering local module com.google.android.gms.providerinstaller:0 and
 remote module com.google.android.gms.providerinstaller:0
 W/ProviderInstaller(11085): Failed to load providerinstaller module: No acceptable module found.
 Local version is 0 and remote version is 0.


text:
Q: Adding string arrays in function and keep getting an error New to solidity so bare with me I'm going to push through
I'm having an issue with this line in my code if anyone could help me out. While learning (applying what I learn as I go) string arrays inside of a function. Currently stuck here at this error
("mycontract.sol:9:21: ParserError: Expected ';' but got '('
funtion addvalue(string memory _value) public {")
pragma solidity ^0.6.0;

contract mycontract {
    //array
    uint[] public uintarray = [1,2,3];
    string[] public stringarray = ["past, present, future"];
    string[] public values;

    funtion addvalue(string memory _value) public {
        values.push(_value);
    }
}

But when I Fix this error there's another. Can someone tell help me find out why?
I fixed the error to no avail


text:
Q: AngularJS, Two level menu add "active" class to both the active sub-item and its parent based on url If it's just one level navigation/menu, url like "localhost/#/user"
I know I can use:

User

and in controller
$scope.isActive = function (path) {
  if ( path == $location.path() )
    return true;
  return false;
};

then when url is "localhost/#/user", "active" will be added.
Yet when it comes to two level menu, url like "localhost/#/user/orders"

    User

Orders

How can I add "active" class to both the item "orders" and its parent "user" based on url?  ( so I can highlight them both )
Thanks in advance.

Update:
Thanks, it's working now :D
@Nikos Paraskevopoulos, @piatek, @Chandermani thanks
here's my final working code written in CoffeeScript, though the code is not good enough, but it works :)
.directive('highlightActive', () ->
    return {
        restrict: "A"
        controller: [
            '$scope', '$element', '$attrs', '$location'
            ($scope, $element, $attrs, $location) ->
                links = $element.find('a')
                path = () ->
                    return $location.path()

                highlightActive = (links, path) ->
                    path = '#' + path

                    angular.forEach(links, (link) ->
                        $link = angular.element(link)
                        $li = $link.parent('li')
                        href = $link.attr('href')

                        if ($li.hasClass('active'))
                            $li.removeClass('active')
                        if path.indexOf(href) is 0
                            $li.addClass('active')
                    )

                highlightActive(links, $location.path())

                $scope.$watch(path, (newVal, oldVal) ->
                    if newVal is oldVal
                        return
                    highlightActive(links, $location.path())
                )
        ]

    }
)

A: One way i can think of, would be to pass multiple arguments to isActive such as

User

and then check match to any one of the paths.

A: If your URLs follow the hierarchy of the menus (i.e. /user → /user/orders → /user/orders/something, where → means submenu), you could check string containment with a simple directive:
app.directive("menuHref", function() {
    return {
        restrict: "A",
        template: "
{{ text }}
",
        scope: {
            text: "="
        },
        controller: ["$scope", "$element", "$attrs", "$location", function($scope, $element, $attrs, $location) {
            $scope.href = "#" + $attrs.menuHref;

            $scope.$watch(
                function() {
                    return $location.hash().startsWith($attrs.menuHref);
                },
                function(newval) {
                    $element.toggleClass("active", newval);
                }
            );
        }]
    };
});

Use it as:

(note href does not start with #, the  is generated by the directive)
I haven't tested this code, it may contain small bugs (we can discuss them) but I think the principle should work.

A: Plenty of ways to do this, I would just add a directive on the top element as angular tends to beef up the HTML anyway.

    User

        Orders

        Account

App.directive('activeli', function ($location) {
  return function ($scope, $el) {
    var links = $el.find('a'),
        path = function(){ return $location.path(); }

    function addActiveClass (links, path) {
        angular.forEach(links, function (link) {
            var $link = angular.element(link);

            if ($link.hasClass('active')) {
                $link.removeClass('active');
            } else if (link.hash === ('#' + path)) {
                $link.addClass('active');
            }
        });
    }

    // Initial state
    addActiveClass(links, $location.path());

    $scope.$watch(path, function (newValue, oldValue) {
        if (newValue === oldValue) return;
        addActiveClass(links, $location.path());
    });
  };

});


text:
Q: Delay Prometheus alert before changing from active to inactive I have an alert in my Prometheus set up that sends an alert when someMetric > 100 has been valid for 5m and then resends the alert every 24h according to the configuration below:
prometheus-alert.yml
 - alert: TestAlert
          expr: someMetric > 100
          for: 5m

alertmanager-config.yml
repeat_interval: 24h

However someMetric has a behaviour where it can be "stable" above 100 (which means an alert is active) but every once in a while it drops to something below 100 for a single scraping before jumping back up above 100. This will cause an active alert to become inactive (resolved) then back to pending and active again after 5 min. This will cause Prometheus to resend the alert which is what I want to avoid.
Is there a way to configure Prometheus to have something similar to for: 5m, but for the transiction active -> inactive (resolved)?

A: You could use one of the aggregation-over-time promQL functions to 'filter out' the blips that dip below 100, in your example? In your case it sounds like max might work? The only down-side being that it could take a few minutes longer to end the alert once the value drops permanently below 100.
- alert: TestAlert
      expr: max_over_time(someMetric[2m]) > 100
      for: 5m