text:
Q: Is there any way to create a fixed accelerometer sensor delay on my Android app? I want to achieve, exactly, 20 Hz sampling rate I want to simulate a fixed accelerometer sensor delay with sampling rate 20Hz. (600 samples/ 30sec)
This is for a Human Activity Recognition Android mobile app, that uses TensorFlow to predict the activity of a user. I experimented with fixed SENSOR_DELAY(NORMAL, UI, FASTEST) and samplingPeriodUS. I noticed that with the custom value on samplingPeriodUS you cannot get a consistent delay, as the sampling rate alters constantly. I ended up, using the SENSOR_DELAY_NORMAL as it gives me a consistent sampling rate, nearly 46Hz.
With this code I collect a 600 accelerometer samples (x,y,z) and then add it to an Arraylist that sends it to Tensorflow to return the probabilities.
With this set I expect to get 600 samples per 13-14 seconds. I want to achieve a 30 seconds delay(20Hz).
Is there any way achieving it with Thread.Sleep, ScheduledExecutorService or maybe a Linear Interpolation?
The source code's taken from curiousily and has been slightly modified: Github Link
protected void onResume() {
    super.onResume();
    getSensorManager().registerListener(this, getSensorManager().getDefaultSensor(Sensor.TYPE_ACCELEROMETER),  SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
public void onSensorChanged(SensorEvent event) {
    specificActivityPrediction(activity);
    x.add(event.values[0]);
    y.add(event.values[1]);
    z.add(event.values[2]);
}

private void specificActivityPrediction(String activity) {

    if (x.size() == N_SAMPLES && y.size() == N_SAMPLES && z.size() == N_SAMPLES) {
        data = new ArrayList<>();
        data.addAll(x);
        data.addAll(y);
        data.addAll(z);

        results = classifier.predictProbabilities(toFloatArray(data));

        downstairsTextView.setText(Float.toString(round(results[0], 2)));
        joggingTextView.setText(Float.toString(round(results[1], 2)));
        sittingTextView.setText(Float.toString(round(results[2], 2)));
        standingTextView.setText(Float.toString(round(results[3], 2)));
        upstairsTextView.setText(Float.toString(round(results[4], 2)));
        walkingTextView.setText(Float.toString(round(results[5], 2)));
        sendProbabilities(activity);
        x.clear();
        y.clear();
        z.clear();
    }
}


text:
Q: Append/Prepend string to a large file in Scala I've got a large file that after some spark processing has a header inside it(but not at the top) so I have to append this string header to the first line of the file.
I tried to do this since I could not find any way to prepend directly to first line (first I read all large content, then I clear the entire file and finally overwrite the file with the header and then append all the large string)
val content: String = txtOutput.contentAsString
    txtOutput.clear()
  txtOutput.overwrite(model_header)
  txtOutput.appendLine().append(content)

But I get the following problem "Requested array size exceeds VM limit" that I can't manage since I am coding in Databricks so I cannot tweak it, so I need any way to process my data

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Check for Variable in another Variable If trying to compare data from a Text File with data collected from a serial input.
Basically I read 'grain' from a file and send it over the serial port which sends it back for the original sender to confirm it was sent correctly.
In other parts of the code I use:
if "AK" in command:
    Do something

This finds the letter AK fine and goes into the if but for the next part I basically need:
if grain in command:
    Do Something
else:
    Do Something else

For some reason it always drops into the else. I'm got the serial port, grain and the buffer (command) all printing out so I can see that grain (A number, normally something like: 22.4) is in command but its not registering in the if loop.
Any ideas of a simple was to do this?
The bit of code in question:
It runs happily but always sends the IC message instead of the AK message at the bottom.
file = open("livedata.txt")
grain = file.readline()
air = file.readline()
file.close()

sending=True
send1=True
send2=False
while(sending==True):
    loop=0
    command=''
    serialport.write("1RDRDR1R")
    print ("DR Sent")

    while (loop<30):
        recieved = serialport.read()
        command = command + recieved
        loop = loop+1
    if "BS" in command:
        if "AK" in command:
            while (send1==True):
                serialport.write("1R"+grain+"1R")
                print ("GrainTemp Sent")
                loop=0
                command=''
                while (loop<30):
                    recieved = serialport.read()
                    command = command + recieved
                    loop = loop+1
                if grain in command:
                    serialport.write("1RAKAK1R")
                    print ("GrainTemp AK Sent")
                else:
                    serialport.write("1RICIC1R")
                    print ("GrainTemp IC Sent")

A: grain = file.readline()

includes in string grain the ending newline so of course it won't be found in another string where there's no such newline immediately after the other content of grain.
Use
grain = file.readline().strip()

to remove whitespace (including newlines) on both sides of grain (if there is some whitespace in grain that's significant to you and you want to match exactly you can do more selective stripping, but it appears from your question that this simple, broad stripping would work for you).


text:
Q: How to display a scrolling banner with alert on a Salesforce record page I have several questions.

*

*How do I post below VisualForce message to be displayed to the Quote record page so when user clicks on the page, they will view this.
Your help is greatly appreciated.

*How do I only show this message when Status is DRAFT?
Markup:
<apex:page >
    showheader="false" sidebar="false">

    <apex:form >

    <marquee scrollamount="15">

    Please save the "PDF Quote" document prior to clicking on the "Submit for Approval."

    </marquee>

    </apex:form>
</apex:page>

A: marquee is deprecated, and you should not use it. It may not work in future browsers. As far as showing/hiding the message, you can use apex:outputText:
<apex:outputText rendered="{!Quote.Status='draft'}">
  You cannot do this, blah blah blah...
</apex:outputText>

You can use other styles, of course, like slds; the warning above is specifically about the use of marquee.


text:
Q: Best practices for writing a Java library in Scala I am planning on writing a library that will primarily be consumed from Java. However, I would like to write this in Scala. I have read most of the documentation on Java/Scala interop, but it is mostly focused on using existing libraries, rather than best practices to ensure seamless interop when writing libraries.
What are some ways of doing this effectively? Ideally, the consumers would not know the library was written in Scala at all.
Are there any other major libraries that do this?
My current plan is to have an API that exposes everything needed with Scala types/features, then having a smaller layer on top of this that converts to Java types. Are there any issues with this approach?

A: Is there any reason you would want to do this?  It's one thing to write a Scala library that can also be used from Scala, but if you want to target Java specifically it probably just makes sense to use Java to write the library.

Ideally, the consumers would not know the library was written in Scala at all.

The biggest issues with this is going to be transient dependencies.  Even if you use no third party libraries from yours, what about the Scala standard library?  If your library would be used in a project that wasn't otherwise using Scala, they would need to pull in the entire Scala library as well unless you don't use the standard lib at all in your code.
You are going to want to use Java collections instead of Scala collections, and  since that's what your client code will be expecting.  You should have no Scala Standard Library classes in your public interface. This also means use Java Functional Interfaces instead of Scala Function Types
Avoid companion objects except for situations where they compile down to static members on a class.  Accessing a Scala companion object from Java is cumbersome.
Use Java Bean conventions for getters/setters/case classes instead of the regular Scala properties (I believe Scala has an annotation for this).
As far as existing libraries, the Spark Java API is written in Scala, but Spark is primary build for Scala with some Java support, but maybe worth looking at (especially to see the differences between the Scala and Java apis.

A: The only concerns I found are needing to included the Scala runtime library, and to append _2.13 to the artifact names.
By publishing via Maven (sbt publishM2), even the Scala library comes automatically to the downstream project.


text:
Q: WebView - нет подключение к blockchain (ETHEREUM) Имеются некоторые DApps на эфире (Ethereum), их мы интегрируем в мобильное приложение (просто передаем туда url и открываем через WebView).
В чём проблема: если на клиенте, где мы открываем DApp, нет подключения к эфиру, то фронтенд мы всё равно видим и можем с ним как-то взаимодействовать, но бэкенд для нас недосупен, и приложение не работает.
Как проблема решается: через браузер на компе подключиться к эфиру можно при помощи плагина MetaMask для Google Chrome, но нужно как-то ещё подключаться и на телефоне, чтобы в установленной .APK можно было работать с DApp через мобильное приложение. Возможно, это можно сделать при помощи установки на телефон какого-то стороннего ПО, возможно что-то нужно сделать на сервере. Кто у нас тут самый умный, подскажите?


text:
Q: How to create constants when we are using VIPER architecture? I am following VIPER design pattern to build application in Swift.
VIPER follows four components:
1) View
2) Wireframe
3) Presenter
4) Interactor
In which component my constants will come and how?

A: If you mean constants that are being used in whole application, they should probably go into separate group, that is independent from any VIPER module. Consider following examplary structure:
MyProject
- Common
    - Constants
    - ...
- Modules
    - MyFirstViperModule
        - View
        - ...
    - MySecondViperModule
        - View
        - ...
- Resources
    - Assets
    - ...

A: If you begin with viper, you can use Generamba with swifty_viper template. this tool will help you to generate your first modules.


text:
Q: Python inner and outer for loop I first want the code to execute the first loop. When done, I want the code to execute the inner loop, which it does. But when there's is no option to run the inner loop anymore, I want the code to go back to the outer loop, but it doesn't do that.
Does anyone know how I can achieve this?
    def loop_function():

    #Search client
    searchCustomerButton = driver.find_element_by_xpath('//*[@id="ibSearchPatient"]')
    searchCustomerButton.click()

    followLoop = range(0, 10)
    for x in followLoop:
        xpath = '//*[@id="ctl00_CPH_Main_ctl00_RadGrid_Patienten_ctl00__'
        xpath += str(x)
        xpath += '"]/td[3]'

        #Click on cliënt ID
        driver.find_element_by_xpath(xpath).click()

        #Click on Zorgtraject
        zorgtrajectButton = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Top_ToolBar_MenuCurrentPage"]/div/ul/li[3]/a/span/span/span')
        zorgtrajectButton.click()

        followLoop2 = range(0,10)
        for x in followLoop2:
        # begin the inner loop with:
            try:
                # inner loop code here
                xpath2 = '//*[@id="ctl00_CPH_Main_ctl00_RadGrid1_ctl00__'
                xpath2 += str(x)
                xpath2 += '"]/td[2]'

                #Click on Zorgtraject ID
                driver.find_element_by_xpath(xpath2).click()

                #Dossier button
                dossierButton = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Top_ToolBar_MenuCurrentPage"]/div/ul/li[5]/a/span/span/span')
                dossierButton.click()

                #Dropdown select
                dropdownSelector = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_Verslagen_radGridBehandelVerloop_ctl00_ctl03_ctl01_PageSizeComboBox_Arrow"]')
                dropdownSelector.click()

                #Prevent not interactable error
                time.sleep(2)

                #Select 50
                selectDropdown = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_Verslagen_radGridBehandelVerloop_ctl00_ctl03_ctl01_PageSizeComboBox_DropDown"]/div/ul/li[4]')
                selectDropdown.click()

                #Check all documents
                tickDossier = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_Verslagen_radGridBehandelVerloop_ctl00_ctl02_ctl01_headerChkboxPrint"]')
                tickDossier.click()

                #Click print
                printButton = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Main_ctl00_Verslagen_btnPrintBehandelverloop"]')
                printButton.click()

                #Click on Zorgtraject ID
                zorgtrajectButton2 = driver.find_element_by_xpath('//*[@id="ctl00_CPH_Top_ToolBar_MenuCurrentPage"]/div/ul/li[3]/a/span/span/span')
                zorgtrajectButton2.click()

            except NoSuchElementException: # define here what type of exception is thrown when there is no option to run the inner loop
                loop_function()  # call the function once again if you want to run the outer loop again

exec(loop_function())

A: You can wrap the whole code into a function like that:
def loop_function():
    followLoop = range(0, 10)
    for x in followLoop:
       # outer loop code here
        for x in followLoop2:
           # begin the inner loop with:
           try:
              # inner loop code here
           except NoSuchElementException: # define here what type of exception is thrown when there is no option to run the inner loop
              loop_function()  # call the function once again if you want to run the outer loop again


text:
Q: Swagger codegen Maven plugin - generate ResponseEntity? Is there a way to tell the Swagger codegen Maven plugin that, when it generates clientside API definitions (i.e. consumers of ApiClient), it should generate method signatures using org.springframework.http.ResponseEntity<T> as the return type, where T is the actual type being returned?
I would like to be able to check for instance the HTTP status codes when invoking methods on the server.
To make it explicit what I want, rather than
public void deleteById(String id);

I want
public ResponseEntity<Void> deleteById(String id);

I'm using 2.3.1 of the plugin. Current configuration:
<execution>
    <id>generate-client</id>
    <phase>generate-sources</phase>
    <goals>
        <goal>generate</goal>
    </goals>
    <configuration>
        <inputSpec>${project.basedir}/src/main/resources/swagger.json</inputSpec>
        <language>java</language>
        <library>resttemplate</library>
        <addCompileSourceRoot>true</addCompileSourceRoot>
        <modelPackage>com.my.group.model</modelPackage>
        <apiPackage>com.my.group.api</apiPackage>
        <invokerPackage>com.my.group.invoker</invokerPackage>
        <configOptions>
            <sourceFolder>src/gen/java/main</sourceFolder>
            <dateLibrary>java8</dateLibrary>
            <java8>true</java8>
            <groupId>com.my.group</groupId>
            <artifactId>client</artifactId>
        </configOptions>
    </configuration>
</execution>


text:
Q: spring boot with hibernate, I can't take away table name with underscore I have tried all alternatives in application.properties (see below) I have found so far but my application is still creating the table with "_" instead of camel case as I set up.
Any suggestion will be highly appreciated.
1
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.cfg.DefaultNamingStrategy

output
DefaultNamingStrategy cannot be cast to org.hibernate.boot.model.naming.ImplicitNamingStrategy

2
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.cfg.DefaultNamingStrategy
output
org.hibernate.cfg.DefaultNamingStrategy cannot be cast to org.hibernate.boot.model.naming.PhysicalNamingStrategy

3
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.DefaultNamingStrategy
output
org.hibernate.SQL                        : drop table tipo_dominio if exists
NOTE: no error but I didn't get the table name without "_"

4
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.EJB3NamingStrategy
output
EJB3NamingStrategy cannot be cast to org.hibernate.boot.model.naming.PhysicalNamingStrategy

my entity
import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity(name="TipoDominio")
@Table(name="TipoDominio")
public class TipoDominio implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

pom
    <properties>
        <main.basedir>${basedir}/../..</main.basedir>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Compile -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <!-- Runtime -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
            <version>1.4.193</version>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.1.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

main
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

*** Edited
I tried
@SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class

without success as well

A: With SpringBoot 1.5.x the hibernate version is "5.x". This means that the naming strategy classes for tables without underscores has changed. This should work for what you have.
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Note that the configuration property name changed as well as the class.

A: probably it does so because it creates table without quotes, which for h2 means case insensitive identifier. Do youreally need a case sensitive identifier?


text:
Q: Microsoft Surface Tablet: Writing Apps for Both Devices? I'm having trouble finding info right now; it might still be too early. But I'm curious if developers will be able to easily write an application that can target both the ARM and Intel versions of the tablet.
I would guess that the ARM version of Windows will come with near full .NET support and that VS2012 would have new templates that can target both device types, no?

A: Is this what you are looking for?
http://blogs.msdn.com/b/b8/archive/2012/02/09/building-windows-for-the-arm-processor-architecture.aspx
Metro style apps in the Windows Store can support both WOA and Windows 8 on x86/64. Developers wishing to target WOA do so by writing applications for the WinRT (Windows APIs for building Metro style apps) using the new Visual Studio 11 tools in a variety of languages, including C#/VB/XAML and Jscript/ HTML5. Native code targeting WinRT is also supported using C and C++, which can be targeted across architectures and distributed through the Windows Store. WOA does not support running, emulating, or porting existing x86/64 desktop apps. Code that uses only system or OS services from WinRT can be used within an app and distributed through the Windows Store for both WOA and x86/64. Consumers obtain all software, including device drivers, through the Windows Store and Microsoft Update or Windows Update.


text:
Q: travis-ci setup releases with --github-token I am having problems using setup releases with a github token. I like travis-ci but I am not willing to hand out my github password - I need to use the token and I read the documentation as this should be possible this way. Unfortunately it still asks for pasword:
$ travis login --github-token XXXXXXXXX
Successfully logged in as ligi!

$ travis whoami
You are ligi (ligi)

$ travis setup releases
Detected repository as ligi/gobandroid, is this correct? |yes|
Username:

A: Here's a route which doesn't involve typing your GitHub password into the terminal. I assume you have the travis CI installed. This assumes you're using travis-ci.org, but replacing --org with --com should work otherwise.
If github.com/your/repo was your repo:

*

*Generate a Github personal access token with the following scope: read:org, public_repo, repo:status, repo_deployment, user:email, write:repo_hook

*(Optional?) Login using travis login <github token> --org

*Run echo <github token> | travis encrypt --org -r your/repo

*Use that secret in your .travis.yml file as described in the documentation

You may need to provide full repo scope, but for the free tier of Travis, public_repo is enough. I'm also not sure which of the other scopes are mandatory.
echo is useful on Windows because Ctrl-D doesn't work properly in Powershell.

A: The Travis CI CLI will not send the GitHub password to Travis CI, instead it will send it to GitHub and use it to generate a GitHub token (the same is true for travis login).
However, if you still feel uncomfortable, you can configure the deployment manually.
Add the following to your .travis.yml:
deploy:
  provider: releases
  api_key: "GITHUB OAUTH TOKEN"
  file: "FILE TO UPLOAD"
  skip_cleanup: true
  on:
    tags: true
    all_branches: true

You can encrypt the GitHub OAuth token via travis encrypt .... It is not necessary to be logged in via the CLI for this, and the encryption happens locally.
See http://docs.travis-ci.com/user/deployment/releases/ for the full documentation

A: I think you can use -t/--token option, e.g.
travis login --org --github-token G1tHu8T0K3N
travis setup releases --org -t G1tHu8T0K3N


text:
Q: Google Trends - Quota limit - IP address changer I am writing a code using the Unofficial Google Trends API (https://github.com/GeneralMills/pytrends#trend), however after hardly 10 requests I have got the following error: Exceeded Google's Rate Limit. Please use time.sleep() to space requests.
It seems that the following command does not properly connect to Google services.
  pytrends = TrendReq(google_username, google_password, custom_useragent=None)

Therefore I tried to change my IP address along with Tor Browser as explained here: https://stackoverflow.com/a/34516846/7110706
controller = Controller.from_port(port=9151)

def connectTor():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5 , "127.0.0.1", 9150, True)
    socket.socket = socks.socksocket

def renew_tor():
    controller.authenticate()
    controller.signal(Signal.NEWNYM)

def showmyip():
    url = "http://www.showmyip.gr/"
    r = requests.Session()
    page = r.get(url)
    soup = BeautifulSoup(page.content, "lxml")
    ip_address = soup.find("span",{"class":"ip_address"}).text.strip()
    print('New IP adress is:' + ip_address)

There main issue is in the following code:
def requestDailydatafromGT(keywords, geography, date):  #parameters must be strings
    from pytrends.request import TrendReq
    import time
    from random import randint

    google_username = ""  #put your gmail account
    google_password = ""
    path = ""

    #Connect to google
    pytrend = TrendReq(google_username, google_password, custom_useragent=None)

    requestdate=str(date)+' 3m'

    trend_payload = {'q': keywords,'hl': 'en-US','geo': geography, 'date': requestdate} #define parameters of the request
    mes=0

    while mes==0:
        try:
            results= pytrend.trend(trend_payload, return_type='dataframe').sort_index(axis=0, ascending=False) #launch request in Google tren0ds
            mes=1

        except Exception:
            renew_tor()
            connectTor()
            time.sleep(randint(5,15))
            mes=0

    return results

The code seems to work as the IP address changes over the time, however I am still stuck with Google request quota limit error:

Exceeded Google's Rate Limit. Please use time.sleep() to space requests.
New IP address is : 178.217.187.39
Exceeded Google's Rate Limit. Please use time.sleep() to space requests.
New IP address is: 95.128.43.164

Do you know if there is a way to bypass the limitation? Perhaps Google Trends does not get the new IP address as the request is not correctly routed by thor.
Thanks in advance.

A: Have you already tried to (re)connect to Google inside the while loop?
while mes == 0:
    pytrend = TrendReq(google_username, google_password, custom_useragent=None) # Connect to google
    try:
        results = pytrend.trend(trend_payload, return_type='dataframe').sort_index(axis=0, ascending=False) # Launch request in Google Trends
        mes = 1

UPDATE 1: As told me by the OP, my solution works only if a random user-agent is used.
Therefore something like the following code should work:
def random_word(length):
"""Return a random word of 'length' letters."""
return ''.join(random.choice(string.ascii_letters) for i in range(length))

[...]

def requestDailydatafromGT(keywords, geography, date):  #parameters must be strings
    [...]
    while mes == 0:
        pytrend = TrendReq(google_username, google_password, custom_useragent=random_word(8)) # Connect to Google
        try:
            results = pytrend.trend(trend_payload, return_type='dataframe').sort_index(axis=0, ascending=False) # Launch request in Google Trends
            mes = 1
    [...]

UPDATE 2: There is no need to authenticate every time you renew Tor.
You can simply do it once after the controller creation.
controller = Controller.from_port(port=9051)
controller.authenticate(<YOUR_TOR_CONTROL_PASSWORD>)

As an additional information, standard ports should be:
Tor: 9050 | Tor control: 9051
Tor Browser: 9150 | Tor Browser control: 9151
I used 9050 and 9051 ports after having un-commented "ControlPort 9051" in default Tor configuration file (and having added my hashed password).


text:
Q: Error with data returned by ajax cross domain request I am creating an webapp where I need to display infromation on map. But I need to convert the cordinates from EPSG:3301 to EPSG:4326. There is website where you can do it http://spatialreference.org/projection/?json={"geometry":{"type":"Point", "coordinates":[527742.81, 6561591.74]}}&inref=EPSG:3301&outref=EPSG:4326 .
So I have my code :
$("#btn1").click(function(event){
var searchString    = $('input[name=check_list1]:checked', '#myForm').val();
var data1            = 'search='+ searchString;
if(searchString) {
    $.ajax({
        type: "POST",
        url: "do_search.php",
        data: data1,
        dataType: 'json',
        success: function(data){
            var otsing_data = (data);
            var json_url = "http://spatialreference.org/projection/?json={'geometry':{'type':'Point', 'coordinates':["+otsing_data['x']+", "+otsing_data['x']+"]}}&inref=EPSG:3301&outref=EPSG:4326";
            $.ajax({
               type: 'GET',
                url: json_url,
                async: false,
                contentType: "application/json",
                dataType: 'jsonp',
                }).done(function (data) {
                var test = data;
                console.log(test);
            });
      }
    });
}
//  return false;
})

But console.log(test) returns me
Object {error: "Expecting property name: line 1 column 1 (char 1)"}

A: I needed to change
var json_url = "http://spatialreference.org/projection/?json={'geometry':    {'type':'Point', 'coordinates':["+otsing_data['x']+", "+otsing_data['x']+"]}}&inref=EPSG:3301&outref=EPSG:4326";

to
var json_url = 'http://spatialreference.org/projection/?json={"geometry":{"type":"Point", "coordinates":['+point_x+', '+point_y+']}}&inref=EPSG:3301&outref=EPSG:4326';


text:
Q: Consulta me resta 2 en lugar de 1 Buen dia estoy tratando de ejecutar una consulta donde cada vez que la ejecuto me reste 1 a un campo entero de una tabla en MySQL al ejecutar la pura consulta desde phpmyadmin me resta correctamente 1 pero al ejecutar la url desde localhost me resta la cantidad de 2 alguien sabe porque sera?
Esta es mi consulta:
    <?php

    require "conn.php";

    $id_fechas = $_GET["id_fechas"];

    $sql="UPDATE fechas SET cupos_disponibles = cupos_disponibles -'1' WHERE id_fechas = '$id_fechas'";
    mysqli_query ($mysqli, $sql);

    if ($mysqli->query($sql)) {
        echo "Actualiza";
    } else {
        echo "Error updating record: " . $mysqli->error;
    }

    mysqli_close($mysqli);

?>

A: Estás ejecutando la consulta dos veces:
$sql="UPDATE fechas SET cupos_disponibles = cupos_disponibles -'1' WHERE id_fechas = '$id_fechas'";
// Primera ejecución
mysqli_query ($mysqli, $sql);

// Segunda ejecución, te recomiendo eliminar la anterior
if ($mysqli->query($sql)) {
    echo "Actualiza";
} else {
    echo "Error updating record: " . $mysqli->error;
}

Otra opción, sería usar una variable para guardar el resultado de la consulta:
$sql="UPDATE fechas SET cupos_disponibles = cupos_disponibles -'1' WHERE id_fechas = '$id_fechas'";
// Ejecutar consulta y guardar resultado en variable
$resultado = mysqli_query ($mysqli, $sql);
// Analizar variable
if ($resultado) {
    echo "Actualiza";
} else {
    echo "Error updating record: " . $mysqli->error;
}


text:
Q: Multi channel variable speaker design problem As part of my my consideration of possible solutions to my multi channel variable speaker number problem arising from my attempts to restore radio functionality to an old hotel intercom system (see previous post on the subject if interested) I have been considering how to distribute say three audio streams delivered to multiple locations (by way of three/four cores per location), where a switch at those locations can be used to select an audio line.
My inexperience is leaving me slightly unsure of what approach to take in terms of the big picture / over all design. Basically what I want to achieve is this...

BUT... I want it for many (10+) rooms (the room being the right hand side of the diagram, where the switch and speaker is).
The problem is this leads to a design that looks more like this:

That's three 'rooms', but with a maximum design consideration of 4 audio channels and 13 'rooms' this means over 50 amplifiers. Small amplifiers are cheap, but still, I can't help feel it's a bit of a mad design!
Trying to come up with something more sane, I considered this:

BUT... The system should obviously survive usage, and here the impedance of the load applied to the amplifiers will change dramatically as variable numbers of speakers are turned on and the audio lines tapped... Obviously it's going to halve just from a second speaker being brought online with the same channel, and whilst it's not a likely use case, what if someone went round turning on 10 or more speakers all on the same channel!? The impedance of the load is going to be REALLY low now, and I have no idea if it is allowable to have such a variable impedance load for an amplifier. I do realise it's not normal or ideal, but is it acceptable if the amplifier is big enough to handle it?
I'd really appreciate any comments and/or help with the above questions or any suggestions for an alternative approach. I'm obviously more than happy to put time and effort into researching and working to expand the ultimate solution, but it's not currently clear to me which direction to go in at the moment!

A: Yes, it is allowed to have that variable a load on your amplifiers, given certain precautions. Most amplifiers can tolerate open circuit on their outputs, and, subject to limiting the output so they don't get too hot, somewhat lower than their 'rated' load.
A common method for supplying multiple speakers from a central location is the '100v line' method. Each speaker has a transformer before it to raise its impedance. This can get expensive in transformers, that have to be rated for the audio range.
You should be able to buy high impedance speakers, 32 ohm is not uncommon. Ten of those in parallel would present around 3ohms to your amplifier, which most audio amps should be able to drive at less than max output with little distress. How much fi and power do you want, I suspect these higher impedance speakers will be lo-fi and low power.
You could precede each speaker by its own local amplifier, which would raise the per room loading to a level where it ceases to be an issue. If powering the amplifiers via the CAT5, you would want a beefy electrolytic across the supply at the amplifier.

A: Warning: potential danger
I have came across this in passing and didn't read the whole thing so my concern here may be baseless. However, having Cat5E wire at the output of an audio amplifier is potentially dangerous. Cat5E has very limited power transfer ability and the cable is rated to 0.5A max current or thereabouts. Anything above this is a potential fire hazard.
In addition, there may be different (and more conservative) ratings for residential cable and running speaker level signals through installed Cat5E may also be a violation of local building codes.
Therefore I strongly that you have any solution you come up with checked out by licensed professional who is familiar with local building codes.


text:
Q: Azure Active Directory B2C with Passport.js error "Cannot get aad federation metadata" error I'm trying to implement customer-facing authentication for my Node.js web app using Passport.js and Azure Active Directory B2C with the OpenID Connect strategy.
I have followed the README instructions from the official GitHub page and studied the source code of the official sample apps, but they seem to be incomplete and/or out of date, as agreed by various threads online.
After piecing together various tips from around the web, I have crossed many bridges, but reached an impasse with the following error:
cannot get AAD Federation metadata from endpoint you specified.
There is a ton of configuration required for AAD authentication, so I will note some important values:

*

*policyName: This is b2c_1_signin, just like I have configured in the Azure portal.

*identityMetadata: I'm using a tenant-specific, v2.0 endpoint. I added ?p=b2c_1_signin to inject the policy name.

*responseType: id_token

*redirectUrl: This is my localhost and port, as configured in Azure. allowHttpForRedirectUrl is set to true. (This works for non-prod environments.)

*isB2C: true

A: For B2C, you need to set validateIssuer: false. For non-common endpoint, we use the issuer from the metadata that is returned from AAD, for B2C, passport.authenticate cannot grab the issuer value from the metadata. For B2C, passport uses the TenantId to handle validation, so that must be provided, which would be part of the identityMetadata.
Also, the identityMetadata should have this format:
identityMetadata: "https://" + b2cDomainHost + "/" + tenantIdGuid + "/" + policyName + "/v2.0/.well-known/openid-configuration/"
I don't think passport is set up to handle this format for the metadata url -> ?p=b2c_1_signin
You can try this node.js sample, and use your own values, which will call into the passport.js library.
Example:
var clientID = "93733604-cc77-4a3c-a604-87084dd55348";
var b2cDomainHost = "fabrikamb2c.b2clogin.com";
var tenantIdGuid = "775527ff-9a37-4307-8b3d-cc311f58d925";
var policyName = "B2C_1_SUSI";
var options = {
    identityMetadata: "https://" + b2cDomainHost + "/" + tenantIdGuid + "/" + policyName + "/v2.0/.well-known/openid-configuration/",

    clientID: clientID,
    policyName: policyName,
    isB2C: true,
    validateIssuer: false,
    loggingLevel: 'info',
    loggingNoPII: false,
    passReqToCallback: false
};


text:
Q: Find angles using the Law of Cosines if you must find the Angle C based on the sides of  a = 2, 3 b = 4,6 og c = 5, 9
I have used the formula:
$$\cos (C) =\frac{a^2 + b^2-c^2}{2ab}$$
use, but I think i'm doing something wrong:
$$\cos(C) = \frac{(2,3^2) + (4,6^2) - (5,9^2)}{2 \cdot 2,3 \cdot 4,6} = -0,395085066$$
$$C = \cos^{-1} ( -0,395085066 ) = \cdots$$

A: By the Cosine Law, we have
$$c^2=a^2+b^2-2ab\cos(C).$$
This can be rewritten as
$$\cos(C)=\frac{a^2+b^2-c^2}{2ab}.$$
Put $a=2.3$, $b=4.6$, and $c=5.9$. We get $\cos(C)=-0.395051$. So far, we agree.
Pressing the $\cos^{-1}$ button, we get $C=113.27128$ (degrees). Doing it in radian mode, we get $C=1.9769568$ (radians). But probably you want the answer in degrees.
You do not explain why you think the answer is not correct.  I noticed that in your first line you say that $b=4.9$, but in your calculation you write $4.6$, and indeed you used $4.6$. If $b$ was really supposed to be $4.9$, you should redo the calculation using $b=4.9$.
One other possibility is that you do not know how to find $C$, knowing its cosine and the fact that the angle is between $0$ and $180$. The notation is a little confusing. Note that $\cos^{-1}x$ does not mean $\frac{1}{\cos x}$.
In a comment, you mention that the issue is with "$-0.395051$", but do not explain why you see it an issue. I will guess that it is the fact that the number is negative. No problem! The cosine of any obtuse angle is negative. The reason we got a negative is that $c^2>a^2+b^2$.  In that case, the angle $C$ will always be obtuse.


text:
Q: QMYSQL driver not loaded QtCreator Estou tentando fazer conexão com o banco de dados com o QtCreator da seguinte maneira:
this->db = QSqlDatabase::addDatabase("QMYSQL");
this->db.setHostName("localhost");
this->db.setDatabaseName("Pessoa");
this->db.setUserName("root");
this->db.setPassword("");
if(this->db.open();

Mas a aplicação retorna:

QSqlDatabase: QMYSQL driver not loaded
  QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QPSQL QPSQL7

Já instalei o qt-mysql e no .pro QT += sql. O que devo fazer além disso para ter conexão?
Obs.:
Versão do Qt = 5.2.1
SO = GNU/Linux Fedora

A: Resolvi instalando o pacote

qt5-qtbase-mysql

e copiando o arquivo

/usr/lib64/qt5/plugins/sqldrivers/libqsqlmysql.so

substituindo o arquivo localizado em

/opt/Qt5.2.1/5.2.1/gcc_64/plugins/sqldrivers/libqsqlmysql.so.

A: Certifique-se de que a biblioteca do mysql está em um local acessível ao Qt (/usr/lib/, /usr/lib/i386-linux-gnu ou algo do tipo).
Como você disse que já instalou o mysql, você deve encontrar a seguinte biblioteca:
libmysqlclient_r.so ou libmysqlclient.so ou libmysqlclient_r.so.16
É essa biblioteca que o Qt necessita para rodar o driver do mysql, como pode ser visto no .pro que compila o driver mysql do Qt, nesse trecho:
unix {
    isEmpty(QT_LFLAGS_MYSQL) {
        !contains(LIBS, .*mysqlclient.*):!contains(LIBS, .*mysqld.*) {
            use_libmysqlclient_r:LIBS += -lmysqlclient_r
            else:LIBS += -lmysqlclient
        }
    }
} else {
    !contains(LIBS, .*mysql.*):!contains(LIBS, .*mysqld.*):LIBS += -llibmysql
}

Se o nome da biblioteca estiver diferente, pode ser que o Qt não esteja encontrando e, por isso, não consegue criar o driver. Se for o caso, você pode tentar criar uma ligação entre a biblioteca que você tem e o nome reconhecível.
Exemplo:
ln -s libmysqlclient_r.so libmysqlclient_r.so.16


text:
Q: get round numbers between 0 to 1 I have UISlider that produce  numbers between 0 to 1,
0.0590829
0.0643739
..

I want to get the rounded number between them, like:
0.1
0.2
0.3
...
1.0

found this (in c):
float x = arc4random() % 11 * 0.1;

but its not working on swift
var x = arc4random() % 11 * 0.1;
//error: binary operator '*' cannot be applied to operands of type 'UInt32' and 'Double'

Thanks

A: *

*Multiply by 10 to get values between 0.0 and 10.0

*round to remove the decimal

*divide by 10

Example:
let values = [0, 0.0643739, 0.590829, 0.72273, 1]

for value in values {
    print("\(value) -> \(round(value * 10) / 10)")
}

// 0.0 -> 0.0
// 0.0643739 -> 0.1
// 0.590829 -> 0.6
// 0.72273 -> 0.7
// 1.0 -> 1.0


text:
Q: Gibbons-Hawking Variation I know there already exist some questions about this and some very good answers. However, I am still having trouble understanding one part of the calculation. The GHY term is given by
$S_{GHY}=-\frac{1}{8 \pi G} \int_{\partial M} d^dx \sqrt{-h} K$
I'm really confused about how to compute $\delta K$:
1, I would have thought $K$ as the trace of the extrinsic curvature $K^{\mu \nu}=-\frac{1}{2} (\nabla^\mu n^\nu + \nabla^\nu n^\mu)$ would be given by $K=K^{\mu \nu} g_{\mu \nu}$. I believe I'm supposed to contract with $g_{\mu \nu}$ rather than $h_{\mu \nu}$ since the normal vector is not confined to $\partial M$ - can someone confirm this please?
2, If I then vary $K$ I find $\delta K =  K^{\mu \nu} \delta g_{\mu \nu} + \delta K^{\mu \nu} g_{\mu \nu}$ but according to Explicit Variation of Gibbons-Hawking-York Boundary Term, I should have $-\frac{1}{2} K^{\mu \nu} \delta g_{\mu \nu}$ on the first term. It appears I'm out by a minus sign and a factor of $\frac{1}{2}$ but I don't know why though?
3, We have $\delta K = \dots + g_{\mu \nu} \delta K^{\mu \nu}$ and I don't know how he gets this expression for the variation. Could somebody please explain how he does the variation of the normal vector and picks up this conrtibution $c_\mu$. N.B. I tried to follow the advice in one of the comments to consider a specific example of $n_\mu$ but I couldn't find the correct variation of $\alpha_\mu$?
Thanks.


text:
Q: How to extract specific data from .csv file and store it in variable using Python I have .csv file contains currency and its rate. I want to extract the highlighted data from .csv and store it in variable.
How can I do that using Python?

I am currently a beginner in Python and I have so many things to learn.

A: The best (and common way) to do it is by using a package called Pandas.
You can install it by typing pip install pandas in your terminal.
If you are using the Anaconda Environment it should be already installed. Skip this "Anaconda" passage if you don't know what I'm talking about (Google it eventually).
With pandas you can do this:
# Import pandas package
import pandas as pd

# Read your file as a dataframe
myDataframe = pd.read_csv("filename.csv")

# Convert 'Rates' column to float (if needed)
myDataframe = myDataframe.astype({"Rates":"float"})

# Extract the 'interesting' row by using this notation
interestingRow = myDataframe[myDataframe["Curr"] == "GBP"]

# Extract the rate value from the row
theRate = interestingRow["Rates"]

A: Considering your .csv file only contains such table, you can open and get the data you want from it in Python using Pandas:
import pandas as pd
# Open the csv file
data = pd.read_csv("yourfilename.csv")
# Get the value
data.loc[data["Curr"] == "GBP", "Rates"][1]

For solving your issue with missing names in the header, you can skip the first row and add custom column names:
# Open the csv file
colnames = ["currency", "rate"]
data = pd.read_csv("yourfilename.csv", names=colnames, skiprows=(0,))
# Get the value
data.loc[data["currency"] == "GBP", "rate"][1]


text:
Q: Flutter ios build for testing I would Like to know how I can build a release app without registering it to the app store. I would Like to have the APK file and share it with friends for testing purposes without registering the app. Cant find information connected with this.
Thanks!
UPDATE:
Found solution for getting .ipa file which was installed with Cydia Impactor on a real device:
# flutter build
flutter build ios --release --no-codesign

# make folder, add .app then zip it and rename it to .ipa
mkdir -p Payload
mv ./build/ios/iphoneos/Runner.app Payload
zip -r -y Payload.zip Payload/Runner.app
mv Payload.zip Payload.ipa

# the following are options, remove Payload folder
rm -Rf Payload

A: You can follow this article to make .ipa file. (.apk is for android only, for iOS it's .ipa)

https://medium.com/mλgnξtλr/how-to-export-a-ipa-file-from-xcode-without-a-dev-account-bac8b2645ad3

Keep in mind that, apple is signing build to be installed on real devices, so you have to turn that off, and after making an ipa file, you can upload it to www.diawi.com and get link from there to share it with your friend. This diawi links are not working some times, in that case you can use cydiaimpector tool for installing the build.
For this installation, your friend has to put their apple id and password upon requested, here NOTE that if your two factor authentication is ON, then you have to create app specific password to be entered in.

How to create app-specific password?
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=2ahUKEwiSvpjUo-fjAhXt8XMBHRtBDlUQFjACegQIDBAI&url=https%3A%2F%2Fwww.imore.com%2Fhow-generate-app-specific-passwords-iphone-ipad-mac&usg=AOvVaw3chF3FoIcfHZLR6jExh_EZ


text:
Q: Building a regular grammar from NFA I'm requested to make a regular grammar from a given NFA.
In this NFA, there's a "death state", which means, when getting to it, there's no way back to the rest of the states (a self-loop to the same state given any letter).
How would I translate that in my grammar?
Thanks in advance

A: It won't translate directly: your grammar simply won't generate strings that would put the NFA into the death state (a much more dramatic term than my garbage state). If you're using some algorithm to do the translation, it should have a provision for dealing with such a state. If not, you'll you'll have to take into account the effect of the death state, but it won't correspond to any actual entity in the grammar.


text:
Q: Taking screenshot of NGLView (NineVehGL engine) I am using NinevehGL 3D engine http://nineveh.gl/
I want to get screenshot of OpenGL object. Problem is with below code
-(UIImage *) screenshot
{

// Capture screen here... and cut the appropriate size for saving and uploading
UIGraphicsBeginImageContext([self theNGLView].bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// crop the area you want
CGRect rect;
rect = CGRectMake(0, 10, 300, 300);    // whatever you want
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return img;
}

Only background comes in screenshot but not actual NGLView or OpenGL object which is drawn on top of it.
I am using iOS SDK 6.0

A: tried using
[[self the NGLView].layer renderInContext:UIGraphicsGetCurrentContext()];

?

A: Please go through this link, you need to download the latest NinevehGL SDK for iPhone5/iOS 6 which is provided in their twitter link.


text:
Q: Passing array to method example makes no sense There is an example program in my java book that makes no sense to me. Basically it passes an array reference to a method. But the outcome is that the array itself is modified even though the method doesn't have a return or something within it that indicates its doing something other than creating it's own instance of the array.
public class PassArray
{
   public static void main( String[] args )
   {
      int[] array = { 1, 2, 3, 4, 5 };

      System.out.println(
         "Effects of passing reference to entire array:\n" +
         "The values of the original array are:" );

      for ( int value : array )
         System.out.printf( "   %d", value );

      modifyArray( array ); // pass array reference to method modifyArray
      System.out.println( "\n\nThe values of the modified array are:" );

      // output the value of array (why did it change?)
      for ( int value : array )
         System.out.printf( "   %d", value );

   } // end main

   // multiply each element of an array by 2
   public static void modifyArray( int array2[] ) // so this accepts an integer array as an arguement and assigns it to local array array[2]
   {
      for ( int counter = 0; counter < array2.length; counter++ )
         array2[ counter ] *= 2;
   } // What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?

   //What if I wanted to not make any changes to array, how would implement this code so that the output to screen would be the same but the value in array would not change?

} // end class PassArray

Please explain why this is the case  and also how this could be implemented somehow so that the values of array are not changed. S

A:
// What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?

Because java is pass by reference value. Copy of the reference will be passed to the method. This reference also still points to original array. Any change you perform on this reference will reflect on original array.

how this could be implemented somehow so that the values of array are not changed.

One way is, create new array inside the method and assign it this reference.
Example:
public static void modifyArray( int array2[] )
   {
      array2 = new int[10];
      //Copy only ten elements from outer array, which populates element at index 2.
      for ( int counter = 0; counter < array2.length; counter++ )
      array2[ counter ] *= 2;
   }

Now the updates/operations you perform on this reference will effect on new array created inside the method, not on original array.
See this SO discussion for more information.

A: When you pass an array to a method, you're really just passing a copy of the reference to the array.
Any changes that are made to the array will be reflected in the object that was passed.
What actually gets passed to modifyArray is a copy of the array reference, which is why people say Java is "pass by reference value".

A: What's happening is that when you pass array to modifyArray(int[]) is that array which is actually not a java primitive, so array2 is really still the same object as array.
A fairly easy way to copy the first array would be to use System's arrayCopy method like this
  public static int[] modifyArray( int array[] )
  {
      int length = array.length; // length of the original array
      int array2[] = new int[length]; // the new array which we will copy the data into
      System.arraycopy(array, 0, array2, 0, length); // now we copy the data from array[] into array2[]
      for ( int counter = 0; counter < array2.length; counter++ ) {
          array2[ counter ] *= 2; // multiply by 2
      }

      return array2; // return the array with the new values
  }

You now have a copy of the original array, but with all the values multiplied by 2.
I hope this helps.

A:   public class PassArray
     {
      public static void main( String[] args )
        {
      int[] array = { 1, 2, 3, 4, 5 };

      System.out.println(
         "Effects of passing reference to entire array:\n" +
         "The values of the original array are:" );

      for ( int value : array )
         System.out.printf( "   %d", value );

      modifyArray( (int[])array.clone(); ); // pass array reference to method modifyArray
      System.out.println( "\n\nThe values of the modified array are:" );

      // output the value of array (why did it change?)
      for ( int value : array )
         System.out.printf( "   %d", value );

   } // end main

   // multiply each element of an array by 2
   public static void modifyArray( int array2[] ) // so this accepts an integer array as an arguement and assigns it to local array array[2]
   {
      for ( int counter = 0; counter < array2.length; counter++ )
         array2[ counter ] *= 2;
   } // What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?

   //What if I wanted to not make any changes to array, how would implement this code so that the output to screen would be the same but the value in array would not change?

   }

Please read this link to understand better


text:
Q: Comparing the slopes of two regression lines where the two slopes are NOT independent (breakpoint) so I am trying to see whether there is a breakpoint in my data set at a certain time. Basically I have 200 data points and am wondering if there is a breakpoint at t=100, ie whether the slopes of the two regression lines change significantly. Le the slope of line 1= b1 and the slope of line 2= b2.
I want to see whether $b1-b2=0$ using a t test, and so I think  that would reduce to evaluating the statistic $t= (b1-b2)/($std error$(b1-b2))$ The problem I have is that I don't know how to compute that standard error since b1 and b2 might be correlated. Furthermore I am not sure what degrees of freedom the corresponding t distribution would have? Finally, how do I even see that the statistic I have written down does follow a t distribution in the first place?
Thanks in advance for anyone who can help me with any of these questions!

A: You are comparing two models: the first fits a common slope, the second fits two slopes. So fit them both and then compare the fit of the two models. If the second has an improvement in fit you needed two slopes. You do not say how you are handling the junction between the two parts of the dataset, whether you are constraining the two lines to meet there but if you are also allowing two separate intercepts then the procedure I outline should work just as well. If you want to read further then in some fields these are known as broken stick models which may help you. Note also that you are assuming you know the breakpoint, if you estimate it things get more complicated.
We assume we know the breakpoint $c$.
We define two basis functions.
\begin{equation}
B_l(x) = \begin{cases}
c - x & \text{if } x < c \\
0 & \text{otherwise}
\end{cases}
\end{equation}
and
\begin{equation}
B_r(x) = \begin{cases}
x - c& \text{if } x > c \\
0 & \text{otherwise}
\end{cases}
\end{equation}
We now fit
\begin{equation}
y = \beta_0 + \beta_1B_l(x) + \beta_2 B_r(x) + \epsilon
\end{equation}
using standard methods.
Note that the coefficients are for the
new variables here
and the way they are coded
means that a negative value shown for
$B_l(x)$ corresponds to a positive slope.


text:
Q: How to pass value from js to php as a variable? For example, I have this on my js
<script>
  var calc=7;
</script>

and I want to use the value from js in php and I want to store the value in  php variable
<?php
  $charge.
?>

A:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
var calc=7;
function sendvariable() {
   $.post('your_file.php',{calc:calc}, function(data) {
      console.log('['+data + ']');

   });
       }
</script>

and your php file :

<?php
$charge = $_POST['calc'];

echo $charge;

?>

normally it works

A: You have a few options:
The best way, in my opinion, is to use AJAX. This will make a call to your PHP script in the background. You can use jQuery, a helper library, to make things easier:
<script>
var calc = 5;
$.ajax("submit.php", {
    data: { "calc": calc },
    type: "POST"
});
</script>

If you don't want to use jQuery, it's possible to make an AJAX call without it. Take a look around the internet for using XMLHttpRequest to make a POST request.
Another way is to use <form method="post"> and <input> tags (type="hidden" if needed) and then send the data using a submit button. Unlike AJAX, this isn't done in the background and redirects the user to another page.
<form id="form" method="post" action="submit.php">
    <input id="calc" name="calc" type="hidden">
    <button type="submit">Submit Data</button>
</form>

<script>
var calc = 5;
document.getElementById("form").onsubmit = function () {
    document.getElementById("calc").value = calc;
};
</script>

In all of these examples, the values of the the data you send will show up under PHP's $_POST variable:
<?php var_dump($_POST["calc"]); ?>


text:
Q: Adding a post outside of a form I have a form in my razor view which works exactly as it should.  I select values from the drop down and press the submit button and it return to me a paginated set of results.  All well and good.
@using (Html.BeginForm())
    {
        int index = 0;
        foreach (var type in @Model.AttributeTypes)
        {
            @Html.DropDownListFor(m => m.SelectedAttributeValueIds[index], Model.AttributeValuesList[Convert.ToInt32(@type.Value)], "Filter by " + type.Text)
            index++;
        }

        <input type="submit" value="Filter"/>
}

The problem is that at the bottom of the page, outside of the form I want a Show all button/link.  Pressing this button should essentially do the same thing that the above submit button does.  In other words I'd like this Show all button to show all of the results of the last query (or the currently selected values in the dropdowns - not too bothered which) without pagination.  I can do the no pagination bit, that is easy.  What I want to know is how will my button/link get the values from the dropdown from outside of the form and submit that form?

A: Use javascript to read information on the dom element you need to grab the info and them submit an ajax request.

A: You can use javascript/jquery to submit the form on click of that button.
$('#formId').submit();

To wire this up you could do the following on your document ready script:
$('#buttonId').click(function() {
  $('#formId').submit();
});


text:
Q: Recognition of changed data in a multi user database I've got a database which will be accessed by multiple users.
For example User 1 retrieves a list of all available datasets in the table "Test". User 2 does the same thing and both users afterwards got the same datasets.
So now, if User 1 wants to write ABC to dataset with Index 1, he can do so and the dataset is persistent.
But if User 2 NOW wants to write ABB to dataset with Index 1, how can he know, that the dataset has already been updated?
Is there a pattern for multi user database access or can I just use hashing algorithms to obtain if there is an updated dataset?
Or are there any other approaches?

A: There are a number of possible answers here and a lot depends on your application architecture.
Are two users going to be working on the same row at the same time? And if so, if they have different ideas about what data should be there, this sounds like a business problem that needs to be considered and resolved.
That said, if you have a front end that is receiving data and then trying to write back, using either a time stamp or a checksum as part of validation is a common and useful way of handling this solution.
If I were implementing this I would use a stored procedure and force my application to pass the checksum back to the proc. The procedure would check to see if the checksum is still accurate and the write would fail if it wasn't.


text:
Q: Where are core dumps written on Mac? On Mac OS X, if I send SIGQUIT to my C program, it terminates, but there is no core dump file.
Do you have to manually enable core dumps on Mac OS X (how?), or are they written to somewhere else instead of the working directory?

A: It seems they are suppressed by default. Running
$ ulimit -c unlimited

Will enable core dumps for the current terminal, and it will be placed in /cores as core.PID. When you open a new session, it will be set to the default value again.

A: On macOS, your crash dumps are automatically handled by Crash Reporter.
You can find backtrace files by executing Console and going to User Diagnostic Reports section (under 'Diagnostic and Usage Information' group) or you can locate them in ~/Library/Logs/DiagnosticReports.
You can also check where dumps are generated by monitoring system.log file, e.g.
tail -f /var/log/system.log | grep crash

The actual core dump files you can find in /cores.
See also:

*

*How to generate core dumps in Mac OS X?

*Technical Note TN2118: Kernel Core Dumps.

A: Additionally, the /cores directory must exist and the user running the program must have write permissions on it.

A: The answer above,

ulimit -c unlimited

works -- but be sure to run that in the same terminal from which you will run the program that dumps core.  You need to run the ulimit command first.

A: by default, specific directories in mac osx are hidden. you might want to enable this feature in the terminal and then the core dump should be visible within the directory /cores.

defaults write com.apple.finder AppleShowAllFiles TRUE

A: There is a great explanation by Quinn "The Eskimo!" on Apple's forums
https://developer.apple.com/forums/thread/694233
I roughly followed that guide. Here are the steps that I did.
Grant write all access to the /cores dir
PROMPT> ls -la / | grep cores
drwxr-xr-x    2 root  wheel    64 Dec  8  2021 cores
PROMPT> sudo chmod 1777 /cores
PROMPT> ls -la / | grep cores
drwxrwxrwt    2 root  wheel    64 Dec 21 23:29 cores

Set size of core file
PROMPT> ulimit -c unlimited

Compile and sign the program
PROMPT> cargo build --release -p my-crashing-program
PROMPT> /usr/libexec/PlistBuddy -c "Add :com.apple.security.get-task-allow bool true" tmp.entitlements
PROMPT> codesign -s - -f --entitlements tmp.entitlements my-crashing-program

Run the program
PROMPT> my-crashing-program
thread 'main' panicked at 'boom', my-crashing-program/src/main.rs:74:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
dumping core for pid 80995
zsh: quit       my-crashing-program

Now there is a core file
PROMPT> ls /cores
core.80995

Also Apple's Console app has a list with Crash Reports.


text:
Q: Set keyboard navigation mode as default one As it's said in android developers blog:

By itself, the touch mode is something very easy to understand as it simply indicates whether the last user interaction was performed with the touch screen. For example, if you are using a G1 phone, selecting a widget with the trackball will take you out of touch mode; however, if you touch a button on the screen with your finger, you will enter touch mode. When the user is not in touch mode, we talk about the trackball mode, navigation mode or keyboard navigation...

But android is booting by default in touch mode. How can I switch device into keyboard navigation mode, or make it a default one?
I'm developing app for a specific device, so it's rooted and I can also modify firmware.

A: You can force an Android device in or out of touch mode using Instrumentation.setInTouchMode(boolean).
new Instrumentation().setInTouchMode(false);

Running this as part of a boot receiver would probably achieve what you are looking for.


text:
Q: Scrapy chain selector with different parents I want to chain two selectors together that have different parents.  The selector I'm using currently:
..css('td:nth-child(8) > span.cap.mtv > ::text')

Which yields:
<Selector xpath="descendant-or-self::td[count(preceding-sibling::*) = 7]/span[@class and contains(concat(' ', normalize-space(@class), ' '), ' cap ') and (@class and contains(concat(' ', normalize-space(@class), ' '), ' mtv '))]/*/text()" data='$725,000'>
The issue I have is that I also want the following:
..xpath('td[8]/div/text()')

Which yields:
<Selector xpath='td[8]/div/text()' data='UFA'>
Ultimately I want to use an item loader and extract to get:
$725,000
UFA
...

I want to achieve something similar to the following..
...xpath('td[8]').css('span.cap.mtv > ::text').xpath('/div/text()')
I have previously just sort of re-scraped an element w/ another set of selectors if the program had previously found nothing but would much rather have this sort of 'either/or' flexibility.  Or would I be better of looking at another selector all together for this situation?
Any help is much appreciated!

A: If you're using item loaders, you can simply add multiple selectors for a single field as shown in  scrapy docs.
Something like this should work, after creating a loader:
loader.add_css('field', 'td:nth-child(8) > span.cap.mtv > ::text')
loader.add_xpath('field', 'td[8]/div/text()')

Your input/output processors would then be responsible for how this information is combined.


text:
Q: Extend + scale a portrait video so the aspect ratio stays and the black borders become a blurry version of the video I have a 720 x 1280 pixels video. How do I extend and scale it to 1920 x 1080 such that the aspect ratio is being kept and the black borders are a blurry version of the video, so you don't really notice that it's just a small vertical stripe.
Example

I started with
ffmpeg -i video720x1280.mp4 -vf "scale=608:1080,pad=width=1920:height=1080:x=656:y=0:color=black" video1920x1080.mp4

A: Use
ffmpeg -i video720x1280.mp4
  -filter_complex
      "[0]scale=hd1080,setsar=1,boxblur=20:20[b];
       [0]scale=-1:1080[v];[b][v]overlay=(W-w)/2"   video1920x1080.mp4

Adjust the two values in the boxblur filter for blur strength. Higher = more blurring.


text:
Q: Get HTTP request parameters in Spring HTTPMessageConverter I am using Spring's AbstractHttpMessageConverter to allow me instantiate my own object.
Converter
    public class PaypalIPNHttpMessageConverter extends AbstractHttpMessageConverter<IPNMessage> {

    public PaypalIPNHttpMessageConverter() {
        super(MediaType.APPLICATION_FORM_URLENCODED, MediaType.TEXT_PLAIN);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz == IPNMessage.class;
    }

    @Override
    protected IPNMessage readInternal(Class<? extends IPNMessage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        //Converts HTTPRequest into map<string,string> that IPNMessage can then parse
        String requestString = IOUtils.toString(inputMessage.getBody(), "UTF-8");
        Map<String, String[]> requestMap = new LinkedHashMap<>();
        for (String keyValue : requestString.split("&")) { //each key value is delimited by &
            String[] pairs = keyValue.split("=", 2); // = pairs a key to a value
            requestMap.put(pairs[0], pairs[1].split(",")); // , splits multiple values for that key
        }
        return new IPNMessage(requestMap);
    }

    @Override
    protected void writeInternal(IPNMessage ipnMessage, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    }
}

In readINternal(), I am passed a HttpInputMessage object, which only has getBody() function that produces an InputStream of the HTTPRequest.
I have tried to write my own code to parse and build a ParameterMap but it does not always work if the urlencoding is different.
Is there anyway I can get Spring's WebRequest or HttpServletRequest object from the converter and use there wonderful getParameterMap() function?
TL;DR
Is there anyway to use WebRequest or HTTPServletRequest in the MessageConverter instead of HttpInput so I can use the wonderful getParameterMap() function, instead of reinventing the wheel?
Thanks

A: Look at how it is implemented in Spring FormHttpMessageConverter. It tokenizes request parameter using & just like your solution. However it dtermines the charset to use from the Content-Type request header if provided. Otherwise it uses default UTF-8
//extract from FormHttpMessageConverter
public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz,
            HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

        MediaType contentType = inputMessage.getHeaders().getContentType();
        Charset charset = (contentType.getCharSet() != null ? contentType.getCharSet() : this.charset);
        String body = StreamUtils.copyToString(inputMessage.getBody(), charset);

        String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
        MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);
        for (String pair : pairs) {
            int idx = pair.indexOf('=');
            if (idx == -1) {
                result.add(URLDecoder.decode(pair, charset.name()), null);
            }
            else {
                String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
                String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
                result.add(name, value);
            }
        }
        return result;
    }

A: You can simply get the current request using the following code
HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();


text:
Q: How do I bypass authentication in an ASP.NET project? Facts:

*

*I have inherited an ASP.NET C# project.

*The project contains the following files: (a) default.aspx (b) index.aspx (c) global.asax (d) Web.config

*The project runs on a server that requires authentication.

*I am trying to do some dev work on my computer without requiring authentication.

*I can't find the right part of the code to comment out or otherwise modify to bypass authentication.

What can I post that would help someone help me?
Update: I found the code
  <asp:Login ID="Login1" runat="server"> <%-- OnAuthenticate="Login1_Authenticate">--%>

in index.aspx. There are no other references to "Login1_Authenticate" in the project.
It's been so long since I worked on this code that I forgot just about everything about how ASP.NET works.


text:
Q: Wishart distribution in pymc3 I am doing a Bayesian analysis with pymc3 (a graphic model with a lot of priors) as below:
import pymc3 as pm
import theano.tensor as T
with pm.Model() as smk:
    a_u = pm.InverseGamma('a_u',alpha=2*np.ones(L),beta=1/A_u**2,shape=L)
    sigma2_u =
    pm.InverseGamma('sigma2_u',alpha=2*np.ones(L),beta=1/a_u,shape=L)
    a_eps = pm.InverseGamma('a_eps',alpha=2,beta=1/A_eps**2)
    sigma2_eps = pm.InverseGamma('sigma2_eps',alpha=2,beta=1/a_eps)
    a_R = pm.InverseGamma('a_R',alpha=2,beta=1/A_R**2,shape=q)
    Sigma_R_inv = pm.distributions.multivariate.Wishart('Sigma_R_inv',nu=v+q-1,V=1/(2*v)*T.nlinalg.AllocDiag(a_R))
    Sigma_R = T.nlinalg.MatrixInverse(Sigma_R_inv)
    u_R = pm.distributions.multivariate.MvNormal('u_R',np.zeros(m*q),T.slinalg.kron(np.eye(m),Sigma_R))
    u_G = pm.distributions.multivariate.MvNormal('u_G',np.zeros(L),T.nlinalg.AllocDiag(sigma2_u))
    beta = pm.Normal('beta',mu=0,sd=sigma_beta,shape=p)
    y = pm.Normal('y',mu = T.dot(X,beta)+T.dot(Z_R,u_R)+T.dot(Z_G,u_G),sd=sigma_eps,observed=Y)
with smk:
    trace= pm.sample(10000)

Then it reports an error, "TypeError: object() takes no parameters" on this line,
Sigma_R_inv = pm.distributions.multivariate.Wishart('Sigma_R_inv',nu=v+q-1,V=1/(2*v)*T.nlinalg.AllocDiag(a_R))

I am wondering why, could someone help me out, thanks!


text:
Q: AngularJS CORS request custom header I'm having trouble getting CORS enabled on my server in combination with AngularJS. I'm using Angular 1.2.16 and this is my server config:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, Authorization"
Header set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"

I can use the following request:
$http.post(configuration.authUrl, {username: 'username', password: 'password'})
    .success(function (data) {
         $cookieStore.put(configuration.sessionName, {
             token: data.authenticationToken,
              user: data.user
         });
    })
    .error(function () {}));

since this request doesn't use a custom header.
When I afterwards try to request the following:
Balance.get() with Balance being:
angular.module('portalApp')
    .factory('Balance', ['$resource', 'Auth', 'configuration', function ($resource, Auth, configuration) {
        return $resource(configuration.balanceUrl, {}, {
            get: {
                method: 'GET',
                isArray: false,
                headers: {
                    Authorization: Auth.getAuthToken()
                }
            }
        });
    }]);

I get a 401 Unauthorized on the balanceUrl.
In the config I have put:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

I even tried putting $http.defaults.headers.common.Authorization = Auth.getAuthToken(); before the $resource in the Balance resource factory but that didn't help.
The headers being sent to the preflight OPTIONS request don't have the Authorization header, no matter what method I use. These are the request headers of the preflight OPTIONS request.
OPTIONS /api/v1.0/user/orders HTTP/1.1
Host: host
Connection: keep-alive
Cache-Control: no-cache
Access-Control-Request-Method: GET
Pragma: no-cache
Origin: origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: referer
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

Any suggestions?

A: As I know you can't use Access-Control-Allow-Origin "*" with Access-Control-Allow-Credentials "true".

A: After much research I found out the problem wasn't occurring because of the AngularJS or Apache configuration. It was a problem in the backend server app (Java). The urls were restricted for all HTTP methods, so when AngularJS wants to execute the preflight OPTIONS request, the access was denied and a 401 was returned.
This was fixed by doing:
if(!authenticationService.isTokenValid(glueToken) && !((HttpServletRequest)servletRequest).getMethod().equals(HttpMethod.OPTIONS.toString()) ){
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
  filterChain.doFilter(servletRequest, servletResponse);
}

In stead of:
if(!authenticationService.isTokenValid(glueToken)){
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
  filterChain.doFilter(servletRequest, servletResponse);
}

A: Why not anonymously (don't perform authentication or authorization) allow the options pre-flight request.
https://stackoverflow.com/a/21458845/101662

A: I'm using quite a different approach but the premise is still the same.
First try putting Bearer in front of your access token:
headers: {
    Authorization: 'Bearer ' + Auth.getAuthToken()
}

If not try this:
app.config may not work if you don't have app set up as a variable, so you may need to adjust.
app.config(
    function($httpProvider) {
        $httpProvider.defaults.headers.common = {};
        $httpProvider.defaults.headers.post = {};
        $httpProvider.defaults.headers.put = {};
        $httpProvider.defaults.headers.patch = {};

        $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + Auth.getAuthToken();
    }
);


text:
Q: How to measure the area of a polygon in ggplot2?
Hi everyone,
I have a number of samples that I would like to draw a polygon for each of them to illustrate the shape of the data. My data look likes this:
01 0.31707317

02 0.12195122

03 0.09756098

04 0.07317073

05 0.07317073

06 0.07317073

07 0.07317073

08 0.07317073

09 0.04878049

10 0.04878049

I can easily draw a radar chart using radarchart, which looks like this:
But I am trying to measure the area of the results shape and use that as a measure of data shape. This is where I struggle.
I tried to save the resulting figure as a vector and use the points there but it looks like I can not pass the chart into a vector. Then I tried rgdal package to exprt my figure as a shapefile and use the coordinates there:
coorddf <- SpatialPointsDataFrame(radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , pfcol=rgb(0.2,0.5,0.5, 0.2))
, data = radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , cglcol = "white", pfcol=rgb(0.2,0.5,0.5, 0.2))

writeOGR(coorddf, dsn = '.', layer = 'mypoints', driver = "ESRI Shapefile")

Which was not a good idea because my data does not have values that can be used as lat and long points..
Any suggestions?

A: To expand on @G5W's excellent point:
library(dplyr)
library(ggplot2)

df <- structure(
  list(
    V1 = 1:10,
    V2 = c(
      0.31707317,
      0.12195122,
      0.09756098,
      0.07317073,
      0.07317073,
      0.07317073,
      0.07317073,
      0.07317073,
      0.04878049,
      0.04878049
    )
  ),
  .Names = c("V1", "V2"),
  class = "data.frame",
  row.names = c(NA, -10L))

You can calculate each triangle from its neighbor to the right using dplyr::lead:
areas <- df %>%
  setNames(c("variable", "value")) %>%
  mutate(nextval = lead(value, default = value[1]),
         angle   = (1/10) * (2*pi),
                   # change 1/n to number of variables
         area    = value*nextval*sin(angle)/2)

   variable      value    nextval     angle         area
1         1 0.31707317 0.12195122 0.6283185 0.0113640813
2         2 0.12195122 0.09756098 0.6283185 0.0034966406
3         3 0.09756098 0.07317073 0.6283185 0.0020979843
4         4 0.07317073 0.07317073 0.6283185 0.0015734881
5         5 0.07317073 0.07317073 0.6283185 0.0015734881
6         6 0.07317073 0.07317073 0.6283185 0.0015734881
7         7 0.07317073 0.07317073 0.6283185 0.0015734881
8         8 0.07317073 0.04878049 0.6283185 0.0010489921
9         9 0.04878049 0.04878049 0.6283185 0.0006993281
10       10 0.04878049 0.31707317 0.6283185 0.0045456327

A couple things: notice that I used the default = value[1] to make sure that the NA that would be caused at the end to wrap around to using the first value instead. Also you need to use angles in radians, so that's just 1/n * 2pi. Now that we have all the triangle areas, we can add them:
areas %>% summarise(total = sum(area))

       total
1 0.02954661

This approach is easily extended to multiple groups to compare.
df <- expand.grid(var = 1:8, grp = c("a", "b")) %>%
  mutate(value = runif(length(var), 0.25, 1)) %>%
  group_by(grp) %>%
  mutate(nextval = lead(value, default = value[1]),
         angle = (1/8)*(2*pi),
         area = value*nextval*sin(angle)/2) %>%
  mutate(total = sum(area))

# A tibble: 16 x 7
# Groups:   grp [2]
     var    grp     value   nextval     angle       area     total
   <int> <fctr>     <dbl>     <dbl>     <dbl>      <dbl>     <dbl>
 1     1      a 0.3101167 0.6831233 0.7853982 0.07489956 0.5689067
 2     2      a 0.6831233 0.4166692 0.7853982 0.10063417 0.5689067
 3     3      a 0.4166692 0.4756976 0.7853982 0.07007730 0.5689067
 4     4      a 0.4756976 0.3426595 0.7853982 0.05763002 0.5689067
 5     5      a 0.3426595 0.3107870 0.7853982 0.03765135 0.5689067
 6     6      a 0.3107870 0.3001208 0.7853982 0.03297721 0.5689067
 7     7      a 0.3001208 0.9039894 0.7853982 0.09592115 0.5689067
 8     8      a 0.9039894 0.3101167 0.7853982 0.09911594 0.5689067
 9     1      b 0.9888119 0.3481213 0.7853982 0.12170243 1.1749789
10     2      b 0.3481213 0.8513316 0.7853982 0.10478143 1.1749789
11     3      b 0.8513316 0.9928401 0.7853982 0.29883611 1.1749789
12     4      b 0.9928401 0.6372992 0.7853982 0.22370605 1.1749789
13     5      b 0.6372992 0.8303906 0.7853982 0.18710303 1.1749789
14     6      b 0.8303906 0.3607232 0.7853982 0.10590379 1.1749789
15     7      b 0.3607232 0.2786354 0.7853982 0.03553575 1.1749789
16     8      b 0.2786354 0.9888119 0.7853982 0.09741033 1.1749789

df %>%
  ggplot(aes(var, value)) +
  geom_polygon() +
  geom_text(aes(0,0, label = round(total, 2)), color = "white") +
  facet_grid(~grp) +
  scale_y_continuous("", limits = c(0, 1), expand = c(0,0)) +
  scale_x_continuous("", breaks = 1:8, expand = c(0,0)) +
  theme_minimal() +
  coord_radar()

If you're doing a lot of these, it's worth looking at the ggradar package: http://www.ggplot2-exts.org/ggradar.html
Since I was just doing this one-off, I used a polar coordinate modification from Erwan Le Pennec:
http://www.cmap.polytechnique.fr/~lepennec/R/Radar/RadarAndParallelPlots.html
coord_radar <- function (theta = "x", start = 0, direction = 1)
{
  theta <- match.arg(theta, c("x", "y"))
  r <- if (theta == "x")
    "y"
  else "x"
  ggproto("CoordRadar", CoordPolar, theta = theta, r = r, start = start,
          direction = sign(direction),
          is_linear = function(coord) TRUE)
}

A: It is possible to solve for the area of your shape analytically.
The area is made up of a bunch of triangles. For example, the wedge
between V1 & V2 looks like this.

This is a side-angle-side problem so the area is v1*v2*sin(pi/5)/2. The area for the second wedge will be v2*v3*sin(pi/5)/2.  Just add up the triangles around the circle.


text:
Q: stop() method will be called when App crashes in CN1 I would like to close the threads or clear cache if the App crashes or Phone switch off or some other abrupt actions. Please advise if this method only gets called when the user kill the App or Signout from the App.

A: I'm pretty sure stop() gets called when you force kill the app, switch apps, lock the screen, phone auto locks, or anything really where the app is no longer visible.
You can also check edge cases by connecting your Android (in dev mode) to your laptop, downloading platform-tools (logcat), adding a print statement inside the stop() function and using the following command "./adb logcat -s "System.out" inside the platform-tools directory. Not sure how to do it on iOS.


text:
Q: Find the missing dollar Three friends eat at a restaurant and finally ask for the bill. They pay the 75 dollars by dividing it equally (so they spend 25 dollars per person.)
The waiter takes the money to the owner, who, in a generous mood, offers a 5 dollar discount. But the waiter turns out to be morally suspect, so he pockets 2 dollars and divides the 3 dollars amongst the three customers equally.
So, in conclusion, the cost to each customer was 24 dollars.
Therefore total customer cost is 24x3 or 72 dollars. The waiter kept 2 dollars, bringing the total to 74, so where is the last dollar?
I feel that some semantic trickery is at play here, but I can't find it...

A: It does not make much sense to add the $72\$$ and the $2\$$. Each customer paid $24\$$ ($=25-1$), so the waiter has $72\$$, two of which he pockets. The owner is left with $70\$$ for the food.

A: There's actually nothing strange in my opinion, the mistake is to assume 75 to be the cost. The cost indeed is $75-5+2 = 72$ which is $\$24$ per head.


text:
Q: how to mysql join for two tables I have two mysql tables:
table-1: advance
id advance_id vamount
1 101 10000
2 101 20000
3 101 10000

table-2: purchase
id advance_id item amount
1 101 Shirt 500
2 101 Pant 700
3 101 Pen 500
4 101 Shoe 1000

What I want to do, sum of vamount against each advance_id from table-1 and purchase information from table-2 against same advance_id. While trying by the following query:
SELECT sum(a.vamount) as vamount, p.item, p.amount FROM advance as a INNER JOIN purchase as p ON a.advance_id=p.advance_id WHERE p.advance_id=101

I want to fetch the result in this way:
Total Advance Amount: 40000
item amount balance
shirt 500 39500
pant 700 38800
pen 500 38300
shoe 1000 37300

but it is returning one one row in result set.
How to do it in right way?

A: Try:
SELECT p.item, sum(a.vamount) as vamount, p.amount FROM advance as a INNER JOIN purchase as p ON a.advance_id=p.advance_id WHERE p.advance_id=101
group by p.item

A: You query should like this
SELECT sum(a.vamount) as vamount
    , p.item
    , p.amount
FROM advance as a
INNER JOIN purchase as p ON a.advance_id = p.advance_id
WHERE p.advance_id=101
GROUP BY p.item
    , p.amount

Use GROUP BY clause  and optional you can remove WHERE clause for group all items


text:
Q: how to group_by a query by date and sum 2 others fields My model looks like this :
class PostMetric(models.Model):
    likes = models.IntegerField()
    comments = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)

I would like to get the sum of likes and comments for each day (note that i need to transform the datetimefield to datefield (probably using Cast?):
   date       engagement (likes+comments)
 2/5/2017         26
 3/5/2017         29

I tried to use : Cast, annotate, aggregate and even rawsql and extra/select functions but with no success.
I think that i need to add an aggregation based to this query :
PostMetric.annotate(engagement=Sum('likes') + Sum('comments')).annotate(date_only=Cast('created_at', DateField()))

A: If you want to emulate a group_by query then you can use the .values method.
PostMetric.objects.values('created_at').annotate(engagement=Count('likes')+Count('comments')


text:
Q: Get computer names from a security group I'm trying to get the names of computers that I have added to a security group.
The searchbase is: CN=Desktops,OU=Business,OU=Hosting,DC=AA,DC=BB,DC=com.
I don't know if I should use Get-ADComputer or Get-ADUser or Get-ADGroupMember.
The computers are added like members of a security group.
How can I get the names of the computers?
Best Regards,
Dimo

A: Well, I figure how to do it. Here is the solution:
get-adgroupmember -Identity "CN=Desktops,OU=Business,OU=Hosting,DC=AA,DC=BB,DC=com"

It wasn't working because I was using -Partition instead of -Identity.


text:
Q: AngularJS loop show the same image In my project I need to show for each element its image.
This is my html:

            <immagine-profilo hashid="@{{ event.created_by.hashid }}"
                              username="@{{ event.created_by.profile.username }}"
                              photo="@{{ event.created_by.profile.photo }}"></immagine-profilo>

            <rating class="user-experience" stars="@{{ event.created_by.level }}"
                    icon="star"></rating>

            @{{ event.unix_date | formatDate }} | @{{ event.time_start }}

                <rating class="difficulty-bar" stars="@{{ event.difficulty_level }}"
                        icon="circle"></rating>

                                    {{ trans('frontend/events/events.strings.difficulty') }}

                    @{{ event.participants_count }}

                {{ trans('frontend/events/events.strings.participants') }}

        {{ trans('frontend/pages/place.sidebar.links.read_more') }}

the image code is this:

and this is the filter:
app.filter('addFullPathToIcon', function () {
    return function (text) {
        return window.paths.categoriesPath + "/" + text;
    }
});

When I run the code, the same image is shown for each event, if I click on one of it, the images will change and show the second image for every event.
Someone can help me to see the error?

A: It looks to me like there's only one "selectedEvent", and it is defined on ng-mouseenter. Perhaps you want

instead inside your ng-repeat if you don't want all the images to change with the event that is selected...


text:
Q: Java generics and inheritence confusion In Kathy Sierra's book on SCJP we learn that, When we write
List <A> list = new ArrayList <A> ();

This means that this list will accept elements of type A only, not it's subtype or supertype, only type A. Then I came across this example
import java.util.*;

interface A {
    public void a();
}
class B implements A {
    public void a() { }
    public void b() { }
}

class C extends B {
    public void a() { }
}

class D extends C {

}

public class Generics {
    public static void main() {
        List <B> lst = new ArrayList <B> ();
        lst.add(new B());
        lst.add(new C());
        lst.add(new D());
    }
}

Here a list has been declared with B as it's bound type. But it looks like it's accepting objects of it's subtype also. Why is it so? And if it is possible then is this declaration available in java
List <? extends B> list = new ArrayList <B> ();

Now with this notation we tell compiler that any type which extends B is allowed to enter this list. Please help, I am really confused

A: There's a distinct between the types permitted in a collection, and the declared type of the collection itself. For
List <A> list = new ArrayList <A> ();

it's declaring a list of elements. Each element is-a A. Each element can be a subclass of A, but the list itself is viewed as a list of As.
Note the distinction. A banana is-a fruit. But a collection of bananas is not a collection of fruit (counterintuitively). Otherwise you could take that collection of bananas, view it as a collection of fruit, and add an apple.
List <? extends B> list = new ArrayList <B> ();

means that the list can be a list of B, or a list of subtype of B. e.g. the below are all valid:
List <? extends B> list = new ArrayList <B> ();
List <? extends B> list = new ArrayList <C> ();
List <? extends B> list = new ArrayList <D> ();

A: The problem in teaching generics with the List examples is that one can understand the examples and still not the rule.
With the advent of generics, the compiler hasn't been instructed with human knowlege, so it doesn't know that a List<A> is an ordered sequence of elements (it could be a proboscidean with long, curved tusks), and thus it can't guarantee that a List will accept elements of type A only. All the compiler knows is supplied by the following definition
interface List<E> {
  public void add(E);
  public E get(int index);
}

This code does not define a single type: it defines an infinite series of types:
interface ListOfStrings {
  public void add(String s);
  public String get(int index);
}

interface ListOfShapes {
  public void add(Shape e);
  public Shape get(int index);
}

depending on how you instantiate the parameterized type. Since in Java each subtype is a valid replacement for its supertypes, a Rectangle is a legal argument to a List<Shape>'s add(Shape s).
Here is when one thinks "Generics, I finally got you!". Then he fires an IDE, types
List<Shape> shapes = new LinkedList<Rectangle>();

and the compiler refuses to compile. "- What's going on here? I can add a rect to a list of shapes, but a list of rects is not a list of shapes?". The problem is one thinks in terms of lists, shapes and rectangles, but the compiler doesn't know any of these. It sees
T reference = <expression returning type S>

so it wonders "- Is S a valid replacement for type T?". Phrased differently, is T a parent of S in the type hierarchy, as constructed according to the Java rules? So it carefully checks its old Java book and finds that no, X<A>is not a X<B> parent. Illegal code. Stop.
"- But a list of rectangles definitely contains shapes! I just compiled a program which added a bunch of rectangles to a List<Shape>!". This doesn't mean anything to a compiler, it's not such a smart program - you see... It can only interpret those few rules it learned some years ago and can't even tell the difference between a List and a Mammoth. It only knows its old Java book, and in the book is clearly stated and remarked that there is no subtyping relation between X<A> and X<B>, no matter how A and B relate to each other. "- If only generics were implemented like arrays... You, stupid Java people..." In fact:
String[] strings = new String[10];
Object[] objects = strings;
objects[0] = new Rectangle(); // ArrayStoreException at runtime

Maybe you now got the point. After all, those Java people are not so stupid... At least, those fancy rules they chosen for their type system serve a purpose, at least they did it for a practical reason. They made arrays covariant, but generics invariant. Since both arrays and lists' contents can be changed (they are mutable), this exposes arrays (but not lists) to the problem seen above. For example, Scala achieves type safety by making lists covariant but immutable (a List[Integer] can be assigned to a List[Number], but they're read-only) and arrays mutable but invariant (you can't use an Array[Integer] where an Array[Number] is required, but you can modify their contents).
Finally, to port the subtyping relation between A and B into the generics world, one can use the wildcard ?, but that's matter for a whole new story. I just anticipate that in the old Java book is written that List<Rectangle> does not extends List<Shape>, but it's a legitimate child of List<? extends Shape>.

A: "This means that this list will accept elements of type A only, not it's subtype or supertype, only type A. Then I came across this example"
This is wrong - it will accept any derived types. Also Java generics is implemented in the compiler using erasure.
It is the same as having a method parameter that takes B, it should accept B, C and D.
Also note that at runtime because of erasure there is no type checking so:
List <B> lst = new ArrayList <B> ();

Becomes
List <object> lst = new ArrayList <object> ();

This might help you:
http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html

A: "This means that this list will accept elements of type A only, not it's subtype or supertype, only type A" - This is incorrect. I can rewrite your code as follows:
List <A> list = new ArrayList <A> ();
B b = new B();
B c = new C();
B d = new D();
list.add(b);
list.add(c);
list.add(d);

variable b, c and d are all of type 'B' when we are assigning them to instance of B, C and D. Polymorphism?
If you see, B, C and D implements A and hence I can assign instances of B, C, D to A.


text:
Q: How to update data as null in mysql using php loop? I have a table named users with a column called user_subs. It looks like this.

In user_subs I have stored the specific users session username. Lets say this specific users name is James.
Now how would I loop through a specific user_subs looking for "James" and remove him from that specific user_subs without removing all the other names.
This is what I have so far and the only problem is, its deleting all the usernames in user_subs instead of just "James".
if(isset($_GET['p_id'])) {
  $the_post_id = $_GET['p_id'];
  $the_post_author = $_GET['author'];
}

if(isset($_POST['delete_sub'])) {
  $username = $_SESSION['username'];

  $query = "SELECT user_subs FROM users WHERE username = '{$username}' ";
  $select_users_by_id = mysqli_query($connection, $query);

  while ($row = mysqli_fetch_array($select_users_by_id)) {
    $user_subs = explode(',', $row['user_subs']);

    foreach($user_subs as $out) {

      $query = "UPDATE users SET user_subs = null WHERE username = '{$the_post_author}' ";

       $unsubscribe_user = mysqli_query($connection, $query);

       echo "Unsubscribed";
    }
  }
}

THIS IS JUST IN TEST, PREPARED STATEMENTS WILL BE USED BEFORE GOING LIVE
Thank you for your time.

A: I second the other user's comment about moving this column to a different table. In the meanwhile, if you want to achieve what you are asking for, you can try removing the user name from the column value and update it with the remaining text.
if(isset($_POST['delete_sub'])) {
  $username = $_SESSION['username'];

  $query = "SELECT user_subs FROM users WHERE username = '{$username}' ";
  $select_users_by_id = mysqli_query($connection, $query);

  while ($row = mysqli_fetch_array($select_users_by_id)) {
    $user_subs = str_replace($username . ',', '', $row['user_subs']);

$query = "UPDATE users SET user_subs = '{$user_subs}' WHERE username = '{$the_post_author}' ";

       $unsubscribe_user = mysqli_query($connection, $query);
       echo "Unsubscribed";

  }
}

OPTION-2
$user_subs = explode(',', $row['user_subs']);
$user_subs_new = [];
foreach($user_subs as $out) {
    if ($out !== $username) {
        $user_subs_new[] = $out;
    }
}
$user_subs = implode(',',user_subs_new);
  $query = "UPDATE users SET user_subs = '{$user_subs}' WHERE username = '{$username}' ";

   $unsubscribe_user = mysqli_query($connection, $query);

   echo "Unsubscribed";
}

A: Let's start over. Let's start here, in fact...
DROP TABLE IF EXISTS users;

CREATE TABLE users
(user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,email VARCHAR(20) NOT NULL UNIQUE
);

DROP TABLE IF EXISTS user_subs;

CREATE TABLE user_subs
(user_id INT NOT NULL
, sub_id INT NOT NULL
, active TINYINT NOT NULL DEFAULT 1
, PRIMARY KEY(user_id,sub_id)
);

INSERT INTO users VALUES
(1,'b.smyth634@gmail.com'),
(2,'james@gmail.com'),
(3,'f@gmail.com'),
(4,'sally@gmail.com'),
(5,'thomas@gmail.com');

INSERT INTO user_subs (user_id,sub_id) VALUES
(1,5),
(1,2),
(1,1),
(1,4),
(2,1),
(2,2),
(2,4);

SELECT * FROM users;
+---------+----------------------+
| user_id | email                |
+---------+----------------------+
|       1 | b.smyth634@gmail.com |
|       2 | james@gmail.com      |
|       3 | f@gmail.com          |
|       4 | sally@gmail.com      |
|       5 | thomas@gmail.com     |
+---------+----------------------+

SELECT * FROM user_subs;
+---------+--------+--------+
| user_id | sub_id | active |
+---------+--------+--------+
|       1 |      5 |      1 |
|       1 |      2 |      1 |
|       1 |      1 |      1 |
|       1 |      4 |      1 |
|       2 |      1 |      1 |
|       2 |      2 |      1 |
|       2 |      4 |      1 |
+---------+--------+--------+

SELECT u.*
     , GROUP_CONCAT(us.sub_id) subs
  FROM users u
  JOIN user_subs us
    ON us.user_id = u.user_id
 GROUP
    BY u.user_id;
+---------+----------------------+---------+
| user_id | email                | subs    |
+---------+----------------------+---------+
|       1 | b.smyth634@gmail.com | 1,2,4,5 |
|       2 | james@gmail.com      | 1,2,4   |
+---------+----------------------+---------+

From here we have a choice. We can either DELETE subs we no longer wish to consider, or simply UPDATE them as 'inactive'.
Either way, we just need a DELETE or an UPDATE. So no SELECT needed. In fact a SELECT would, as I mentioned, be counterproductive - because a user may modify the data set in between the execution of the SELECT and the execution of the UPDATE/DELETE. This is known as a 'race condition'.


text:
Q: Accept a pop up dialog in ios using appium without having the appium driver instance I use java to run an appium test, and there is an issue with a pop up notification dialog that appears before I have the instance of the appium driver.
Because of that I am not able to press the accept button.
I read here that I should use:
capabilities.setCapability("autoAcceptAlerts",true)
this also not working.
Any idea how can I solve this issue?
thanks

A: The issue resolved after adding Thread.sleep(10000) right after I get the instance of the Appium driver.