text:
Q: how to record/stream multiple audio output from a single input? This is the command I am currently using to stream live audio under the Raspbian distro:
ffmpeg -f alsa -ac 1 -i hw:1 -ar 44100 -f flv rtmp://10.255.11.53/

The functionality I am looking for is called the "Tee" command, which I will use to record the stream as an mp3 file while it is streaming live.
Is there any hope of getting this functionality from the Raspbian repository?  Or is there an different command which does the same thing?

A: Unless putting this all in a single command is absolutely vital, I would say that changing the entire OS to a less stable one for this one purpose is probably overkill. I would just use one of the alternative commands on the page you linked to in the question:
ffmpeg -f alsa -ac 1 -i hw:1 -ar 44100 -c:a libmp3lame -f mpegts - | \
ffmpeg -f mpegts -i - -c copy output.mp3 -c copy -f flv rtmp://10.255.11.53/

Even on a Raspberry Pi, I doubt that the minor extra overhead of the extra ffmpeg process will be too much - especially since -c copy takes a tiny amount of processing.
Depending on how old your ffmpeg is, you may have to use -acodec copy instead of -c copy.
Also, you can get an up-to-date static build of ffmpeg from here; I know that Raspbian is based off of Debian, so maybe the Debian repos listed there could be handy?


text:
Q: Как вывести данные $_POST в php Отправляю аяксом POST формы
$('#_formOrder').on('submit', function(e){
            e.preventDefault();
            let $form = $(this);
            let $order = $form.serialize()
            $.ajax({
                method: 'POST',
                url: "/assets/ajax.php",
                dataType: "json",
                data: {
                   "action": "order",
                    "order" : $order
                },
                success: function(data) {

                },
                error: function(data) { // Данные не отправлены

                }
              });
        });

уходят вот так данные

как вывести данные order?
пробовал так,
$product = $_POST['order']['username'];
print_r($product);

но не работает

A: Вы отправляете два параметра, action и order. Чтобы увидеть, что получает сервер, напишем функцию вывода этих полученных данных:
<?php
    $action = $_POST['order'];
    $order = $_POST['order'];
    echo "Action: ".$action."
";
    echo "Order: ".$order."
";
?>

Аргументируйте минус? Вопрос был в том, как вывести данные переданные методом POST, ответ я дал. Вопрос заключался не в том, как правильно передавать данные, а в том как их вывести..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error creating UI component in react-native I'm trying to create a react-native UI component with google Ad Exchange (AdX).
However when the application is rendered no ads is displayed, when checking the android logcat I noticed the following message:

W/unknown:ViewManagerPropertyUpdater(21182): Could not find generated
  setter for class com.adx.AdxViewManager

Does anyone have any idea where I'm going wrong?
For ease of understanding I put my code below how I am trying to develop this component.
MainApplication.java
package com.adx;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new AdxPackage()
      );
    }
  };

AdxPackage.java
package com.adx;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.Collections;
import java.util.List;

public class AdxPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.<ViewManager>singletonList(
                new AdxViewManager()
        );
    }
}

AdxViewManager.java
package com.adx;

import android.util.Log;

import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class AdxViewManager extends SimpleViewManager<AdView> {

    public static final String REACT_CLASS = "AdxBanner";

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected AdView createViewInstance(ThemedReactContext reactContext) {
        AdView adView = new AdView(reactContext);
        return adView;
    }

    @ReactProp(name = "adUnit")
    public void setAdUnit(AdView adView, String adUnit) {
        adView.setAdUnitId(adUnit);
    }

    @ReactProp(name = "size")
    public void setSize(AdView adView, String size) {

        Log.d(size, "setSize: ");

        adView.setAdSize(AdSize.BANNER);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);

        Log.d("Adx", "createViewInstance: OK");
    }
}

AdxBanner.js
import React from "react";
import PropTypes from "prop-types";
import { requireNativeComponent, View } from 'react-native';

var iface = { name: 'AdxBanner'}.propTypes =  { ...View.propTypes }

module.exports = requireNativeComponent('AdxBanner', iface);

index.android.js
import React, { Component } from 'react';
import AdxBanner from "./AdxBanner";
import { AppRegistry, StyleSheet, Text, View } from 'react-native';

export default class Adx extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <AdxBanner
           size="BANNER"
           adUnit="ca-app-pub-3940256099942544/6300978111"
           style={{height: 400, width: 400}}
         />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('Adx', () => Adx);


text:
Q: Occupation where the person receives the punishment for upper class kids I've read it somewhere but I don't remember it, it was apparently very popular during medieval times especially for the wealthy. The people that are taking the punishment are usually kids.
What was this occupation called?

A: It wasn't an occupation so much as slavery/oppression, but the term is whipping boy.

A whipping boy was a boy educated alongside a prince (or boy monarch)
in early modern Europe, who received corporal punishment for the
prince's transgressions in his presence. The prince was not punished
himself because his royal status exceeded that of his tutor; seeing a
friend punished would provide an equivalent motivation not to repeat
the offence.

[Wikipedia]
Apart from historic reference, the term is now only encountered in the metaphorical usage (anyone blamed / punished for the misdemeanours or incompetence of others).


text:
Q: python3 running old version of script I've changed a script by commenting out a section and adding some print statements above it for testing purposes, the problem is when I run the script from any other directory than the one it's in, python is running the old version of the script.
Clearing __pycache__ had no effect.
Here's the python script in question:
import discord
import watson
import configparser
import os
from discord.ext.commands import Bot
from getpass import getuser

print("WHY ISN'T THIS BEING CALLED!!")

#print(os.getcwd())
#os.chdir("/home/{}/discordBotStaging".format(getuser()))
#print(os.getcwd())

#if(not os.path.isfile("./config.ini")):
#    print("No config file found, make sure you have one in the same directory as this python script\nexiting")
#    quit()

config = configparser.ConfigParser()
config.read("./config.ini")

TOKEN = config["DEFAULT"]["DISCORD_KEY"]
BOT_PREFIX = ("!", "$")

client = Bot(command_prefix=BOT_PREFIX)

@client.command(name="memealyze",
        description="When uploading image include command \"!memealyze\" | \"!Memealyze\" | \"!MemeAlyze\" | \"!ma\" as a comment",
        brief="Neural network put to good use",
        aliases=["Memealyze", "MemeAlyze", "ma"],
        pass_context=True)

async def GetMemeContents(context):
    await client.say("Sending image to the mothership, hold tight.")

    if(not context.message.attachments):
        await client.say(
                "Couldn't find image attachement. Make sure you include \"!memealyze\" or any of it's variants as a comment when submitting an image")
        return

    imageUrl = str(context.message.attachments[0]["url"])
    messageContent = ""
    resultDict = watson.ReturnWatsonResults(imageUrl)

    for key,val in resultDict.items():
        messageContent += "{} : {}%\n".format(key, val)

    await client.say("Done, the boys at IBM said they found this:\n" + messageContent)

client.run(TOKEN)

And here's the issue:
yugnut@RyzenBuild:~$ python3 discordBotStaging/main.py
No config file found, make sure you have one in the same directory as this python script
exiting
yugnut@RyzenBuild:~$

yugnut@RyzenBuild:~/discordBotStaging$ python3 main.py
WHY ISN'T THIS BEING CALLED!!
^Cyugnut@RyzenBuild:~/discordBotStaging$

EDITS:
@ShadowRanger suggestions:

Try moving the print above all the imports in your script.

This yields promising results, I do get output by trying this but right after that I still run into the same issue

You can't use relative paths like that if the config file is expected to be in the same directory as the script; you have to do config.read(os.path.join(os.path.dirname(__file__), 'config.ini'))

I think my ignorance is showing :^), I changed this in my script as well
After making these edits along with trying to run the script after commenting out my import configparser line I still get the same error.


text:
Q: SQL Order By with column, which has numbers and Letters separately The data looks like this when I do an ORDER BY in SQL.
ColumnName
----------
1
100
10000
25
30
33
7000
ABC
XZY

I want the order by to work like this.
ColumnName
----------
10000
7000
100
33
30
25
1
ABC
XYZ

First order by the numeric value and then by the letters.

A: Using this solution:
SELECT someColum as sort, someColumn, otherColums...
WHERE someOther = 'somevalue'
ORDER BY sort ASC, (someColumn +0) ASC

A: Solution for SQL-Server.
You can use CASE. When values are numeric convert it to INT and order by - descending, otherwise if values are not numeric, order by - ascending.
QUERY
SELECT ColumnName
FROM tbl
ORDER BY CASE WHEN ISNUMERIC(ColumnName) = 1 THEN CAST(ColumnName AS INT) END DESC,
         CASE WHEN ISNUMERIC(ColumnName) = 0 THEN col END ASC

Note: you have to convert numeric values to datatype INT to achieve correct order. If you try to order numeric values stored as varchar you will get incorrect results. For example:
If we use descending order then '10000' will go after '7000', that because first symbol 1 of '10000' is lower then 7 of '7000' varchar value. So It will be:
7000
10000

DEMO
You can test It at SQL FIDDLE

A: You can achieve this by following SQL query:
SELECT ColumnName
FROM tbl
ORDER BY CAST(ColumnName as UNSIGNED) DESC, ColumnName ASC;


text:
Q: Updating single attribute in json column triggers a full column update I'm wondering if this is a bug or normal rails behavior. I'm on 5.2.3
I have a JSON type column on my PostgreSQL db, that looks like this
id | name | address(json)
1  | josh | { line1: nil, line2: nil, city: nil }

If i do:
@account = Account.find(1)
@account.address['city'] = "new york"
@account.save

This updates the entire column by re-writing the entire json and every attribute. I imagine this could introduce race conditions in certain use cases, outside of just an address getting updated.
 UPDATE "accounts" SET "address" = $1, "updated_at" = $2 WHERE "accounts"."id" = $3  [["address", "{'is_foreign':false,'line1':'54 Lemon Ave",'line2':null,'city':'new york','state':'NY','country':'US'}"], ["updated_at", "2019-11-15 18:09:07.698093"], ["id", 2]]

A: It looks like a normal behavior, try this instead it should work
@account = Account.find(1)
address_json = @account.address
address_json['city'] = 'new york'
@account.address = address_json
@account.save

Hope that helps!
More helpful info here - How to perform update operations on columns of type JSONB in Postgres 9.4


text:
Q: spring batch 3. File conversion
Need to read multiple txt files and generate multiple csv files,
  I want to read multiple txt files such that i can select some columns from one txt file and some from >other.My txt file is pipe seperated.
  i am able to read a single txt file and generate multiple csv files
  Thanks in advance.

<!-- ItemReader reads a complete line one by one from input file -->
<bean id="flatFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader"  scope="step">
    <property name="resource" value="classpath:student.txt" />

    <property name="lineMapper">
        <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
            <property name="fieldSetMapper">
                <!-- Mapper which maps each individual items in a record to properties in POJO -->
                <bean class="com.springbatch.ExamResultFieldSetMapper" />
            </property>

            <property name="lineTokenizer">
                <!-- A tokenizer class to be used when items in input record are separated by specific characters -->
                <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                    <property name="delimiter" value="|" />
                </bean>
            </property>
        </bean>
    </property>
</bean>
<!-- CSV ItemWriter which writes the data in CSV format -->
<bean id="CSVWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
    <property name="resource" value="file:output/examResultcsv1.csv"></property>
    <property name="shouldDeleteIfExists" value="true"></property>

    <property name="lineAggregator">
        <bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
            <property name="delimiter" value=","></property>

            <property name="fieldExtractor">
                  <bean
                    class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
                    <property name="names" value="studentName, percentage" />
                   </bean>
            </property>
        </bean>
    </property>
</bean>


text:
Q: How to adapt current code to run without using a form? How would I adapt this code to run without using the form, but the prompt() method instead? By including a prompt instead of a form to ask for user input.

        <title>Login page</title>

Simple Login Page

        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>

Thanks!


text:
Q: How do I check if I have a data that fits a parameter through a macro I want to check if I have a data that fits the month and year the user inputed my macro so I could know to which query to go, how do I do that?
my code so far:
Sub macro1()
    Dim year As Integer
    Dim month As Integer
    year = InputBox("What year would you want to get data from?")
    month = InputBox("What month would you want to get data from")
End Sub

A: You can use DLookup:
Dim DataExists As Boolean

If Not IsNull(DLookup("[SomeField]", "[YourTable]", "DateDiff('m', [YourDateField], DateSerial(" & year & ", " & month & ", 1)) = 0") Then
    DataExists = True
End If


text:
Q: MySQL join with null values I have the following query:
SELECT
    A.player, A.score, B.kills, C.deaths, D.killed AS most_killed, D.kills AS most_killed_count, E.player AS most_killed_by, E.kills AS most_killed_by_count
FROM
(SELECT player, score FROM pvpr_scores WHERE player = 'Neutronix' AND milestone = 'default') AS A
LEFT JOIN (SELECT player, COUNT(*) AS kills FROM pvpr_kills WHERE player = 'Neutronix' AND milestone = 'default') AS B ON B.player= A.player
LEFT JOIN (SELECT killed, COUNT(*) AS deaths FROM pvpr_kills WHERE killed = 'Neutronix' AND milestone = 'default') AS C ON C.killed= A.player
LEFT JOIN (SELECT player, killed, COUNT(*) AS kills FROM pvpr_kills WHERE player = 'Neutronix' GROUP BY killed ORDER BY kills DESC LIMIT 1) AS D ON D.player= A.player
LEFT JOIN (SELECT player, killed, COUNT(*) AS kills FROM pvpr_kills WHERE killed = 'Neutronix' GROUP BY player ORDER BY kills DESC LIMIT 1) AS E ON E.killed= A.player

However, if one of these subqueries return null, the entire query fails. I would like to have the null queries instead make those columns null in the returned result set (1 row).
If I changed Neutronix to something not in the database, like dfdsjf, there is an error.
EDIT: Here's the fix I did.
SELECT
    A.player, A.score, B.kills, C.deaths, D.killed AS most_killed, D.kills AS most_killed_count, E.player AS most_killed_by, E.kills AS most_killed_by_count
FROM
(SELECT player, score FROM pvpr_scores WHERE player = 'Gutterknife' AND milestone = 'default') AS A
LEFT OUTER JOIN (SELECT COUNT(*) AS kills FROM pvpr_kills WHERE player = 'Gutterknife' AND milestone = 'default') AS B ON TRUE
LEFT OUTER JOIN (SELECT COUNT(*) AS deaths FROM pvpr_kills WHERE killed = 'Gutterknife' AND milestone = 'default') AS C ON TRUE
LEFT OUTER JOIN (SELECT killed, COUNT(*) AS kills FROM pvpr_kills WHERE player = 'Gutterknife' GROUP BY killed ORDER BY kills DESC LIMIT 1) AS D ON TRUE
LEFT OUTER JOIN (SELECT player, COUNT(*) AS kills FROM pvpr_kills WHERE killed = 'Gutterknife' GROUP BY player ORDER BY kills DESC LIMIT 1) AS E ON TRUE

A: I don't think the problem is the subqueries.  I think the problem is the driver query:
FROM (SELECT player, score
      FROM pvpr_scores
      WHERE player = 'Neutronix' AND milestone = 'default'
     ) AS A . . .

If nothing matches this query, then the there are no rows to match in the other queries.
I'm not quite sure how to fix this.  I suppose you could do something like this:
FROM (select 'Neutronix' as player) t left outer join
     (SELECT player, score
      FROM pvpr_scores
      WHERE player = 'Neutronix' AND milestone = 'default'
     ) AS A
     on t.player = a.player left outer join . . .

And then change the join conditions in the rest of the from clause to t. instead of a..

A: Why are you running a sub select on the FROM - you could just a straight FROM scores.
You can also have multiple conditions on the 'ON' clause - e.g. ON b.player = a.player and b.milestone = a.milestone.
Rather than sub-selects you can use SUM and IF combined to give you the results - e.g. SUM( IF( row not null, 1, 0)) - this essentially sums 1's and 0's.
Obviously this isn't tested, but I'd approach your query along the lines of:
SELECT scores.player,
        scores.score,
        sum(if(kills.player is not null, 1, 0) as kills,
        sum(if(deaths.player is not null, 1, 0) as deaths
        killed.kills as most_killed,
        killed.killed as most_killed_count,
        killed_by.kills as most_killed_by_count,
        killed_by.killed as most_killed_by
FROM pvpr_scores as scores
LEFT JOIN pvpr_kills as kills
    on kills.player = player
    and kills.milestone = scores.milestone
LEFT JOIN pvpr_deaths as deaths
    on deaths.player = player
    and deaths.milestone = scores.milestone
LEFT JOIN (SELECT killed, player, count(killed) as kills
            FROM kills
            GROUP BY killed, player
            HAVING MAX( count(killed) ) ) as killed
    ON killed.player = scores.player
LEFT JOIN (SELECT killed, player, count(player) as kills
            FROM kills
            GROUP BY player, killed
            HAVING MAX( count(player) ) ) as killed_by
    ON killed_by.killed = scores.player

WHERE scores.player = 'neutronix'
  AND scores.milestone = 'default'

   GROUP BY scores.player


text:
Q: Multiplication of extreme vector This question might be elementary and standard.
Standard Notions: Let $g$ be a semisimple Lie algebra. Let $\pi=({\alpha_{1},....\alpha_{n}})$
be simple roots
$P^{+}(\pi)=\Sigma\mathbb{N}\alpha _{i}$
Suppose $\lambda,\nu\in P^{+}(\pi)$ and $e_{w\lambda}, e_{w\nu}$ are extreme vector.  ($\lambda,\nu$ are highest weight and $w\in W$, Weyl group).
Claim 1:  $e_{w\lambda}\otimes e_{w\nu}$ is an extreme vector of weight vector $e_{w(\lambda+\nu)}$.(This has been done, easily follows from the definition of tensor products of representations)
Claim 2: $e_{w\lambda}\otimes e_{w\nu}=A^{*}e_{w(\lambda+\nu)}$, where $A^{*}$ is multiplicative set of invertible elements
There is a paper by A.Joseph talking about this observation. He claimed that it follows from Weyl Character formula. I think he might talk about the decomposition of tensor product of irreducible representations. However, I can not find a proof.
Any comments are welcome.
Edit: The paper I talked about is "Faithfully flat embeddings for minimal primitive quotients of quantized enveloping algebras" by Anthony Joseph. There is another paper by A.Rosenberg and V.Lunts on "localization for quantum group" page 138
Section 2: Ore localization of rings $R_{A}$. They claimed
$e_{w\lambda}\otimes e_{w\nu}=A^{*}e_{w(\lambda+\nu)}$, where $A^{*}$ is multiplicative set of invertible elements by using Weyl character formula,but how?

A: If $e_\lambda$ and $e_\nu$ are highest weight vectors, of their respective representations, then $e_\lambda \otimes e_\nu$ is a highest weight vector in the tensor product: being a highest weight vector just means that it's an eigenvector for our fixed Borel subalgebra, which remains true using the action of a Lie algebra on a tensor product of representations. Applying $w$, we see that $e_{w\lambda} \otimes e_{w\nu}$ is an extreme vector.

A: Maybe I understand what the basic question is, after looking at the two papers mentioned:
MR1261902 (94m:17013) 17B37 (17B35)
Joseph, Anthony (F-PARIS6-F),
Faithfully flat embeddings for minimal primitive quotients of quantized enveloping algebras.
Quantum deformations of algebras and their representations (Ramat-Gan, 1991/1992; Rehovot,
1991/1992), 79–106, Israel Math. Conf. Proc., 7, Bar-Ilan Univ., Ramat Gan, 1993.
MR1694897 (2001f:17028) 17B37 (16S32 22E47)
Lunts,V. A. (1-IN); Rosenberg, A. L. [Rosenberg, Alexander L.] (D-MPI),
Localization for quantum groups.
Selecta Math. (N.S.) 5 (1999), no. 1, 123–159.
Fortunately I have the conference volume containing Joseph's paper and can get the other paper online via the library Springer subscription.
Both papers discuss how to pass from classical results on localization and such to quantized enveloping algebras (not easy to do), but I think the immediate issue just concerns the classical theory of finite dimnsional representations of a semisimple Lie algebra.    Here each simple module $E(\lambda)$ has a unique highest weight
vector $e_\lambda$ up to scalars (with French espace $E$ instead of English vector space $V$).   When tensoring two such modules $E(\lambda) \otimes E(\mu)$, a summand $E(\lambda +\mu)$ occurs uniquely and involves
the highest weight of the tensor product.   By taking the direct sum of all simple modules, one gets a transparent description of the representation ring due to complete reducibility.    To get a unique choice of highest weight vector $e_\lambda$ for each dominant integral weight, it is enough here to specify arbitrary choices for the fundamental weights and then tensor systematically.
In Joseph's 2.2 the wording may be misleading.    He comments parenthetically
that the analogous simple modules for the quantized enveloping algebra also
satisfy the Weyl character formula.   But this is unrelated to the following
line "Consequently ..."   (Joseph's papers are interesting but not always easy to read in detail.)


text:
Q: Need help creating analog world clock widget for Android I have to create an android world clock widget. It should show the selected country's time as an analog clock widget.
But I don't know how to update the time in the widget view.
I tried using the widget configuration activity. But it was not successful. Please give me some ideas for doing it
My widget.xml file contains the following:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:id="@+id/Widget"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_margin="8dip"
  android:background="@drawable/myshape" >
<AnalogClock android:id="@+id/AnalogClock"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:dial="@drawable/widgetdial"
 android:hand_hour="@drawable/widgethour"
 android:hand_minute="@drawable/widgetminute"/>
</LinearLayout>

A: You can look at my code on bitbucket: https://bitbucket.org/EmilYo/another_clock_widget
It's a digital clock widget for android (https://market.android.com/details?id=com.omgbutton.anotherclockwidget).


text:
Q: Winston: The error instance is not an error instance anymore I give an instance of Error into the logger:
console.log(error instanceof Error) // This shows true
logger.error(error)

But inside errors.js of the logform library einfo is not an instance of Error:
module.exports = format((einfo, { stack }) => {
  console.log(einfo instanceof Error) // This shows false
  if (einfo instanceof Error) {
  ...

I am not sure at what point the inserted Object becomes not an Error instance, but it prevents me from getting an error stack, even when there is one.
SyntaxError: Unexpected token T in JSON at position 0
    at JSON.parse (<anonymous>)
    ...

My transports settings:
new transports.DailyRotateFile({
    level: 'error',
    filename: 'core-errors-%DATE%.log',
    dirname: './logs',
    frequency: (config.logging.rotationInterval * 24) + 'h',
    maxFiles: config.logging.deletionInterval + 'd',
    format: format.combine(
        format.errors({ stack: true }),
        format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        errorFormat
    )
})

And my errorFormat:
const errorFormat = format.printf((info) => {
    const sym = Object.getOwnPropertySymbols(info).find(function(s) {
        return String(s) === "Symbol(message)";
    })

    return JSON.stringify({
        timestamp: info.timestamp,
        level: info.level,
        message: info.message ? info.message : sym ? info[sym] : ''
    })
})

The info parameter in my errorFormat is this:
{
  level: 'error',
  timestamp: '2022-08-04 18:07:38',
  [Symbol(level)]: 'error',
  [Symbol(message)]: '{"level":"error"}'
}

So, stack has not been added, because the error.js in the logform library hasn't recgonized the error instance.
How does the error instance get turned into not being an instance of Error?
Winston version 3.8.1
Node version 16.13.0

A: I have found, what my mistake was. You have to add format.errors({ stack:true }) into the format property of the logger and not of the transport. The code below works for me. Maybe it helps someone else, too.
const logger = createLogger({
    format: format.combine(
        format.errors({ stack:true }),
        format.json()
    ),
    transports: [
      new transports.DailyRotateFile({
        level: 'error',
        filename: 'core-errors-%DATE%.log',
        dirname: './logs',
        frequency: (config.logging.rotationInterval * 24) + 'h',
        maxFiles: config.logging.deletionInterval + 'd',
        format: format.combine(
            format.timestamp({
                format: 'YYYY-MM-DD HH:mm:ss'
            }),
            errorFormat
        )
      })
    ]
})


text:
Q: page number in category I have a function which named kriesi_pagination this is a function for showing page numbers in php. I wrote the codes in function.php for my site. And I call this function in index.php for showing the page numbers in index. I use this code in index : <?php kriesi_pagination(); ?>
Now the question is what should I do if I want to show the page numbers in other places such as category. It just show the page numbers in home page of site not any other places.
I want to have page numbers for the categories like sports, musics, technology, .....
By the way I use wordpress cms for my website.
Please help me to solve this problem
Thanks in advance

A: You should be able to use the query var value for paged to get the current page number:
function echo_page_number(){
    $page_number = isset($wp_query->query_vars["paged"])?
        $wp_query->query_vars["paged"] : // page number
        1; // not set, default to 1
    echo $page_number;
}


text:
Q: form.$valid undefined in angularJS When I used angular form validation, it gives undefined error in angular controller.
My HTML View
Index.xhtml (Main View)

   <select ng-model="val">
      <option value="A"></option>
      <option value="B"></option>
      <option value="C"></option>
   </select>

           @Html.Partial("A")

           @Html.Partial("B")

           @Html.Partial("A")

A.chtml (partial view)

   <form name="formA" ng-submit="A();">

     <input type="submit" value="Add"/>
   </form>

B.chtml (partial view)

   <form name="formC" ng-submit="B();">

     <input type="submit" value="Add"/>
   </form>

JS File
$scope.A = function(){
           if($scope.formA.$valid){
            }
    };

First I Select Value A in main view drop-down and, insert data and clicked Add button. Then it will checked the form validation. if validation true, function work success.
But,
after that I select value C i drop-down and try add inserted value, angular controller cannot identify the form name. It gives undefined error.
If I select B value after A selected, function execute without error. I tried to after set
 $scope.formA.$setPristine();
 $scope.formA.$setUntouched();

But It doesn't give any effect for this erro.
Can anyone help me?
any explanation about internal functionality?

A: You must have $scope prefixed to formA, that was more than likely the issue


text:
Q: Access to listbox in static method I have one static method which I call from another class when I need update data in listbox. But then I need scroll listbox to last item. Here is code:
 public static void updateMessages()
  {
      MyDatasCurentUser.Clear();//clear messages from previewous user from datas
      foreach (var items in UniDB.returnlistOfMessagesData(IdOfChoosenUser, MainContentPage.myID))
      {
          _mydataCurentUser.Add(new BindingData
          {
              MessengerReadTime = new DateTime(items.readTime.Year, items.readTime.Month, items.readTime.Day, items.readTime.Hour, items.readTime.Minute, 0),
              MessengeFullName = items.senderName,
              MessengerTime = new DateTime(items.sendTime.Year, items.sendTime.Month, items.sendTime.Day, items.sendTime.Hour, items.sendTime.Minute, 0).ToString("dd.MM.yyyy - HH:mm"),
              MessengerMessage = items.message,
              MessengerIsFromMe = items.isFromMe,
          });
      }

      lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
  }

But I get error cannot access to non static field in static context at this: lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
Is there any way how I can do this lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last()); when is method updateMessages() called?

A: If you have a non static method of one class:
class Form1
{
   public void UpdateMessages()
   {
       // ...
       lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
   }
}

And you want to call it from an object of a different class, that object will need a reference to the first object. A common solution is to pass the reference to the first object into the constructor of the second:
class OtherClass
{
   Form1 _form;
   OtherClass(Form1 form)
   {
       _form = form;
   }

   void Method()
   {
       //can access the methods of the other object
       _form.UpdateMessages();
   }
}

Alternatively you could pass the object in later:
class OtherClass
{
   public void Method(Form1 form)
   {
       form.UpdateMessages();
   }
}


text:
Q: Home folder icons are black-and-white symbolic icons with the Adwaita icon theme How can I get the standard colored Gnome Adwaita folder icons when I select the Adwaita icon theme?
When I select Adwaita (default) as my icon set in GnomeTweaks, all of the icons displayed in Nautilus in my home folder are black-and-white symbolic icons.
I reinstalled the adwaita-icon-theme package, but this did not solve the problem.
There is only one places folder inside my Adwaita icon theme.
find /usr/share/icons/Adwaita -name places
/usr/share/icons/Adwaita/scalable/places

I looked in /usr/share/icons/Adwaita/scalable/places, and I see the same black-and-white symbolic icons:
ls -1 /usr/share/icons/Adwaita/scalable/places
folder-documents-symbolic.svg
folder-download-symbolic.svg
folder-music-symbolic.svg
folder-pictures-symbolic.svg
folder-publicshare-symbolic.svg
folder-remote-symbolic.svg
folder-saved-search-symbolic.svg
folder-symbolic.svg
folder-templates-symbolic.svg
folder-videos-symbolic.svg
network-server-symbolic.svg
network-workgroup-symbolic.svg
start-here-symbolic.svg
user-bookmarks-symbolic.svg
user-desktop-symbolic.svg
user-home-symbolic.svg
user-trash-symbolic.svg

(I am using Ubuntu 19.04, and I have the gnome-session package installed).
Here is a screenshot of my home folder:

A: Try installing the adwaita-icon-theme-full package using the following command:
sudo apt install adwaita-icon-theme-full


text:
Q: Use the Transform operator to remove one or more key/value pairs from an Object? JSONata newbie checking in. I have reviewed all the questions in this forum and cannot find the answer so am asking here.
Given this source...
{
  "Price": 34.45,
  "Product Name": "Bowler Hat",
  "ProductID": 858383,
  "Quantity": 2,
  "SKU": "0406654608"
}

I would like to reduce it to...
{
  "Product Name": "Bowler Hat",
  "ProductID": 858383,
  "SKU": "0406654608"
}

...using the Transform operator to delete Price and Quantity. I've tried various permutations of this...
$ ~> |*|{}, ['Price', 'Quantity']|

..but am not getting the result I am looking for. Here is an Exerciser link.
Thanks in advance for any assistance.

A: Just a small modification needed - the 'matching' clause needs to match the object that you wish to modify, in your case it is the context item '$'.  The wildcard '*' is going to return the sequence of values in that object rather than the object itself.  So your expression should be:
$ ~> |$|{}, ['Price', 'Quantity']|

See https://try.jsonata.org/qUwOtT-pt


text:
Q: How should I profile intermittent lags/slowdown for optimization in Java? (see example inside) I'm developing an action-platformer game using Java and just recently finished coding the AI for an enemy unit. I started to notice that at certain points in the game, it would slowdown and lag before going back to normal. See an example here on this video. The lagging part is somewhere at the midpoint of the video and is annotated, so you won't miss it:
LoGaP 06.14.2013 on YouTube
I would guess that there's some code that it tries executing that becomes a bottleneck. Is this typically the symptom of a memory issue or CPU issue?
More importantly, what is the best way in this case to identify what the problematic code is so that I could analyze how to optimize it? The only optimization tool I've only ever used for Java is jvisualvm and I only used it for a while. Will that do the trick in this scenario?

A: It is a common problem in profiling that you have a method that typically executes in acceptable time, but every once in a while becomes a bottleneck.
Profiling the entire run will likely not help you since the one slow invocation will be drowned out by all the other regular invocations.
In JProfiler, you can mark a method so that exceptional method runs are kept separately and you can examine the slowest operations in detail. You can use the method statistics view to see the call distribution and mark them for exceptional method recording there:

In the call tree view, the slowest invocations will be marked with an [exceptional run] suffix and you can investigate their call tree in isolation:

Disclaimer: My company develops JProfiler.


text:
Q: How can I make a website as an iPhone native application? I'm planning to convert my website into an iPhone native application. I'm stuck at the point of how to achieve this.
Initially, I have developed the first screen i.e., LOGIN screen of my application. My server is built in Java. I'm able to send the login credentials to the server and able to see the request on the server. But I'm unable to receive the response from the server for the request I've sent.
A part of my code is:
NSString *post = @"username=";

    post = [post stringByAppendingString:username];
    post = [post stringByAppendingString:@"&password="];
    post = [post stringByAppendingString:password];

    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:@"http://mysite.com/login.action?"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  //  [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn)
    {
        receivedData = [[NSMutableData data] retain];
        NSLog(@"In \"LOGIN()\" :  receivedData = %@",receivedData);
    }

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];

    NSLog(@"In \"didReceiveResponse()\" :  receivedData = %@",receivedData);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    NSString *ReturnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"In \"didReceiveData()\" :  receivedData = %@",receivedData);
    NSLog(@"Return String : %@", ReturnStr);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    NSString *urlData;
    if (nil != receivedData) {
        urlData = [[[NSString alloc] initWithData:receivedData
                                         encoding:NSUTF8StringEncoding] autorelease];
    }
    NSLog(@"In \"connectionDidFinishLoading()\" :  urlData = %@",urlData);

    [receivedData release];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{

    [connection release];

    [receivedData release];

    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

*

*How do I develop a LOGIN application?

*I'm sending a request successfully to the server but I'm unable to get the response from the server. How can I overcome this issue?

A: If your experience is with web development you may be interested in looking at NimbleKit for iPhone. It's a simple XCode plugin that allows you to use HTML and JavaScript to develop the entire native application.


text:
Q: Browser.inputBox does not work in GoogleScript web app This code will work if I run my app in a spreadsheet
var name = Browser.inputBox("Enter your name");

But when I deployed it as a web app, it doesn't work. What other alternative can be used to capture information from a user in a GoogleScript web app?

A: See the Guide to UI Service, and the Guide to Html Service which introduce the two primary ways to create user interfaces for Google Apps WebApps.


text:
Q: In MonoDevelop, how do I set the application output to a fixed-width font? I can't find any sort of font settings for Application Output. I'm not sure why it's not fixed-width by default. Any ideas?

A: MonoDevelop is still pretty much in development, there are quite a few features we would like to see.
You could report it as a feature request here, or even better, contribute and propose a patch for it.

A: You can change it via Edit->Preferences->Visual Style
Check "Custom font for Output pads" and select the font you would like.


text:
Q: Find the maximum of $f(x)=\sum_{i=1}^{4}x_ia_i^2$ under the constraints Find the maximum of $f(x)=\sum\limits_{i=1}^{4}x_ia_i^2$ under the constraints $|x|=1$ and $\langle x,a\rangle=0$.
My try
I set $$L(x,\lambda,\mu)=f(x)-\lambda\left(\sum x_i^2-1\right)-\mu\left(\sum x_ia_i\right)$$
I found that $$\lambda=\frac12\sum_{i=1}^{4}x_ia_i^2$$
I didn't manage to find $\mu$ any hints please?

A: It can actually be found in a very similar method to how you find lambda. As a hint before I show how to do it, try multiplying $\frac{\partial L}{\partial x_i}$ by $a_i$ and then adding all these equations.
We know $\nabla L=0$. This gives the following equations. $$\frac{\partial L}{\partial x_i}=a_i^2-2\lambda x_i-\mu a_i=0\\ \frac{\partial L}{\partial \lambda}=\sum_{i=1}^4 x_i^2-1=0 \\ \frac{\partial L}{\partial \mu}=\sum_{i=1}^4 x_i a_i=0$$
Multiplying the first equation by $a_i$ and then using the third equation gives $$a_i^3 -2\lambda x_ia_i-\mu a_i^2=0 \\ \sum_{i=1}^4 (a_i^3 -2\lambda x_ia_i-\mu a_i^2)=0 \\ \sum_{i=1}^4 a_i^3 -\mu a_i^2 =0 \\ \mu=\frac{\sum_{i=1}^4 a_i^3}{\sum_{i=1}^4 a_i^2}$$
For the interest of anyone else reading I will include the working for lambda. $$a_i^2-2\lambda x_i-\mu a_i=0 \\ a_i^2x_i-2\lambda x_i^2-\mu a_i x_i=0 \\ \sum_{i=1}^4 a_i^2x_i-2\lambda x_i^2-\mu a_i x_i=0 \\ \sum_{i=1}^4 a_i^2x_i-2\lambda =0\\ \lambda = \frac 12 \sum_{i=1}^4 a_i^2x_i$$

A: Update
We are given two vectors $a=(a_1,\ldots, a_n)$ and $b:=(a_1^2,\ldots,a_n^2)$, and are told to maximize
$$f(x):=b\boldsymbol{\cdot} x$$
under the constraints
$$|x|=1,\qquad a\boldsymbol{\cdot} x=0\ .$$
When $a$ and $b$ are linearly dependent then $f(x)=0$ for all $x$. Discarding this case project $b$ orthogonally into the plane $a\boldsymbol{\cdot} x=0$. We then obtain a vector
$$u:=b-{a\boldsymbol{\cdot} b\over |a|^2}a\ne0\ .$$
This $u$ in the plane $a\boldsymbol{\cdot} x=0$ points in the direction that has the smallest angle with $b$. Letting
$$x_*:={u\over|u|}$$
then gives the maximal $f(x)$ under the given constraints.
You now can compute $x_*$ and $f(x_*)$ in terms of the $a_i$.


text:
Q: How can i insert text into html tag in php string? i have been dealing with this for awhile and i could not figure out how to do the following in PHP:
$string = "this is test
somrthing in
pharagraph

 dont know tell me
value33 kooo ok
 this is php regress
teeth value
 ok how";

function get_innercode($string) {
preg_match_all("#
(.*?)
#", $string, $foo);
echo implode("\n", $foo[1]);
}
    $insert1=get_innercode($string);

    $insert2=" 2 place me in the pre tag"; // you can ignore this

    $string="this is test
 WHERE $insert1 SHOULD BE
 dont know tell me
WHERE $insert2 SHOULD BE
 ok how ";

how can i do this?
Please note i cannot do
$string="some text here
 WHERE $insert1 SHOULD BE
 some more text here
WHERE $insert2 SHOULD BE
 ok how";

because i am getting $insert1 and $insert2 from $string to modify. i need to place it back in there where they come from.
thank you

A: It's pretty easy to do:
$insert1 =" 1 place me in the pre tag";
$insert2 =" 2 place me in the pre tag";

$string = "some text here
{$insert1}
 some more text here
{$insert2}
 and may be some more text or ";

You can echo a variable from inside a string when it's wrapped around double quotes. This does not work with single quotes.
Edit: This might be what you are looking for then:
$string = "This my awesome code";

$string = preg_replace('/(.*?)<\/code>/', '
$1
', $string);

A: In php you can concatenate strings with a "." before and after, example:
$var1 = "hello";
$var2 = "What's up";

$concat = "Hey, ".$var1." ,".$var2."
";

echo $concat;

A: Similar methodology here. This allows for larger areas to be filled
$insert[0] = "Some Text";
$insert[1] = "Some More Text";

function Parser($content){
$i = 0;
    while (preg_match_all('`\<pre\>(.*?)\</pre\>`', $content, $matches)) {
       foreach ($matches[0] as $key => $match) {
         //$innertext = $matches[1][$key]; //replace with your preferred filler
         $innertext = $insert[$i]; //such as this
         $replacement = '
' . trim($innertext) . '
';
         $content = str_replace($match, $replacement, $content);
         $i++;
       }
    }
}

Parse your line(s) of content like so:
Parser("this is test
 WHERE $insert1 SHOULD BE
 dont know tell me
WHERE $insert2 SHOULD BE
 ok how");

This is untested so may have a couple of bugs in it.

A: Try this,
I am adding div tag before each pre content. You can also modify content as needed by using $matches[1]
$string_new = preg_replace_callback(
   '#
(.*?)
#',
    function ($matches) {
        return "
".$matches[0]."
";
    },
    $string
);

echo $string_new;


text:
Q: ExtJS data store does not sort I'm using ExtJS 4.2 and created a store with a sorter. The store loads data from a JSONP web service call just fine, but it refuses to sort. Below is a representation of my model, store and load call.
Model:
Ext.define('Desktop.models.products.DtoProductFamilyModel', {
extend: 'Ext.data.Model',
fields: [
    {
        name: 'ProductFamilyId',
        type: 'string',
        useNull: false,
        defaultValue: Util.getBlankGuid()
    },
    {
        name: 'ParentProductFamilyId',
        type: 'string',
        useNull: true,
        defaultValue: Util.getBlankGuid()
    },
    {
        name: 'BaseItemId',
        type: 'string',
        useNull: true,
        defaultValue: Util.getBlankGuid()
    },
    {
        name: 'Name',
        type: 'string',
        useNull: false,
        defaultValue: ''
    },
    {
        name: 'DisplayName',
        type: 'string',
        useNull: false,
        defaultValue: ''
    },
    {
        name: 'ExternalReferenceId',
        type: 'string',
        useNull: true,
        defaultValue: null
    }
]
});

Store:
Ext.define('Desktop.stores.products.GetProductFamiliesStore', {
extend: Ext.data.Store,
model: 'Desktop.models.products.DtoProductFamilyModel',
proxy: {
    type: 'jsonp',
    url: 'http://www.somejsonpwebservice.com',
    method: 'GET',
    pageParam: false,
    startParam: false,
    limitParam: false,
    timeout: 9000000,
    noCache: true,
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    sorters: [{
        property: 'Name',
        direction: 'ASC'
    }],
    sortRoot: 'Name',
    sortOnLoad: true,
    remoteSort: false,
    reader: {
        type: 'json'
    }
}
});

Combobox component utilizing the store:
    {
        xtype: 'combo',
        zzid: 'cmbProductManufacturersFamily',
        store: 'Desktop.stores.products.GetProductFamiliesStore',
        width: 250,
        labelWidth: 50,
        forceSelection: true,
        fieldLabel: Util.translate('Family'),
        emptyText: 'Select Product Family',
        margin: '0 0 0 10',
        displayField: 'Name',
        valueField: 'ProductFamilyId'
    }

Actual call to load store:
this.stoProductFamilies = this.cmbProductManufacturersFamily.getStore();
this.stoProductFamilies.load()

The data loads just fine, but the store refuses to sort my data. I'm loading over 100 dynamic records into a combobox and need this feature working. If anyone can provide insight as to what I'm doing wrong I would greatly appreciate it.

A: sortOnLoad, remoteSort and the sorters configurations are not set on the proxy, instead they are set on the store like this:
Ext.define('Desktop.stores.products.GetProductFamiliesStore', {
    extend: Ext.data.Store,
    model: 'Desktop.models.products.DtoProductFamilyModel',
    sorters: [{
        property: 'Name',
        direction: 'ASC'
    }],
    sortRoot: 'Name',
    sortOnLoad: true,
    remoteSort: false,
    proxy: {
       type: 'jsonp',
       url: 'http://www.somejsonpwebservice.com',
       method: 'GET',
       pageParam: false,
       startParam: false,
       limitParam: false,
       timeout: 9000000,
       noCache: true,
       headers: { 'Content-Type': 'application/json;charset=utf-8' },
       reader: {
           type: 'json'
       }
    }
});


text:
Q: Am I doing something wrong with the asset pipeline? Since "upgrading" to Rails 3.1 my app is really slow in development mode
(> 30 per request)
I have a lot of images and it seems most of this time-delay is the asset pipeline processing each GET request for each image.
Don't have this problem in Staging or Production mode as the assets are cached etc.
Is there something I haven't been told or is this how we're expected to work now?

A: Requests can be slow if you have gems or portions of your app that load code at the start of each request - or that merely reference portions of your app, causing much of it to be loaded.  For most of these, the autoloader is the prime cause of request delay.
The rails auto-reloader deletes any autoloadable classes/modules/etc at the start of each request, and can cause significant delays at the beginning of each request as Rails reloads all the source files it needs.
You might want to try playing with https://github.com/wavii/rails-dev-tweaks, which gives you granular control over which requests cause the auto-reloader to kick in.  This really isn't a fix of the root cause (something is doing extra work at the start of every request that it probably doesn't need to be doing) - but it certainly mitigates most such issues.

A: In the meantime:

cp -R app/assets/images public/assets

really helps
remember to add public/assets/* to .gitignore

A: If your app is slow it is because of your app or one of the gems that you use. I had similar issue and it looks like Mongoid was the case more you can read here:
http://martinciu.com/2011/06/rails-3-1-and-slow-asset-pipeline.html

A: You can use a rake task:
rake assets:precompile RAILS_ENV=development RAILS_ASSETS_NONDIGEST=true
And as it was mentioned above, don't forget to include public/assets/* to .gitignore


text:
Q: Galasoft MVVMlight creating issues while app certification in windows phone 8.1 I have a windows phone 8.1 app that is ready for certification but i get an error saying that galasoft mvvm light was built using the debug mode so we cannot accept this.
Any solutions to this ?


text:
Q: scikit-learn pipeline preprocessing with TypeError: '<' not supported between instances of 'str' and 'float' when fitting Hi I am currently working on a classification problem using scikit-learn pipeline, I have used pipeline preprocessing to impute missing value for numeric and categorical columns respectively, however, still have TypeError. I know there are many similar questions regarding this but I've tried their fixes and still didn't solve the problem. My dataset contains both object, float64, and int64, some of records are nulls (showing NaN).
This is the error message I got:
TypeError: '<' not supported between instances of 'str' and 'float'
TypeError: argument must be a string or number

So I impute them with median and 'missing' respectively. Below is my code:
from sklearn.pipeline import make_pipeline, Pipeline
from mlxtend.preprocessing import DenseTransformer

numeric_features=X.select_dtypes(include=['int64', 'float64']).columns
numeric_transformer=Pipeline(steps=[
    ('imputer',SimpleImputer(strategy='median')),
    ('scaler',StandardScaler())])

categorical_features=X.select_dtypes(include=['object']).columns
categorical_transformer=Pipeline(steps=[
    ('imputer',SimpleImputer(strategy='constant',fill_value='missing')),
    ('onehot',OneHotEncoder(handle_unknown='ignore')),
    ('to_dense', DenseTransformer())])

preprocessor=ColumnTransformer(transformers=[
    ('num',numeric_transformer,numeric_features),
    ('cat',categorical_transformer,categorical_features)])

from sklearn.ensemble import RandomForestClassifier
rf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', RandomForestClassifier())])
rf.fit(X_train1, Y_train1) #--> this is when the error message points to

My question is that I thought the preprocessor part will impute and handle the missing cells, why would there still be the type error. Did I do something wrong?
Really appreciate the help. Any suggestions to fix this are welcome!! Thanks!!


text:
Q: How to get a Scala Map[String, Seq[String]] to a MapType in GraphQL Sangria I am trying to get a Scala Map[String, Seq[String]] to a MapType in GraphQL Sangria. I think the way could be using:
ScalarType[Map[String, Seq[String]]]

A: Unfortunately, at the moment a generic Map is not supported by the GraphQL spec. There are several alternatives available though. I would suggest you to check out this on-going discussion:
https://github.com/facebook/graphql/issues/101
Also, it is possible to implement a raw JSON scalar type, but in general I would discourage you from using it.


text:
Q: Read two visa instruments in parallel with Matlab I try to read data from two Keysight oscilloscopes in parallel with Matlab (2015a). To do that I use the parallel computing toolbox with the spmd command. I have a function to read the data which accepts a visa object as parameter and returns the rawdata. This works fine outside the spmd command like this (scope1 and scope2 are open visa objects):
scope = {scope1, scope2}
scopedata1 = scopeGetCh1Raw(scope{1});
scopedata2 = scopeGetCh1Raw(scope{2});

I get the data from both oscilloscopes.
If I do:
spmd
    scopedata = scopeGetCh1Raw(scope{labindex});
end

I get the following error:
Error detected on workers 1 2.

Caused by:
    Error using icinterface/fprintf (line 147)
    OBJ must be connected to the hardware with FOPEN.
    Error using icinterface/fprintf (line 147)
    OBJ must be connected to the hardware with FOPEN.

Any ideas what's going wrong?
Cheers
Nils

A: The workers operating on the body of your spmd block are separate processes. I presume you'll need to call fopen inside spmd, something like:
spmd
    myScope = fopen(...); % do whatever to open the scope
    scopedata = scopeGetCh1Raw(myScope);
end


text:
Q: duplicate foreign key column using sequelize I have a node project using sequelize, and have the following two tables
"use strict";

module.exports = function(sequelize, DataTypes) {
  var asset = sequelize.define("asset", {
    description   : DataTypes.STRING,
    maker         : DataTypes.STRING,
    model         : DataTypes.STRING,
    serialNumber  : DataTypes.STRING,
    barcode       : DataTypes.STRING,
    account       : DataTypes.INTEGER,
    usefulLife    : DataTypes.INTEGER,
    downtimeCosts : DataTypes.FLOAT,
    purchasePrice : DataTypes.FLOAT
  }, {
    classMethods: {
      associate: function(models) {
        /*Un estado es de muchas categorias, y no se puede borrar si tiene un activo asociado*/
        asset.belongsTo(models.assetState, {
          onDelete: "RESTRICT",
          foreignKey: {
            allowNull : false,
            name      : 'assetState_id'
          }
        });
      }

    }
  });

  return asset;
};

"use strict";

module.exports = function(sequelize, DataTypes) {
  var assetState = sequelize.define("assetState", {
    state: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        assetState.hasMany(models.asset)
      }
    }
  });

  return assetState;
};

The problem is that when i check the asset tables in postgres I have two columns ("assetState_id", "assetState") I suppose that is because i give the name of the relation explicitly, as I can do to not generate the column "assetState"?
thanks

A: You can declare a primary key in the assetState table and then reference that in the association definition:
var assetState = sequelize.define("assetState", {
  assetState_id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  state: DataTypes.STRING
}, {
  classMethods: {
    associate: function(models) {
      assetState.hasMany(models.asset, { foreignKey: 'assetState_id' })
    }
  }
});


text:
Q: test a multi-step registration system using SpecFlow I'm using SpecFlow whilst writing an asp.net mvc 3 website. The registration system in the site consists of two views.
the first view asks for basic information e.g eMail, password and location, whilst the second view asks the user for the type of account (developer or standard user) and then name, address etc.
In SpecFlow terms then I have one feature Registration and two succeeding senarios, registering as a developer and as a standard user.
if this was one view I could test this using something like:
given I am on the registration page
when I enter Data1
and I enter data2
and I click the next button
then the registration should be successfull
as I have two views is it best practice to chain several given, when, and, then statements or is there a better way of doing something like this?
Any help apreciated.
Sean

A: I would avoid mentioning the different pages within the feature file, and handle that at the step definition level instead, e.g.
Given I am registering
When I fill in my basic information
And I choose to register as a developer
Then I should be registered as a developer

Given I am registering
When I fill in my basic information
And I choose to register as a standard user
Then I should be registered as a standard user


text:
Q: SQL - How can I Increment a field in a results set by 1 for every 10 records returned How can I Increment a field in a results set by 1 for every 10 records returned?
So the first ten items will have a field called "BoxNumber" and that value will be 1. items 11-20 will have BoxNumber = 2
etc
Any help appreciated

A: SELECT  *,
        BoxNumber = (ROW_NUMBER() OVER(ORDER BY Col1)-1)/10+1
FROM dbo.YourTable


text:
Q: Customize labels with Plotly I am trying to customize the data labels which appear when hovering:

Here is the code giving me the output above:
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go

# Create random data
labels = ['A', 'B', 'C']
N = 20
df = pd.DataFrame(index = range(N))
standardized_cols = []

for col in labels:
    df[col] = np.random.randn(N)
    standardized_colname  =  col + "_standardized"
    standardized_cols.append(standardized_colname)
    df[standardized_colname] = (df[col]-df[col].mean())/df[col].std()

# Cluster
c = KMeans(n_clusters=3, random_state=1).fit(df[standardized_cols]).labels_

# Plot
trace = go.Scatter3d(
    x=df.A_standardized,
    y=df.B_standardized,
    z=df.C_standardized,

    mode='markers',
    marker=dict(
        size=5,
        color=c,
        colorscale='Viridis',
    ),
    name= 'test',
    text= c
)

data = [trace]

fig = go.Figure(data=data, layout=layout)
iplot(fig)

My data:
]
The chart shows me clustering of the standardized columns.
But when hovering over the data I'd like to see the not standardized data in the lable, i.e.something like
A: 0,999
B: 0,565
C: 0,765
Cluster: 2

I experimented but could not figure out how to achieve this. Is this possible?

A: You can do some list comprehension and add whatever columns you want to text see sample below (note, I am plotting offline):
# data
np.random.seed(1)
labels = ['A', 'B', 'C']
N = 20
df = pd.DataFrame(index = range(N))
standardized_cols = []

for col in labels:
    df[col] = np.random.randn(N)
    standardized_colname  =  col + "_standardized"
    standardized_cols.append(standardized_colname)
    df[standardized_colname] = (df[col]-df[col].mean())/df[col].std()

c = KMeans(n_clusters=3, random_state=1).fit(df[standardized_cols]).labels_

plot:
import plotly as py
import plotly.graph_objs as go

trace = go.Scatter3d(
    x=df.A_standardized,
    y=df.B_standardized,
    z=df.C_standardized,

    mode='markers',
    marker=dict(
        size=5,
        color=c,
        colorscale='Viridis',
    ),
    name= 'test',

    # list comprehension to add text on hover
    text= [f"A: {a}
B: {b}
C: {c}" for a,b,c in list(zip(df['A'], df['B'], df['C']))],
    # if you do not want to display x,y,z
    # hoverinfo='text'

)

layout = dict(title = 'TEST',)

data = [trace]
fig = dict(data=data, layout=layout)

py.offline.plot(fig, filename = 'stackTest.html')

you can modify the list comprehension to display whatever you want
if you do not want to display x,y,z then add hoverinfo='text'


text:
Q: Excel variant array contents to file, with row contents joined please bear with me as I'm very new to VBA, with prior experience primarily from Rhinoscript and other dedicated scripting options. The question is really very simple and I reckon someone can answer this very quickly, as I'm poor with arrays in VBA:
I have a spreadsheet where the objective is to import a number of values and text strings (resulting in some blanks) into e.g. A:L. This is done manually. I need to read these values into an array and then print them into a file so that each file row corresponds to a row of columns in the array. Currently I cannot seem to be able to convert the variant array into a string array (apparently necessary) and then join the subarrays into temporary arrays which are printed into the file. The following bit I've managed to scrape together results in a file output where each array value is on a single row, where as I'd like the contents of e.g. A1:L1 to be printed on single row.
Sub writerangetofile()

'Write data to a text file

'Declaring variables
Dim valarray() As Variant
Dim R As Long
Dim C As Long

'Set array as range
Sheet1.Activate
valarray() = Range("A1:L40")

'Setting the name and the path of text file based on workbook path
sFName = ThisWorkbook.Path & "\Output.txt"

'Get an unused file number
intFNumber = FreeFile

'Create a new file (or overwrite an existing one)
Open sFName For Output As #intFNumber

For R = 1 To UBound(valarray, 1) ' First array dimension is rows.
   For C = 1 To UBound(valarray, 2) ' Second array dimension is columns.
        Print #intFNumber, valarray(R, C)
   Next C
Next R

'Close the text file
Close #intFNumber

End Sub

For simplicity as I've also not figured out how to obtain the last row with any content in it I've restricted the range to row 40 for now.
Any ideas on how to accomplish what I want elegantly? I've solved it by assigning single cells to variables, but I'd prefer to do it with an array. Ultimately I will later be interjecting a fixed text string after a recurring text string in the imported text, which is then followed by a numerical value obtained from a calculation.
Many thanks for any help and apologies for the ignorance.

A: Nevermind, I think I got a step forward:
For R = 1 To UBound(valarray, 1) ' First array dimension is rows.

    For C = 1 To UBound(valarray, 2) ' Second array dimension is columns.

        ReDim Preserve tvalarray(1 To C) 'Reset the array dimension on each iteration of loop whilst keeping results
        'Input each single value into subarray for joining
        tvalarray(C) = valarray(R, C)
        'Join the subarray
        jstring = Join(tvalarray)

    Next C

    ReDim Preserve jvalarray(1 To R) 'Reset the array dimension on each iteration of loop whilst keeping results
    'Input the joined result into the new array
    jvalarray(R) = jstring
    'Print to file
    Print #intFNumber, jvalarray(R)

Next R

This seems to do the job, I'll see if I run into pitfalls later.

A: In case you have any issues, this versions shows how to determine the last row and column
Option Explicit

Public Sub RangeToFile()
    Dim ws As Worksheet, lr As Long, lc As Long, r As Long, c As Long
    Dim arr As Variant, fName As String, fNumber As Long, txtLine As String

    fName = ThisWorkbook.Path & "\Output.txt"   'File name & path based on workbook path

    Set ws = Sheet1 'set a reference to main sheet
    lr = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row         'find last row in column A
    lc = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column 'find last column in row 1

    arr = ws.Range(ws.Cells(1, "A"), ws.Cells(lr, lc))      'Copy range to array

    fNumber = FreeFile                  'get next available file number assigned by windows
    Open fName For Output As #fNumber   'create a new file, or overwrite an existing one

    For r = 1 To UBound(arr, 1)                    '1st array dimension is rows
        For c = 1 To UBound(arr, 2)                '2nd array dimension is columns
            txtLine = txtLine & arr(r, c) & ", "   'concatenate each cell in row, on a line
        Next c                                     'the end of the row, moving to next one
        txtLine = Left(txtLine, Len(txtLine) - 2)  'remove the extra comma at end of line
        txtLine = txtLine & vbCrLf                 'append a carriage return to the line
    Next r
    txtLine = Left(txtLine, Len(txtLine) - 2)      'remove carriage return at end of line

    Print #fNumber, txtLine 'print entire text to the file with an extra carriage return
    Close #fNumber          'close the text file
End Sub

and this one transposes columns to rows:
Public Sub RangeToFileColumnsToRows()
    Dim ws As Worksheet, lr As Long, lc As Long, r As Long, c As Long
    Dim arr As Variant, fName As String, fNumber As Long, txtLine As String

    fName = ThisWorkbook.Path & "\Output.txt"   'File name & path based on workbook path

    Set ws = Sheet1 'set a reference to main sheet
    lr = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row         'find last row in column A
    lc = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column 'find last column in row 1

    arr = ws.Range(ws.Cells(1, "A"), ws.Cells(lr, lc))      'Copy range to array

    fNumber = FreeFile                  'get next available file number assigned by windows
    Open fName For Output As #fNumber   'create a new file, or overwrite an existing one

    For c = 1 To UBound(arr, 2)                    '2nd array dimension is columns
        For r = 1 To UBound(arr, 1)                '1st array dimension is rows
            txtLine = txtLine & arr(r, c) & ", "   'concatenate each cell in col, on a line
        Next r                                     'the end of the col, moving to next one
        txtLine = Left(txtLine, Len(txtLine) - 2)  'remove the extra comma at end of line
        txtLine = txtLine & vbCrLf                 'append a carriage return to the line
    Next c
    txtLine = Left(txtLine, Len(txtLine) - 2)      'remove carriage return at end of line

    Print #fNumber, txtLine 'print entire text to the file
    Close #fNumber          'close the text file
End Sub


text:
Q: Splash server with Docker not running on Mac I am trying to configure a Splash server with Docker in order to render javascript for scrapy.
I downloaded and installed Docker Toolbox (The latest version of Docker does not install on my Macbook pro 2009 due to lack of CPU MMU support).
I runned "docker run -p 5023:5023 -p 8050:8050 -p 8051:8051 scrapinghub/splash" in Docker Quickstart Terminal. The command performs but after "Starting factory..." I can not get my shell prompt back.
I tried to access http://localhost:8050/ in my browser and to ping localhost:8050 but this does not work: "This site can't be reached". I would appreciate any help to understand what is the problem. Thank you!
                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/

docker is configured to use the default machine with IP 192.168.99.100
For help getting started, check out the docs at https://docs.docker.com

Ordinateur:~ jb$ docker run -p 5023:5023 -p 8050:8050 -p 8051:8051 scrapinghub/splash
Unable to find image 'scrapinghub/splash:latest' locally
latest: Pulling from scrapinghub/splash
75c416ea735c: Pull complete
c6ff40b6d658: Pull complete
a7050fc1f338: Pull complete
f0ffb5cf6ba9: Pull complete
be232718519c: Pull complete
de1c9f88de34: Pull complete
0b8cdf21020f: Pull complete
cf35f91dcdb5: Pull complete
bfbc20b51f2f: Pull complete
f434ae0e9eb2: Pull complete
Digest: sha256:0a91eb2de229289b0c83f39d8bd079d2464a954001869417a5297aa60820af5b
Status: Downloaded newer image for scrapinghub/splash:latest
2017-07-26 10:45:59+0000 [-] Log opened.
2017-07-26 10:45:59.513146 [-] Splash version: 3.0
2017-07-26 10:45:59.515698 [-] Qt 5.9.1, PyQt 5.9, WebKit 602.1, sip 4.19.3, Twisted 16.1.1, Lua 5.2
2017-07-26 10:45:59.516027 [-] Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609]
2017-07-26 10:45:59.516214 [-] Open files limit: 1048576
2017-07-26 10:45:59.516349 [-] Can't bump open files limit
2017-07-26 10:45:59.657299 [-] Xvfb is started: ['Xvfb', ':806019943', '-screen', '0', '1024x768x24', '-nolisten', 'tcp']
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
2017-07-26 10:45:59.992921 [-] proxy profiles support is enabled, proxy profiles path: /etc/splash/proxy-profiles
2017-07-26 10:46:00.273110 [-] verbosity=1
2017-07-26 10:46:00.273490 [-] slots=50
2017-07-26 10:46:00.275082 [-] argument_cache_max_entries=500
2017-07-26 10:46:00.276541 [-] Web UI: enabled, Lua: enabled (sandbox: enabled)
2017-07-26 10:46:00.278098 [-] Site starting on 8050
2017-07-26 10:46:00.278647 [-] Starting factory <twisted.web.server.Site object at 0x7f751d78ccf8>

If I restart docker and run "docker ps" I can see that the container is running:
Ordinateur:~ jb$ docker ps
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
e2c23b576b88        scrapinghub/splash   "python3 /app/bin/..."   2 hours ago         Up 2 hours          0.0.0.0:5023->5023/tcp, 0.0.0.0:8050-8051->8050-8051/tcp   gallant_feynman

A: Docker is available at address other than localhost. From your logs:

docker is configured to use the default machine with IP 192.168.99.100

Try accessing http://192.168.99.100:8050 instead of localhost. If you're using docker-machine, you can also get an ip address using docker-machine ip default command.

A: The server was running normally, I just had to replace localhost by my IP. Thank you!


text:
Q: Excel 32bit vs OLEDB vs Oracle Environment: Small corporate with hundreds of employees using Excel and consuming DWH data.
Scenario: refreshing data from Oracle DWH to 32bit Excel via Oracle OLEDB provider on daily basis
Problem: with large data sets (hundreds of thousands of rows) Excel eats up over 3GB RAM and crashes
Tested: the same data with different Excel versions (2013, 2016, 32bit, 64bit), different OLEDB provider (MSDAORA, Oracle 12.1 - 19)
Findings:

*

*MSDAORA is much less memory intensive, but very slow and formally unsupported for years. And what is worse - there are rumours, that it doesn't work with Oracle 19 DB and we are upgrading to 19 in some months.

*OraOLEDB 32-bit - until version 12.1 it worked fine, since 12.2 the memory consumption is multiple times bigger, thus 32bit Excel usually crashes.

*OraOLEDB 64-bit - I tested v19 and it worked just fine. But it is unlikely, that all of our users will get 64bit Excel because of other compatibility issues.

*Tested CacheType=File parameter in connection string and it didn't do anything...

Questions:

*

*Did you encounter the same problem?

*Do you have a solution for this?

*What is your approach with pulling data from Oracle DB to Excel?

A: MSDAORA does not work anymore with Oracle 19. However, it means Oracle Client version 19. If the Database is 19 and the client is 12.2 or lower it should still work (but of course not recommended)
What about ODBC drivers? Of course, the ODBC drivers from Oracle.
Or have a look at How to connect to Oracle 11 database from . net and check one of the third-party provided drivers.


text:
Q: Aggregate Output of Script So, I'm a bit lost here.
I'm trying to detect the presence of iBeacons.
I have a script which puts out data like this:
F992A0DE-5A63-4BC1-80F9-5F47A53A0C31 1 1 -60 -55 1.09090 1.87003

I can control the output so if necessary I can add semicolons or something like that.
The problem is: I need the output of the script aggregated.
The first field represents the UID of the beacon that is detected.
I want to always take 20 lines of every UID that appears, aggregate the 4th value and so get a average.
If this average is over a value a http request should be sent.
I have really no idea how to move on.
Would it be better to push the output to a file first?
I found a few threads and think I could accomplish this with awk, is this the right way?

A: awk to the rescue!
something like this?  not tested.
awk -v threshold=$th 'c[$1]<20 {s[$1]+=$4; c[$1]++}
                      END      {for(k in a)
                                  {avg = s[$1]/c[$1];
                                   if(avg>threshold) print k,a[k]}}' file

set the required threshold (here assumed to be in variable $th)


text:
Q: Ошибка кодировки.Python Помогите пожалуйста, я решил изучать парсинг данных и написал свой первый парсер при помощи bs4 и requests,после исполнения скрипта все русские символы почему-то превращаются в иероглефы.Если что в настройках винды стоит параметр:'использовать utf-8 для поддержки языка во всем мире'.Вот код:
import requests
from bs4 import BeautifulSoup

URL = 'https://auto.ru/moskva/cars/lexus/new/'
HEADERS = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko', 'accept' : '*/*'}

def get_html(url, params=None):
    r = requests.get(URL, headers = HEADERS, params = params)
    return r

def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    items = soup.find_all('div', class_= "ListingItemGroup__column ListingItemGroup__column_left")
    cars = []
    for item in items:
        cars.append({
            'title' : item.find('a', class_='Link ListingItemTitle-module__link').get_text(),
            item.find('dd', class_='ListingItemGroup__techSummaryName').get_text() : item.find('dt', class_='ListingItemGroup__techSummaryValue').get_text(),
            'price' : item.find('div', class_='ListingItemGroup__price').get_text()

        })
        f = open('test.txt', 'a+')
        f.write(str(cars))
        f.close()
    print(cars)

def parse():
    html = get_html(URL)
    if html.status_code == 200:
        get_content(html.text)
    else:
        print('Что-то пошло не так :(')

parse()

И вот, что выдает интерпретатор:
[{'title': 'Lexus RX IV Ð\xa0еÑ\x81Ñ\x82айлинг', 'Ð\x9cоÑ\x82оÑ\x80': '2.0 л / бензин', 'price': '3â\x80\x89468â\x80\x89000 â\x80\x93 4â\x80\x89785â\x80\x89000 â\x82½'}, {'title': 'Lexus LX III Ð\xa0еÑ\x81Ñ\x82айлинг 2', 'Ð\x9cоÑ\x82оÑ\x80': '4.5, 5.7 л / бензин, дизелÑ\x8c', 'price': '7â\x80\x89023â\x80\x89000 â\x80\x93 9â\x80\x89021â\x80\x89000 â\x82½'}, {'title': 'Lexus GX II Ð\xa0еÑ\x81Ñ\x82айлинг 2', 'Ð\x9cоÑ\x82оÑ\x80': '4.6 л / бензин', 'price': '5â\x80\x89215â\x80\x89000 â\x82½'}, {'title': 'Lexus NX I Ð\xa0еÑ\x81Ñ\x82айлинг', 'Ð\x9cоÑ\x82оÑ\x80': '2.0 л / бензин', 'price': '2â\x80\x89394â\x80\x89000 â\x80\x93 4â\x80\x89708â\x80\x89000 â\x82½'}, {'title': 'Lexus ES VII', 'Ð\x9cоÑ\x82оÑ\x80': '2.5, 3.5 л / бензин', 'price': '2â\x80\x89986â\x80\x89000 â\x80\x93 4â\x80\x89450â\x80\x89000 â\x82½'}, {'title': 'Lexus RX IV', 'Ð\x9cоÑ\x82оÑ\x80': '3.5 л / бензин', 'price': '4â\x80\x89386â\x80\x89000 â\x82½'}, {'title': 'Lexus UX I', 'Ð\x9cоÑ\x82оÑ\x80': '2.0 л / бензин', 'price': '2â\x80\x89585â\x80\x89000 â\x82½'}]

A: requests не угадал кодировку
>>> r.headers['content-type']
'text/html'
>>> r.encoding
'ISO-8859-1'

ему нужно подсказать
r.encoding='utf-8'

и r.text теперь читает по-русски.
Кодировка этой странички записана только в meta, а её requests не смотрит. Чтоб bs4 пытался угадать кодировку - скормить ему надо r.raw
>>> r = requests.get('https://example.com/', stream=True)
>>> data = r.raw.read()


text:
Q: FactoryGirl sequence not incrementing I'm using FactoryGirl to create instances of a date dimension model for a Rails-related gem. My factory looks like this:
FactoryGirl.define do
  sequence :next_day do |n|
    Date.new(2000,12,31) + n.days
  end

  factory :date_dimension do
    the_date = FactoryGirl.generate(:next_day)
    date {the_date.to_s}
    calendar_year {the_date.strftime("%Y")}
    (...other attributes created similarly to calendar_year)
  end

end

Out of frustration I actually built a little test to show what's not working:
describe "working date factories" do
  before(:all) do
    @date_dimension = FactoryGirl.create(:date_dimension)
    @jan_two = FactoryGirl.create(:date_dimension)
  end

  describe "sequence incrementing" do
    it "returns a date dimension object ok" do
      @date_dimension.date.should == "2001-01-01"
    end
    it "returns the next date in the sequence" do
      @jan_two.date.should == "2001-01-02"
    end
  end
end

When I run that test, I get:
working date factories
  sequence incrementing
    returns a date dimension object ok
    returns the next date in the sequence (FAILED - 1)

Failures:

  1) working date factories sequence incrementing returns the next date in the sequence
     Failure/Error: @jan_two.date.should == "2001-01-02"
       expected: "2001-01-02"
            got: "2001-01-01" (using ==)

I've read a bunch of other questions related to sequences, but it doesn't seem that I'm making the mistakes identified therein. It's a different (likely dumber) mistake. What is it?

A: I finally found an approach that works, and is probably a little better anyway. I still don't understand why the code above doesn't work - if someone can explain that to me (maybe with a reference to a doc or part of the source code), I'll go ahead and accept that answer - this post is just for those who follow. Here's what worked:
FactoryGirl.define do

  factory :date_dimension do
    sequence(:date) { |n| (Date.new(2000,12,31) + n.days).to_s }
    calendar_year { Date.parse(date).strftime("%Y") }
    day_of_week { Date.parse(date).strftime("%A") }
  end

end

The code above passes this test:
describe "working date factories" do
  before(:all) do
    @date_dimension = FactoryGirl.create(:date_dimension)
    @jan_two = FactoryGirl.create(:date_dimension)
  end

  describe "sequences" do
    it "returns the proper first date in the sequence" do
      @date_dimension.date.should == "2001-01-01"
      @date_dimension.calendar_year.should == "2001"
      @date_dimension.day_of_week.should == "Monday"
    end
    it "returns the next date in the sequence" do
      @jan_two.date.should == "2001-01-02"
      @jan_two.calendar_year.should == "2001"
      @jan_two.day_of_week.should == "Tuesday"
    end
  end
end


text:
Q: Pagestyle uheadings. No page number on first page with chapter title I am using uheadings pagestyle. First page of every chapter should have page number at the bottom (default plain style), but in my document there is no page number there.
This is my master page:
\documentclass[a4paper,onecolumn,oneside,11pt,wide,floatssmall]{mwrep}
\usepackage{bookman}
\pagestyle{uheadings}
\usepackage[pdftex, bookmarks=false]{hyperref}
\begin{document}
\pagenumbering{roman}
\renewcommand{\baselinestretch}{1.0}
\raggedbottom
\tableofcontents
\newpage
\pagenumbering{arabic}

\input {chap_a}
\input {chap_b}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:

Files chap_a, chap_b are similar. Files chap_a.tex, chap_b.tex are two A4 pages long, contains:
\chapter {WSS}
\label{chap:wss}
\section{WSS}
aa bb ...
aa bb

\subsection{BBAA}
bb aa ...
bb aa

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:

Why first page of every chapter doesn't have page number in footer? How to fix this?

A: Add the following lines
\makeatletter
  \def\ps@uheadings{%
    \let\@mkboth\markboth
    \let\ps@normal\hf@uheadings
    \let\ps@opening\hf@plain
    \let\ps@closing\hf@uheadings
    \let\ps@blank\hf@empty
    \ps@normal
    \def\chaptermark##1{%
      \markright{%
        \ifHeadingNumbered
            \thechapter.\enspace
        \fi
        ##1}}}
\makeatother

just before
\pagestyle{uheadings}

and the problem is solved.

A: Each \chapter sets the page style to opening. A patch using etoolbox to change this to plain fixes it:

\documentclass[a4paper,onecolumn,oneside,11pt,wide,floatssmall]{mwrep}
\usepackage{lipsum,geometry,etoolbox}
\makeatletter
\patchcmd{\mw@sectionxx}{opening}{plain}{}{}
\makeatother
\pagestyle{uheadings}
\begin{document}

\chapter{A chapter}
\lipsum[1-10]

\end{document}


text:
Q: How do I expose a C# Web API method to any calling origin? I have a C# Web API with this method (in its entirety):
public JsonResult PlanItems(string sessionId)
{
    Response.Headers.Add("Access-Control-Allow-Origin", "*");
    DTDBDataService svc = new DTDBDataService(_db);
    VM.PlanItems = svc.GetPlanItems(VM.User);

    return Json(VM.PlanItems);
}

I have a decoupled Angular client that makes this call to the api:
this.http.get<[DTPlanItem]>(url).subscribe( data => {
    console.log("Plan items: ", data);

    for (let i = 0; i < data.length; i++)
    {
        console.log(data[i]);
        this.planItems.push(data[i]);
    }

    console.log("Loaded items: ", this.planItems);
});

When running in dev (localhost), the client calling from http://localhost:4200 uses this url:
https://localhost:44324/Planner/PlanItems?sessionId=e829fb5c-aa6d-43c9-99e7-0552afd8bc7e.

When the Web API is deployed, the client (still calling from http://localhost:4200) use this url:
https://7822-54268.el-alt.com/Planner/PlanItems?sessionId=8d240409-09ba-4d9d-914a-7c0031fd8a6b.

The deployed API results in an error:

Access to XMLHttpRequest at 'https://7822-54268.el-alt.com/Planner/PlanItems?sessionId=4207b27d-7f65-4289-beb5-8ae35c7c5da3' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It can't be unusual to deploy a Web API with the expectation that the clients will be calling from any, unknown domain. How do I expose a C# Web API method to any calling origin? This can't be an unusual situation. There are an uncountable number of Web APIs that are allowable from a cross origin. How is it done?

A: What is CORS? Why do we use it?

It can't be unusual to deploy a webapi with the expectation that the clients will be calling from any, unknown domain.

I'm going to start with this because I sense there might be some misunderstanding here. Although the server can influence CORS by way of headers, it's primarily a security feature of the browser, and is enforced by the browser.
Generally APIs not intended as backends for a browser-based frontend will be accessed with HTTP client libraries, which have no reason to implement CORS. As such, these don't need to concern themselves with configuring CORS and the clients will just work.
If you're creating a frontend and it's on the same host as the backend API, then CORS will not be an issue because there are no cross-origin requests. That is to say, if the page making the request is at https://www.example.com/frontend, and it's making a request to https://www.example.com/api/login then this will succeed without any additional configuration as they're both on https://www.example.com.
CORS applies when your frontend is on a different host to the API. This is a security feature.
Consider this scenario:

*

*Your frontend allows you to launch intercontinental nukes, but you have to first log in with a username and password.

*When you log in, the backend generates a session cookie for you, and your browser automatically uses that for subsequent requests.

*CORS doesn't exist.

Unfortunately, a bad actor has befriended you and sends you a link to a website with funny cat videos. What you don't realise is that website actually has a script running on it. That script makes a request to your Nukes API, requesting that it launch a nuke.
Without CORS (if it didn't exist), or with excessively permissive CORS rules, your browser will happily make this request using your existing session cookie from the Nukes frontend. This is very bad. CORS allows you to configure what origins (essentially websites) the browser should allow to make requests to your API. You can control what verbs (GET, POST, PUT, DELETE, etc.) are allowed, what headers are allowed, whether credentials can be used, etc. This allows you to ensure that malicious scripts running on other websites can't impersonate your users against your API.
When a browser makes an AJAX request, it will first call the endpoint with the OPTIONS verb, and get the CORS rules for that endpoint. Next it will make the actual request to that endpoint, once again validating the CORS rules in the response (although after the request has been processed by the server).
How do I configure CORS?
You can use the EnableCorsAttribute, which can be placed on an individual controller method, or on the controller class as a whole:
[EnableCors("https://localhost:55912",       // Origin
          "Accept, Origin, Content-Type", // Request headers
          "PUT",                          // HTTP methods
          PreflightMaxAge=600             // Preflight cache duration
)]
public HttpResponseMessage Put(Resource data)
{
    return Request.CreateResponse(HttpStatusCode.OK, data);
}

Source
Or you can configure it at the application level:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
    // Other configuration omitted
        config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // origins, request headers, methods
    }
}

More fine-grained approaches are also described in the documentation.
There's also DisableCorsAttribute that can be applied to a controller action or a controller class to disable CORS for that action or controller. Please bear in mind the security implementations of using this if you choose to.

A: Okay, 8 days into this, I have a definitive answer.
If one want a C# WebApi endpoint to be exposed to any origin, one needs to have this in the header:

The most certain way to do this is by adding something like this to the controller methods that need to accommodate any origin:
            if (!cResponse.Headers.Keys.Contains("Access-Control-Allow-Origin"))
                Response.Headers.Add("Access-Control-Allow-Origin", "*");

The "best" way is a matter of opinion. This can be a line in the method. It can be in the method attributefilters. (I do it in OnActionExcuting with an ActionFilterAttribute.)
Some important things.
[DisableCors] may work. But it may not. Implementations of this decoration do not work everywhere. (I don't know why.)
Calls need to be sequential, and not async. I know. But if the processing thread switches to a thread from the same origin after you have set the header, and then comes back the Response Header gets reset to whatever was in the original Request. So, async calls run the risks of "stomping" on your Access-Control-Allow-Origin header entry.


text:
Q: Handling large numbers of optional fields in redux-form The app I'm working on has an array of suppliers, each containing an array of products. We're looking at about 20 suppliers, and 4k products total (across all suppliers) at the moment, although this could easily get much larger.
Our ordering view displays the list of suppliers on the side of the page, and clicking the supplier then renders a list of products for that supplier. Each item in the list contains an amount field for that specific product. Essentially the entire form requires 4k fields, one for each product.
My question is what is the best approach for controlling this large a number of fields when using redux-form?
The first solution might be to use redux-form's <FieldArray /> and have a form structure like so:
{
  suppliers: [
    {
      id: 'supplier0',
      notes: 'Some notes for this supplier',
      products: [
        {
          id: 'product0',
          amount: 10
        }
      ]
    }
  ]
}

However if I'm not mistaken this would require initialising the form with entries for all 4k products (since they're not being added or removed dynamically while the form is in use). It also means that any sort of processing on the form, like submitting, requires looping over all products to check if they have an amount value.
Alternatively I've been thinking I could maybe use an indexed structure like this:
{
  suppliers: {
    {{supplierId}}: {
      notes: 'Some notes for this supplier',
      products: {
        {{productId}}: {
          amount: 10
        }
      }
    }
  }
}

Then for each rendered row I just construct the amount field name using the supplier and product ids:
<Field name={`suppliers.${supplierId}.products.${productId}.amount`} />

This would save having to do any initialisation, and therefore keep the form state much more manageable.
I haven't really come across this anywhere else, and can't see any examples of such a use case in redux-form's docs. Is there any downside to this second indexed approach? Any reason I absolutely should be using FieldArray instead?


text:
Q: Calculating mode with modeest package in R I am using the below code for calculating the mode of a dataframe:
library(modeest)
apply(df[ ,2:length(df)], 1, mfv)

My data looks like this:
Item    A   B   C
Book001 56  32  56
Book002 95  95  20
Book003 50  89  50
Book004 6   65  40

It gives me the following output:
[[1]]
[1] 56

[[2]]
[1] 95

[[3]]
[1] 50

[[4]]
[1]  6 40 65

This code is perfect only if the data contains a recurring term.
How can I display the mode as NA when there is no recurring term?

A: Let's try with a custom function:
foo <- function(x){
  out <- mfv(x)
  if(length(out) > 1)  out <- NA
  return(out)
}
apply(df[ ,2:length(df)], 1, foo)
# [1] 56 95 50 NA


text:
Q: Is it possible to implement Property Changed as Attribute? I have found an implementation of Propperty Changed Event, where i can Call Property changed without the Name of the Property in the web. And then i have build a Extension Method with it wich is here
public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged, string    propertyName = null)
{
    if (propertyName == null)
        propertyName = new StackTrace().GetFrame(1).GetMethod().Name.Replace("set_", "");
    FieldInfo field = iNotifyPropertyChanged.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
    if (field == (FieldInfo) null)
        return;
    object obj = field.GetValue((object) iNotifyPropertyChanged);
    if (obj == null)
        return;
    obj.GetType().GetMethod("Invoke").Invoke(obj, new object[2]
    {
        (object) iNotifyPropertyChanged,
        (object) new PropertyChangedEventArgs(propertyName)
    });
}

So i can call Property changed like this:
private bool _foo;
public bool Foo
{
    get { _foo; }
    private set
    {
        _foo = value;
        this.OnPropertyChanged();
    }
}

But I thought, it would be nicer if i don't have to implement the getter and setter of a Property when i use Property changed.
Does anyone now how to implement the OnPropertyChanged Method as Attribute, maybe with AOP?
So that Auto-Property can be used for Property Changed like this:
[OnPropertyChanged]
public bool Foo {set;get;}

A: Check out Fody, and the PropertyChanged add-in. It will modify the IL after compilation to add the code to raise the PropertyChanged event for your properties. It's similar to PostSharp, mentioned in Lasse's answer, but it's free and open-source.

A: You will need some kind of AOP system to do this.
Either something where you wrap or inherit from your class, and dynamically generate the necessary plumbing in the wrapper/descendant to handle this, or some system like Postsharp that rewrites your code after compilation.
There is nothing built into .NET to handle this.


text:
Q: Emacs Python.el, Syntax Highlighting Quirks I'm using python.el version 0.23.1 for Emacs right now.  The syntax highlighting seems to be a bit off -- any variable name containing an underscore followed by a keyword will result in the keyword being highlighted.  Example, "foo_list" will result in "list" being highlighted.
More for my own understanding of Emacs-Lisp than anything (it's not a big deal) how do I go about fixing that.  Here is where I think the relevant code is in "python.el", lines 312-318.  I suspect the problem is with the definition of "symbol-start" but I have no idea what that name refers to.
(defvar python-font-lock-keywords
  ;; Keywords
  `(,(rx symbol-start
         (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
             "assert" "else" "if" "pass" "yield" "break" "except" "import"
         "print" "class" "exec" "in" "raise" "continue" "finally" "is"
         "return" "def" "for" "lambda" "try" "self")
     symbol-end)

One thing I've struggled with in Emacs-Lisp so far is that I am finding it difficult in situations like these to follow names back to their definitions.
Thanks in advance!

A: When you say you're using python-mode 0.23.1, do you mean the one that comes bundled with Emacs or this one: http://launchpad.net/python-mode ? (which seems to be on version 6.something)
The reason I'm asking is that I can't reproduce what you're seeing. In an empty python buffer, I inserted
def x ():
    a_list =3

and "list" is only highlighted when I delete the "a_". I'm using the version bundled with Emacs, with a snapshot version of Emacs so this might be the difference?
Incidentally, the font lock rule that you quote looks right to me: maybe the problem is that in your version "_" isn't set to have symbol syntax? You can check by typing
M-: (string (char-syntax ?_))

when in a python buffer. You should get "_" (which means symbol). If you get "." (punctuation) or something else weird, that probably explains what's gone wrong.


text:
Q: 3d effect using JazzyViewPager in Android Below is the image of the effect i want. This effect has been achieved using JazzyViewPager.
I tried to do the same but i'm not able to get the same effect. any help will be appreciated.


text:
Q: Scanner.Buffer - max value has no effect on custom Split? To reduce the default 64k scanner buffer (for microcomputer with low memory), I try to use this buffer and custom split functions:
scanner.Buffer(make([]byte, 5120), 64)
scanner.Split(Scan64Bytes)

Here I noticed that the second buffer argument "max" has no effect. If I instead insert e.g. 0, 1, 5120 or bufio.MaxScanTokenSize, I can' t see any difference.
Only the first argument "buf" has consequences. Is the capacity to small the scan is incomplete and if it's to large the B/op benchmem value increases.
From the doc:

The maximum token size is the larger of max and cap(buf). If max <= cap(buf), Scan will use this buffer only and do no allocation.

I don't understand which is the correct max value. Can you maybe explain this to me, please?
Go Playground
package main

import (
    "bufio"
    "bytes"
    "fmt"
)

func Scan64Bytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
    if len(data) < 64 {
        return 0, data[0:], bufio.ErrFinalToken
    }
    return 64, data[0:64], nil
}

func main() {
    // improvised source of the same size:
    cmdstd := bytes.NewReader(make([]byte, 5120))
    scanner := bufio.NewScanner(cmdstd)

    // I guess 64 is the correct max arg:
    scanner.Buffer(make([]byte, 5120), 64)
    scanner.Split(Scan64Bytes)

    for i := 0; scanner.Scan(); i++ {
        fmt.Printf("%v: %v\r\n", i, scanner.Bytes())
    }

    if err := scanner.Err(); err != nil {
        fmt.Println(err)
    }
}

A:
max value has no effect on custom Split?

No, without split there is the same result. But this wouldn't be possible without split and ErrFinalToken:
//your reader/input
cmdstd := bytes.NewReader(make([]byte, 5120))

// your scanner buffer size
scanner.Buffer(make([]byte, 5120), 64)

The buffer size from the scanner should be larger. This is how I would set buf and max:
scanner.Buffer(make([]byte, 5121), 5120)


text:
Q: c3 scaling similar to d3? I have used c3 to make some graphs and am impressed with its ease of use. However, I'm not sure if it is possible to a 3 value scaling like you can in d3 like the code below:

var yScale= d3.scale.linear()
.domain([0,100,500])
.range([height, height - 20, 0]);

so then i can make my graphs scaled mainly for values below 100 since this is where the majority of values will be and I don't want the bars scale to be skewed by values exceeding 100.
Is it possible to do something like this in c3? or do I need to use d3 to get this sort of scaling?
Thanks

A: You could use a scale to map the value and scale.invert to get all the labels. For example...
var myScale = d3.scale.linear().domain([0, 5, 50]).range([0, 40, 50]);

var chart = c3.generate({
    data: {
        columns: [
            ['A', 3, 2, 1, 4, 1.5, 42.5].map(function (value, index) {
                return index ? myScale(value) : value;
            })],
        type: 'spline'
    },
    tooltip: {
        format: {
            value: function (value) {
                return parseFloat(myScale.invert(value).toFixed(5));
            }
        }
    },
    axis: {
        y: {
            tick: {
                format: function (d) {
                    return myScale.invert(d)
                }
            }
        }
    }
});

The parseFloat and toFixed is to get rid of precision problems when you convert back and forth.
Fiddle - http://jsfiddle.net/rujx39fw/

There is a similar issue on the c3 github at  https://github.com/masayuki0812/c3/issues/252. It was closed with a similar workaround (there is a linked question too - that was closed by referencing this workaround)
There is also a related question you may be interested in at https://github.com/masayuki0812/c3/issues/971 that suggests another option, if you are feeling adventurous.