text:
Q: Login Form is not rendering I'm having an issue when i want to render a login form view those issues started when i began to use context api for React. the error that show me right now is:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  Check the render method of LoginForm.

the error is there:

Index.js:
    // React
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { LoginPage } from '../src/views/Login';

// 1
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

// Context Provider
import AppProvider from './context/context';
import { LoginForm } from './components/Form';

// 2
const httpLink = createHttpLink({
  uri: 'http://localhost:3000/graphql'
});

// 3
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

// 4
export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})

ReactDOM.render(

    <ApolloProvider client={client}>
    <BrowserRouter>
      <AppProvider>
        <App />
      </AppProvider>
    </BrowserRouter>
    </ApolloProvider>,
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();

when i take the line out of the script, the one with Context.Consumer at the LoginForm component the error goes away. i tried to export the component with the default then wihout it with no success.
Login Form:
        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // import mutations
    import mutations from './mutations';

    // React bootstrap
    import { Container, Row, Form, Button } from 'react-bootstrap';

    // Import Style
    import './style.css';

    // Component
    import NavbarLayout from '../Navbar';

    // Context
    import Context from '../../context/context';

    export class LoginForm extends React.Component {

        render() {

            return(

                <Fragment>
                    <Context.Consumer>
                        {c => {
                            return(
                                <Container>
                                    <Form className="form-container">

Ingreso

                                        <Form.Group controlId="formBasicEmail">
                                            <Form.Control name='email' onChange={e => c.get_data(e)} type="email" placeholder="Email" />
                                        </Form.Group>

                                        <Form.Group controlId="formBasicPassword">
                                            <Form.Control name='password' onChange={e => c.get_data(e)} type="password" placeholder="Contraseña" />
                                        </Form.Group>

                                            <Button className="button-login" variant="primary" onClick={e => c.submit(e)} type="submit">
                                                Ingresa
                                            </Button>

                                    </Form>
                                </Container>
                            );
                        }}
                    </Context.Consumer>
                </Fragment>
            );
        }
    }

This component is called into this view:
        // React
    import React, { Fragment } from 'react';

    // Component React
    import { LoginForm } from '../../components/Form';

    // React bootstrap
    import { Container, Row } from 'react-bootstrap';

    export const LoginPage = () => {
        return(
            <Fragment>
                <Container style={{marginTop: '2rem'}}>
                    <LoginForm />
                </Container>
            </Fragment>
        );
    }

The context Api file is:
        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // Mutation
    import mutations from './mutations';

    // Context
    const Context = React.createContext();

    class AppProvider extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                // Login & logout states
                login_credentials: {},
                isLogged: false,
                get_data: this.get_data,
                submit: this.submit,
            }
        }

        // Actions

        // Login & Logout

        get_data = async(e) => {
            e.preventDefault();
            const { name, value } = e.target;
            const data = { [name]: value };
            const newData = { ...this.state.login_credentials, ...data };
            this.setState({
                login_credentials: newData
            });

        }

        submit = async(e) => {
            e.preventDefault();
            const { signinUser } = this.props;
            const { login_credentials, isLogged } = this.state;

            try {
                let variables = login_credentials;
                const response = await signinUser({variables});
                const get_token = response.data.signinUser.token;

                // setting localStorage
                localStorage.setItem('token', get_token);
                this.setState({
                    isLogged: true
                });

                this.props.history.push({pathname: '/home', state: {isLogged: this.state.isLogged}});

            } catch(error) {
                console.log(error);
            }

        }

        // END LOGIN & LOGOUT ACTIONS

        render() {
            return(
                <Context.Provider value={this.state}>
                    {this.props.children}
                </Context.Provider>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signinUser, { name: 'signinUser' }),
    )(AppProvider)

A: // Component React
import { LoginForm } from '../../components/Form';

try removing the curly braces and import directly
// Component React
import  LoginForm  from '../../components/Form';

you should import files using curly braces when you're importing it from an index file
else try checking your path
         '../../components/Form';
check for spelling both upper and lower case also not you went back twice in your directory ../../ try once ../

A: Well i have the answer finally for this bug. the fixed lines shown is this solutions has been inherit from the question at the top

*

*I was not exporting context from context.js so i have to add export:
// Context
export const Context = React.createContext();

*I was importing the context as if it were a default export so to fix:
// Context
import { Context } from '../../context/context';


text:
Q: PHP, database issue I have this piece of code
<?php

$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("tables", $con);
$sql="INSERT INTO customer (Name, Telephone, Email, Address, PostCode, Specialisation )
VALUES
($_POST['firstname'], $_POST['telephone'],$_POST['email'],         $_POST['address'],$_POST['postcode'],$_POST['special'])";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Inserted into Worker database";

mysql_close($con);
?>

I keep getting this error-  Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in.
I am not sure what else to do. Please help. Thanks

A: You have several issues.
First, string values you're inserting into the database need single quotes around them.
Second, array variables in strings need to be wrapped in {} (i.e. $string = "Something something {$_POST['variable']}..."; to help the PHP parser figure them out.
Third, this code (once working) is massively vulnerable to hacking via SQL injection. Consider using PDO and prepared statements (as the mysql_* functions are being deprecated), or at the very least run user input through mysql_real_escape_string().
$sql="INSERT INTO customer (Name, Telephone, Email, Address, PostCode, Specialisation) VALUES ('" . mysql_real_escape_string($_POST['firstname']) . "', '" . mysql_real_escape_string($_POST['telephone']) . "', '" . mysql_real_escape_string($_POST['email']) . "', '" . mysql_real_escape_string($_POST['address']) . "', '" . mysql_real_escape_string($_POST['postcode']) . "', '" . mysql_real_escape_string($_POST['special']) . "')";

Fourth, you really shouldn't use the database's root user to connect.

A: Change your $sql variable to read on one line and to send the proper format to SQL:
$sql="INSERT INTO customer (Name, Telephone, Email, Address, PostCode, Specialisation ) VALUES ({$_POST['firstname']}, {$_POST['telephone']},{$_POST['email']}, {$_POST['address']},{$_POST['postcode']},{$_POST['special']})";

That should correct the PHP error of unexpected T_ENCAPSED_AND_WHITESPACE but you will need more corrections to fix the SQL Injection possibility.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to call NSURLSession Delegate in NSObject class not in viewcontroller? NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:(id<NSURLSessionDelegate>)self delegateQueue:nil];

NSString *body = [[NSString alloc] initWithData:bodyData encoding:NSASCIIStringEncoding];
RMLog(@"RestManager:[%@]\nRequest URL = %@\nMethod = %@\nHeaders\n%@\nBody\n%@",  keyPath, url.absoluteString, method, additionalHeaders, body);

if (bodyData != nil && ([method isEqualToString:kMethodPost] || [method isEqualToString:kMethodPut])) {
    NSURLSessionUploadTask *uploadTask =
    [session uploadTaskWithRequest:request
                          fromData:bodyData
                 completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
                     [self parseKeyPath:keyPath responseData:data reponse:response error:error completionHandler:completionHandler];
                 }];
    [uploadTask resume];
}

I am trying to call Nsurlsession delegate in NSObject class. I am using this line NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:(id<NSURLSessionDelegate>)self delegateQueue:nil] but delegate method is not called.

A: init your NSObject-Class and set it as the Sessions Delegate...
NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:NSObjectClass delegateQueue:nil];

in NSObjectClass:
#import <Foundation/Foundation.h>

@interface Object : NSObject <NSURLSessionDelegate, ...>

@end

A: You can create a NSObject class as below
    @interface ServerAPI : NSObject<NSURLSessionDelegate, NSURLSessionTaskDelegate>
   -(void)startUploadTask;
    @end

    @implementation ServerAPI
    -(void)startUploadTask{
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];// here you can use your own custom configuration
        NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:(id<NSURLSessionDelegate>)self delegateQueue:nil];

        NSString *body = [[NSString alloc] initWithData:bodyData encoding:NSASCIIStringEncoding];
        RMLog(@"RestManager:[%@]\nRequest URL = %@\nMethod = %@\nHeaders\n%@\nBody\n%@",  keyPath, url.absoluteString, method, additionalHeaders, body);
        if (bodyData != nil && ([method isEqualToString:kMethodPost] || [method isEqualToString:kMethodPut])) {
            NSURLSessionUploadTask *uploadTask =
            [session uploadTaskWithRequest:request
                                  fromData:bodyData
                         completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
                             [self parseKeyPath:keyPath responseData:data reponse:response error:error completionHandler:completionHandler];
                         }];
            [uploadTask resume];
        }
    }
    // Implement delegates method here
    @end

And create instance of ServerAPI class wherever you want and call startUploadTask method.
For example:
ServerAPI *instance = [ServerAPI alloc] init];
[instance startUploadTask];


text:
Q: Как вывести по отдельности поля из группы полей ACF? Всем добра! Есть группа полей (ACF Field Group) "sites". В ней есть два поля:

Первое поле "Сайт" с именем "siteicon" и типом "Выбор(Select) где есть два варианта
internet : Сайт
vk : Вконтакте

И второе поле "URL сайта" с именем "siteurl" и типом "Текст".

Собственно нужны поля, чтобы указывать для салонов массажа сайт и группу ВК. Сейчас стал вопрос, как вывести это дело на фронт. Знаний не хватает, как обычные поля они не выводятся. Гуглил и пробовал много. Удалось вывести сразу оба значения. Как в цикле, так и без просто сплошняком. Собственно вопрос, как разделить мне siteurl, чтобы получить два значения отдельно и оперировать ими, чтобы можно было встроить их в ссылки, а на основе выбранного первого siteicon создать для них нужные иконки. В итоге получить на выходе иконку сайта с ссылкой сайта и иконку ВК с ссылкой на группу ВК.

Update:
Вроде пока решил таким образом (может и костыль, но мну не прогер). Вывело две строчки со своими иконками и нужными значениями в каждой строке.
<?php if( have_rows('sites') ): ?>
<?php while( have_rows('sites') ): the_row();
$website = get_sub_field('siteurl');
?>
<?php
if( get_sub_field('siteicon') == 'internet' ) {
   ?><a href="<? echo $website ?>"><? echo $website ?>
<?}?>

<?php
if( get_sub_field('siteicon') == 'vk' ) {
   ?><a href="https://vk.com/<? echo $website ?>"><? echo $website ?>
<?}?>
<?php endwhile; ?>
<?php endif; ?>


text:
Q: Change data order in a specific column Based on files LastWriteTime property my script create a table 'File Age' with a custom output. The script work fine, my problem is with the output of a specific column 'Age' that i'cant set the order like i will.
I already try to use cmdlet "Sort-Object -descending" but without success,data is randomly positioned.
Maybe there is another way to customize that?
My desired output look like that:
    Age
1 Day - 1 Week
1 Week - 1 Month
1 Month - 6 Months
6 Months - 1 Year
1 Year - 2 Years
< 2 Years

Here is my script:
$scan = gci c:\MyFolder
$scan | Add-Member ScriptProperty -Name FileAgeDays -Value {
            [int]((Get-Date) - ($this.LastWriteTime)).TotalDays}
$scan | Add-Member ScriptProperty -Name FileAge -Value {

if ($this.FileAgeDays -le 7) {
    "1 Day - 1 Week"
}
elseif ($this.FileAgeDays -ge 7 -and $this.FileAgeDays -le 30) {
    "1 Week - 1 Month"
}
elseif ($this.FileAgeDays -ge 30 -and $this.FileAgeDays -le 180) {
    "1 Month - 6 Months"
}
elseif ($this.FileAgeDays -ge 180 -and $this.FileAgeDays -le 365) {
    "6 Months - 1 Year"
}
elseif ($this.FileAgeDays -ge 365 -and $this.FileAgeDays -le 730) {
    "1 Year - 2 Years"
}
elseif ($this.FileAgeDays -ge 730) {
    "< 2 Years"
}
}
$grp = $scan | ?{ ! $_.PSIsContainer } | Group FileAge |
           Add-Member -MemberType ScriptProperty -Name SizeMB -Value {
           ($this.Group | Measure-Object Length -sum).Sum / 1MB} -PassThru

$age_frag = $grp | select`
 @{l='Size (MB)';e={"{0:n}" -f ($_.sizemb)}},`
 @{l='Age';e={$_.name}}, Count|
ConvertTo-Html -Fragment -As Table -PreContent "

File Age
"|
Out-String

Any help will be welcome.

A: You could use a switch to replace the text-value with sortable data, ex. an integer.
Sample data:
$data = [pscustomobject]@{ ID=1; FileAge="1 Day - 1 Week"},
[pscustomobject]@{ ID=4; FileAge="6 Months - 1 Year"},
[pscustomobject]@{ ID=2; FileAge="1 Week - 1 Month"},
[pscustomobject]@{ ID=5; FileAge="1 Year - 2 Years"},
[pscustomobject]@{ ID=6; FileAge="< 2 Years"},
[pscustomobject]@{ ID=3; FileAge="1 Month - 6 Months"}

$data

ID FileAge
-- -------
 1 1 Day - 1 Week
 4 6 Months - 1 Year
 2 1 Week - 1 Month
 5 1 Year - 2 Years
 6 < 2 Years
 3 1 Month - 6 Months

Now, let's sort it:
$data | Sort-Object {
    switch($_.FileAge) {
    "1 Day - 1 Week" { 1 }
    "1 Week - 1 Month" { 2 }
    "1 Month - 6 Months" { 3 }
    "6 Months - 1 Year" { 4 }
    "1 Year - 2 Years" { 5 }
    "< 2 Years" { 6 }
    }
}

ID FileAge
-- -------
 1 1 Day - 1 Week
 2 1 Week - 1 Month
 3 1 Month - 6 Months
 4 6 Months - 1 Year
 5 1 Year - 2 Years
 6 < 2 Years

Personally, I would design the script differently. I would have added a FileAgeGroup-property with integer-values like 1,2,3.., sorted by that and then used Select-Object to genereate the user-friendly output:
$data | Sort-Object ID | Select-Object @{n="FileAgeName";e={
    switch($_.ID) {
    1 { "1 Day - 1 Week" }
    2 { "1 Week - 1 Month" }
    3 { "1 Month - 6 Months" }
    4 { "6 Months - 1 Year" }
    5 { "1 Year - 2 Years" }
    6 { "< 2 Years" }
    }
}}

FileAgeName
-----------
1 Day - 1 Week
1 Week - 1 Month
1 Month - 6 Months
6 Months - 1 Year
1 Year - 2 Years
< 2 Years

UPDATE: Here's an untested, modified version of your sample where my first solution implemented (sorting only without rewriting your code). I've added comments above the added code.
$scan = gci c:\MyFolder
$scan | Add-Member ScriptProperty -Name FileAgeDays -Value {
            [int]((Get-Date) - ($this.LastWriteTime)).TotalDays}
$scan | Add-Member ScriptProperty -Name FileAge -Value {

if ($this.FileAgeDays -le 7) {
    "1 Day - 1 Week"
}
elseif ($this.FileAgeDays -ge 7 -and $this.FileAgeDays -le 30) {
    "1 Week - 1 Month"
}
elseif ($this.FileAgeDays -ge 30 -and $this.FileAgeDays -le 180) {
    "1 Month - 6 Months"
}
elseif ($this.FileAgeDays -ge 180 -and $this.FileAgeDays -le 365) {
    "6 Months - 1 Year"
}
elseif ($this.FileAgeDays -ge 365 -and $this.FileAgeDays -le 730) {
    "1 Year - 2 Years"
}
elseif ($this.FileAgeDays -ge 730) {
    "< 2 Years"
}
}
$grp = $scan | ?{ ! $_.PSIsContainer } | Group FileAge |
           Add-Member -MemberType ScriptProperty -Name SizeMB -Value {
           ($this.Group | Measure-Object Length -sum).Sum / 1MB} -PassThru

#Scriptblock that can be used to sort by FileAge (Name-property in a Group)
$fileageSorting = {
    switch($_.Name) {
    "1 Day - 1 Week" { 1 }
    "1 Week - 1 Month" { 2 }
    "1 Month - 6 Months" { 3 }
    "6 Months - 1 Year" { 4 }
    "1 Year - 2 Years" { 5 }
    "< 2 Years" { 6 }
    }
}

$age_frag = $grp |
#Sorting
Sort-Object $fileageSorting |
select @{l='Size (MB)';e={"{0:n}" -f ($_.sizemb)}}, @{l='Age';e={$_.name}}, Count |
ConvertTo-Html -Fragment -As Table -PreContent "

File Age
"|
Out-String


text:
Q: Is this a correct way of declaring an array I have to make an array of whole numbers K(L) (L<=30) in c++,and i need some help declarating it correctly ,because im certain my way is wrong.
    #include <iostream>
    using namespace std;
    const int L = 30;
    void main ()
     {
       int K[L]
       int br =0;
       int i;
       for (i = 0; i < L; i++)
       cout <<endl << "Enter a number" ;
       cin >> K[i];
       }

A: Your array declaration is simply missing a semicolon.
Use int K[L]; instead of int K[L].

A: The first error the compiler gives is pretty self-explanatory:
main.cpp:4:16: error: '::main' must return 'int'
     void main ()
                ^

The next two are trickier. They are caused by the forgotten ; on the int K[L] line.
main.cpp: In function 'int main()':
main.cpp:7:8: error: expected initializer before 'int'
        int br =0;
        ^~~
main.cpp:11:15: error: 'K' was not declared in this scope
        cin >> K[i];

The forgotten ; makes the compiler read the line as int K[L] int br =0; so the declaration of both K and br fails, and it's the failed declaration of K that causes the third error.
I corrected it and removed an oddly placed std::endl.
#include <iostream>

const int L = 30;

int main()
{
    int K[L];
    // int br =0; // unused
    int i;
    for (i = 0; i < L; i++) {
        std::cout << "Enter a number: ";
        std::cin >> K[i];
    }
}


text:
Q: How to manage many variables I am making a program that asks a user a lot of questions, and I have each question defined at the top of my file.  Unfortunately because of the ridiculous number of questions I need to have, the file has become extremely packed and difficult to navigate.  The questions are organized by different sections, so I thought it would be great if I could fold all of the variables by section and label them with a comment.
I am using Pydev for Eclipse. I have done some searching but haven't found anything promising. Any suggestions for how to do this or how to better organize my variables?

A: "Data driven programming": store your questions in a data file, and your program just needs the required logic to load and present them.

A: The short answer is that you shouldn't have a lot of variables to manage, rather they should be organized in some way, using a list or a dictionary or some other technique.
The answer really depends on the nature of your questions and answers, but, for example, if I wanted to sum the answers together or plot the answers on a graph, it might make sense to have a list of questions and a corresponding list of answers:
qlist = [ "What's your chem grade", "What's your Math grade", . . . ]
alist = []
for q in qlist:
    a = <answer>
    alist.append(a)

Of course, if your questions and answers are not amenable to that approach, you could organize them some other way, for example, using a dictionary.  One simple approach would be to use the question as the key, though that could get cumbersome.


text:
Q: Is it possible to change the anchornode of a textnode object? Here's my code:
function moremagic()
    {
        var txt = '';
         if (window.getSelection)
        {
            txt = window.getSelection();
                 }
        else if (document.getSelection)
        {
            txt = document.getSelection();
                }
        else if (document.selection)
        {
            txt = document.selection.createRange().text;
                }
        else return;
    if(txt=="" || txt==" "){
        alert("No Text Selected");
        return;}
    var start = txt.anchorOffset;
    var countstring = txt.toString();
    alert(txt.anchorNode);
    var end = txt.anchorOffset+countstring.length;
    var type = prompt("Annotation Type: ");
    if(type=="lp-token"){
        var description = prompt("Lisp Statement: ");}
    else if(type=="section-head-annotation"){
        var description = "Section Head";}
    else if(type=="list-item-annotation"){
        var description = "list-element";}
    else if(type=="sentence-annotation"){}
    else {var description = prompt("Description: ");}
    Arraystring = Arraystring+"#"+type+"#"+description+"#"+start+"#"+end;
    alert(Arraystring);
    var custom = document.getElementById("custom");
    custom.value=Arraystring;
    }

It generates a textnode object from text highlighted by the cursor but this function is called many different times and for each different highlight the anchorNode changes. I need the anchorNode to be a constant for all of the created textnode objects. Is there any way that the anchorNode of a textobject can be changed? Thank you!

A: Not totally sure what you are trying to achieve, but in reading this http://help.dottoro.com/ljkstboe.php I would have to say "No, there is no way to make the anchorNode constant" since it is based off of the selection. Now, if you always want the reference to the first character in the selected string for a particular selection (assuming the selection is only textNode), then you might be able to do this (replacing code where your var start is):
var firstNode, start;
if(txt.anchorOffset < txt.focusOffset) {
  firstNode = txt.anchorNode;
  start = txt.anchorOffset;
}
else {
  firstNode = txt.focusNode;
  start = txt.focusOffset;
}

var countstring = txt.toString();
etc...

This is because if the selection is made from right-to-left rather than left-to-right, most browsers place the anchorNode at the last character and the focusNode at the first character of the selection, because the anchorNode indicates where the user started their selection.


text:
Q: working on parent UI from containerview (iOS - objective-c) I have a method in my main viewcontroller:
- (void)playMusic:(NSString*)songTitle :(NSString*)songArtist :(NSString*)songDuration :(NSString*)songUrl{

    [songPlayer pause];

    songPlayer = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:songUrl]];

    [songPlayer play];

    self.songSlider.maximumValue = 100;

    self.songSlider.value = 0;

}

I call it from a view inside a containerview like this (from a button click)
 [mainController playMusic:songTitle:songArtist :songDuration :songUrl];

songPlayer (it s an AVPlayer) is doing his job well, the song start without problem.
But the songSlider (it s an UISlider) is not updated.
If I call the exam same instructions:
self.songSlider.maximumValue = 100;

self.songSlider.value = 0;

inside viewDidLoad method of my main cotroller, songSlider is updated without problem.
That makes me think the problem is that I call the function from the containerview? in this case how can I fix this? Thank you

A: I answered a similar question about an hour ago.
I suspect the problem to be that your button click action is not being called on the main thread. I didn't find any resources to indicate if UIControl always fires events on the main thread and thus there is a possibility that your code is running on a background thread. This is important because you cannot make UI modifications on any other thread than the main thread.
Try the following in your button callback
dispatch_sync(dispatch_get_main_queue(), ^{
     [mainController playMusic:songTitle:songArtist :songDuration :songUrl];
});


text:
Q: r-exams Questions about the same data on 2 separate xxx.Rmd files Using R exams, I am developing a pdf exam with several questions (hence several Rmd files) but the questions are connected and would use a dataset created in the first question file. Questions would not be amenable to a cloze format.
Is there a way to write the exercises so that the second exercise can access the data generated by the first exercise ?

A: Is it an option to save the data you need to disk in one Rmd file
```{r, echo=FALSE}
saveRDS(df, "my_stored_data.rds")
```

and then load it in the other one
```{r, echo=FALSE}
readRDS(df, "my_stored_data.rds")
```

A: Another option could be to knit the Rmd files from an R script and then knit them from this R script. If you do that, the Rmd files use the environment of the R script (!) instead of creating their own. Hence you can use the same objects (and therefore of course let one Rmd script store the data, while the other uses it as input.
In this thread: Create sections through a loop with knitr
there is a post from me about doing this. It's basically this:
The first Rmd file:
---
title: "Script 1"
output: html_document
---

```{r setup, include=FALSE}
a_data_frame_created_in_script_1 <- mtcars
```

saved as rmd_test.Rmd
The second one:
---
title: "Script 1"
output: html_document
---

```{r setup}
a_data_frame_created_in_script_1
```

saved as rmd_test_2.Rmd.
And then you have an R-script that does this:
rmarkdown::render("rmd_test.Rmd", output_file = "rmd_test.html")
rmarkdown::render("rmd_test_2.Rmd", output_file = "rmd_test_2.html")

A: The easiest solution is to use a shared environment across the different exercises, in the simplest case the .GlobalEnv. Then you can simply do
exams2pdf(c("ex1.Rmd", "ex2.Rmd"), envir = .GlobalEnv)

and then both exercises will create their variables in the global environment and can re-use existing variables from there. Instead of the .GlobalEnv you can also create myenv <- new.env() and use envir = myenv.
For Rnw (as opposed to Rmd) exercises, it is not necessary to set this option because Sweave() Rnw exercises are always processed in the current environment anyway.
Note that these approaches only work for those exams2xyz() interfaces, where the n-th random draw from each exercise can be assured to end up together in the n-the exam. This is the case for PDF output but not for many of the learning management system outputs (Moodle, Canvas, etc.). See: Sharing a random CSV data set across exercises with exams2moodle()


text:
Q: Make a function to run only for CPTs I found an answer where the author comments in the code that the post_type_link filter is (only?) for CPTs. How he/she can be sure that his code will run only for CPTs?
From the Wordpress Codex:

post_type_link is a filter applied to the permalink URL for a post OR
  custom post type prior to being returned by the function
  get_post_permalink.

The code in discussion:
add_filter( 'post_type_link', 'custom_post_permalink' ); // for cpt post_type_link (rather than post_link)
function custom_post_permalink ( $post_link ) {
    global $post;
    $type = get_post_type( $post->ID );
    return home_url( $type . '/' . $post->post_name . '.html' );
}

A: Before returning it's result, get_permalink() applies one of 4 filters on the permalink it has generated, depending on the post_type of the post in question:

*

*post_link, when post_type == 'post'

*page_link, when post_type == 'page', via get_page_link()

*attachment_link, when post_type == 'attachment', via get_attachment_link()

*post_type_link, when post_type is not one of the above (i.e., a CPT), via get_post_permalink()


text:
Q: SSRS data driven subscription I have created a data driven subscription for an SSRS report where I have written the dataset query to fetch the report parameters. Now, whatever email id I provide gets all the reports generated by passing different parameters.
Here, I want to achieve is sending the report generated by a particular parameter to a particular email id. For all the different parameters, the reports generated should be delivered to different email ids.
Please help me if this is achievable in SSRS and how to achieve this?
Your help will be very much appreciated. Thank you!

A: When you create your subscription, check the "data driven subscription" radio box. This will display a "Dataset" heading with "Edit Dataset" button. Press that button and an empty text box will open. Paste your query in here and press validate. If the query validates, press apply. If it doesn't, it means there is an error in the query.
Now in your dataset you will see your fields. Sometimes these will be formatted with xml. Go down to your delivery and in the email field you can select "Get value from dataset". Next to it pick the email field from your query. (If you have the xml field this might be hard to decipher... if you have dual screens put it on the left screen and mouse over for the full value)
For your parameters you can do the same theing with the "Get value from dataset" option.
That's subscriptions via dataset in a nutshell.

A: I did a workaround and got the solution. I created a new table having two columns, one column with all the parameters and the next column with the corresponding email id. In the dataset query I wrote the select statement by inner joining the two tables. So, this way I achieved the required dataset and using that got me the required data driven subscription.
Thanks everyone for your replies.

A: As a standard variant of Mrityunjay Kumar's answer you may press EditDataSet on SubscriptionPage
and may select  field#1 as the input parameter of the report
and may select field#2 as the email to send.
After that you may choose field#1 in DeliveryOption
and field#2 in ReportParameter on the same SubscriptionPage.
So sending reports will be depends on email in field#1 and parameter in field#2.


text:
Q: Firebase sending multiple push notifications instead of stacking or replacing I am trying to have a previous push notification stack with the new one or replace it in the system tray for android.
I am not sure how to do this as the push notification is sending back both data and notification objects, and from what I understand the notification goes directly to the system tray. If so how do I stop the notification from appearing independently. Some users would get 5-10 notifications and it would keep pushing up.
EDIT:
I tried collapse_key but it still does not replace prior notifications with the same key... am I doing it wrong somehow here?
method: 'POST',
                            uri: 'https://gcm-http.googleapis.com/gcm/send',
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': authorize //GOOGLE API KEY
                            },

                            body: JSON.stringify({
                                "registration_ids": [otherUserResult.reg_id],

                                "collapse_key": "follow",
                                "data": {
                                    "notifyToUserId": to,
                                    "notifyFromId": from,
                                    "notifyMsg": msg,
                                    "notifyItemPicture": itemPic,
                                    "notifyItemName": itemName,
                                    "notifyFromName": fromName,
                                    "notifyType": type,
                                    "dateNotified": dateNotified

                                },
                                "notification": {
                                    "title": fromName,
                                    "body": notifyMsg,
                                    "icon"  : "ic_pushnotify"
                                },
                                "priority": "high",
                                "content_available": true

A: For me worked when I included in my 'notification' 2 lines:
collapse_key: 'your_app_unique_string',
tag: 'your_app_unique_string'

So the full code would be:
var payload = {notification: {
                                        title: "Mensaje de "+message.name,
                                        body: message.text,
                                        sound: "default",
                                        collapse_key: 'charlero',
                                        tag: 'charlero'
                                    }
                                };


text:
Q: pg_restore using PostGIS/PostgreSQL Dump Changes Data in Geography Column Two PostGIS databases (PostGIS 3.0, PostgreSQL 13.1) were setup on two separate machines to be as close to each other as possible using Docker images.
A dump of the database was taken from the first machine using
pg_dump --host=db1.foo.com --dbname=foo --username=postgres -Fc --file=/tmp/foo.dump

and then restored on the database on the second machine using
pg_restore --clean --dbname=foo /tmp/foo.dump

When we view a query result using a GUI software TablePlus, we noticed that the column named coordinates of type Geography contains values that look very different after restoring.
Query Result on 1st Machine (pg_dump source):
SELECT coordinates FROM locations LIMIT 5;

Query Result on 2nd Machine (after pg_restore):
SELECT coordinates FROM locations LIMIT 5;

However, our app that queries this database for coordinate data appears to be plotting the data correctly on a map. This makes me think that the data on both machines are the same, but stored in different representation.
Question: Why did the Geography data values in the column coordinates changed, and how can we restore from the dump while keeping the original data values?

Update: Tried using -b when performing pg_dump, but the problem persist.
pg_dump --host=db1.foo.com --dbname=foo --username=postgres -Fc -b --file=/tmp/foo.dump

A: Your first output is showing as EWKT (Extended Well Known Text) while the second output is WKB (Well Known Binary). These are both standard representations of the internal geometry but are designed for different end users (human v machine).
To be honest I have never see PostGIS return WKT in a standard select statement, usually you would wrap the geometry in ST_AsTEXT or ST_AsEWKT to see that.
Any way I think your data is just fine.


text:
Q: Try to use JDBC connection got access denied Hey guys : I tried to use JDBC connection to mySQL database, I got the error message as following: "java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)] with root cause". I have no problem using commend line "mysql -u root -p" to access mySQL and I'm quite sure I set the right password. Is that anything for my setting as following:
        dataSource.setUrl("jdbc:mysql://localhost:3306/my_schema");
        dataSource.setUsername("root");
        dataSource.setPassword("mypassword");

Much appreciated.


text:
Q: Facebook Like-button comment box event subscribe Long story short;
I have facebook Like-button on my website with comment box enabled.
I need to refresh current page every time user clicks like button (likes or unlikes my content).
I can achieve this with event.subscribe and edge.create / edge.remove events but the problem is that user should be able to post comments with like-clicks, too.
Currently this works fine with like-clicks only but the edge.create / edge.remove event executes in a few seconds after user has clicked like button and therefor not giving user enough time to write her comment in the comments box and post it.
I've tried comment.create and comment.remove events, but they're not firing at all when the comment is posted and because of that the page just won't refresh at all.
So the problem is;
Does anyone know how I can execute page refresh when user posts comment with like-click via the comment box that is integrated with like-button?
Any help would be appreciated! Thanks!

A: After struggling with this same problem for a while, and not being able to find a solution, I decided to go another approach.
While I see value in the Comments Box, I also see it as not very good design to have a Comments Box appear seconds before the page redirects/refreshes. So... with a little CSS you can hide the Comments Box, which might be a good option for you until Facebook makes Subscribing to a Like Comment Post, or Close of the Comments Box.
.fb_edge_comment_widget {
  display: none !important;
}


text:
Q: Torch- why don't people use activation explicitly? Whenever I saw neural networks implemented in Torch, nn, they only plug modules together. For example, there is a sequencer module with LookupTable, Splittable, FasLSTM, Linear, LogSoftMax.
Why don't people use activation functions in between, such as tanh/Sigmoid/ReLu?

A: Do you have an example? Typically, ReLu or TanH are used between layers.
You would not use them between table manipulation functions and such, as they are not 'real' neural network layers with parameters.


text:
Q: Prove that for $a, b \in \mathbb{R}$ $|a + b -a| \geq |a| - |b-a|$
Prove that for $a, b \in \mathbb{R}$ $|a + b -a| \geq |a| - |b-a|$

I'm not sure how to go about proving this, I can't seem to find any reasonable way to use the triangle inequality and this doesn't seem to follow immediately from the other properties of the absolute value function.

A: $|a+b-a|+|b-a|=|a+b-a|+|a-b|\ge|(a+b-a)+(a-b)|=|a|$

A: Proof: Observe that $|b| = |a +b - a|$, and by the triangle inequality we have $|a| = |a-0| \leq |a-b| + |b-0| = |a-b| + |b|$.
Hence $|a| \leq |a-b| +|b|$, but $|a-b| = |b-a|$ so we have $|a| \leq |b-a| + |b|$ which implies $|a| - |b-a| \leq |b| = |a +b - a|$ as desired. $\square$

Thanks @Bram28 for the hint in the comments section.

A: Alternatively:
$$|a|=|a-b+b|\le |a-b|+|b|=|b-a|+|a+b-a|.$$


text:
Q: React state array is being updated by a different value other than the setState const selectToppingSide = (ww, j) => {
    var extraName = ww.ExtraName;
    var extraCodeI = ww.ExtraCode;
    var extraDescription = j.extraDescription;
    var extraCode = j.extraCode;

    var a = ww;

    if (j.extraDescription === "FirstHalf") {
      a.PizzaFirstHalf = 1;
      a.PizzaSecondHalf = null;
      a.ExtraPrice = j.extraPrice;
      a.CartExtra_MenuItemExtraID = j.menuItemExtraID;
    }
    if (j.extraDescription === "Full") {
      a.PizzaFirstHalf = null;
      a.PizzaSecondHalf = null;
      a.ExtraPrice = j.extraPrice;
      a.CartExtra_MenuItemExtraID = j.menuItemExtraID;
    }
    if (j.extraDescription === "SecondHalf") {
      a.PizzaFirstHalf = null;
      a.PizzaSecondHalf = 1;
      a.ExtraPrice = j.extraPrice;
      a.CartExtra_MenuItemExtraID = j.menuItemExtraID;
    }

    if (selectedToppings.length < 1) {
      setSelectedToppings(selectedToppings.concat(ww));
     // setSelectedToppings([...selectedToppings, ww]);
    }
}

When I hit this function it takes in data (ww, j). I set a = ww and set the values of a based on j's data. When i am debugging this and am changing a.PizzaFirstHalf, a.PizzaSecondHalf, a.ExtraPrice, a.CartExtra_MenuItemExtraID in the if statements it is updating my setSelectedToppings state array with those lines of code when it should not be updating them. Later on down this function (not shown in the code i have posted) I am trying to check the selectedToppings array values but I am not checking the values I want to check because the if statements above are changing the values in my setSelectedToppings state array.


text:
Q: Reading in strings without header  I am a newbie in C and for an exercise I have to write a program, where I can read in strings. If my reserved memory (length BUFFER_SIZE) isn't enough, it should reserve memory in increments of +=BUFFER_SIZE, as long as needed to read the string. I tried to write some functions to get this done, but it doesn't work. Can somebody please help me?
My code:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 10

size_t string_length(char *string)
{
  size_t i = 0;
  while(string[i] != '\0')
  {
    i++;
  }
  return i;
}
void string_concatenate(char *string, char *string_to_chain)
{
  size_t length = string_length(string);
  for(size_t i = 0; *(string_to_chain + i) != '\0'; i++, length++)
  {
    string[length] = string_to_chain [i];
  }
  string[length] = '\0';
}
char *string_search(char *string, char character)
{
  do
  {
    if (*string == character)
      {
        return (char*)string;
      }
  } while (*string++);
  return NULL;
}
char *get_line()
{
  int line_size = BUFFER_SIZE;
  char* line = malloc(line_size * sizeof(char));
  if(line == NULL)
  {
    return NULL;
  }
  printf("Bitte Text eingeben: \n");
  fgets(line, BUFFER_SIZE, stdin);

  char *new_line_character = string_search(line, '\n');
  while(new_line_character == NULL)
  {
    line_size += BUFFER_SIZE;

    line = realloc(line, (line_size * sizeof(char)));
    if(line == NULL)
    {
      return NULL;
    }

    char *new_line = line + BUFFER_SIZE - 1;
    fgets(new_line, line_size, stdin);
    new_line_character = string_search(line, '\n');
  }

  *new_line_character = '\0';
  return line;

}
}
int main(void) {
    char *string = get_line();
    printf("s%\n", string);
}


text:
Q: Schwarzian derivative, accessory parameters, projective connections I am looking at the following Riemann surface (let's call it $M$),
\begin{equation}
y^n=\frac{(x-x_1)(x-x_3)}{(x-x_2)(x-x_4)}
\end{equation}
which is a Riemann surface of genus $n-1$. It can be thought of as a quotient of the complex plane by a Schottky group $\Sigma$,
\begin{equation}
M\cong\mathbb{C}'/\Sigma
\end{equation}
where $\mathbb{C}'$ is the domain of discontinuity of $\Sigma$. Then, we can look at the covering,
\begin{equation}
\pi_{\Sigma}:\mathbb{C}'\rightarrow \mathbb{C}'/{\Sigma}
\end{equation}
which takes $z$ to $[z]$. The inverse map $w=\pi^{-1}_{\Sigma}$ is multivalued on $\mathbb{C}'$,
\begin{equation}
w\sim\gamma w
\end{equation}
where $\gamma\in\Sigma$. However, the Schwarzian derivative of $w$ in some coordinate patch $z$ is single valued,
\begin{equation}
\{w,z\}=\frac{w'''}{w'}-\frac{3}{2}\left(\frac{w''}{w'}\right)^2.
\end{equation}
On overlapping coordinate patches, it transforms like,
\begin{equation}
\{w',z'\}=\left(\frac{dz}{dz'}\right)^2\{w,z\}+\{z',z\}
\end{equation}
which means it is a projective connection on $M$. Also, near the $z_i$s, since we can use the coordinate, $y^n\sim(z-z_i)$,
\begin{equation}
\{w',y\}\sim\{z,y\}=-\frac{1}{2}\frac{n^2-1}{y^2}+\cdots.
\end{equation}
According to Faulkner - The Entanglement Renyi Entropies of Disjoint Intervals in AdS/CFT, these properties are enough to fix the Schwarzian derivative up to $3g-3$ unknown accessory parameters,
\begin{equation}
\{w,z\}=\Delta\left(\sum_{i=1}^4\frac{1}{(z-z_i)^2}+\frac{-z_3+z_1+z_2+z_4-2z}{(z-z_1)(z-z_2)(z-z_4)}\right)+\sum_{s=1}^{3(n-2)}p_s\omega_s
\end{equation}
where $\omega$s are a basis for the quadratic differentials on $M$ and $\Delta=1/2(1-1/n^2)$. I understand that we can add any linear combination of quadratic differntials on $M$ to the form of the Schwarzian because they transform uniformly, but the first term in the brackets is not clear to me. It should transform like a projective connection. Does anyone have a justification for including the first term multiplying $\Delta$?

A: First of all, you should take care about which coordinates you take. Namely, Faulkner uses the coordinate $x$ given by the defining equation  $$y^n=\frac{(x-x_1)(x-x_2)}{(x-x_3)(x-x_4)}$$ as a branched projective structure (he denotes this by $z$ in his paper!). He then computes the Schwarzian derivative of $w$ - the Schottky uniformisation - with respect to $x$. As $x$ is a well-defined branched projective structure $${w,x}(dx)^2$$ is a well-defined meromorphic differential on $M$, having prescribed  singularities at $x_1,\dots,x_4$. He derives in equation (4.10) in his paper that the quadratic residues must be $\Delta$. This is well-known since Mandelbaum.
The second term in the brackets is needed as ${w,x}(dx)^2$ has no pole over $x=\infty.$ It might look a bit unnatural as it has no pole at $z_3$, but in fact $\frac{(dx)^2}{(x-x_1)\dots(x-x_4)}$ is a holomorphic quadratic differential.


text:
Q: Can a function pointer typedef be forward declared in C? The title says it all! Can it be done and if so, how?

A little background if you must know: We've recently taken over a project from another team (because they were disbanded) that has strongly interdependent headers. Changing that is difficult without yanking stuff out of the header file they logically belong in and stuffing somewhere else, where it does not logically belong.
Until now, the approach to deal with this has been to simply forward declare structs and functions from other headers where necessary. That worked fairly well until we got into the typedef'd function pointers, which is how our callback function types are currently implemented.
We would like to solve this without having to disturb the logic of the header files if possible, but have been unable to forward declare those typedefs to far. Various searches for 'forward declare typedef' only yielded results about forward declaring typedef'd structs, which doesn't help us at all.

Example:
a.h
/* @file a.h */
#ifndef _a_
#define _a_

#include "b.h"

// Definitions that need stuff from b.h

typedef void (some_callback_function) (uint32_t, uint16_t, uint8_t*);

// More definitions that need stuff from b.h
#endif

b.h:
/* @file b.h */
#ifndef _b_
#define _b_

#include "a.h"

// Definitions that need stuff from a.h

struct some_struct {
    // Stuff
    some_callback_function *cb_someting; // ERROR: some_callback_function not defined yet!
    // Other stuff
};

// More definitions that need stuff from a.h
#endif

EDIT: In this example, the problem arises when including a.h. The first thing it does before declaring anything itself in including b.h, which in turn also includes a.h before declaring anything. The guards prevent an endless loop here, but I still end up with a.h trying to declare something using stuff that will later be declared in b.h but has not yet been. Thus a forward declaration should does the trick for structs and functions.
If typedefs cannot be forward declared, I could think of two ugly workarounds:

*

*Remove the includes from the header files and leave it up to the user to include the other headers. As far as I know, this is considered bad coding styles as headers should include their dependencies themselves.

*Move the typedefs before the #includes. I am not sure whether this is actually bad style, but my intuition tells me that putting anything before the #includes is evil. Also, this only works as long as the typedefs do not need anything from another header file.


text:
Q: Send a textstring from android app to a form on a website? I'm trying to paste a string from my application to a website.
My application looks as following: one EditText and one Button. My button opens a website with an open text box.
<input name="FreeTextBox" type="text" id="FreeTextBox" style="width:64px;">

this is the text box on the website
My application's EditText id is et2 which is then the variable klass in java.
klassen = klass.getText().toString(); The klass variable is then made into a string called klassen
When I click my button I open a website and then I want my application to automatically enter whatever I wrote in my EditText into the FreeTextBox on the website.
Please give me advice on how to do this. This is my first application so I could really use some help.
Thanks in advance

A: Do you have control over the website? if not, then you are gonna need to get some more information, like the form action, and the input name, for example
<form name="input" action="html_form_action.php" >
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>

If the form is like the one above I like using JSOUP (Download and import to your project)
Then I would use a code like this:
Jsoup.connect("http://****/html_form_action.php").data("user",yourTextString).post();

This code has the same effect as if you would have pasted the string in the website and then hit the Submit button. But again this might not be what you are looking for so please be more specific (Form source code and stuff)

A:     Use This Code

  // Getting String from EditText
   String url=editTextObj.getText().toString();

    /// Declear Intent For open browser**/

  Intent i = new Intent(Intent.ACTION_VIEW);

    /// pass url which i want to send or get from edittext**/
  i.setData(Uri.parse(url));
    // fire intent
  startActivity(i);

A: I think you can add your text into a GET parameter or a POST parameter for your HTTP request.
If you choose the GET option (which is the less secure, but the easiest), you just have to do something like this :
String url = "http://www.mysite.com/myPage.php?parameter=value"

If you're using PHP, $_GET['parameter'] will be equal to "value" then you can set the field like you want with your PHP code.
Now, if you want to use the POST way, you'll have to take a look to the documentation. Actually, the answer of Rishabh is a great start.
(please do not forget to accept the answer that helps you ;-) )


text:
Q: How to randomly assign group based on count/repeat in Excel? All, I am trying to randomly assign groups (column F) based on "Count" and "Group" column (B and A)  and been having some trouble finding the right formula and would appreciate some pointers.
Screenshot below shows, a sample output in column F. Here, you may see Group A is assigned 4 times and B is assigned 6 times randomly

A: Try this in F2 and drag down:
IF(AND(RAND()<0.5,COUNTIF($F$1:F1,$A$2)<$B$2),$A$2,IF(COUNTIF($F$1:F1,$A$3)>=$B$3,$A$2,$A$3))


text:
Q: Apache, PHP Invalid Content Length I have a PHP (PHP 5.3.2) application running on Apache (2.2.14) on Linux server. More then once in its history user started to see in their browsers the following message: "Request entity too large".
First google search suggested that it happens when an uploaded file is too big or when cookies are too big. But it is not happening on file upload, only at logging in and always at the login page. User enters this page just through a normal POST form on a page. And the cookies are only containing session id.
Furthermore, apache is logging "Invalid Content-Length". This is being logged before any of my code executes. $_POST is empty despite it should contain some data. When I added the following line:
error_log("Content-Length: ".$_SERVER['CONTENT_LENGTH']);

it says
Content-Length: 32, 32

which seems to be indeed invalid. Changing browser or resetting user PC does not seem to help. Everything just started to work the next day.
Where can the problem lay? Is it something with Apache, PHP, user's network settings? If I need to add some more information, please let me know.

A: In the past days we encountered "Invalid Content-Length" messages logged by Apache in error_log.
Tracked the issue to some visitor from just a few specific IP classes, for example Movistar Argentina: 200.81.44.201
Further checking the request with tcpdump / whireshark we observed that the POST request contained some

duplicate Headers, namely Content-Length and Content-Type

The real issue is with Content-Length, because Apache treat multiple variables, by concatenating them, for example:
Content-Length: 51
Content-Length: 51

The result will be:
Content-Length: 51, 51

Then Apache try to convert the string "51, 51" into an integer which is not possible.
In newer Apache > 2.2.17, or with backported patches Apache logs an error: 413 Request Entity Too Large, with older Apache, the process just hungs consuming a lot of CPU times.
Behind that IP class we see more distinct clients, so maybe they are 3G gateway proxy servers wrongly configured, because they duplicate that headers.
So we find a solution to configure Apache to rewrite the Request with just one Content-Length and one Content-Type Headers:
Here is my code for this, using mod_headers, and SetEnvIfNoCase inserted in httpd.conf:
SetEnvIfNoCase Content-Length (.*), MyContentLength=$1
SetEnvIfNoCase Content-Type (.*), MyContentType=$1
RequestHeader set Content-Length: "%{MyContentLength}e" env=MyContentLength
RequestHeader set Content-Type: "%{MyContentType}e" env=MyContentType

You are free to test and use this code in order to filter out duplicate Content-Length HTTP Header variables.

A: The easiest way to investigate issues like this is to use TCPDump to capture the packets being sent between the client and the server to a file, and then use Wireshark to view the packets as a TCP stream.
An example of the command to capture the packets would be.
tcpdump -vvv -A -i eth0 'host 123.123.10.12 && port 80' -w eth0.dat
As it's your login page, you will probably need to decode the TCP stream as it should be behind HTTPS - which can be done using the instructions from http://segfault.in/2010/11/decrypt-https-traffic-using-wireshark-and-key-file/
Plasmid87 is almost certainly correct though - it sounds like one of the headers is just growing massively and eventually becoming larger than the Apache LimitRequestFieldSize.
So long as it's growing slowly rather than all at once, you could investigate it by checking the global variables.
function checkVars(){
    $varsToCheck = array($GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_REQUEST, $_SESSION, $_ENV, $_COOKIE);

    foreach($varToCheck as $var){
        foreach($var as $key => $value){

            if(count($key) > 1024){
                logToFile("Found ridiculous key: ".$key." value is ".$value);
            }
            if(count($value) > 1024){
                logToFile("Found ridiculous value for key: ".$key." value is ".$value);
            }
        }
    }
}


text:
Q: how to display an inserted query data without refreshing using ajax jquery What i have right now is a form and a container that displays the submitted data and it is submitting without refresh using ajax request, the form and the container that displays the data are on the same page.
I have tried getting the input value inside the form using $("id").val(); and display it using $('#display').html();
But I have many input fields inside the form and I dont wanna copy paste all of the input values inside the jquery because it seems like it's unprofessional and dirty and not efficient.
javascript
$(document).ready(function(){
    $("#add_rec").click(function(e){
        var me = $(this);
        e.preventDefault();
        if ( me.data('requestRunning') ) {
            return;
        }
        var inputs = $("#u_rec_form").serialize();

        me.data('requestRunning', true);
        $.ajax({
            type: 'POST',
            url: 'process.php',
            data: inputs,
            success: function(data){
                    alert(data);

                },
                 complete: function() {
                    me.data('requestRunning', false);
                }
            });

        return false;

    });
});

HTML
<form id="u_rec_form">

            Patient's Username
            <input type="text" name="cust_username" placeholder="Username" class="form-control" />

            Patient's Password
            <input type="password" name="cust_password" placeholder="Password" class="form-control input-normal" />

            Patient's First Name
            <input type="text" name="cust_fname" placeholder="First name" class="form-control" />

            Patient's Last Name
            <input type="text" name="cust_lname" placeholder="Last name" class="form-control" />

            Patient's Date of Birth
            <input type="text" name="cust_age" placeholder="DD/MM/YYYY" class="form-control" />

            <input type="hidden" name="submitted" value="1">
            <button type="submit" id="add_rec" class="btn btn-default">Submit</button>

    </form>

Is there any other way to do it?
I have these inputs
First Name: <span id="view_<?php echo $row['id']?>"><?php echo $row['cust_fname']?>

Last Name: <span id="view_<?php echo $row['id']?>"><?php echo $row['cust_lname']?>

Age: <span id="view_<?php echo $row['id']?>"><?php echo $row['cust_age']?>

I tried using this
      $('input').each(function(){
            var inputVal = $(this).val();
            $('span').append(inputVal);
        });
I will display all the input values in each label and thats not what i want

A: use the ".append()" method instead of .html().
UPDATE:
If you want to get all the data of the input and then display it you can iterate to each input field and then display it. Add a class first to the input elements so it will be easily editable.
$('.input-class').each(function(){
      var inputVal = $(this).val();
      $('#display').append(inputVal);
})


text:
Q: Rsync on a browser does not work I am trying to transfer files from one server to another with the code below.
rsync -avz -e "ssh -i /root/.ssh/somekey" /var/www/admin/somefiles.txt root@xxx.xxx.xxx.xxx:/var/www/html_public/some-folder/

It works just fine if I do this on putty but if I do shell_exec this code on a php page and run the page on a browser. It does not work. It returns an empty string.
I hope someone can help me with this. Thanks in advance.

A: First, you need to check if you need to be a root or (sudo user) for running rsync.
If yes then exec() command will only work if it is run by same user on php-cli (not on browser by Apache user). i.e. Which user you are loggined into shell for run rsync.
If it is root or any elavated permission user with sudo permission then, This rsync command may not be available to apache/www-data user which is working when php script run from browser.
So You try to make a normal user and login through it, Then try rsync if you are successful then it may be interesting to see what are other problems can be, But if you getting access/permission denied then obviously you can not run this script at-least on browser.
Besides this One more thing permission may not be directly related to rsync  command itself but with folder /etc/test/ which is owned by root user in normal scenario.


text:
Q: Copy specific filenames from different files So I've got a bunch of folders with a file in each of them called: CLOSEUP-PLAIN.PNG and need to copy each of them to a new folder.
The folder layout is:

*

*Listing Images

*

*000001

*

*CLOSEUP-PLAIN.PNG

*000002

*

*CLOSEUP-PLAIN.PNG

*000003

*

*CLOSEUP-PLAIN.PNG

*000004

*

*CLOSEUP-PLAIN.PNG

And i need to copy all of them CLOSEUP-PLAIN files into a new folder, Preferable if possible to rename it to the folder it was in.
Thank you for any help provided!

A: Try the below, replacing the path to the source and the destination directories:
[string] $Source = "D:\Listing Images"
[string] $Destination = "D:\Output"

if (!(Test-Path $Destination)) {
    New-Item -Type Directory $Destination
}

Get-ChildItem $Source -Recurse | Where-Object {!$_.PSIsContainer -and $_.Name -eq 'CLOSEUP-PLAIN.PNG'} | ForEach-Object { Copy-Item  $_.FullName "$Destination\$($_.Directory.Name).png" }

This finds all of the images named "CLOSEUP-PLAIN.PNG" in any of the folders beneath $Source and copies them to $Destination, with their name set to the folder they were found in.


text:
Q: size of a structure containing bit fields
Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?

I was trying to understand the concept of bit fields.
But I am not able to find why the size of the following structure in CASE III is coming out as 8 bytes.
CASE I:
struct B
{
    unsigned char c;  // +8 bits
} b;

sizeof(b); // Output: 1 (because unsigned char takes 1 byte on my system)
CASE II:
struct B
{
    unsigned b: 1;
} b;

 sizeof(b); // Output: 4 (because unsigned takes 4 bytes on my system)

CASE III:
struct B
{
    unsigned char c;  // +8 bits
    unsigned b: 1;    // +1 bit
} b;

sizeof(b); // Output: 8

I don't understand why the output for case III comes as 8. I was expecting 1(char) + 4(unsigned) = 5.

A: You can check the layout of the struct by using offsetof, but it will be something along the lines of:
struct B
{
    unsigned char c;  // +8 bits
    unsigned char pad[3]; //padding
    unsigned int bint; //your b:1 will be the first byte of this one
} b;

Now, it is obvious that (in a 32-bit arch.) the sizeof(b) will be 8, isn't it?
The question is, why 3 bytes of padding, and not more or less?
The answer is that the offset of a field into a struct has the same alignment requirements as the type of the field itself. In your architecture, integers are 4-byte-aligned, so offsetof(b, bint) must be multiple of 4. It cannot be 0, because there is the c before, so it will be 4. If field bint starts at offset 4 and is 4 bytes long, then the size of the struct is 8.
Another way to look at it is that the alignment requirement of a struct is the biggest of any of its fields, so this B will be 4-byte-aligned (as it is your bit field). But the size of a type must be a multiple of the alignment, 4 is not enough, so it will be 8.

A: I think you're seeing an alignment effect here.
Many architectures require integers to be stored at addresses in memory that are multiple of the word size.
This is why the char in your third struct is being padded with three more bytes, so that the following unsigned integer starts at an address that is a multiple of the word size.

A: Char are by definition a byte. ints are 4 bytes on a 32 bit system. And the struct is being padded the extra 4.
See http://en.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86 for some explanation of padding

A: To keep the accesses to memory aligned the compiler is adding padding if you pack the structure it will no add the padding.

A: The alignment and total size of the struct are platform and compiler specific. You cannot not expect straightforward and predictable answers here. Compiler can always have some special idea. For example:
struct B
{
    unsigned b0: 1;    // +1 bit
    unsigned char c;  // +8 bits
    unsigned b1: 1;    // +1 bit
};

Compiler can merge fields b0 and b1 into one integer and may not. It is up to compiler. Some compilers have command line keys that control this, some compilers not. Other example:
struct B
{
    unsigned short c, d, e;
};

It is up to compiler to pack/not pack the fields of this struct (asuming 32 bit platform). Layout of the struct can differ between DEBUG and RELEASE builds.
I would recommend using only the following pattern:
struct B
{
    unsigned b0: 1;
    unsigned b1: 7;
    unsigned b2: 2;
};

When you have sequence of bit fields that share the same type, compiler will put them into one int. Otherwise various aspects can kick in. Also take into account that in a big project you write piece of code and somebody else will write and rewrite the makefile; move your code from one dll into another. At this point compiler flags will be set and changed. 99% chance that those people will have no idea of alignment requirements for your struct. They will not even open your file ever.

A: I took another look at this and here's what I found.

*

*From the C book, "Almost everything about fields is implementation-dependant."

*On my machine:

 struct B {
    unsigned c: 8;
    unsigned b: 1;
}b;
printf("%lu\n", sizeof(b));

print 4 which is a short;
You were mixing bit fields with regular struct elements.
BTW, a bit fields is defined as: "a set of adjacent bits within a sindle implementation-defined storage unit" So, I'm not even sure that the ':8' does what you want. That would seem to not be in the spirit of bit fields (as it's not a bit any more)


text:
Q: How to load in a Grails, the external CSS that within a JAR dependency I have a Grails project how I need to load a CSS how is located in a Jar dependency. I've looked for resources plugin but it not respond to my issue.
In my jar dependency, my css is located in public folder
public/styles/bootstrap/**.css
What is the process to declare in grails an external css, "my css is declared on xxx.jar" ?
Can you help me ?
Thank you

A:
What is the process to declare in grails an
  external css, "my css is declared on xxx.jar" ?

There is no such declaration. Keep in mind that css files are something that has to be published on some URL so the browser can download and apply it.


text:
Q: How the LLVM handle the debug location information of continue keyword and right brace? Let me show you the following simple C code:
int main()
{
  int i;

  for (i = 0; i < 256; i++)
  {
      i++;
  }
}

In this simple C code, if we use Clang to compile it and debug it:
We will get something like this:
(gdb) b main
Breakpoint 1 at 0x100000f7b: file a.c, line 5.
(gdb) r
Starting program: a.out
[New Thread 0x1403 of process 23435]
warning: unhandled dyld version (15)

Thread 2 hit Breakpoint 1, main () at a.c:5
5     for (i = 0; i < 256; i++)
(gdb) n
7         i++;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7         i++;

That is to say, the right brace of location LLVM doesn't emit. However if we have the continue keyword:
int main()
{
  int i;

  for (i = 0; i < 256; i++)
  {
    continue;
    i++;
  }
}

Then we compile and debug it:
Thread 2 hit Breakpoint 1, main () at a.c:5
5     for (i = 0; i < 256; i++)
(gdb) n
7       continue;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7       continue;
(gdb)
5     for (i = 0; i < 256; i++)
(gdb)
7       continue;

We will stop the line of continue. But if we compare the LLVM IR between them:
The right brace and continue keyword both are the following the br instruction and !dbg !23. Except that the line number of !dbg !23 not the same.
; :6:                                      ; preds = %3
  br label %7, !dbg !23
The question is how LLVM know whether to generate the debug location(generate for the continue keyword line, but not for the loop's right brace)? Because they are the same instruction and others are the same.

A: The brace is just a syntactic scope, there is no difference for the compiler between:
for (i = 0; i < 256; i++)
{
  i++;
}

and
for (i = 0; i < 256; i++)
  i++;

The parser is using the scope you create to group statement together, but this will not appear in the LLVM IR. The LLVM IR represent more the instructions that the program needs to execute.
When you using n in a debugger, you are asking to continue executing the program until you reach an instruction that corresponds to a different source line. The brace does not correspond to any instruction in the executable.


text:
Q: rmarkdown kable pander print matrix without border I have a character matrix:
df <- cbind(c("a", "b"), c("$\\sin\\theta$", "$\\cos\\theta$"))
df
     [,1] [,2]
[1,] "a"  "$\\sin\\theta$"
[2,] "b"  "$\\cos\\theta$"

I want this table in a PDF document without any border. I tried kable which produced an error saying that it needs table heading. I also tried pander and printr which did a good job but I don't want any grid line neither inside or outside. How can remove all grid lines?

A: I used the xtable package. With xtable() it is possible to control where you want to have lines.
---
pdf_document: default
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r results='asis'}
library(xtable)
options(xtable.comment = FALSE)
df <- data.frame(cbind(c("a", "b"), c("$\\sin\\theta$", "$\\cos\\theta$")))
print(xtable(df),type="latex", hline.after = NULL, sanitize.text.function=function(x){x})
```


text:
Q: Discard audio before certain time from Hls.js stream I am using Hls.js to live stream an audio feed into an audio element in my HTML. In my custom audio controls I limit the user to only be able to scroll back to the most recent five minutes of audio in the stream. However the audio for any time beyond the most recent five minutes still exists.
Is there any way to discard/trim the audio source beyond the most recent five minutes? Given i only care about the most recent five minutes of audio and the livestream could be constantly playing for multiple hours on end, what is the best method discard any of the unneeded audio from the source?
Thanks!

A: Hls.js has a config property for it!
https://github.com/video-dev/hls.js/blob/master/docs/API.md#backbufferlength


text:
Q: Why does this insertBefore not create a dom element before and after the target div I'm trying to write a new dom element before and after the target div.  This code only works for one or the other but not both.
function addElement () {

    var newDiv = document.createElement("div");
    var newContent = document.createTextNode("This is a new text node.");
    newDiv.appendChild(newContent);

    var currentDiv = document.querySelector("#results");

    document.body.insertBefore(newDiv, currentDiv);
    document.body.insertBefore(newDiv, currentDiv.nextSibling);
}

addElement();

A: You can't insert the same element in two places.
If you want to insert two elements, you need to create two elements.


text:
Q: C# Web Browser Component Memory Leak logHopefully someone can help.
I've added a web browser component to my form and I've noticed a memory leak when calling a JavaScript function repeatedly.
Every time I run (this command gets called every 2 - 3 seconds):
browser.Document.InvokeScript("TestFunction", new object[] { "Test", "Test" });

The memory just keeps rising until I get a crash with an out of memory warning.
Has anyone else noticed memory problems when invoking a script with an object?
UPDATE:
Added the test function I have been calling. The leak happens with any JS I call with arguments.
function TestFunction(var1, var2)
{
  console.log(var1 + " " + var2);
}


text:
Q: How can I return a parameter as a union case value? How can I return a parameter as a union case value?
I have the following function:
let jumpBlack ((blackChecker:BlackChecker),(blackCheckers:BlackChecker list))  (redPiece:RedPiece) =

    let yIncrementValue = -1
    let minY = 0

    match redPiece with
    | RedPiece.RedChecker rc ->
       let position = rc.Position |> jump blackChecker.Position yIncrementValue
       match position with
       | pos when pos = rc.Position -> RedPiece.RedChecker { rc with Position= position }, blackCheckers
       | pos when pos.Y = minY      -> RedPiece.RedKing    { RedKing.Position=position },  blackCheckers |> remove blackChecker
       | _ ->                          RedPiece.RedChecker { rc with Position= position }, blackCheckers |> remove blackChecker

    | RedPiece.RedKing rk ->
       let position = rk.Position |> jump blackChecker.Position yIncrementValue
       match position with
       | pos when pos = rk.Position -> RedPiece.RedKing { rk with Position= position }, blackCheckers
       | pos when pos.Y = minY      -> RedPiece.RedKing { Position=position }, blackCheckers |> remove blackChecker
       | _                          -> RedPiece.RedKing { rk with Position= position }, blackCheckers |> remove blackChecker

Specifically, I want to refactor this part of the above function into one function:
match redPiece with
| RedPiece.RedChecker rc ->
   let position = rc.Position |> jump blackChecker.Position yIncrementValue
   match position with
   | pos when pos = rc.Position -> RedPiece.RedChecker { rc with Position= position }, blackCheckers
   | pos when pos.Y = minY      -> RedPiece.RedKing    { RedKing.Position=position },  blackCheckers |> remove blackChecker
   | _ ->                          RedPiece.RedChecker { rc with Position= position }, blackCheckers |> remove blackChecker

| RedPiece.RedKing rk ->
   let position = rk.Position |> jump blackChecker.Position yIncrementValue
   match position with
   | pos when pos = rk.Position -> RedPiece.RedKing { rk with Position= position }, blackCheckers
   | pos when pos.Y = minY      -> RedPiece.RedKing { Position=position }, blackCheckers |> remove blackChecker
   | _                          -> RedPiece.RedKing { rk with Position= position }, blackCheckers |> remove blackChecker

How do I refactor the duplicated code above?
I'm stuck on how to remove the duplication and still return the two different union types (i.e. red checker and red king)
Domain:
(* Types *)
type North = NorthEast | NorthWest
type South = SouthEast | SouthWest

type Direction =
    | NorthEast
    | NorthWest
    | SouthEast
    | SouthWest

type Position =     { X:int; Y:int }

type BlackChecker = { Position:Position }
type RedChecker =   { Position:Position }
type BlackKing =    { Position:Position }
type RedKing =      { Position:Position }

type Checker =
    | BlackChecker of BlackChecker
    | RedChecker   of RedChecker
    | BlackKing    of BlackKing
    | RedKing      of RedKing

type King =
    | BlackKing of BlackKing
    | RedKing of RedKing

type RedPiece =
    | RedChecker of RedChecker
    | RedKing of RedKing

(* Functions *)
let rec remove item list = list |> List.filter (fun x -> x <> item)

let setRowPosition y1 y2 y3 index =
    match index with
    | x when x < 4 -> { X=x; Y=y1 }
    | x when x < 8 -> { X=x-4; Y=y2 }
    | _            -> { X=index-8; Y=y3 }

let initializeBlack () =
    let setPosition index =
        index |> setRowPosition 7 6 5

    let blackCheckers = List.init 12 setPosition |> List.map (fun pos -> { BlackChecker.Position= { X=pos.X; Y=pos.Y } })
    blackCheckers

let initializeRed () =
    let setPosition index =
        index |> setRowPosition 0 1 2

    let redCheckers =   List.init 12 setPosition |> List.map (fun pos -> { RedChecker.Position= { X=pos.X; Y=pos.Y } })
    redCheckers

let set (x, y) positions (position:Position) =
    match not (positions |> List.exists (fun pos -> pos = { X=x; Y=y })) with
    | true -> { X=x; Y=y }
    | false -> position

let moveBlack direction positions (checker:BlackChecker) =
    let position = checker.Position

    match direction with
    | North.NorthEast -> { BlackChecker.Position= (positions, position) ||> set ((position.X + 1), (position.Y + 1 )) }
    | North.NorthWest -> { BlackChecker.Position= (positions, position) ||> set ((position.X - 1), (position.Y + 1 )) }

let moveRed direction positions (checker:RedChecker) =
    let position = checker.Position

    match direction with
    | South.SouthEast -> { RedChecker.Position= (positions, position) ||> set ((position.X + 1), (position.Y - 1 )) }
    | South.SouthWest -> { RedChecker.Position= (positions, position) ||> set ((position.X - 1), (position.Y - 1 )) }

let moveKing direction positions (king:King) =

    let position = match king with
                   | King.BlackKing bk -> bk.Position
                   | King.RedKing   rk -> rk.Position

    let result = match direction with
                 | NorthEast -> (positions, position) ||> set ((position.X + 1), (position.Y + 1 ))
                 | NorthWest -> (positions, position) ||> set ((position.X - 1), (position.Y + 1 ))
                 | SouthEast -> (positions, position) ||> set ((position.X + 1), (position.Y - 1 ))
                 | SouthWest -> (positions, position) ||> set ((position.X - 1), (position.Y - 1 ))

    match king with
    | King.BlackKing _ -> King.BlackKing { BlackKing.Position= result }
    | King.RedKing   _ -> King.RedKing   { RedKing.Position=   result }

let jump target yDirection source =
    let updateX value = { X=target.X + value
                          Y=target.Y + yDirection }
    match source with
    | position when position.Y + yDirection = target.Y &&
                    position.X + 1 = target.X -> updateX 1

    | position when position.Y + yDirection = target.Y &&
                    position.X - 1 = target.X -> updateX -1
    | _ -> source

let jumpRed ((redChecker:RedChecker), (redCheckers:RedChecker list)) (blackChecker:BlackChecker) =

    let yIncrementValue = 1
    let maxY = 7
    let position = blackChecker.Position |> jump redChecker.Position yIncrementValue

    match position with
    | pos when pos = blackChecker.Position -> BlackChecker { blackChecker with Position= position }, redCheckers
    | pos when pos.Y = maxY                -> Checker.BlackKing { BlackKing.Position=position }, redCheckers |> remove redChecker
    | _ -> BlackChecker { blackChecker with Position= position }, redCheckers |> remove redChecker

let jumpBlack ((blackChecker:BlackChecker),(blackCheckers:BlackChecker list))  (redPiece:RedPiece) =

    let yIncrementValue = -1
    let minY = 0

    match redPiece with
    | RedPiece.RedChecker rc ->
       let position = rc.Position |> jump blackChecker.Position yIncrementValue
       match position with
       | pos when pos = rc.Position -> RedPiece.RedChecker { rc with Position= position }, blackCheckers
       | pos when pos.Y = minY      -> RedPiece.RedKing    { RedKing.Position=position },  blackCheckers |> remove blackChecker
       | _ ->                          RedPiece.RedChecker { rc with Position= position }, blackCheckers |> remove blackChecker

    | RedPiece.RedKing rk ->
       let position = rk.Position |> jump blackChecker.Position yIncrementValue
       match position with
       | pos when pos = rk.Position -> RedPiece.RedKing { rk with Position= position }, blackCheckers
       | pos when pos.Y = minY      -> RedPiece.RedKing { Position=position }, blackCheckers |> remove blackChecker
       | _                          -> RedPiece.RedKing { rk with Position= position }, blackCheckers |> remove blackChecker

Tests:
[<Test>
let ``red king jumps checker``() =
    let blackChecker = { BlackChecker.Position= { X=1 ; Y=1 } }
    let target = (blackChecker, [blackChecker])

    RedKing { RedKing.Position= { X=0 ; Y=2 } } |> jumpBlack target
                                                |> fst
                                                |> should equal (RedPiece.RedKing { RedKing.Position= { X=2 ; Y=0 } })

[<Test>]
let ``black checker removed after being jumped``() =
    let target = { BlackChecker.Position= { X=1 ; Y=1 } }, []
    RedChecker { RedChecker.Position= { X=2 ; Y=2 } } |> jumpBlack target
                                                      |> snd
                                                      |> should equal []
[<Test>]
let ``red checker jumps black checker southeast``() =
    let blackChecker = { BlackChecker.Position= { X=3 ; Y=2 } }
    let target = blackChecker, [blackChecker]

    RedChecker { RedChecker.Position= { X=2 ; Y=3 } } |> jumpBlack target
                                                      |> fst
                                                      |> should equal (RedChecker { RedChecker.Position= { X=4 ; Y=1 } })

A: In the code that you want to refactor, there seemed to be only two places where the two parts of the code do something different - one is the pattern matching (where one looks for RedChecker and another for RedKing) and the other part is the body of the first and the third line of the pattern matching (where one returns RedChecker and another RedKing).
The code also works over different types, but those are all the same type:
type BlackChecker = { Position:Position }
type RedChecker =   { Position:Position }
type BlackKing =    { Position:Position }
type RedKing =      { Position:Position }

Extracting the common part will be a lot easier if you just use the same type for all of these:
type Piece = { Position:Position }
type BlackChecker = Piece
type RedChecker = Piece
type BlackKing = Piece
type RedKing = Piece

So, you need to parameterize the code by two things - both of them can be represented as functions of the following types:
detector       : Checker -> Piece option
wrapper        : Piece -> Checker

The key trick here is that these two functions behave like the discriminated union case - the first one behaves as pattern matching using DU case and the second one behaves like a constructor of the DU case.
Now you can extract the common functionality into something like:
match detector redPiece with
| Some rk ->
    let position = rk.Position |> jump blackChecker.Position yIncrementValue
    match position with
    | pos when pos = rk.Position -> wrapper { rk with Position= position }, blackCheckers
    | pos when pos.Y = minY      -> RedPiece.RedKing { Position=position }, blackCheckers |> remove blackChecker
    | _                          -> wrapper { rk with Position= position }, blackCheckers |> remove blackChecker

| None -> // Handle the case when it is not the piece we are interested in

I have not tested everything, but hopefully this at least shows the line of thought that you can follow to extract the common functionality from the two parts. That said, I would not be all too worried about refactoring the code - if you repeat similar thing just twice, I feel it is often easier just to keep two copies...

A: Alright your model is really complicated... I made the following simplification:
type Position = { X:int; Y:int }

type Color =
    | Red
    | Black

type PieceType =
    | King
    | Checker

type Piece = Color*PieceType*Position

Then translating your jumpBlack function I get:
let jumpBlack ((blackChecker:Piece),(blackCheckers:Piece list))  (redPiece:Piece) =

    let yIncrementValue = -1
    let minY = 0

    match redPiece, blackChecker with
    | (Red, Checker, position), (_, _, blackCheckerPosition) ->
       let newposition = position |> jump blackCheckerPosition yIncrementValue
       match newposition with
       | pos when pos = position ->    (Red, Checker, pos), blackCheckers
       | pos when pos.Y = minY      -> (Red, King, pos) ,  blackCheckers |> remove blackChecker
       | pos ->                          (Red, Checker, pos), blackCheckers |> remove blackChecker
    | (Red, King, position), (_, _, blackCheckerPosition) ->
       let newposition = position |> jump blackCheckerPosition yIncrementValue
       match newposition with
       | pos when pos = position -> (Red, King, pos), blackCheckers
       | pos when pos.Y = minY      -> (Red, King, pos), blackCheckers |> remove blackChecker
       | pos                          -> (Red, King, pos), blackCheckers |> remove blackChecker
    | _ -> failwith "Invalid" //Deal with Black pieces here!

But now, it's really easy to refactor the code since we see that if pos isn't equal to the minY value, it stays the same PieceType, but if it reaches minY it always becomes a King.
let jumpBlackNew ((blackChecker:Piece),(blackCheckers:Piece list))  (redPiece:Piece) =

    let yIncrementValue = -1
    let minY = 0

    match redPiece, blackChecker with
    | (Red, pieceType, position), (_, _, blackCheckerPosition) ->
       let newposition = position |> jump blackCheckerPosition yIncrementValue
       match newposition with
       | pos when pos = position ->    (Red, pieceType, pos), blackCheckers
       | pos when pos.Y = minY      -> (Red, King, pos) ,  blackCheckers |> remove blackChecker
       | pos ->                        (Red, pieceType, pos), blackCheckers |> remove blackChecker
    | _ -> failwith "Invalid" //Deal with Black pieces here!

This also makes it much easier for you to make jump take in both black and red checkers.


text:
Q: Why is Wordpress inserting "#!" into URLs? if ( window.location.href.search('#!/') == -1 && window.location.href !== et_site_url && window.location.href !== ( et_site_url + '#' ) ) {
            access_without_ajax = true;
            $et_main_content.css( { opacity : 1, top : '77px', width : '800px', height : ( et_window_height - 200 ), marginTop : 0, marginLeft : '-400px' } );
            $logo_area.hide();
            $main_menu.hide();
            $et_footer_menu.css({'display':'block','opacity':1, bottom: '0'})
            $('#content').appendTo( $et_page_content );
            $et_main_content.jScrollPane( { animateScroll: true } );
            et_center_content_area();
            et_init_scripts();
        } else if ( window.location.href === et_site_url || window.location.href === ( et_site_url + '#' ) ) {
            $et_main_content.css( { 'margin-left' : '-' + ( content_width / 2 ) + 'px', top: ( ( et_window_height - $et_main_content.height() ) / 2 - 100 ) } ).animate( { opacity : 1, 'top' : ( ( et_window_height - $et_main_content.height() ) / 2 ) }, fade_in_speed, 'easeInOutQuad' );

This is adding /#!/ right in the middle of my URL when creating pages in Wordpress. How do I get rid of this garbage?


text:
Q: How to add a new header in kendo treelist? How to add a new header in the top of kendo treelist, like it is done in this picture:

I have tried
$("#treelist th.k-header").before('
Stuff
');

but it doesn't work......
My source:
    var dataSource = new kendo.data.TreeListDataSource({
        data: [
                { Id: 1, Name: "EASG", YQ: "150,000,000", M1: "1,000", M2: "1,000", M3: "1,000", MT: "5,000", MR: "50%", parentId: null },
                { Id: 2, Name: "MASD", YQ: "150,000,000", M1: "1,000", M2: "1,000", M3: "1,000", MT: "5,000", MR: "50%", parentId: 1 },
                { Id: 3, Name: "MASD_SD1", YQ: "150,000,000", M1: "1,000", M2: "1,000", M3: "1,000", MT: "5,000", MR: "50%", parentId: 2 },
                { Id: 4, Name: "New Biz", YQ: "150,000,000", M1: "1,000", M2: "1,000", M3: "1,000", MT: "5,000", MR: "50%", parentId: 3 },
                { Id: 8, Name: "FBU", YQ: "150,000,000", M1: "156,000", M2: "177,000", M3: "1,000", MT: "577,000", MR: "50%", parentId: 1 },
                { Id: 9, Name: "FBU_1", YQ: "150,000,000", M1: "156,000", M2: "177,000", M3: "1,000", MT: "577,000", MR: "50%", parentId: 8 }
        ],
        schema: {
            model: {
                id: "Id",
            }
        }
    });

    $("#treelist").kendoTreeList({
        dataSource: dataSource,
        columns: [
                  { field: "Name", title: "部門" },
                  { field: "YQ", title: "Yearly Quota" },
                  { field: "M1", title: "1月" },
                  { field: "M2", title: "2月" },
                  { field: "M3", title: "3月" },
                  { field: "MT", title: "合計" },
                  { field: "MR", title: "合計" }
        ]
    });

A: https://d585tldpucybw.cloudfront.net/forums/treelist-multi-column-headers
It seems not available.................


text:
Q: delete elements from canvas graphics in p5js I using canvas graphics to draw objects and need to undo the last drawn object, but could not find any option to delete last object from graphics, please suggest how to delete last object (i.e. creating undo function)
below is the code to in setup() -
    canvas=createCanvas(1000,1000);
    canvsGraphics = createGraphics(1000,1000);

Below is the object created in mouseDragged() function -
noStroke();
        fill(R,G,B);
        rectMode(CENTER);
        rect(mouseX,mouseY,20,20);

    //CREATES BUFFER
    canvsGraphics.noStroke();
    canvsGraphics.fill(R,G,B);
    canvsGraphics.rectMode(CENTER);
    canvsGraphics.rect(mouseX,mouseY,20,20);

A: You can't just delete an object once it's drawn.
But you can clear out all of the objects using the background() function, and then redraw all of the objects that you still want to see.
You might consider creating a data structure that holds all of the objects. Then each frame, loop through that data structure and draw each object. To delete an object, simply remove it from the data structure.

A: So basically, if you make an empty array and every mouse press push a random name which describes your ellipse/any shape with your current mouse position X and Y, in your ever running draw function loop through the array, in the for loop evaluate what shape you want to draw at what position. look at the code for better understanding.

var canvas;
var posX;
var posY;
var pg;
var arr = [];

function setup() {
    let WndH = 620;
    canvas = createCanvas(WndH, WndH);
    canvas.position(200,50);
    canvas.mousePressed(func);
}

function func() {
    posX = mouseX;
    posY = mouseY;
    arr.push("e",posX,posY);
}

function draw() {
    background(200);
    fill(255);
    for (i = 0; i < arr.length; i++) {
        if(arr[i] == "e") {
            ellipse(arr[i + 1], arr[i + 2], 100, 100);
            i += 2;
        }
    }
}

so the first image is when i run the code but didn't yet take any action(mouse press)
this 2nd image is of me clicking around randomly on the canvas


text:
Q: Hibernate mapping - Is it possible to get rid of one Java class? Currently I have two tables - Product and Statistics. And two java enitities (Product, Statistics)
Mapping between them is 1:1.
I would like to get rid of one entity(Statitics), because from this entity I need only one column called "magicValue".
Is there any way how to use only one Entity - Product, which contains magicValue?  (without need of Statistics class?)
I was thinking about OneToOne mapping or Embedded type usage, but for all of these possibilities, there is need of Statistics java class
If my question is not reasonable, please write me what is best solution according your knowledge.
More detail informations:
From table Product I need all columns.
From table Statistics I need only one column (MAGIC_VALUE)
Sql tables:
        CREATE TABLE PRODUCT
        (
            "PRODUCT_ID"         NUMBER(20,0),
            "NAME"               VARCHAR2(30 BYTE),
             PRIMARY KEY  (`PRODUCT_ID`)
        );

        CREATE TABLE STATISTICS
        (
            "STATISTICS_ID"         NUMBER(20,0) PRIMARY KEY,
            "PRODUCT_ID_FK"         NUMBER(20,0),
            "MAGIC_VALUE"           VARCHAR2(30 BYTE),
            "OTHER_USELESS_COLUMN"  VARCHAR2(30 BYTE),
             ...

             PRIMARY KEY  (`STATISTICS_ID`)
             FOREIGN KEY (`PRODUCT_ID_FK`) REFERENCES PRODUCT(PRODUCT_ID)
        );

Current java classes looks like:
    @Entity
    @Table(name="PRODUCT")
    class Product {
        @Id
        @Column(name = "PRODUCT_ID")
        protected Integer productId;

        @Column(name = "NAME")
        protected String name;

        @OneToOne(cascade = CascadeType.ALL)
        @PrimaryKeyJoinColumn
        protected Statistics stat;
    }

This is Statistics java class
I need only one column (magicValue)
        @Entity
        @Table(name="STATISTICS")
        class Statistics {
            @Id
            @Column(name = "STATISTICS_ID")
            protected Integer statisticsId;

            @OneToOne(mappedBy = "statistics")
            protected Product product;

            @Column(name = "MAGIC_VALUE")
            protected String magicValue; // <-- only this is needed

            @Column(name = "OTHER_USELESS_COLUMN")
            protected String uselessColumn;
            ...
        }

Desired solution

*

*no sql changes

*get rid of Statistics java class (if possible)

*change only Product java class like:
@Entity
@Table(name="PRODUCT")
class Product {
    @Id
    @Column(name = "PRODUCT_ID")
    protected Integer productId;

    @Column(name = "NAME")
    protected String name;

    @someHowMap to sql table Statistics, but in Product have direct magicValue value
    protected String magicValue;
}

Other (minor) informations:

*

*Connection to DB is read-only.

*I'm using only annotations (no cfg file)

*I have no privileges to change sql schema

*using Java 8 or Scala 2.10, Hibernate 5.2

Thank you

A: @Entity
@Table(name="PRODUCT")
class Product {
    @Id
    @Column(name = "PRODUCT_ID")
    protected Integer productId;

    @Column(name = "NAME")
    protected String name;

    @Formula("(select MAGIC_VALUE from STATISTICS where PRODUCT_ID_FK = PRODUCT_ID)")
    protected String magicValue;
}

That formula will work, it uses SQL instead of HQL, so shouldn't need the entity for STATISTICS in your Java classes.
You can see more details about the usage of @Formula here


text:
Q: what exactly is python typing.Callable? I have seen typing.Callable, but I didn't find any useful docs about it. What exactly is typing.Callable?

A: I would like to add to other answers that starting with Python 3.9, typing.Callable is deprecated. You should use collections.abc.Callable instead.
For more details and the rationale, you can take a look at PEP 585

A: typing.Callable is the type you use to indicate a callable. Most python types that support the () operator are of the type collections.abc.Callable. Examples include functions, classmethods, staticmethods, bound methods and lambdas.
In summary, anything with a __call__ method (which is how () is implemented), is a callable.
PEP 677 attempted to introduce implicit tuple-with-arrow syntax, so that something like Callable[[int, str], list[float]] could be expressed much more intuitively as (int, str) -> list[float]. The PEP was rejected because the benefits of the new syntax were not deemed sufficient given the added maintenance burden and possible room for confusion.

A: The typing module is used for type hints:

This module provides runtime support for type hints.

What are type hints?
The documentation provides this example:
def greeting(name: str) -> str:
    return 'Hello ' + name

In the function greeting, the argument name is expected to be of type str and the return type str. Subtypes are accepted as arguments.

How to use typing.Callable
Assume you want to define a function that takes two integers and performs some kind of operation on them that returns another integer:
def apply_func(a: int, b: int, func) -> int:
    return func(a, b)

So the expected type of the func argument in apply_func is "something that can be called (e.g. a function) that takes two integer arguments and returns an integer":
typing.Callable[[int, int], int]

Why bother with type hints in the first place?
Using type hints enables you to perform type checking. If you use an IDE like PyCharm or Visual Studio Code, you'll get visual feedback if you're using unexpected types:

A: See the documentation here.
Short version, Callable is a type hint that indicates a function or other object which can be called.
Consider a simple example below. The bar parameter is a callable object that takes two ints as parameters and returns an int.
>>> def foo(bar: Callable[[int, int], int], a: int, b: int) -> int:
...     return bar(a, b)
...
>>> foo(int.__add__, 4, 5)
9
>>> class A:
...     def __call__(self, a, b):
...         return a * b
...
>>> foo(A(), 6, 7)
42
>>> foo(lambda x, y: x - y, 8, 3)
5
>>>


text:
Q: Magnetic force between broken magnetic circuit
The above image shows the flux flow through a rectangular core. We know the purpose of the core is to concentrate as much of the flux through it as possible, so we'll assume no or minimal stray field lines exist. Let's assume the primary coil is the same as the secondary and each are energized equally with opposite current direction. Let also assume I slice this core vertically in the middle forming two equally magnetized core with a miniscule air gap between them. What is the closest approximation to calculating the force between the two half cores with a simple equation relating force to a magnetic field property (like magnetic flux) that's accurate enough to use in a practical application not requiring the upmost precision. A simple equation showing the approximated relationship of force to area and flux should do.


text:
Q: Using timestamp for indexing a pandas data frame gives value error I have a list of Timestamp called dates_list, which I want to use to extract values from another data frame df. However,
df.loc[dates_list,:]
>>ValueError: mixed datetimes and integers in passed array

dates_list looks like:
dates_list
>>[Timestamp('2000-06-02 00:00:00'),
  Timestamp('2010-06-13 00:00:00'),
  Timestamp('1997-06-26 00:00:00'),
  Timestamp('2014-06-03 00:00:00'),
  Timestamp('2007-06-14 00:00:00'),
  Timestamp('1982-06-06 00:00:00'),
  Timestamp('1998-06-21 00:00:00'),
  Timestamp('2006-07-15 00:00:00'),
  ....]

 df.index[1]
 >>Timestamp('1979-01-01 00:00:00')

 df.info()
 >><class 'pandas.core.frame.DataFrame'>
 DatetimeIndex: 164880 entries, 1979-01-01 to 2017-02-01
 Data columns (total 2 columns):
 longitude    164880 non-null float64
 Var1         164880 non-null float64
 dtypes: float64(2)
 memory usage: 8.8 MB

I also tried converting my dates_list to datetime using
 dates_list2 = pd.to_datetime(dates_list)

But still, I see the same error. However, using just one item of the list flags another KeyError
dates_list2[1]
>>Timestamp('2010-06-13 00:00:00')

df.loc[dates_list2[1], : ]
>>KeyError: 1276387200000000000

This question also has a similar problem but doesn't have a solution. And this also gets the same ValueError but it's performing a different operation all together.