text:
Q: How can I make a Readable stream from a Writable stream? (Node.js) I'm creating Excel data on the fly using Exceljs
I want to buffer this thing in memory, then send it off to the user using Koa.
The write method for Exceljs expects a writableStream:
workbook.xlsx.write(writableStream, options)
BUT Koa expects a readable stream:
response.body = readableStream
I know I can pipe a readable stream into a writable stream, but how do I do the opposite? I want Exceljs to write into the writable stream and have Koa read from the same stream. I'm so frustrated with the streams API!
Among 20 other things, I tried this:
const ReadableStream = require("memory-streams").ReadableStream

const reader = new ReadableStream()

const writer = new stream.Writable({
    write: function(chunk, encoding, next) {
        console.log(chunk.toString())
        // reader.push(chunk, encoding)
        next()
    }
})

const reader = new MemoryStream(null, {readable: true})
// reader.write = reader.unshift
const writer = reader

workbook.xlsx.write(writer, {})
return reader

But it doesn't work, I get some weird error about not being able to write to a stream that is closed. Even if I handle the error, however, my Excel file doesn't open.
So how can I make a readable stream out of a writable stream?

A: For all who need to have a stream writable and readable. This is what finally worked for me.
Use case was QRCode package generating QRCode png image from dynamic var (ex: userId) only using stream.Writable --> to uploading to AWS S3 bucket only using stream.Readable.
import QRCode from 'qrcode';
import AWS from 'aws-sdk';
import { Transform } from 'stream';

const userId = 'userIdString';

// AWS Config, import this from a safe place!!!
AWS.config.update({
  accessKeyId: 'xxxxxxxxxx',
  secretAccessKey: 'xxxxxxxxx',
  region: 'xxxxxxx',
});

const s3 = new AWS.S3({ apiVersion: '2006-03-01' });

// Create Stream, Writable AND Readable
const inoutStream = new Transform({
  transform(chunk, encoding, callback) {
    this.push(chunk);
    callback();
  },
});

// Need writable stream
QRCode.toFileStream(inoutStream, userId);

//Just to check
inoutStream.on('finish', () => {
  console.log('finished writing');
});

// Need readable stream
  s3.upload(
    {
      Bucket: 'myBucket',
      Key: `QR_${userId}.png`,
      Body: inoutStream,
      // ACL: 'public-read',
      ContentType: 'image/png',
    },
    (err, data) => {
      console.log(err, data);
    },
  )
  .on('httpUploadProgress', (evt) => {
    console.log(evt);
  })
  .send((err, data) => {
    console.log(err, data);
  });

If you never used stream before this is a very good source.

A: You need a transform stream. It's both readable and writable.
stream = new require('stream').Transform()
stream._transform = function (chunk,encoding,done)
{
    this.push(chunk)
    done()
}

A: Have you considered Passthrough  stream? That's a simple transform stream that passes all data passed to it, so you can read from a writable stream.


text:
Q: java.lang.UnsatisfiedLinkError: debugLevel Alright, I've been going thru posts left and right trying to figure out this error.. I've managed to fix a few errors, but this is just driving me nuts.. it has almost no information.. or atleast none that makes any sense to me.
  D/dalvikvm(431): Trying to load lib /data/data/com.hyperlinkup.manglerbt/lib/libventrilo_interface.so 0x405156c8
D/dalvikvm(431): Added shared lib /data/data/com.hyperlinkup.manglerbt/lib/libventrilo_interface.so 0x405156c8
D/dalvikvm(431): No JNI_OnLoad found in /data/data/com.hyperlinkup.manglerbt/lib/libventrilo_interface.so 0x405156c8, skipping init
D/dalvikvm(431): GC_EXTERNAL_ALLOC freed 61K, 53% free 2565K/5379K, external 1027K/1038K, paused 89ms
W/dalvikvm(431): No implementation found for native Lcom/hyperlinkup/manglerbt/VentriloInterface;.debuglevel (I)I
D/AndroidRuntime(431): Shutting down VM
W/dalvikvm(431): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime(431): FATAL EXCEPTION: main
E/AndroidRuntime(431): java.lang.UnsatisfiedLinkError: debuglevel
E/AndroidRuntime(431):  at com.hyperlinkup.manglerbt.VentriloInterface.debuglevel(Native Method)
E/AndroidRuntime(431):  at com.hyperlinkup.manglerbt.ServerList.onCreate(ServerList.java:96)
E/AndroidRuntime(431):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(431):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime(431):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime(431):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime(431):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime(431):  at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(431):  at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(431):  at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(431):  at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(431):  at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(431):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(431):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(431):  at dalvik.system.NativeStart.main(Native Method)
I/Process(431): Sending signal. PID: 431 SIG: 9

I'm trying to rework the Mangler app to use Bluetooth recording (via startBluetoothSco), but I want to make sure the original is working before incorporating the bluetooth functionality.. Any help I can get on this matter would be greatly appreciated.
edit: thinking maybe my issue is with jni_wrappers.c.. first 3 #include's are unresolved.. original build was on linux system it would appear, so it's looking for jni.h, stdint.h and ventrilo3.h

A: Answer is in the Logcat Stacktrace itself
No implementation found for native Lcom/hyperlinkup/manglerbt/VentriloInterface;.debuglevel (I)I D/AndroidRuntime(431): Shutting down VM
There is a Native method called debuglevel in VentriloInterface. You have not implemented that method. So, the VM throws java.lang.UnsatisfiedLinkError.

redpajama_set_name: RedPajamaStackExchange


text: Q: Positive/negative octupole moment of nuclei? Does octupole moment of nuclear charge distribution show any positive/negative character, like the quadrupole moment does? Quadrupole moment has prolate and oblate types, but what about characterization of octupole moment?


text:
Q: Importing CSV file to teradata using SQL ASSISTANT I am importing a CSV file to teradata using SQL ASSISTANT, there is a date column, the dates are in the formats d/m/yyyy,d/mm/yyyy,dd/m/yyyy and dd/mm/yyyy. How can i get all of them from the CSV file to teradata in the format dd/mm/yyyy using the SQL ASSISTANT.
Thanks

A: Cast(RegExp_Replace(?,'\b([\d])\b', '0\1') AS DATE FORMAT 'dd/mm/yyyy')

The RegEx pads single digits with a leading zero, then it can be safely casted.
SQL Assistant is not the best/fastest way to import, don't forget to set the Maximum Batch size for simple Imports option to 999 to increase speed.


text:
Q: Log4JavaScript server-side receiving I'm trying to use Log4Javascript to send client-side errors to the server where results can then be written to file. I'm using the AjaxAppender to try to send the data to the server. I started with a simple "Hello world" to see if I can figure out how to receive error messages because the documentation literally says "no server-side code is provided".
Basically, I'm relatively new to this. A good Java programmer, HTML, CSS, Javascript, etc. But I've recently dived into the world of JSP and I was trying to use that to receive the error messages and (for now) print them to the debug console.
I have minimal code in my index.jsp file. Just an h1 tag that says "Hello World" and links to my javascript and jquery.
My Javascript is as follows:
var url = "logger.jsp";
$(function(){
    var log = log4javascript.getDefaultLogger();
    var ajaxAppender = new log4javascript.AjaxAppender(url);
    ajaxAppender.addHeader("Content-Type", "application/json");
    log.addAppender(ajaxAppender);
    window.onerror = function(errorMsg, url, lineNumber){
        log.fatal("Uncaught error "+errorMsg+" in "+url+", line "+lineNumber);
    };
    log.info("Hello World");
}

And I wasn't sure how the data would be passed to the server so I decided to list all attributes and start there. So far, I have the following as server-side code (logger.jsp):
<%@page import="java.util.*"%>

<%
for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) {
    String attribName = (String) e.nextElement();
    Object attribValue = session.getAttribute(attribName);
    System.out.println(attribName+" - "+attribValue);
}
%>

Which prints the following to the console:
logger - test.Logger@5a5517ef

I've done a lot of Google searches but came up with nothing that helps with the server side so far. It's quite possible that I missed something so if anyone has gone through this and has any tips or even a VERY bare-bones example of how to receive messages from the AjaxAppender for Log4JavaScript, I would greatly appreciate it!

A: If you want to send JSON, use a JsonLayout in your AjaxAppender:
var log = log4javascript.getDefaultLogger();
var ajaxAppender = new log4javascript.AjaxAppender(url);
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
log.info("Hello World");

This will send the logging message as HTTP form data with one name/value pair whose name is data and whose value is a JSON representation of your logging message.
This is covered in the documentation for AjaxAppender.


text:
Q: Call to undefined method PHP_CodeCoverage_Filter::getInstance() in Netbeans 7.4 I am new to PHPUnit.
I have installed PHPUnit using PEAR
I am using PHP 5.4.7
When I give command phpunit --bootstrap src/autoload.php tests/MoneyTest I got the below error

Fatal error: Call to undefined method PHP_CodeCoverage_Filter::getInstance() in D:\xampp\php\phpunit on line 39

If I run the same code with Netbeans 7.4, the same error occurs.
Please provide your suggestions.
Thanks in advance.


text:
Q: For an universal set $U$, prove or disprove, for sets $A,B,C \subseteq U, A \cap C = B \cap C \implies A = B$ I've tried to solve the question in two different ways :

*

*Using Characteristic function(CF).

$$CF(A) = \{ 1, x \in A \text{ ; } 0, \text{elsewhere}\}$$
$$CF(B) = \{ 1, x \in B \text{ ; } 0, \text{elsewhere} \}$$
$$CF(C) = \{ 1, x \in C \text{ ; } 0, \text{elsewhere} \}$$
Since, $$A \cap C = B \cap C $$
$$CF(A) * CF(B) = CF(B) * CF (C)$$
$$\text{Therefore, } CF(A) = CF(B)$$
$$\implies A=B$$

*

*Consider the following counter example :
Let $$A = \{1,2,3\} , B = \{2,3,4,5\} , C = \{2,3\}.$$
$$A \cap C = \{2,3\} \text{ and } B \cap C = \{2,3\} \text{ but } A \neq B.$$
Hence disproved by counter example.
Which one is correct ? Many thanks in advance.

A: The statement $A \cap C = B \cap C \implies A = B$ is false.
Your conclusion that "Therefore, $CF(A) = CF(B)$" is false, since you didn't consider the possibility of dividing by zero.
Your counterexample is sufficient to disprove the statement. Also, I would suggest considering three disjoint sets $A, B, C$. In this case, $A \cap C = \varnothing = B \cap C$, yet $A \neq B$

A: A picture might help with this one too:

A: And, of course, if $C = \varnothing$ then $A \cap C = B \cap C = \varnothing$
for any $A$ and $B$.


text: Q: How do I disable shortcuts from Chrome IOS app? How can you disable the chrome shortcuts from showing up on my IOS devices using Chrome Browser?  I see I can manually remove them one at a time by pressing and holding but they keep returning when I visit sites.


text:
Q: Get mid point between 4 LonLat Android I have 4 LonLat points and i would like to find the midpoint of the 4.
To do so I took the first 2 found the mid point, then the second 2 found the point, then find the midpoint between the 2 first results.
To find the mid point between my points i used the code found on this post: https://stackoverflow.com/a/4656937/4489629
Unforuntaly it does not work i get a value that is on the equator for some reason, while the locations that I am trying to find the midpoint are in the UK.
Here is my code:
private void treatForDispaly(double averageSpeed, double averageElevation, RecordObject[] records) {
        String currentDateTimeString = String.valueOf(new java.util.Date());

        LatLng firstTwo = midPoint(records[0].getLatitude(), records[0].getLongitude(), records[1].getLatitude(), records[1].getLongitude());
//        LatLng seconTwo = midPoint(records[2].getLatitude(), records[2].getLongitude(), records[3].getLatitude(), records[3].getLongitude());
//        LatLng averageLatLng = midPoint(firstTwo.latitude, firstTwo.longitude, seconTwo.latitude, seconTwo.longitude);

        ContentValues newValues = new ContentValues();
        newValues.put(ContentProviderContract.DAILY_RECORDS_TREATED_DATETIME,currentDateTimeString);
        newValues.put(ContentProviderContract.DAILY_RECORDS_TREATED_ALTITUDE, averageElevation);
        newValues.put(ContentProviderContract.DAILY_RECORDS_TREATED_SPEED, averageSpeed);
        newValues.put(ContentProviderContract.DAILY_RECORDS_TREATED_LATITUDE, records[0].getLatitude()); // firstTwo.latitude
        newValues.put(ContentProviderContract.DAILY_RECORDS_TREATED_LONGITUDE, records[0].getLongitude()); //firstTwo.longitude

        getApplicationContext().getContentResolver().insert(ContentProviderContract.DAILY_RECORDS_TREATED_URI, newValues);

        RecordTreatedObject tempRecord = new RecordTreatedObject();
        tempRecord.setDateTime(new Date(currentDateTimeString));
        tempRecord.setElevation(averageElevation);
        tempRecord.setLatitude(firstTwo.latitude);
        tempRecord.setLongitude(firstTwo.longitude);
        tempRecord.setSpeed(averageSpeed);
        dailyRecordsTreated.add(tempRecord);
    }

    public static LatLng midPoint(double lat1,double lon1,double lat2,double lon2){
        double dLon = Math.toRadians(lon2 - lon1);

        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
        lon1 = Math.toRadians(lon1);

        double Bx = Math.cos(lat2) * Math.cos(dLon);
        double By = Math.cos(lat2) * Math.sin(dLon);
        double lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By));
        double lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx);

        //return out in degrees
        LatLng midpoint = new LatLng(lat3, lon3);
        return  midpoint;
    }

Here are the values that I am inputing:
D/DEBUG: first locatoin lat: 52.954037691647834 long: 52.954037691647834
D/DEBUG: second locatoin lat: 52.95385240191483 long: 52.95385240191483

and here is what i get as a result:
D/DEBUG: midpoint lat 0.9242206929866051 midpoint long: 0.9242206929866051

Thanks

A: This is just a wild guess but it seems to be that you are getting results in radians. Convert result back to degrees and you get 52.9539448 which is correct I presume.


text:
Q: Implementing Stocktwit Share in php loop? I am working on a site and I require that stocktwit share button appears against each post which are running in loop. i tried integrating the share button from the stocktwit site. The first button is working fine, it fetches the data i m providing in the "data-text". But for the rest they simply open a share screen with no values fetched. Please suggest how I should use the share button in a loop?

A: If I understand this correctly you are trying to have multiple share buttons on one page. You can go about this 2 ways.
Using the share button coded as so should work:

The issue you are seeing is because of the multiple button ID's. You can only have one per page.
The other option is to use our API and the message/share endpoint. This will give you more control. http://stocktwits.com/developers/docs/api#messages-create-docs


text:
Q: How to create a file properly in dart? My app was working normally until the simulator changed to iPhone 13, now I'm getting an error when creating files:
Future<File> get planDataFile async {
    final path = await _localPath;
    return File('$path/planData');
}

Future<Plan> createFile() async {
var syncPath = await planDataFile;
    if (!File('$syncPath').existsSync()) {
        new File('$syncPath').createSync();
    }
    // more code
}

I tried using the non sync version, doesn't help either.. am I missing something? I also tried using the recursive true flag.
Error logs:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot create file, path = 'File: '/Users/[user]/Library/Developer/CoreSimulator/Devices/086D31E9-3552-440C-A5D4-134520461353/data/Containers/Data/Application/212EDDC5-E435-45D0-9415-1FE4957DF8F8/Documents/planData'' (OS Error: No such file or directory, errno = 2)
#0 _File.throwIfError (dart:io/file_impl.dart:635:7)
#1 _File.createSync (dart:io/file_impl.dart:273:5)
#2 readPlan (package:planner/utils/utils.dart:25:27)

Application finished.
Any suggestions?


text:
Q: Deploy a Cloud Function to different Firebase projects I have two firebase projects, one for development (project-dev) and one for production (project-prod).
I initialized firebase CLI for writing and deploying cloud functions linked to project-prod. Then I ran firebase use --add and added project-dev so that I can deploy the same function to both projects; I don't want to rewrite the same function twice.
At this point, I faced the problem. Into the function, I have to write something to the realtime database, but when I deploy the function to project-dev it writes to project-prod's database.
What I want to achieve is that the function has to refer to the database of the project that it is deployed to. So that I have one function and when it is deployed to project-dev it writes to project-dev's database and when it is deployed to project-prod it writes to project-prod's database.
Is it possible to achieve that? If not, what's the way to go?
EDIT
Function code:
exports.AddOrders= functions.https.onRequest(async (req, res) => {
    async function addOrder(key, value) {
        var ref = app.database().ref("/orders");
        return ref.child(key).set(value);
    }

    var orders = req.body['orders'];
    var promises = [];
    for (var key in orders) {
        promises.push(addOrder(key, orders[key]));
    }
    Promise.all(promises).then(
        _ => {
            res.sendStatus(200);
            return null;
        }
    ).catch(err => {
        res.send(err);
    })
});

(This function works fine, the problem is that it writes on the wrong database)

A: After you add a project with firebase use --add <projektName> you need to select it with firebase use <projectName>. Then you can deploy to the selected project with firebase deploy or firebase deploy --only functions.

A: This is the answer for anyone wondering what the problem was.
He was initialising the admin sdk with the credentials of a service account tied to the production project. The solution was to change it to admin.initializeApp() without passing any arguments. This made Firebase use the default credentials for each project.
I know its a common mistake but again, here is the link to the corresponding documentation https://firebase.google.com/docs/admin/setup


text:
Q: How to read csv file in string format in C#? The entire workflow is that I need to read a csv file located at a path, then do some modifications in the data and then load the data into specific tables  through C#. The C# code is running inside MSBI SSIS package script.
I am using .Net StreamReader to read the data from the file path.
var reader = new StreamReader(File.OpenRead(@"filepath"));

This works very fine but after that I'm unable to convert the StreamReader output to string format for some complex data modification in string.
Is there any direct type casting that I can use here? Any alternate solutions are also welcome.

A: I'd use
var reader = new StreamReader(File.OpenRead(@"filepath"));
while (!reader.EndOfStream)
{
    var line = reader.ReadLine();
    var values = line.Split(',');

    //Do processing here, modify values and add to tables etc
}

the values object will then be an array of values in order of the csv.
You can then access using values[0], values[1], values[n] etc.  Do your processing on the individual values and add to tables record by record.


text:
Q: Adobe illustrator Script paste I found that command app.paste() but it doesnt return string its just pasting into document text. Basicaly i need command that return clipboard!
http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf
http://prntscr.com/cg5qtb

A: I suppose there is no command in Illustrator that will return clipboard data. You can use app.copy() and app.paste() if you want to copy paste between different applications and if you want to use only in Illustrator you can use the duplicate method provided in Illustrator documentation.

A: app.paste() causes the new layer it creates to be the only selected layer, so you can access the text contents by returning its .contents property like this:
#target illustrator

function getClipboard() {
    var doc = app.activeDocument;
    var clipboard = '';

    app.paste();
    clipboard = doc.selection[0].contents;
    doc.selection[0].remove();

    return clipboard;
}
function main() {
    alert( getClipboard() );
}
main();```


text:
Q: Método render me duplica los datos? Tengo un component que al poner una función dentro del método componentDidMount me ejecuta 2 veces lo que tengo en el método render, la 1ra que es la debería ejecutar y vuelve y me ejecuta lo mismo y si pongo otra función dentro del componentDidMount se ejectura una más, o sea 3 veces.
Me di cuenta de esto porque estaba validando algunos datos con el console.log en el método render y mostraba 2 veces la data que pasaba por el console.log.
Aquí mi código, hasta ahora estoy empezando en React y he revisado todo y no se por qué me pasa esto.
import React from 'react';

class WeatherApp extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      data: [],
    }
  }

componentDidMount = () => {

    this.geolocation(this.location);

  }

 geolocation = position => {

    if (navigator.geolocation) {

      navigator.geolocation.getCurrentPosition(position);

    } else {
      console.log('No Soporta ubicación')
    }

  }

location = async position => {

    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    await this.getData(latitude, longitude);
  }

 getData = async (lat, lon) => {

    const latitude = lat;
    const longitude = lon;
    const API_URL = `https://api.openweathermap.org/data/2.5/onecall?
    lat=${latitude}&lon=${longitude}`;
    const API_KEY = `c196bcdce7bad59b552b30dbfefd9b2b`;

    try {

      const response = await fetch(`${API_URL}&appid=${API_KEY}`);
      const data = await response.json();
      this.setState({
        data: data,

      });

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

render() {
    console.log(this.state.data);
    const lat = this.state.data.lat
    return(

      <div>{lat}</div>

    );

  }

El JSX se renderiza una vez pero el console.log(this.state.date) se pinta 2 veces en la consola, una con el array vacio del estado y otra con la data de la petición ya en el estado, si pongo un console.log con algún string me muestra igualmente 2 veces el string en la consola.

A: Así es como funciona React JS.
Cuando el componente padre se acopla al árbol DOM, se dispara un primer snapshot de la app en memoria, aquí se propagan objetos como state y props a los componentes Leaf.
Este primer snapshot, es lo que te muestra la consola en el primer console.log(this.state.date).
No hay datos en el estado, configuración inicial.
Luego, el Lifecycle Method componentDidMount(), espera a que se acople el componente para ejecutar alguna acción. En este caso, en algun punto de la función que llamas ahí dentro, tienes un API method setState, que dispara otro snapshot(conocido como re-render).
Este segundo snapshot, es el segundo console.log(this.state.date) que te muestra la consola.
Aqui ya vez los datos en el estado, pues la operación asíncrona ya se completó.
Se puede decir que un snapshot, es una recarga (re-render) del árbol virtual DOM de React en la memoria del explorador web, es imperceptible a simple vista, pasa muy rápido. Pero se puede observar por medio de capturas en la consola.
Espero que esta respuesta sea de ayuda,
Saludos


text:
Q: mongoose is giving error invalid type on findById I am new to node js, I was trying to get user from Mongo db with mongoose but it is giving me error. THis is my UserScheme in db.js:
const config = require('config');

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

mongoose.connect(config.get('mongo.uri'));
mongoose.set('debug', config.get('app.verbose') === true);
mongoose.set('useFindAndModify', false);

const UserSchema = new Schema({
       phone             : String,
       shortPhone        : String,
       password          : String,
       averageRating     : Number,
       profile           : {
               email        : String,
               mainlyHereFor: String,
               enabledVideoResume: {type: Boolean, default: false},
               seekingOpportunityType: String,
               fullName     : String,
               username     : String,
               address      : {
                       city   : {type: String, default: 'Unknown'},
                       state  : String,
                       country: String,
                       zip    : String
               },
      }
}

exports.User = mongoose.model('User', UserSchema);

The user is being created, but when I am trying to find the user by id with mongoose it is giving me some invalid type error:
const express = require('express');
const db = require('../db');

router.get('/search', (req, res) => {
  db.User.findById('5f20ec88d5cf2f2994bc42d4') // req.user.id)
    .then((user) => {
      let connsFilter = user.connections.filter((conn) => conn.relationship == 'connected');
      const users = connsFilter.map((conn) => conn.user);

      let query = {
        'connections.user': { $in: users }
      };

      return db.User.find(query)
        .select('-contacts')
        .populate({ path: 'jobs', match: { spam: false } });
    })
    .then((result) => {
      res.json(result);
    })
    .catch((err) => {
      res.status(400).json({ status: 'bad', error: err });
    });
});

Clicking on db.User always takes me to the definition of User schema but it still goes to the catch block, even if this user exists in my database.

A: use that
db.User.findById(ObjectId('5f20ec88d5cf2f2994bc42d4')),
you have to use ObjectId if ur _id is object_id instead of normal string


text:
Q: from google.cloud import monitoring_v3 ImportError: cannot import name monitoring_v3 I am trying to utilize the Google Cloud Platform's Stack Driver API with the following Python/Flask code below...
view.py
import google.cloud
from google.cloud import monitoring_v3
# from google.cloud.monitoring_v3 import query

requirements.txt
Flask==0.12.2
oauth2client==2.0.1
google-api-python-client==1.6.2
facebookads==2.11.1
httplib2==0.10.3
enum==0.4.6
requests-toolbelt==0.8.0
google-cloud-storage==1.6.0
google-resumable-media==0.3.1
google-auth
google-cloud-monitoring==0.28.0
google-cloud

For whatever reason it can't seem to find the monitoring_v3 library as when whenever I run the code I am getting the following error...
from google.cloud import monitoring_v3
ImportError: cannot import name monitoring_v3

I have tried to update to google-cloud-monitoring==0.29.0 and that just churns out another non-related error.

A: I solved it by upgrading monitoring 0.29.0 to 1.1.0
pip install --upgrade google-cloud-monitoring

Latest version now available is 2.0.0
https://pypi.org/project/google-cloud-monitoring/

A: Could be a conflict (dependency or otherwise) between google-api-python-client and google-cloud*.
The former is a REST client which includes the monitoring API, the latter is gRPC based client.
Are you using 'google-api-python-client' for anything else?  If no, try removing that?

A: Make sure your requirements.txt file is proper, and located in the source directory where you have the main.py.
If everything fails , copy a requirements.txt file from a working function , and replace the requirements modules in it (strangely this worked for me :P)


text:
Q: Is there any disavantages/drawbacks of storing commas after arrays? I've seen some of this "lazy coding technique" lately when creating arrays (in PHP):
$arr = array(
    array(
        'name' => 'mr magoo',
        'pet' => 'dog',
    ),
    array(
        'name' => 'superman',
        'pet' => 'cat',
    ),
    array(
        'name' => 'the hulk',
        'pet' => 'bear',
    ),
}

I absolutely see the point of having commas after each array, because it's easy to insert or delete some array without having to care about adding/deleting commas. (If I want to delete superman I just delete those rows)
$arr = array(
    array(
        'name' => 'mr magoo',
        'pet' => 'dog',
    ),
    array(
        'name' => 'the hulk',
        'pet' => 'bear',
    ),
}

Is there are any distadvantages/drawbacks using this "technique"?
(I think what's really bugging me is that I think that PHP should generate an error or at least a warning because this commas is really not needed)
In javascript I know that there could be issues with some browsers (internet explorer of course) when having a comma (where it merely shouldn't be)
var info = {'mr maggo', 'hukl',}

but javascript is of course on the client-side, so that's another thing.


text:
Q: Vue.js Import Objects I'm facing a problem with importing Objects from the App.vue file to a component. But first I should explain the purpose of this project.
There's a component (navigation-drawer) and an App.vue file. The Navigation drawer has vue props in it, which you can dynamically change in the App.vue file. The problem with that is that I can only use as many links as there are in the Navigation-Drawer file.
I would like to edit it so I can use as many links as I need, without even having to open the Navigation-Drawer.vue file. Before I go into more detail, here are the files with the props & limited amount of links:
App.vue
<template>

    <navigation-drawer
    name1="TFBern"
    name2="Stackoverflow"
    name3="YouTube"
    name4="Google"
    link1="https://vuejs.org"
    link2="https://stackoverflow.com"
    link3="https://youtube.com"
    link4="https://google.com"
    />

    <HelloWorld msg="Welcome to Your Vue.js App"/>

</template>

Navigation-Drawer.vue
<template>

        ☰

            ×
            {{ name1 }}
            {{ name2 }}
            {{ name3 }}
            {{ name4 }}

</template>

Now, what I had in mind was to create a js object, which can import the links from App.vue into the Drawer. Something like this:
<navigation-drawer links="[ {title="Google", link="www.google.ch"} , {title="Youtube", link="www.youtube.com"} , {title=…, link=…} ]"

I don't really know how to do it... Can anyone help?
Thank you.

A: You are pretty close to the answer already. Change = to :, the values to be surrounded with ' instead of " so you have a list of objects
<navigation-drawer v-bind:links="[ {title:'Google', link:'www.google.ch'} , {title:'Youtube', link:'www.youtube.com'} , {title:…, link:…} ]"

Then the navigation-drawer props look like:
props: {
    links: Array
},

and the html loops through the links with a v-for and template:

    ☰

        ×
        <template v-for=v-for="(link, index) in links">
            {{ link.title}}
        </template>


text:
Q: The parsing of an eml with javamail doesn't recognize properly nested messages I'm implementing an .eml parser using Javamail 1.5.6, I've started copying from msghow.java a sample provided within javamail.
I'm testing an eml which contains as attachment another eml, this is an extract:
MIME-Version: 1.0
Date: Tue, 30 Apr 2019 16:20:45 +0200
Message-ID: <CA+fLqEW8TUfSxih9DTp2WXa63pS7wf1eZiro_9k1XS4AShN5Zg@mail.gmail.com>
Subject: Message with an eml as attachment
From: a b <ab@gmail.com>
To: cd@pec.cd.it
Content-Type: multipart/mixed; boundary="00000000000057f76c0587c01bc9"

--00000000000057f76c0587c01bc9
Content-Type: multipart/alternative; boundary="00000000000057f7670587c01bc7"

--00000000000057f7670587c01bc7
Content-Type: text/plain; charset="UTF-8"

Hello guys,

this is a simple message from a not certified account, it contains only one
attachment, an eml message

--00000000000057f7670587c01bc7
Content-Type: text/html; charset="UTF-8"

Hello guys,

this is a simple message from a not certified account, it contains only one attachment, an eml message

--00000000000057f76c0587c01bc9
Content-Type: message/rfc822; name="Cena zerebao.eml"
Content-Disposition: attachment; filename="Cena zerebao.eml"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_jv3vpu760
Content-ID: <f_jv3vpu760>

WC1Ob3Rlcy1JdGVtOiBGcmksIDYgSnVsIDIwMTggMTc6NDA6MDAgKzAyMDA7DQogdHlwZT00MDA7
IG5hbWU9T3JpZ2luYWxNb2RUaW1lDQpYLU5vdGVzLUl0ZW06IE1lbW87DQogbmFtZT1Gb3JtDQpY
LU5vdGVzLUl0ZW06IFN0ZE5vdGVzTHRyMjU7DQo.... and so on

Javamail recognizes that eml but when I get its subject, date, body, attachments and so on, they all are null.
msghow.java itself doesn't see them.
Before javamail I implemented my parser with mime4j and I haven't this problem, but now I would like to parse emls using only javamail if possible

A: From the javadocs describing the mail.mime.allowencodedmessages property:

The MIME spec does not allow body parts of type message/* to be encoded. The Content-Transfer-Encoding header is ignored in this case. Some versions of Microsoft Outlook will incorrectly encode message attachments. Setting this System property to "true" will cause the Content-Transfer-Encoding header to be honored for message attachments. The default value of this property is false.


text:
Q: JSF 2.2(Mojarra 2.2.0) Primefaces Issue - While clicking on download button, application is throwing out to sessionExpired page Here is a snippet of SupportingDocs.xhtml code

        <p:commandButton value="Download" ajax="false" icon="ui-icon-arrowthick-1-s" styleClass="blue-button" actionListener="#{entityType.downloadDFile}">
            <f:attribute name="selectedFile" value="#{supportingDoc[column['supportingDocument.downloadlink.column']]}" />
        </p:commandButton>

When clicking on Download button, it is downloading file perfectly but in the same time it is logging out as well.
Here is some pointers which I have got while debugging the application.

*

*Click "Download" button

*It calls loginFilter ->doFilter()

*then it calls loginController -> destroySession()

*then it calls sessionListener -> sessionDestroyed()

*then it creates new session by calling sessionListener ->sessionCreated()

*then loginFilter -> doFilter()


text:
Q: using skimage shannon-entropy to calculate image entropy I'm using shannon-entropy function in skimage to calculate entropy of grey-scale image.
After examine the its source code:
def shannon_entropy(image, base=2):
    return scipy_entropy(image.ravel(), base=base)

where scipy_entropy is :
def scipy_entropy(pk, qk=None, base=None):
    pk = asarray(pk)
    pk = 1.0*pk / np.sum(pk, axis=0)
    if qk is None:
        vec = entr(pk)
    else:
        qk = asarray(qk)
        if len(qk) != len(pk):
            raise ValueError("qk and pk must have same length.")
        qk = 1.0*qk / np.sum(qk, axis=0)
        vec = rel_entr(pk, qk)
    S = np.sum(vec, axis=0)
    if base is not None:
        S /= log(base)
    return S

we can see that scipy_entropy receive pk as a sequence of probability. However, the img.ravel() only give the flatten array of image.
I suppose it should do sth. like img.hist() to get the frequency distribution of different grey-scale value.
Can any one explain what does it mean? Of maybe I have some misunderstand of entropy calculation?


text:
Q: Command history in zsh Currently I have zsh set up in such a way that command history is shared between all sessions immediately.
Say I have a terminal emulator open with two tabs, each with a zsh session, A1 and A2. If I enter ls -la in A1, and then go to A2 and press up arrow key, I will see ls -la in the command prompt.
I would like to change it so sessions don't share the command history with each other although when you start new session it gets all the previous history from all sessions before it.

A: Check out the available options to control history. I think you want
setopt append_history no_inc_append_history no_share_history

This is the default zsh setup, by the way.
You can save the history explicitly at any point with fc -AI and merge it back in with fc -RI.


text:
Q: Jquery implementing a success and error callback for my plugin that works with AJAX I have written a small Jquery plugin that makes it easy for me to implement Facebook like "likes" on any item in my application. My only issue now is that I struggle to implement the success / error callback of my plugin.
$('.user-like').like({
    success: function(data, textStatus, jqXHR) {
        $(this).text('Liked');
    }
});

My issue with the above code is this line:
$(this).text('Liked');

I'm aware of what why the issue happens, I just can't find a good way to make it work like I want it. Let me explain how the script works and what my Goal is:
As you can see I'm passing the call along to the likeApi() function that executes an AJAX call. Further you see that I merge my Options with the defaults and that you can override the success and error callback of the AJAX object.
The issue is now that this in the above code is the scope of the AJAX call and not my original method. I want to allow the user to define his own success / error callback that depends on the result of the API call and allows me to do something based on the state if it was a success or failure so that I can change the like text for example. How can I do this?
(function ($) {

    $.likeApi = function (action, options) {
        if (action != 'like' && action != 'unlike') {
            return false;
        }
        var options = jQuery.extend({}, jQuery.likeApi.defaults, options);
        $.ajax({
            type: "POST",
            url: options.baseUrl + action + '.json',
            data: {
                data: {
                    Like: {
                        foreign_key: options.id,
                        model: options.model
                    }
                }
            },
            success: options.success,
            error: options.error,
            dataType: 'json'
        });
    };

    $.fn.like = function (options) {
        var scopedOptions = options;
        this.on('click', function(event) {
            event.preventDefault();
            $.likeApi('like', $.extend({}, scopedOptions,{
                'id': $(event.target).data('like-fk'),
                'model': $(event.target).data('like-model')
            }));
        });
        return this;
    };

    $.fn.unlike = function (options) {
        var scopedOptions = options;
        this.on('click', function(event) {
            event.preventDefault();
            var result = $.likeApi('unlike', $.extend({}, scopedOptions,{
                'id': $(event.target).data('like-fk'),
                'model': $(event.target).data('like-model')
            }));
            alert(result);
        });
        return this;
    };

    $.likeApi.defaults = {
        baseUrl: '/likes/likes/',
        action: null,
        model: null,
        id: null,
        error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function(data, textStatus, jqXHR) {
            alert(textStatus);
        }
    };

}(jQuery));

A: Two options: you can maintain context by adding a variable that references the original this, or you can use jquery.proxy()
Option 1:
Maintain the context by adding a variable that references the original this like so:
(function ($) {
    $.likeApi = function (action, options) {
        var self = this;

Then you just call self whenever you are out of context.
If you want to keep self available externally, you can inject it using jquery extend.
http://api.jquery.com/jquery.extend/
options.success = $.extend(options.sucesss, {el: self});

inside your ajax call
$('.user-like').like({
    success: function(data, textStatus, jqXHR) {
        $(data.el).text('Liked');
    }
});

Option 2:
Alternatively, you can use jQuery.proxy()
http://api.jquery.com/jquery.proxy/
proxy can change the this context for you...


text:
Q: Unable to select an element from dropdown list in an React web page using Robotframework selenium I am trying to automate an react web page using selenium2library and Robotframework. While trying to select an element from a list, selenium could not locate the value/ index in the list.
Code used to select the element
Inspect of the list element.

        <form class="col-md-12 center-form-container">

                ThemePark

                    <select class="form-control" name="factory">
                        <option index="0" value="">Select a ThemePark</option>
                        <option index="1" value="2018061109361161">Wonderla Kochi</option>
                        <option index="2" value="2018061109394722">Wonderla Bangalore</option>
                    </select>

        </form>

The code used to select the element from the list.
Click Element    //*[@id="basic0"]/form/div/diventer code here
Sleep    2s
Capture Page Screenshot
Click Element    //*[@id="basic2018061109361161"]/form/div[1]/div/select
Wait Until Page Contains Element    //select[@name="factory"]    timeout=60s
Select From List By Value   //select[@name="factory"]   2018061109361161

Also tried 'Select From List By Index' and 'Select From List By Label', but all the options are throwing error that 'unable to find the value / index/ label in the selected element.

A: Try the following code:
browser.find_element_by_css_selector("select.form-control > option[value='2018061109361161']").click()


text:
Q: Using my own security algorithm on a tcp connection I know there are several techniques out there to encrypt data. I am not familiar with them so I been thinking on a way to make my application more secure. I basically have a server application and a client application. The client application sends data to the server app. anyways if you are probably familiar with this protocol you'll know that every thing that get's written to the network stream will be received by the other party. I am basically sending bytes. so my algorithm is something like:
I have a byte array ready to be sent to the server. Modify that byte array. all the bytes that hapend to have values greater than 0 and less than 50 add 5 to them. all the bytes that are greater than 49 and less than 100 add 2 two them. and keep doing the same thing for the rest of the bytes.
and then on the server side I will have the reverse technique.
will this be secure? how will someone sniffing packages will be able to find what I am sending?

Edit
Thanks guys for the help. I been thinking about algorithms and I came up with several ones:
technique 1
Let's say I want to send the byte[] {5,89,167,233,23,48,79}
first step: I will add a random byte to index 0 of the array:
so now the new byte array is {X, 5, 89, 167, 233, 23,48,79}
let's assume that x came out to be 75
if is greater than -1 and less than 50 I will apply algorithm number 2 two it. If it is greater than 49 and less than 100 I will apply algorithm 3 two it... etc...
In this case we will use algorithm 3:
so algorithm 3 will basically change the order of every 3 consecutive bytes so the actual byte that I will send is:   {X, 167 (last item of the three consecutive bytes), 5 (first item), 89 (second Item), 48 (last item of the next three consecutive bytes), 233 (fist), 48, null,79,null)
get read of the null bytes in order to get {X, 167, 5,89,48,233,48,79}
------->
now the server will get {X, 167, 5,89,48,233,48,79}   recall that x was 75 therefore it will apply algorithm 3 to decrypt. it will be basically the same thing in reverse order.
so it will do { 5 (the second item of the first three consecutive bytes), 89 (the last item), 167 (first item of those first three bytes),
233 (the second item of the next three bytes), 23, 48,
79
then the server will have 5,89,167,233,23,48,79
if X will have been 1 for instance I will do the same thing but instead of doing that in chuks of three I would do it on chunks of 2. basically flipping bytes. if x would had been 130 then do the same thing in chunks of 4....

I am not going to place the next technique. I may come up with several techniques I love algorithms lol.
I have to say that I agree with all of you let me show you why...
I think I have to be thinking what a hacker will do. I will probably be a bad hacker since I don't know about encryption but I thought about this. Ok I am a hacker and I want to be able to see what is being sent through the network. so if I am the hacker and I see {X, 167, 5,89,48,233,48,79} I will not be able to say nothing right. But since I am a clever hacker I get the program that streams those bytes in order to try to figure it out. I will then use the program to send something easy such as a file that contains the bytes {0,1,2,3,4,5,6}
by sending this bytes several times the hacker is going to be able to see stuff like:
{ 45, 1,0,3,2,5,4,6}
then maybe
{44  1,0,3,2,5,4,6}
.... etc
from that point of view now I understand why it might be easier to figure it out.

A: A good encryption CAN'T depend on the algorithm, it must depends on the key! The encryption algorithms are well known standards and rely on the secretness of the key, not of the algo!

A: First off, your scheme can't decrypt since e.g. 47 becomes 52 and 50 becomes 52, also. Second, it's insecure since anybody with your algorithm can easily decode your ciphertext (well, at least as well as you can, given that not even you can decode all messages). Moreover, a simple frequency-based approach would work since this is essentially a substitution cipher...

A:
I am not familiar with them so I been thinking on a way to make my
  application more secure.

Stop right there. Being unfamiliar with solutions that already exist isn't a reason to try to invent, from scratch, a new solution that is at least as secure as those solutions that do already exist. Your efforts should be directed towards becoming familiar with at least one of those solutions, i.e. SSL. I assure you it is infinitely more secure than anything you are likely to come up with in the short term.
And of course as you have just published your algorithm, it is already insecure.


text:
Q: Template level constant I'm used to declare ui element selectors, when I'm implementing UI module in ASP.NET.
It goes something like this:
...
var loginSelector = '#btnLogin';
var textBoxSelector = 'form.login[type=text]';
...
$(textBoxSelector).val('');
...

That way I have only one place to change if html got updated.
How can declare template level constants in Meteor, to used across all template helpers and events? What are the best practices for that?

A: If you want template-level scope you can simply declare these in the same file as your template helpers and events. They will be available in all your helpers and events. If you want a wider scope then you can create global variables.


text:
Q: How to reference cells from another sheet I have two sheets, s1 and s2. I want to make calculations on the data in s1 and enter them in cells in s2.
If data in s1 is in column A from rows 1 - 10, I should be able to find the mean by typing =MEAN(s1!A1:A10), right? All the google searches I've done support this. But all that happens is that I see '=MEAN(s1!A1:A10)' typed in the cell in s2. Its like the function isn't applying.

A: From your description of the problem it sounds like the Number Formatting is set to TEXT for the range where you are entering formulas that do not calculate, but instead just display as the entire formulas.
To fix this problem, the solution is to set the Number Formatting to GENERAL for the affected range and then to re-enter the formulas.


text:
Q: Distinct left join for foreign id I need to find the latest 'message' from each 'user' and list them (like an inbox of conversations as per iPhone etc).
The fields in my messages table are:
id|to|from|body|timestamp
to = the current users ID
from = sender user id
How would I construct a query that gets the latest post for every distinct user where the 'from' field is unique? Obviously, the first condition is that the 'to' field matches the current users ID.
Each message from a distinct user should also join the user details into the results.
Also if you're able to demonstrate how this would work in CakePHP that would be awesome..! If not, just the SQL should do :)

A: You can use SQL with subquery, like:
SELECT
  messages.*,
  max_stamps.max_stamp
FROM
  (SELECT
    MAX(timestamp) as max_stamp,
    `from`
   FROM
     messages
   WHERE
     messages.`to`=$currentUser
   GROUP BY
    `from`
  ) as max_stamps
  LEFT JOIN
    messages
    ON messages.`from`=max_stamps.`from`
       AND max_stamps.max_stamp=messages.timestamp

-i.e. select max timestamps first in subquery, then use them for main table.
(update) If you want get maximum id value, then use it in MAX():
SELECT
  messages.*,
  max_ids.max_id
FROM
  (SELECT
    MAX(id) as max_id,
    `from`
   FROM
     messages
   WHERE
     messages.`to`=$currentUser
   GROUP BY
    `from`
  ) as max_ids
  LEFT JOIN
    messages
    ON messages.`from`=max_ids.`from`

edit: misunderstood id, from and to meanings. Tip: naming tables/columns with MySQL reserved words may cause troubles (at least you have to enclose that with backticks).


text:
Q: How to decide whether it is a system of Differential Algebraic Equations or a System of Ordinary Differential Equations? I am struggling to name some of my dynamic models right. To be specific, I am not sure whether I should call it a system of Differential Algebraic Equations (DAEs) or a System of Ordinary Differential Equations (ODEs) with parameters defined by algebraic equations.
Example:
Equations:
$\frac{dx_1}{dt} = x_1 \times (x_2 \times a_0)$
$\frac{dx_2}{dt} = x_2 + (x_1 \times a_1)$
$a_0 = c_0 \times T$
$a_1 = c_1 \times T$
$T = c_2 \times t$
$c_0, c_1, c_2$ are constants $\in \mathbb{R} $
$a_0, a_1, T, x_1, x_2$ are variables $\in \mathbb{R} $
Is it save to define such systems as DAEs?

A: You can call it a DAE, but since it is so easy to replace both $a_0$ and $a_1$ by a constant times $t$, better do it first and than call the result a differential equation.


text:
Q: Is "due to be published" correct? An excerpt from The Economist:

A white paper, due to be published as the Economist went to press but leaked beforehand, sets out plans for the first major NHS legislation in a decade.

I believe "due to" is a preposition, so how does "be published" follow it? Shouldn't it be "being published"?

Just to make it clear, I am not asking the meaning of the sentence, but rather the grammatical construction.

A: If it were the causal sense of "due to", you'd be right.
However, there's another sense of "due" that means "scheduled". Try replacing the word and it makes sense:

A white paper, scheduled to be published...

This sense probably grows out of the sense "owed", which is the meaning the word originally had in French: "Ten dollars are due to the plaintiff." From there, at least two metaphorical senses developed. One is the causal usage, which developed that way in French as well: a result is "owing to, due to" a cause.
The other is a little more subtle. Here's a set of examples that show the meaning balancing between "owed" and "scheduled" till the line blurs.

When is the assignment due? (owed, i.e. obligated to be given to the teacher)

It's due on the 27th.

The 27th is the due date. Don't miss the deadline.

Your library book is overdue! You had to return it yesterday.

A raise and some time off are overdue.

You're due for a raise!

When is it due to be published?


text:
Q: misunderstanding array pointers passed to functions in C Why don't the print statements in the function match the top level prints?
#include<stdio.h>
#include <stdlib.h>
#include<math.h>

void bar(float **foo)
{
  printf(" &foo[0][0]    %f \n", &foo[0][0]);
}

int main()
{
  float mat[5][5], **ptr;
  mat[0][0] = 3.0f;
  ptr = (float **)mat;
  printf("  mat[0][0]    %f \n",  mat[0][0]);
  printf(" &ptr[0][0]    %f \n", &ptr[0][0]);
  bar(ptr);
}

the results:
 mat[0][0]     3.000000
 &ptr[0][0]    3.000000
 &foo[0][0]    -0.005548

A: You should print pointers using %p. not %f. Also, the cast (float**)mat doesn't make any sense.
When you say &((float**)mat)[0][0], you actually look for a pointer in the address of mat. if pointers are wider than floats, you will read from some other bytes in the stack, and they can changed when you call functions.

A: Several others have gotten you for what looks like confusion between mat[0][0] being of type float and &ptr[0][0] being of type float *, but you have another more subtle problem: ARRAYS ARE NOT POINTERS.
Normally arrays are a lot like pointers, but for very subtle reasons, float [][] is not compatible with float ** the way float [] and float * are.
In many contexts (such as being passed to a function), an array decays to a pointer to its first element. Thus, mat decays to &mat[0]. The type of an array T [] decays to a pointer T *, which means that the type mat decays to (and the type of &mat[0]) is float (*)[] - that is, a pointer to an array of fixed size.
Here is the difference between a float * and a float[]:
float *     float[]
+-----+     +-----+-----+
| ptr | --> | 0.0 | 1.0 |
+-----+     +-----+-----+

Now here is the difference between a float ** and a float[][]:
float **    float *[]   float[][]         float (*)[]
+-----+     +-----+     +-----+-----+     +-----+     (imagine this
| ptr | --> | ptr | --> | 0.0 | 1.0 | <-- | ptr |     pointing to
+-----+     +-----+     +-----+-----+     +-----+     the 0.0 cell)
            | ptr | --> | 2.0 | 3.0 |
            +-----+     +-----+-----+

Those types are, from left to right, pointer-to-pointer-to-float, array-of-pointers-to-float, array-of-arrays-of-floats, and pointer-to-array-offloats. The address of &float[0], converted to a float **, gets dereferenced twice as a pointer even though there is only one pointer - the pointer to float[0] (and thus, the rest of the array). Any value you get through this is garbage.


text:
Q: Please provide a mobile-optimized captcha page When working with the mobile version of one of the mobile sites, my connection got really slow, and (I think this is what) caused Apple.SE to show me a captcha. I'm okay with that, but  I'd like to point out that the mobile site should have a mobile optimized captcha.
With slow internet connections in mind, I suggest to implement a mobile-optimized captcha page.


text:
Q: Uniformly distribute points in 4D I am trying to distribute points onto a 4D surface. I have an implementation that evenly distributes data points onto a 3D surface octant.
n_samples = 100
N = int(np.floor(np.sqrt(0.25+2*n_samples) -0.5))

phis = np.linspace(start=0, stop=0.25*np.pi, num=N)

# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
    phi = phis[n-1]
    for theta in np.linspace(start=0, stop=0.5*np.pi, num=n):
        x = np.sin(phi)*np.cos(theta)
        y = np.sin(phi)*np.sin(theta)
        z = np.cos(phi)
        points.append([x,y,z])

points = np.array(points)

df = pd.DataFrame(points, columns=['x', 'y', 'z'])
fig = px.scatter_3d(df, x='x', y='y', z='z')
fig.show()

I am having difficulties in extending this to a 4D surface and visualizing it. Am I thinking about this correct? I need all my points evenly distributed in an octant. For 3D, I am leveraging the quadratic equation to distribute the points, for 4D, I am leveraging the cubic equation for the same.
n_samples = 100
poly = [1, 1.5, 0.5, 3*n_samples]
N = int(np.floor(-np.real(np.roots(poly)[0])) - 1)

phi_1s = np.linspace(start=0, stop=0.25*np.pi, num=N)

# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
    phi_1 = phi_1s[n-1]
    for phi_2 in np.linspace(start=0, stop=0.25*np.pi, num=n):
        for phi_3 in np.linspace(start=0, stop=0.5*np.pi, num=n):
            x1 = np.cos(phi_1)
            x2 = np.sin(phi_1)*np.cos(phi_2)
            x3 = np.sin(phi_1)*np.sin(phi_2)*np.cos(phi_3)
            x4 = np.sin(phi_1)*np.sin(phi_2)*np.sin(phi_3)
            points.append([x1, x2, x3, x4])

points = np.array(points)

df = pd.DataFrame(points, columns=['x', 'y', 'z', 'c'])
fig = px.scatter_3d(df, x='x', y='y', z='z', color='c')

Any thoughts on this is appreciated..


text:
Q: Conversion failed when converting the varchar value '!AA24!' to data type int I'm getting this error when I execute a stored procedure that contains negative values. Is there any way of converting or resetting a column value to fix it?

Conversion failed when converting the varchar value '!AA24!' to data type int.

Code:
DECLARE @PartnerId VARCHAR(10) = 'ITS';
DECLARE @DASHBOARD_ID VARCHAR(20) = '-1'

DECLARE @AGENT_ID INT

SELECT @AGENT_ID = IdAgent
FROM DGSDATA.dbo.AGENT WITH (NOLOCK)
WHERE agent = @PartnerId

IF (@DASHBOARD_ID = '-1' OR @DASHBOARD_ID = '-2' OR @DASHBOARD_ID = '-3')
    UPDATE [WAR_DB].[dbo].[WAR_DGS_CORE_USER]
    SET PrimaryLayoutType = @DASHBOARD_ID
    WHERE @AGENT_ID = USER_ID

UPDATE [dbo].[WAR_GLOBAL_DASHBOARD]
SET IS_PRIMARY_DASHBOARD = 0
WHERE @AGENT_ID = AGENT_ID AND IS_PRIMARY_DASHBOARD = 1

A: It is hard to tell where the exact conversion problem is occurring, but I suspect that IdAgent is really a string.  So I would start by changing:
DECLARE @AGENT_ID VARCHAR(255);  -- use the actual type of the agent

SELECT @AGENT_ID = IdAgent
FROM DGSDATA.dbo.AGENT
WHERE agent = @PartnerId;


text:
Q: Return a multiple lined string with a specific number of characters I have a very long string that I would like to output in the following format:
I need to output a maximum number of characters say 40 per line while I maintain a maximum of say 5 lines and discard the rest.  This should be the return string of the webservice (SOAP).
Here is a snippet of what am trying to implement.
String output = "A veeery long string with more than 200 characters";

StringBuilder sb = new StringBuilder(output);
int i = 0;
while ((i = sb.indexOf(" ", i + 40)) != -1)
{
    sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());

result = sb.toString();
...

return result;

Now the System.out.println(sb.toString()); works just fine, but when I user the webservice tester it returns 1 line on the browser which is not what I wanted to achieve

A: You can also use Guava library for these kinds of operations. Have a look at Splitter
Also, try to search on the website beforehand, since there's ton of questions like these :)

A: I think you need to do this....
result = result + sb.toString();

when you do this result = sb.toString(); then you are making result to point to a new String object, and it looses the reference to the previous String object.
using result = result + sb.toString(); you STILL ARE POINTING TO A NEW STRING OBJECT, but this time the new String object has the previous and current String.

A: If you view the source of the page in your browser, are the lines split?  If so, you will need to replace the newlines with <br> tags.


text:
Q: How to keep both filters active using jquery? I am trying to filter a table on columns department and location.
These filters are working one at a time.
I am clueless on how to make both filters working at the same time.
For example if I need to filter all "Engineering" departments with the "New York" location.
How can I make the code remember and apply both filters at the same time? Thanks for the help.

//function to filter the departments based on selection
function filterTextDept() {
  var rexD = new RegExp($('#filterTextDept').val());
  if (rexD == "/all/") {
    clearFilter()
  } else {
    $('.content').hide();
    $('.content').filter(function() {
      return rexD.test($(this).text());
    }).show();
  }
}

function clearFilter() {
  $('#filterTextDept').val('');
  $('.content').show();
}

//function to filter the locations based on selection
function filterTextLoc() {
  var rexL = new RegExp($('#filterTextLoc').val());
  if (rexL == "/all/") {
    clearFilter()
  } else {
    $('.content').hide();
    $('.content').filter(function() {
      return rexL.test($(this).text());
    }).show();
  }
}

function clearFilter() {
  $('#filterTextLoc').val('');
  $('.content').show();
}

    <title></title>

  <select id="filterTextDept" onchange="filterTextDept()">
    <option disabled="disabled" selected="selected">Filter by Department</option>
    <option value="Compliance">Compliance</option>
    <option value="Data Science">Data Science</option>
    <option value="Engineering">Engineering</option>
    <option value="Growth">Growth</option>
    <option value="Product Management">Product Management</option>
    <option value="Sales">Sales</option>
    <option value="all">All</option>
  </select>
  <select id="filterTextLoc" onchange="filterTextLoc()">
    <option disabled="disabled" selected="selected">Filter by Location</option>
    <option value="New York">New York</option>
    <option value="Chennai">Chennai</option>
    <option value="San Francisco">San Francisco</option>
    <option value="San Diego">San Diego</option>
    <option value="Remote">Remote</option>
    <option value="all">All</option>
  </select>

        Job Title
        Department
        Location

        Account Manager
        Growth
        New York

          Link

        Associate Account Manager
        Growth
        New York

          Link

        Director, Account Executive
        Sales
        New York

          Link

        Director, Account Executive
        Sales
        San Diego

          Link

        Director, Account Executive
        Sales
        San Francisco or Remote

          Link

        Director of Engineering
        Engineering
        New York

          Link

        Director of Product Management, Fraud Risk
        Product Management
        New York

          Link

        Director of Strategic Alliances
        Sales
        San Diego

          Link

        Head of Solution Consulting
        Growth
        San Diego, New York or Remote

          Link

        IT Risk and Compliance Officer
        Compliance
        New York

          Link

        Lead Data Scientist
        Data Science
        New York or Remote

          Link

        Senior Data Engineer
        Data Science
        New York or Remote

          Link

        Senior Data Scientist
        Data Science
        New York or Remote

          Link

        Senior Product Manager, Document Verification
        Product Management
        New York

          Link

        Senior Software Engineer
        Engineering
        Chennai

          Link

        Software Engineer (All Levels)
        Engineering
        New York or Remote (East Coast)

          Link

        Solution Consultant
        Growth
        San Francisco or New York

          Link

        Staff Software Engineer - Chennai
        Engineering
        Chennai

          Link

        Staff Software Engineer - Core Platform
        Engineering
        New York or Remote (East Coast)

          Link

A: I tried to modify your code as little as possible. You were very close to the solution
My approach is to run all the filters every time.
EDIT
You can check the count of line displayed with $('.content:visible').length

function updateFilters () {
clearFilter()
filterTextDept()
filterTextLoc()
postFilter()
}
function postFilter() {
  $visibleLinesCount = $('.content:visible').length
  if ($visibleLinesCount === 0) {
    // here your logic when no result
    console.log('no result')
  } else if ($visibleLinesCount === 1) {
    console.log('only one result')
  } else {
    console.log($visibleLinesCount + ' results')
  }
}
//function to filter the departments based on selection
function filterTextDept() {
  var rexD = new RegExp($('#filterTextDept').val());
  if (!$('#filterTextDept').val()) {
    // nothing selected
    return;
  } else if (rexD == "/all/") {
    return;
  } else {
    //$('.content').hide();
    $('.content').filter(function() {
      return !rexD.test($(this).text());
    }).hide();
  }
}

//function to filter the locations based on selection
function filterTextLoc() {
  var rexL = new RegExp($('#filterTextLoc').val());
  if (!$('#filterTextLoc').val()) {
    // nothing selected
    return;
  } else if (rexL == "/all/") {
    return;
  } else {
    //$('.content').hide();
    $('.content').filter(function() {
      return !rexL.test($(this).text());
    }).hide();
  }
}

function clearFilter() {
  $('.content').show();
}

    <title></title>

  <select id="filterTextDept" onchange="updateFilters()">
    <option disabled="disabled" selected="selected">Filter by Department</option>
    <option value="Compliance">Compliance</option>
    <option value="Data Science">Data Science</option>
    <option value="Engineering">Engineering</option>
    <option value="Growth">Growth</option>
    <option value="Product Management">Product Management</option>
    <option value="Sales">Sales</option>
    <option value="all">All</option>
  </select>
  <select id="filterTextLoc" onchange="updateFilters()">
    <option disabled="disabled" selected="selected">Filter by Location</option>
    <option value="New York">New York</option>
    <option value="Chennai">Chennai</option>
    <option value="San Francisco">San Francisco</option>
    <option value="San Diego">San Diego</option>
    <option value="Remote">Remote</option>
    <option value="all">All</option>
  </select>

        Job Title
        Department
        Location

        Account Manager
        Growth
        New York

          Link

        Associate Account Manager
        Growth
        New York

          Link

        Director, Account Executive
        Sales
        New York

          Link

        Director, Account Executive
        Sales
        San Diego

          Link

        Director, Account Executive
        Sales
        San Francisco or Remote

          Link

        Director of Engineering
        Engineering
        New York

          Link

        Director of Product Management, Fraud Risk
        Product Management
        New York

          Link

        Director of Strategic Alliances
        Sales
        San Diego

          Link

        Head of Solution Consulting
        Growth
        San Diego, New York or Remote

          Link

        IT Risk and Compliance Officer
        Compliance
        New York

          Link

        Lead Data Scientist
        Data Science
        New York or Remote

          Link

        Senior Data Engineer
        Data Science
        New York or Remote

          Link

        Senior Data Scientist
        Data Science
        New York or Remote

          Link

        Senior Product Manager, Document Verification
        Product Management
        New York

          Link

        Senior Software Engineer
        Engineering
        Chennai

          Link

        Software Engineer (All Levels)
        Engineering
        New York or Remote (East Coast)

          Link

        Solution Consultant
        Growth
        San Francisco or New York

          Link

        Staff Software Engineer - Chennai
        Engineering
        Chennai

          Link

        Staff Software Engineer - Core Platform
        Engineering
        New York or Remote (East Coast)

          Link

A: This snippet does it with a logical OR:

const filters = {
  dept: '',
  loc: ''
}

const deptFilter = document.getElementById('filterTextDept')
const locFilter = document.getElementById('filterTextLoc')

deptFilter.addEventListener('change', function(e) {
  setFilters('dept', e.target.value)
})

locFilter.addEventListener('change', function(e) {
  setFilters('loc', e.target.value)
})

const setFilters = (type, val) => {
  filters[type] = val === 'all' ? '' : val
  const r = Object.values(filters).filter(e => e).join('|')
  const regex = new RegExp(`(${r})`)
  $('.content').hide();
  $('.content').filter(function() {
    return regex.test($(this).text());
  }).show();
}

<select id="filterTextDept">
  <option disabled="disabled" selected="selected">Filter by Department</option>
  <option value="Compliance">Compliance</option>
  <option value="Data Science">Data Science</option>
  <option value="Engineering">Engineering</option>
  <option value="Growth">Growth</option>
  <option value="Product Management">Product Management</option>
  <option value="Sales">Sales</option>
  <option value="all">All</option>
</select>
<select id="filterTextLoc">
  <option disabled="disabled" selected="selected">Filter by Location</option>
  <option value="New York">New York</option>
  <option value="Chennai">Chennai</option>
  <option value="San Francisco">San Francisco</option>
  <option value="San Diego">San Diego</option>
  <option value="Remote">Remote</option>
  <option value="all">All</option>
</select>

      Job Title
      Department
      Location

      Account Manager
      Growth
      New York

        Link

      Associate Account Manager
      Growth
      New York

        Link

      Director, Account Executive
      Sales
      New York

        Link

      Director, Account Executive
      Sales
      San Diego

        Link

      Director, Account Executive
      Sales
      San Francisco or Remote

        Link

      Director of Engineering
      Engineering
      New York

        Link

      Director of Product Management, Fraud Risk
      Product Management
      New York

        Link

      Director of Strategic Alliances
      Sales
      San Diego

        Link

      Head of Solution Consulting
      Growth
      San Diego, New York or Remote

        Link

      IT Risk and Compliance Officer
      Compliance
      New York

        Link

      Lead Data Scientist
      Data Science
      New York or Remote

        Link

      Senior Data Engineer
      Data Science
      New York or Remote

        Link

      Senior Data Scientist
      Data Science
      New York or Remote

        Link

      Senior Product Manager, Document Verification
      Product Management
      New York

        Link

      Senior Software Engineer
      Engineering
      Chennai

        Link

      Software Engineer (All Levels)
      Engineering
      New York or Remote (East Coast)

        Link

      Solution Consultant
      Growth
      San Francisco or New York

        Link

      Staff Software Engineer - Chennai
      Engineering
      Chennai

        Link

      Staff Software Engineer - Core Platform
      Engineering
      New York or Remote (East Coast)

        Link

Logical AND:

const filters = {
  dept: '',
  loc: ''
}

const deptFilter = document.getElementById('filterTextDept')
const locFilter = document.getElementById('filterTextLoc')

deptFilter.addEventListener('change', function(e) {
  setFilters('dept', e.target.value)
})

locFilter.addEventListener('change', function(e) {
  setFilters('loc', e.target.value)
})

const setFilters = (type, val) => {
  filters[type] = val === 'all' ? '' : val

  const regex1 = new RegExp(filters.dept)
  const regex2 = new RegExp(filters.loc)
  $('.content').hide();
  const list = $('.content').filter(function() {
    return regex1.test($(this).text()) && regex2.test($(this).text());
  }).show();
}

<select id="filterTextDept">
  <option disabled="disabled" selected="selected">Filter by Department</option>
  <option value="Compliance">Compliance</option>
  <option value="Data Science">Data Science</option>
  <option value="Engineering">Engineering</option>
  <option value="Growth">Growth</option>
  <option value="Product Management">Product Management</option>
  <option value="Sales">Sales</option>
  <option value="all">All</option>
</select>
<select id="filterTextLoc">
  <option disabled="disabled" selected="selected">Filter by Location</option>
  <option value="New York">New York</option>
  <option value="Chennai">Chennai</option>
  <option value="San Francisco">San Francisco</option>
  <option value="San Diego">San Diego</option>
  <option value="Remote">Remote</option>
  <option value="all">All</option>
</select>

      Job Title
      Department
      Location

      Account Manager
      Growth
      New York

        Link

      Associate Account Manager
      Growth
      New York

        Link

      Director, Account Executive
      Sales
      New York

        Link

      Director, Account Executive
      Sales
      San Diego

        Link

      Director, Account Executive
      Sales
      San Francisco or Remote

        Link

      Director of Engineering
      Engineering
      New York

        Link

      Director of Product Management, Fraud Risk
      Product Management
      New York

        Link

      Director of Strategic Alliances
      Sales
      San Diego

        Link

      Head of Solution Consulting
      Growth
      San Diego, New York or Remote

        Link

      IT Risk and Compliance Officer
      Compliance
      New York

        Link

      Lead Data Scientist
      Data Science
      New York or Remote

        Link

      Senior Data Engineer
      Data Science
      New York or Remote

        Link

      Senior Data Scientist
      Data Science
      New York or Remote

        Link

      Senior Product Manager, Document Verification
      Product Management
      New York

        Link

      Senior Software Engineer
      Engineering
      Chennai

        Link

      Software Engineer (All Levels)
      Engineering
      New York or Remote (East Coast)

        Link

      Solution Consultant
      Growth
      San Francisco or New York

        Link

      Staff Software Engineer - Chennai
      Engineering
      Chennai

        Link

      Staff Software Engineer - Core Platform
      Engineering
      New York or Remote (East Coast)

        Link

SUGGESTION
The concept you are applying here is based on that the DOM stores data, and you make your code work based on that data. A better approach would be to decouple the DOM and the data in your functions:

  Account Manager
  Growth
  New York

    Link

The DOM element above could be represented by a JavaScript object like this:
const content = [
  {
    jobTitle: "Account Manager",
    department: "Growth",
    location: "New York",
    link: "Account%20Manager",
    show: true
  }
]

You would have to add one render function to add the list of elements to the DOM:
const table = document.getElementById('jobTable')

let rows = content.filter(e => e.show).map({ jobTitle, department, location, link } => {
  let h = `

    ${jobTitle}
    ${department}
    ${location}

      Link

`
}).join('')

table.innerHTML = rows

This way you would just have to toggle the items show element (boolean - true, false) and run the render function - and it would always give you the list of items you want.


text:
Q: Vite app not rendered properly on Netlify Is there any environment variable to set up for my Vite app deployed on Netlify. When I use npm run dev on localhost, my site is rendered as expected, but when I use the same build command on Netlify, it just renders the pure HTML page without using the Vite main.js. I include my link to my project here: https://github.com/nguyenvothuan/Portfolio/tree/master and to netlify: https://quizzical-jepsen-e78ac7.netlify.app/

A: Update: Set the following:
build command: npm run build (not npm run dev)
publish directory: dist


text:
Q: Is there a LaTeX template for electronics data sheets? Many electronics data sheets appear in very similar formats.  E.g., Analog Devices DAC data sheet in PDF has a very common format.
Is there a LaTeX template for generating a document like the above?


text:
Q: Return random image SQL I have a database which holds information about user-created items. Each item can have a number of images associated with it, and I'd like to have an SQL query that 4 random item images, but should not return images from the same item twice.
Here's a review of the table structures (not full, but including the pertinent information):
Table 1 : item_images:
+----------+--------------+
| item_id  |   filename   |
+----------+--------------+
|    1     |   test.jpg   |
|    1     |   test2.jpg  |
|    5     |   testy.jpg  |
+----------+--------------+

Table 2: item_link:
+----------+-------------+
| item_id  | category_id |
+----------+-------------+
|    1     |      1      |
|    5     |      1      |
+----------+-------------+

So given the above data, I'd like to return a random image for item # 1 and 5, since they both exist in category # 1.
Here's the SQL query I have already tried, but for some reason, it always returns the same two images. How might I modify this to return a random image from the matched items?
SELECT `item_images`.`filename` AS `url` FROM `item_images`
  INNER JOIN `item_link` ON `item_images`.`item_id` = `item_link`.`item_id`
  WHERE `item_link`.`category_id` = 1
  GROUP BY `item_link`.`item_id`
  ORDER BY RAND()
  LIMIT 4

A: To find random image from table the query is below:
SELECT distinct `item_images`.`filename` AS `url` FROM `item_images`, `item_link`
  WHERE `item_images`.`item_id` = `item_link`.`item_id` and `item_link`.`category_id` = 1
  ORDER BY RAND()
  LIMIT 4

It solve your qry

A: webduos is right distinct should solve your problem
here is explaination
SELECT distinct `item_images`.`filename` AS `url` FROM `item_images`
INNER JOIN `item_link` ON `item_images`.`item_id` = `item_link`.`item_id`
WHERE `item_link`.`category_id` = 1
GROUP BY `item_link`.`item_id`
ORDER BY RAND()
LIMIT 4


text:
Q: Trying to extract JSON data from an URL into Jupyter? Trying to extract data from the website below:
https://gbfs.fordgobike.com/gbfs/gbfs.json

A: Is this what you want?
import requests

url = 'https://gbfs.fordgobike.com/gbfs/gbfs.json'
data = requests.get(url).json()

print(data)

Number of rides available, try this:
import requests

url = 'https://gbfs.fordgobike.com/gbfs/en/station_status.json'
data = requests.get(url).json()

d = {s['station_id']:s['num_bikes_available'] for s in data['data']['stations']}

print(d)

Result:
{'10': 28,
 '100': 14,
 '101': 8,
 '102': 22,
 '103': 0,
 '104': 0,
 '105': 5,
 '106': 1,
 '107': 14,
 '108': 1,
 '109': 2,
 '11': 16,
 '110': 10,
 '112': 13,
 '113': 5,
 '114': 9,
  ...


text:
Q: Convert.ToString() and .ToString() method in c# I know Convert.ToString(obj) handles null value and ToString(obj) doesn't handle null value.It means it will throw an error if the obj value is null.
ex:-
object b = null;
textBox1.Text = b.ToString(); // It will throw a null reference exception because the object value is null.

It is correct and working as expected.
But,
ex:-
int? c = null;
textBox1.Text = c.ToString();

I tried in this way.
But in this case it is not throwing null reference exception error.
Why it is not throwing null reference exception error. Can anyone answer?
Suggestions welcome.

A: This is because Nullable<int> (which is the Type for which int? is shorthand) is a struct and therefore never null.
int? c = null is actually assigning c.Value to be Null rather than c itself, so c.ToString() is still a valid operation.

A: Nullable<T> is a struct/value type. The actual nullable isn't null, but the value is. object is a class/reference type.


text:
Q: Python Tuple vs List check for inclusion bytecode performance/size profiling Given that the following code in python3.9 gives the same bytecode. (The List gets compiled to a Tuple)
"x" in ["a", "b", "c"]
"x" in ("a", "b", "c")

  1           0 LOAD_CONST               1 ('x')
              2 LOAD_CONST               2 (('a', 'b', 'c'))
              4 CONTAINS_OP              0
              6 RETURN_VALUE
  2           0 LOAD_CONST               1 ('x')
              2 LOAD_CONST               2 (('a', 'b', 'c'))
              4 CONTAINS_OP              0
              6 RETURN_VALUE

Why does timeit always say that a lookup in a tuple is faster than a lookup in an array?
Does timeit take into consideration compiling?
Similarly, when I use sys.getsizeof it says a Tuple uses less space.
When this code is ran, is there ever any space difference between the Tuple and the List in this example? Meaning, once compiled to bytecode there is no space difference if I'm understanding, but since a List is not immutable is the space allocated before the List is compiled into a Tuple?
import dis
import sys
from timeit import timeit

bcode = dis.dis(lambda: "x" in ["a", "b", "c"])
bcode2 = dis.dis(lambda: "x" in ("a", "b", "c"))

# why is the bottom always faster? - accounts for compile/start up time?
print(timeit(lambda: "x" in ["a", "b", "c"]))
print(timeit(lambda: "x" in ("a", "b", "c")))
# 0.10836188100000001
# 0.10678786800000001

# similarly I get that this is just returning __sizeof__(), but in practice (execution) is there any memory difference since the bytecode is the same?
print(sys.getsizeof(["a", "b", "c"])) # 120
print(sys.getsizeof(("a", "b", "c"))) # 64


text:
Q: Google Spreadsheet - Write to Blank Worksheet I'm creating a new worksheet in a Google Spreadsheet using the C# library.  After creating the worksheet, I want to write to it.  I don't have a LocalName, since it's a new sheet with no header.  Has anybody done this before?
newRow.Elements.Add(new ListEntry.Custom
{
    Value = value,
    LocalName = local
});

A: For new worksheet, I would suggest using the Cell based feed to add the first row:
  https://developers.google.com/google-apps/spreadsheets/#changing_contents_of_a_cell
Simply use the indexes A1 to A{N} to add the header and continue using the list based feed as you used to.


text:
Q: PostCSS css-next - global variables without having to use @import I have a file variables.css with CSS variables inside a :root{}
Right now each time I need to use it in another .css file I use:

@import './path/to/variables.css'.

I want to know if there is a way to have variables.css available globally without having to import it every single time I need it.
I tried to use the option customProperties on cssnext plugin, but it gives an error compiling css to a js object...
I'm using React with webpack 1 and as postcss plugins I have import, mixins, cssnext and nested.
Thanks

A: As far as I understand, no, but you can make your life easier. In your config for import, set the path, such as:
cssImport({ path: './src' })
And assuming your variables.css is in src/variables.css, you can simply do:
@import 'variables';
instead of dot walking back up the tree to find the right spot.

A: You import the variable.css to main.css(your global css file)
//main.css
@import "./variable.css";

Then in _app.js import the main.css:
// Your path to main.css
import "../assets/main.css"


text:
Q: Android Studio java sources c с ошибками Android Studio 2.2 jdk 1.8
Открываю в редакторе к примеру класс java.net.Socket
код отображается с ошибками:
к примеру, в блоке import присутствует import libcore.io.IoBridge;,который не найден.
Кто знает, почему исходники открываются с ошибками?
Второй вопрос:
Открываю класс sun.net.www.protocol.http.HttpURLConnection
открывается декомпилированный код без документации и с обсфуцированными именами переменных:
private boolean isRestrictedHeader(String var1, String var2) {
    if(allowRestrictedHeaders) {
        return false;
    } else {
        var1 = var1.toLowerCase();
        return restrictedHeaderSet.contains(var1)?!var1.equals("connection") || !var2.equalsIgnoreCase("close"):var1.startsWith("sec-");
    }
}

Может кто-нибудь знает, как загрузить данный класс с javadoc и с исходниками в Android Studio?


text:
Q: Почему программа не работает? После ввода числа программа замирает Задача:

Вычислить сумму ряда с заданной степенью точности Е (0,1^2+0,01^2/2!+
  0,001^2/3!+ …).

После ввода числа программа замирает и не вычисляет ничего.
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    float a, b=1, c = 2, s, i = 1,d=1;
    cout << "value for a =";
    cin >> a;
    s = 0;
    do {
        s = s + pow((d / 10),2) / b;
        d = d / 10;
        for (i; c; i++)
        {
            b = b* i;
        }
        c++;
    }
    while ( c <= a);

    cout << "s=" << s << endl;
    system("pause");
    return 0;
}

A: Программа не замирает, а вечно выполняет цикл:
for (i; c; i++)
{
      b = b* i;
}

так как условие, что с != 0, всегда выполняется


text:
Q: Fortran trim or adjustl not working while using twice I am trying to use trim/adjustl for the following code. It seems that I'm getting either X_eq_      10.0.dat or X_eq_10.0      .dat as the output file's name where I'm expecting it to be X_eq_10.0.dat (no blank space). Any remedy?
           Program Test
           double precision:: X
           character (len=10) :: tag
           character (len=100) :: outfile

           X=10.0

           write(tag,'(f10.1)') X
           print*,'tag=',tag

           outfile='X_eq_'//trim(tag)//'.dat'
           print*,'Output file: ',outfile

           outfile='X_eq_'//trim(tag)//trim('.dat')
           print*,'Output file: ',outfile

           outfile='X_eq_'//adjustl(trim(tag))//adjustl(trim('.dat'))
           print*,'Output file: ',outfile

           End Program Test

I have used gfortran as the compiler.

A: What you want is:
outfile='X_eq_'//trim(adjustl(tag))//'.dat'
adjustl shifts the characters left, leaving trailing blanks, so you need to trim that result. It does no good to do trim(tag) as that is already right-adjusted. Lastly, '.dat' doesn't need any processing.

A: In
write(tag,'(f10.1)') X

we say that we want tag to be of width 10 with one digit in the fractional part.  With the one decimal symbol that leaves us 8 places before the decimal: there will be blank padding beyond the (optional) sign.
This is why we see lots of blanks in outfile='X_eq_'//trim(tag)//'.dat'.
We can avoid this either with adjustl as noted in the question or another answer, or by using 0 in the edit descriptor:
write(tag,'(F0.1)') X

The F0.d form makes the field width the smallest appropriate field with: without leading blanks.
When tag has length 100 there will still be (lots of) trailing blanks, so a trim will be necessary.
Further, there are even ways to avoid using an intermediary such as tag without using trim.


text:
Q: Compiling ImGui in C++ On https://github.com/ocornut/imgui it says: No specific build process is required. You can add the .cpp files to your existing project. I tried this using Code Blocks with the relevant .cpp files, however it gives me about 500+ Undefined Reference to ... errors. The first beginning in imgui.cpp being |1994|undefined reference to `ImGui::InputText(char const*, char*, unsigned long, int, int (*)(ImGuiInputTextCallbackData*), void*)'. This is the following code I tried.
#include "imgui.h"

int main()
{

    bool my_tool_active = true;
    float my_color = 0.5;

    // Create a window called "My First Tool", with a menu bar.
    ImGui::Begin("My First Tool", &my_tool_active, ImGuiWindowFlags_MenuBar);
    if (ImGui::BeginMenuBar())
    {
        if (ImGui::BeginMenu("File"))
        {
            if (ImGui::MenuItem("Open..", "Ctrl+O")) { /* Do stuff */ }
            if (ImGui::MenuItem("Save", "Ctrl+S"))   { /* Do stuff */ }
            if (ImGui::MenuItem("Close", "Ctrl+W"))  { my_tool_active = false; }
            ImGui::EndMenu();
        }
        ImGui::EndMenuBar();
    }

    // Edit a color (stored as ~4 floats)
    ImGui::ColorEdit4("Color", &my_color);

    // Plot some values
    const float my_values[] = { 0.2f, 0.1f, 1.0f, 0.5f, 0.9f, 2.2f };
    ImGui::PlotLines("Frame Times", my_values, IM_ARRAYSIZE(my_values));

    // Display contents in a scrolling region
    ImGui::TextColored(ImVec4(1,1,0,1), "Important Stuff");
    ImGui::BeginChild("Scrolling");
    for (int n = 0; n < 50; n++)
        ImGui::Text("%04d: Some text", n);
    ImGui::EndChild();
    ImGui::End();

    return 0;
}

What am I missing? I can't find any linker commands on the webpage which (in my experience "undefined reference to..." is usually a result of missing linker options)


text:
Q: querying elasitcsearch parent child documents We work with two types of documents on elastic search (ES): items and slots, where items are parents of slot documents.
We define the index with the following command:
curl -XPOST 'localhost:9200/items' -d @itemsdef.json

where itemsdef.json has the following definition
{
"mappings" : {
    "item" : {
        "properties" : {
            "id" : {"type" : "long" },
            "name" : {
                "type" : "string",
                "_analyzer" : "textIndexAnalyzer"
            },
            "location" : {"type" : "geo_point" },
        }
    }
},
"settings" : {
    "analysis" : {
        "analyzer" : {

                "activityIndexAnalyzer" : {
                    "alias" : ["activityQueryAnalyzer"],
                    "type" : "custom",
                    "tokenizer" : "whitespace",
                    "filter" : ["trim", "lowercase", "asciifolding", "spanish_stop", "spanish_synonym"]
                },
                "textIndexAnalyzer" : {
                    "type" : "custom",
                    "tokenizer" : "whitespace",
                    "filter" : ["word_delimiter_impl", "trim", "lowercase", "asciifolding", "spanish_stop", "spanish_synonym"]
                },
                "textQueryAnalyzer" : {
                    "type" : "custom",
                    "tokenizer" : "whitespace",
                    "filter" : ["trim", "lowercase", "asciifolding", "spanish_stop"]
                }
        },
        "filter" : {
                "spanish_stop" : {
                    "type" : "stop",
                    "ignore_case" : true,
                    "enable_position_increments" : true,
                    "stopwords_path" : "analysis/spanish-stopwords.txt"
                },
                "spanish_synonym" : {
                    "type" : "synonym",
                    "synonyms_path" : "analysis/spanish-synonyms.txt"
                },
                "word_delimiter_impl" : {
                    "type" : "word_delimiter",
                    "generate_word_parts" : true,
                    "generate_number_parts" : true,
                    "catenate_words" : true,
                    "catenate_numbers" : true,
                    "split_on_case_change" : false
                }
        }
    }
}
}

Then we add the child document definition using the following command:
curl -XPOST 'localhost:9200/items/slot/_mapping' -d @slotsdef.json

Where slotsdef.json has the following definition:
{
"slot" : {
    "_parent" : {"type" : "item"},
    "_routing" : {
        "required" : true,
        "path" : "parent_id"
    },
    "properties": {
        "id" : { "type" : "long" },
        "parent_id" : { "type" : "long" },
        "activity" : {
            "type" : "string",
            "_analyzer" : "activityIndexAnalyzer"
        },
        "day" : { "type" : "integer" },
        "start" : { "type" : "integer" },
        "end" :  { "type" : "integer" }
    }
}
}

Finally we perform a bulk index with the following command:
curl -XPOST 'localhost:9200/items/_bulk' --data-binary @testbulk.json

Where testbulk.json holds the following data:
{"index":{"_type": "item", "_id":35}}
{"location":[40.4,-3.6],"id":35,"name":"A Name"}
{"index":{"_type":"slot","_id":126,"_parent":35}}
{"id":126,"start":1330,"day":1,"end":1730,"activity":"An Activity","parent_id":35}

I'm trying to make the following query: search for all items within a certain distance to a location that have children (slots) in the specified days and within certain start and end ranges.
An item with more slots fulfilling the condition should score higher.
I tried starting with existing samples but the docs are really scarce and its hard to move forward.
Clues?

A: I don't think there is a way to write an efficient query that would do something like this without moving location to slots. You can do something like this, but it can quite inefficient for some data:
{
    "query": {
        "top_children" : {
            "type": "blog_tag",
            "query" : {
                "constant_score" : {
                    "query" : {
                        ... your query for children goes here ...
                    }
                }
            },
            "score" : "sum",
            "factor" : 5,
            "incremental_factor" : 2
        }
    },
    "filter": {
        "geo_distance" : {
            "distance" : "200km",
                "location" : {
                    "lat" : 40,
                    "lon" : -70
                }
            }
        }
    }
}

Basically, what this query is doing is this, it takes your range query or filter for children and whatever other conditions you need and wraps it into constant_score query to make sure that all children have score of 1.0. The top_children query collects all these children and accumulates their scores to the parents. And then filter filters out parents that are too far away.


text:
Q: Best practices using python mock for testing functions within sub modules So,
consider I have a simple library that I am trying to write unit-tests for. This library talks to a database and then uses that data to call an SOAP API. I have three modules, and a testfile for each module.
dir structure:
./mypkg
    ../__init__.py
    ../main.py
    ../db.py
    ../api.py

./tests
    ../test_main
    ../test_db
    ../test_api

Code:
#db.py
import mysqlclient
class Db(object):
    def __init__(self):
        self._client = mysqlclient.Client()

    @property
    def data(self):
        return self._client.some_query()

#api.py
import soapclient
class Api(object):
    def __init__(self):
        self._client = soapclient.Client()

    @property
    def call(self):
        return self._client.some_external_call()

#main.py
from db import Db
from api import Api

class MyLib(object):
    def __init__(self):
        self.db = Db()
        self.api = Api()

    def caller(self):
        return self.api.call(self.db.data)

Unit-Tests:
#test_db.py
import mock
from mypkg.db import Db

@mock.patch('mypkg.db.mysqlclient')
def test_db(mysqlclient_mock):
    mysqlclient_mock.Client.return_value.some_query = {'data':'data'}
    db = Db()
    assert db.data == {'data':'data'}

#test_api.py
import mock
from mypkg.api import Api

@mock.patch('mypkg.db.soapclient')
def test_db(soap_mock):
    soap_mock.Client.return_value.some_external_call = 'foo'
    api = Api()
    assert api.call == 'foo'

In the above example, mypkg.main.MyLib calls mypkg.db.Db() (uses third-party mysqlclient) and then mypkg.api.Api() (uses third-party soapclient)
I am using mock.patch to patch the third-party libraries to mock my db and api calls in test_db and test_api separately.
Now my question is, is it recommended to patch these external calls again in test_main OR simply patch db.Db and api.Api? (this example is pretty simple, but in larger libraries, the code becomes cumbersome when patching the external calls again or even using test helper functions that patch internal libraries).
Option1: patch external libraries in main again
#test_main.py
import mock
from mypkg.main import MyLib

@mock.patch('mypkg.db.mysqlclient')
@mock.patch('mypkg.api.soapclient')
def test_main(soap_mock, mysqlcient_mock):
    ml = MyLib()
    soap_mock.Client.return_value.some_external_call = 'foo'
    assert ml.caller() == 'foo'

Option2: patch internal libraries
#test_main.py
import mock
from mypkg.main import MyLib

@mock.patch('mypkg.db.Db')
@mock.patch('mypkg.api.Api')
def test_main(api_mock, db_mock):
    ml = MyLib()
    api_mock.return_value = 'foo'
    assert ml.caller() == 'foo'

A: mock.patch creates a mock version of something where it's imported, not where it lives. This means the string passed to mock.patch has to be a path to an imported module in the module under test. Here's what the patch decorators should look like in test_main.py:
@mock.patch('mypkg.main.Db')
@mock.patch('mypkg.main.Api')

Also, the handles you have on your patched modules (api_mock and db_mock) refer to the classes, not instances of those classes. When you write api_mock.return_value = 'foo', you're telling api_mock to return 'foo' when it gets called, not when an instance of it has a method called on it. Here are the objects in main.py and how they relate to api_mock and db_mock in your test:
Api is a class                     : api_mock
Api() is an instance               : api_mock.return_value
Api().call is an instance method   : api_mock.return_value.call
Api().call() is a return value     : api_mock.return_value.call.return_value

Db is a class                      : db_mock
Db() is an instance                : db_mock.return_value
Db().data is an attribute          : db_mock.return_value.data

test_main.py should therefore look like this:
import mock
from mypkg.main import MyLib

@mock.patch('mypkg.main.Db')
@mock.patch('mypkg.main.Api')
def test_main(api_mock, db_mock):
    ml = MyLib()

    api_mock.return_value.call.return_value = 'foo'
    db_mock.return_value.data = 'some data' # we need this to test that the call to api_mock had the correct arguments.

    assert ml.caller() == 'foo'
    api_mock.return_value.call.assert_called_once_with('some data')

The first patch in Option 1 would work great for unit-testing db.py, because it gives the db module a mock version of mysqlclient. Similarly, @mock.patch('mypkg.api.soapclient') belongs in test_api.py.
I can't think of a way Option 2 could help you unit-test anything.
Edited: I was incorrectly referring to classes as modules. db.py and api.py are modules