text:
Q: convert data to error in a custom ApolloLink I'm trying to create a custom ApolloLink that converts specific graphql data to an error which will be passed to the onError link. The omg help! error is successfully passed as a network error to onError, but I also get a run time error in my browser: Uncaught (in promise) Error: omg help! at new ApolloError which should not be happening. How do I make sure the error is entirely handled in onError and not also throwing a runtime error from the TransformErrorLink code?
TransformErrorLink.js:
import { ApolloLink, Observable } from 'apollo-link-core';

class TransformErrorLink extends ApolloLink {
  request(operation, forward) {
    const observable = forward(operation);

    return new Observable((observer) => {
      observable.subscribe({
        next: (value) => {
          // reroute Error types as proper errors
          for (const [req, res] of Object.entries(value.data)) {
            if (res?.__typename?.includes('Error')) {
              observer.error(new Error('omg help!'));
            }
          }
          observer.next(value);
        },
        error: observer.error.bind(observer),
        complete: observer.complete.bind(observer)
      });
    });
  }
}

export default new TransformErrorLink();

the composite set of apollo links:
import { from, HttpLink } from '@apollo/client';
import { onError } from '@apollo/client/link/error';
import transformErrorLink from './transformErrors';

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.forEach(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    );
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const additiveLink = from([
  errorLink,
  transformErrorLink,
  new HttpLink({ uri: process.env.GRAPH_API_URL })
]);

export default additiveLink;

I tried swapping the order of errorLink and transformErrorLink in the additiveLink, but that resulted in just a runtime error with no console log first.
I have also been reading https://www.apollographql.com/blog/frontend/apollo-link-creating-your-custom-graphql-client-c865be0ce059/ which does the reverse of what I'm doing - convert an error to data.

A: I haven't used apollo-link-core before, but should you not return observable's projection like in the last line below?
class TransformErrorLink extends ApolloLink {
  request(operation, forward) {
    const observable = forward(operation);

    return new Observable((observer) => {
      **return** observable.subscribe({
      ...

A: I figured it out - I needed to add an errors property (of type Array) to value and then call observer.next with value instead of calling observer.error with an Error.


text:
Q: No response from Service and BroastReciver running on App install There are many duplicate related to mine but mostly have not given answer regarding to my query: I want to make only service based App not even single activity.I have read tutorials and took help from  stackoverflow. I have implement in this way

*

*Made BroadcastReciver

*Delcared BroadcastReciver in Manifest

*started service in BroadcastReciver

My problem:

*

*My broadcastReciver doesn't even start.and also no service  started
    by it

*It doesn't show me any Toast nether Log

*Please help me figure
    out where i m making mistake
Manifest
<receiver android:name=".BroadcastReciverOnInstalltion" >
            <intent-filter  >
                <action android:name="android.intent.action.PACKAGE_INSTALL" />
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_FIRST_LAUNCH" />

                <data android:scheme="com.example.latest.sampleaudio" />
            </intent-filter>
        </receiver>

BroastcatReciver
public class BroadcastReciverOnInstalltion extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {

                Log.i("installeded", "installeded");
                Toast.makeText(context, "...", Toast.LENGTH_LONG).show();
                context.startService(new Intent(context, ServiceMusic.class));

    }
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with linking inline functions in C++ test2.h
#ifndef TEST2_H_INCLUDED
#define TEST2_H_INCLUDED
#include "test1.h"

inline int add(int,int);

#endif // TEST2_H_INCLUDED

test2.cpp
#include "test2.h"

inline int add(int a,int b){
    return a+b;
}

main.cpp
#include <iostream>
#include "test2.h"

int main()
{
    std::cout << add(1,2);
    return 0;
}

Eror:

warning: inline function add(int,int) used but never defined
undefined reference to add(int,int)
ld returned 1 exit status

But if I remove inline from the files, the code compiles and executes fine. What am I doing wrong?
Note: I have seen all the threads on stack overflow,although they were similar to my question, the answers could not solve my issue
Using the mingw compiler with Code Blocks

A: You have to define the inline function inside the header file, more info under
https://stackoverflow.com/questions/5057021/why-are-c-inline-functions-in-the-header#:~:text=If%20you%20want%20to%20put,compiler%20cannot%20inline%20the%20function.

A: //test2.h
#ifndef TEST2_H_INCLUDED
#define TEST2_H_INCLUDED
#include "test1.h"

inline int add(int a,int b) {
    return a+b;
}

#endif // TEST2_H_INCLUDED


text:
Q: Why can't I feed a function as a default variable in a PHP function? I have a function that returns a custom day-of-the-week, used in calculating custom week-periods.
What I am having a problem with is the default variable values when instantiating the function. I am using a different function to return the default value and this throwing an error.
When I call a simple function with something like:
function myFunction ($myVar = "test") { ... }

Then there is no problem.
As soon as I throw a function into the variable as a default, I get the following error:
[Tue Nov 03 15:00:41 2015] [error] [client 10.64.241.13] PHP Parse error:  syntax error, unexpected '(', expecting ')' in /var/www/service/test.php on line 6

Here is my function that is throwing this error in case you want an example:
function get_mod_week_day($day = date('N'), $hour = date('H') ) {

$myDay = null;

switch ($day) {

    case 1:
        $myDay = 5;
        break;
    case 2:
        $myDay = 6;
        break;
    case 3:
        $myDay = 7;
        break;
    case 4:
        $myDay = 1;
        break;
    case 5:
        $myDay = 2;
        break;
    case 6:
        $myDay = 3;
        break;
    case 7:
        $myDay = 4;
        break;
    default:
        $myDay = false;
}

return $myDay;

}

Is it impossible to call a function to return a default variable or is there some way to get around this?

A: From the docs Function Arguments:

The default value must be a constant expression, not (for example) a
  variable, a class member or a function call.

Generally something similar to this would be done:
function get_mod_week_day($day=null, $hour=null) {
    $day  = is_null($day)  ? date('N') : $day;
    $hour = is_null($hour) ? date('H') : $hour;
}

Also, your switch seems lengthy seeing that you are just adding 4 or subtracting 3 from $day.

A: The default value must be a constant expression, not (for example) a variable, a class member or a function call.


text:
Q: Execute tableau commands Through java I am trying to execute 3-7 commands using Java. First, I need to change the directory with cd and later execute commands 2) and 3).
1)
Process p = runtime.exec("cmd /c start cmd.exe /C \"cd C:\\Program Files\\Tableau\\Tableau Server\\8.2\\bin");

and then i want to write
2)
runtime.exec("cmd /c start cmd.exe /K \tabcmd login -s http://localhost:80 -u c200433 -p venkat@#");

and in the below command i am getting file name from a string, can I use this format ?
3)
runtime.exec("tabcmd publish C:\\Users\\c200433\\Desktop\\Ana\\".getBytes()+filename+" --db-username IIP_RBM_USER --db-password Ytpqxsb9dw".getBytes()));

I need to execute all these commands. How do i do this?

A: I think the problem here is that you are missing something important about how cmd works.  Specifically, each cmd instance has its own "current directory".  So  ...

*

*When you run cd in  a cmd it only affects that instance.

*When you run runtime.exec("cmd /c start cmd.exe ... twice, you get two separate cmd instances, one after the other.

So what (I think) you are attempting to do here simply won't work.
Instead you should:

*

*generate a BAT file that contains the entire sequence of commands, OR

*put a cd into every cmd line that you execute, OR

*use absolute pathnames so that you don't need to cd.


text:
Q: Not getting xkeyval to work (as intended) for a simple custom command I'm trying the use the xkeyval package to define a very simple command using keys. However, I'm utterly confused by its behavior, and the package documentation is not exactly helpful either. Here's a MWE with what I wanted to achieve (expected) and what I actually got. Why is this happening and what do I need to do to get the result I'm after? I've also consulted: How to create a command with key values? and: A package template using xkeyval? without any luck
\documentclass{article}

\usepackage{xkeyval}

\makeatletter
\define@key[]{fam}{foo}[XX]{#1}
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   ``Using the macro: \fam@foo ''
   \endgroup
}
\makeatother

\begin{document}

% Example where I hoped to get the default value (XX)
\mycommand % Expected: "Using the macro XX" - Got: "Using the macro"

% Example where I hoped to override the default value
\mycommand[foo=YY] % Expected: "Using the macro YY" - Got: YY "Using the macro"

\end{document}

A: When you do
\define@key[]{fam}{foo}[XX]{<code>}

you are essentially doing
\def\fam@foo#1{<code>}

In your case you have
\def\fam@foo#1{#1}

which is confirmed if I change the code into
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   \texttt{\meaning\fam@foo}\\
   ``Using the macro: \fam@foo ''
   \endgroup
}

getting

When you do \setkeys[]{fam}{foo} you're doing \fam@foo{YY} which, by definition, expands to YY. Later, you're doing \fam@foo' and this expands to '.
If you want to save a value, you have to say something like
\documentclass{article}

\usepackage{xkeyval}

\makeatletter
\define@key[]{fam}{foo}[XX]{\def\fam@foo@toks{#1}}
\setkeys[]{fam}{foo} % initialize
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   ``Using the macro: \fam@foo@toks ''
   \endgroup
}
\makeatother

\begin{document}

\mycommand

\mycommand[foo=YY]

\end{document}

The alternative is to use \define@cmdkey, that does the above using \cmdfam@foo as container.
\define@cmdkey[]{fam}{foo}{}
\setkeys[]{fam}{foo=XX} % initialize
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   ``Using the macro: \cmdfam@foo''
   \endgroup
}


text:
Q: Select row based on max date across several columns For a mysql database
I have a table which includes duplicate rows because of date values in several columns. I am looking to select a single row for each unique customer id based on a max date value evaluated across several date columns
[customer id, startDate, StopDate, modifyDate, buyDate]
For each customer id, i'd like to return the row that has the maximum date either in the startDate, StopDate, modifyDate or buyDate columns ( there are some nulls in the date columns.
editing to include example - but to sure how to create a table here:
*** Edit
Been trying for quite awhile now to create a table here with an example. can't figure out. So posting an image? the desired rows to the returned indicated in red.

A: Assuming that the values are never NULL, you can use greatest():
select t.*
from table t
where greatest(t.startDate, stopDate, buyDate) =
          (select max(greatest(t.startDate, stopDate, buyDate))
           from t t2
           where t2.customerid = t.customerid
          );

Note:  this will return multiple rows for a customer if more than one row contains the maximum date.


text:
Q: heroku -- npm postinstall script to run grunt task depending on enviro I've got two heroku node.js apps, one for prod and one for dev, and I also have a Gruntfile with dev- and prod-specific tasks. I know you can set up package.json to run grunt as a postinstall hook for npm, but can you specify somehow different tasks to be run depending on what enviro you're in?
Here's what the relevant section of my package.json looks like so far:
"scripts": {
    "postinstall": "./node_modules/grunt/bin/grunt default"
},

Rather than run grunt default every time, I'd love to run "grunt production" if NODE_ENV is production, etc.
Is this possible?

A: Sadly there's no difference like postInstall and postInstallDev. You can make an intermediate script to handle the difference though. For example, if you have the following:
"scripts": { "postinstall": "node postInstall.js" },

Then in this script you could check the environment variable and execute the correct Grunt task from there:
// postInstall.js
var env = process.env.NODE_ENV;

if (env === 'development') {
    // Spawn a process or require the Gruntfile directly for the default task.
    return;
}

if (env === 'production') {
    // Spawn a process or require the Gruntfile directly to the prod task.
    return;
}

console.error('No task for environment:', env);
process.exit(1);

A couple of peripherally related points...

*

*Try not to have Grunt and co. as dependencies. Keep them to devDependencies to avoid having to install all that stuff in production. Having an intermediary script in vanilla Node like the above will allow you to do this. I like to use a postInstall script like this to install git hook scripts too (but also only on development environments).

*You don't have to use ./node_modules/grunt/bin/grunt default. If grunt-cli is a dependency or devDependency, npm knows where to look and grunt default will work fine.

A: For some reason, my dev environment was never running my "development" if statement. I sent a ticket to Heroku support, and this was their answer: "By default, your environment is not available during slug compilation. If you would like to make this available, you can enable an experimental feature called "user-env-compile". Please see the following article for details:
http://devcenter.heroku.com/articles/labs-user-env-compile". Good to know. So, I went another route using the heroku-buildpack-nodejs-grunt buildpack, and then creating a heroku:development grunt task.


text:
Q: Mutually closest point of two lines defined by vectors. I have two 3D lines defined by tangent vectors $A$ and $B$. I need to find a point that lies on the line defined by $A$. The point has to be the closest to $B$ out of all points that lay on $A$. Assume that the lines are not parallel.
I feel it's easy and solved somewhere, but I probably google it wrong.

A: Suppose the two lines are given by $At+a$ and $Bs+b$, where $a$ is a fixed point on one, $b$ on the other. Then the vector between a point on each line is
$$ At-Bs+(a-b). \tag{1}$$
Hence the problem is mathematically the same as finding the shortest distance from the plane given by $ At-Bs $ to the point $a-b$.
The shortest distance is when the vector in $(1)$ is perpendicular to $A$ and $B$, i.e. a multiple of $A \times B$, which is nonzero since $A \not\parallel B$ and $A,B \neq 0$. Hence we have
$$ At^*-Bs^*+(a-b) = \nu (A \times B), $$
for the optimal values $t^*,s^*$.
We can now get straight to $\nu$ by dotting with $A \times B$:
$$ (a-b) \cdot (A \times B) = \nu\lVert A \times B \rVert^2. $$
The length of the vector (and hence the distance between the lines) is then
$$ \lVert \nu (A \times B) \rVert = \lvert \nu \rvert \lVert A \times B \rVert = \frac{\lvert (a-b) \cdot (A \times B) \rvert}{\lVert A \times B \rVert^2} \lVert A \times B \rVert = \frac{\lvert (a-b) \cdot (A \times B) \rvert}{\lVert A \times B \rVert}. $$


text:
Q: PHP require() or include() and call a class variable? I imagine this is fairly simple and one I should be able to get but I am having trouble with it. I can't seem to find an answer for this anywhere.
Consider the scenario: I have two files (we'll call them index.php and global.php). I am properly referencing the require_once() file.
Index.php:
<?php
require_once('./global.php');

$database = new database();
echo $database->dbname;
?>

Global.php:
<?php
class database {
public $dbname = 'jdoe';
}
?>

This does not output 'jdoe' on the index.php page. However...if I place the following into global.php, it works:
<?php
class database {
public $dbname = 'jdoe';
}

$database = new database();
echo $database->dbname;
?>

A: $database = new database();

You forgot the parenthesis. Also, take a look at the php documentation for Classes and Objects if you need more information about using classes in php.
Update:
Reading up on PHP Class Properties I came across this little tid-bit:

[Class member variables] must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

I'm not 100% certain on this, but it seems like PHP is seeing your string assignment as "run-time information". Try assigning your variable in the constructor (its probably better practice anyway).
class database {
    public $dbname;
    function __construct() {
        $this->dbname= 'jdoe';
    }
    // Rest of class
}

Hope that helps! And if anyone could verify my assumption that would be great.

A: The syntax of making an object in php is
$obj=new class();
You have missed () after class name.

A: I think it should be
$database = new database();

instead of
$database = new database;


text:
Q: ActiveAdmin user display bug I use ActiveAdmin, I have projects and tasks. When I create a new task, the Admin user dropdown displays as # adminuser:0x007fbe6d74deb0. Friends, how to fix it? I would like to simply displaying an email of user.

Rails 4.1.0
ActiveAdmin 1.0.0
ruby 2.1

app/admin/task.rb
ActiveAdmin.register Task do

    scope :all, :default => true      # Defines the default scope, showing all rows
    scope :due_this_week do |tasks|   #
      tasks.where('due_date > ? and due_date < ?', Time.now, 1.week.from_now)
    end
    scope :late do |tasks|
      tasks.where('due_date < ?', Time.now)
    end
    scope :mine do |tasks|
      tasks.where(:admin_user_id => current_admin_user.id)
    end

    show do
      panel "Task Details" do
        attributes_table_for task do
          row("Status") { status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :ok : :error) }
          row("Title") { task.title }
          row("Project") { link_to task.project.title, admin_project_path(task.project) }
          row("Assigned To") { link_to task.admin_user.email, admin_admin_user_path(task.admin_user) }
          row("Due Date") { task.due_date? ? l(task.due_date, :format => :long) : '-' }
        end
      end

      active_admin_comments # Provides a simple commenting system for each model. Enabled it here because commenting on a task could be very useful to discuss functionality, or something similar.
    end

    # Creates a sidebar panel, titled "Other Tasks For This User", which is shown only on the "show" page.
    # It will show a table for the currentadminuser, and all tasks where the project is the same as the project being shown.

    sidebar "Other Tasks For This User", :only => :show do
      table_for current_admin_user.tasks.where(:project_id => task.project) do |t|
        t.column("Status") { |task| status_tag (task.is_done ? "Done" : "Pending"), (task.is_done ? :ok : :error) }
        t.column("Title") { |task| link_to task.title, admin_task_path(task) }
      end
    end

    permit_params :title, :project_id, :admin_user_id, :due_date, :is_done

  # See permitted parameters documentation:
  # https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
  #
  # permit_params :list, :of, :attributes, :on, :model
  #
  # or
  #
  # permit_params do
  #  permitted = [:permitted, :attributes]
  #  permitted << :other if resource.something?
  #  permitted
  # end

end

A: Your object (AdminUser) should implement one of the below methods:

# Active Admin makes educated guesses when displaying objects, this is
# the list of methods it tries calling in order
setting :display_name_methods, [ :display_name,
                                  :full_name,
                                  :name,
                                  :username,
                                  :login,
                                  :title,
                                  :email,
                                  :to_s ]

(taken from the code)


text:
Q: $g'-g> 0$ with boundary condition $g(0)=0$
Exercise:
Let $g$ be a differentiable function $[0,1]\rightarrow\mathbb{R}$ such that $g'-g>0$ on $(0,1)$ and $g(0)=0$. Prove that $g>0$ on $(0,1]$.

There exists a solution using the function $\exp$:

Solution:
Let $h=\exp(-x)g$. Then $h'$ is strictly positive on $(0,1)$ and $h(0)=0$, whence $h>0$ on $(0,1]$ and therefore $g>0$ on $(0,1]$.

Intuitively, the function $g$ starts at $0$ with the value $0$. From there on, its increasing rate $g'$ stays greater than $g$, hence strictly positive. Thus the function $g$ can never decrease.

My question is, does there exist an argument which clarifies the above intuition? (an alternative to the function $\exp$).

A: A priori, $g'$ and $g$ can be both negative, so solely by intuition may not be enough. However one can get a proof without using the exponential function as follows.
Proving by contradiction, assume that there exists $a_0\in (0,1]$ such that $g(a_0)\leq  0.$ Then by mean value theorem, $$\exists a_1\in (0,a_0)~{\rm such~that~}g'(a_1)=\frac{g(a_0)-g(0)}{a_0-0}=\frac{g(a_0)}{a_0}\leq 0.$$ But $$g'(a_1)>g(a_1)$$$$\Rightarrow g(a_1)<g'(a_1)=g(a_0)/a_0\leq 0$$ $$\Rightarrow g(a_1)<g(a_0)\leq0~(\because 0<a_0\leq 1),$$ which shows that the absolute minimum of $g$ on $[0,a_0]$ occurs at a point in $(0,a_0)$. Let $\alpha$ be such a point, so $g(\alpha)$ is the absolute minimum of $g$ on $[0,a_0]$. By mean value theorem again, there exists $\beta\in (0,\alpha)$ such that $$g'(\beta)=\frac{g(\alpha)-g(0)}{\alpha-0}=\frac {g(\alpha)}{\alpha}$$ and $$g'(\beta)-g(\beta)>0$$ $$\Rightarrow g(\beta)<g'(\beta)=\frac{g(\alpha)}{\alpha}<g(\alpha)~(\because 0<\alpha<1,g(\alpha)<0).$$ But $g(\beta)<g(\alpha)$ gives a contradiction that $g(\alpha)$ is the absolute minimum of $g$ on $[0,a_0]$. One concludes that $g(x)>0,\forall x\in (0,1].$ QED


text:
Q: how to debug this lithium request? I am trying to work on whats wrong with my lithium current setup. I have installed the Xdebug and verified that remote host can establish the connection as requested.
http://myinstance.com/test/lithium/tests/cases/analysis/logger/adapter/CacheTest?filters[]=lithium\test\filter\Coverage
Please note in fresh installation in local environment , "Coverage" Filter is working as expected.
I added some test code inside the "apply" function in coverage.php but it is not even called !!!! Can some have experience in debugging the above URL ?
I am not able to understand why coverage filter is not called up and executed ...Any hints are highly appreciated !

A: The filters in the query string are added to the options in lithium\test\Controller::__invoke() and then passed into the test Report object created by the test Dispatcher. The Report object finds the test filter class and then runs the applyFilter() method for that test filter as can be seen in lines 140 to 143 of the current code. So those lines would be another place to debug. Those should wrap the run() method of your tests with this filter code inside the apply() method that uses xdebug_get_code_coverage() and related functions. You said you added test code in the apply method and it isn't called. I'm not sure what the issue is. Are you sure you are pointing to the right server and code location? It is possible to run tests from the command line. Maybe you should try that. See code comments in lithium\console\command\Test or run li3 test --help for info on how to use the command-line test runner.
I can confirm on nginx I also have /test/lithium/tests/cases/analysis/logger/adapter/CacheTest?filters[]=lithium\x5Ctest\x5Cfilter\x5CCoverage in my access log. The \x5C is expected url encoding of the backslash character.


text:
Q: OpenShift 3 Webapp With Access to File System I have a Tomcat 8 web app running on OpenShift 3.
I want to be able to read and write files on 'the file system'.
I have been wading through documentation and looking for examples of how to achieve this.
I see that there are many types of persistent storage, for example NFS, EBS, GlusterFS etc.
So, my first question is.
What is the best file system to use for simple read/write access to text based xml files?
Preferably like a *nix file system.
Any example would be much appreciated...

A: The free OpenShift 3 Starter service ONLY allows 'filesystem storage' to EBS (Amazon Elastic Block Storage). Which can only be written to ONCE.
To get access to GlusterFS of NFS you have to go to the paid service which starts at $50 per month. They are the only filesystems that allow multiple writes to a file.


text:
Q: `fetch` in React Native doesn't return expected data from URL I want to use the fetch() API to load data from a URL in a React Native Application. Specifically, I want to load all items from the Hackernews Jobs page.
As stated in their API doc, the corresponding call has to go out to URL: https://hacker-news.firebaseio.com/v0/jobstories.json
When navigating to this URL in the browser, I receive a simple javascript array of IDs as expected:
[11379939,11379294,11378554,11377293,11375582,11373919,11372195,11371135,11369985,11369460,11361426,11357881,11356669,11354578,11351786,11350273,11349328,11347911,11346192,11343590,11342818,11342137,11341262,11340129]

However, when I want to load the data in my React Native app using the following method, I don't receive the same javascript array I get when sending the request through the browser.
export const fetchJobs = () => {
  return (dispatch) => {
    return fetch('https://hacker-news.firebaseio.com/v0/jobstories.json', {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      }
    })
    .then( (response) => {
      console.log('Actions - fetchJobs - received response: ', response)
      const json = JSON.parse(response)
    })
    .then( (jobs) => {
      console.log('Actions - fetchJobs - received jobs: ', jobs)
      dispatch(receiveJobs(jobs))
    })
    .catch( (error) => {
      console.warn('Actions - fetchJobs - recreived error: ', error)
    })
  }
}

I am calling fetchJobs() using dispatch from Redux in my initial React component like so:
componentDidMount() {
   var fetchJobsAction = fetchJobs()
   console.log('JobsRootComponent - fetch jobs: ' + fetchJobsAction)
   const { dispatch } = this.props
   dispatch( fetchJobs() )
}

However, when inspecting the output in the Chrome debugging console, the output looks like this:

Can someone tell me why the content of the response differs between the requests I am sending from the browser and the one from my React Native app?
Update: As requested in the comments, I now printed response.json() as well, giving me the following result:

So indeed, the array data now seems to be there. But I still don't understand how I can access it from where I am at the moment...

A: The response of a fetch has it's own JSON parse function, just call
response.json() which will return a new Promise.
fetch('https://hacker-news.firebaseio.com/v0/jobstories.json')
  .then(reponse => response.json())
  .then(json => console.log(json))

A: Use return inside then
You have to return the result of response.json(), if you are chaining then calls.
export const fetchJobs = () => {
  return (dispatch) => {
    return fetch('https://hacker-news.firebaseio.com/v0/jobstories.json', {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      }
    })
    .then( (response) => {
      console.log('Actions - fetchJobs - received response: ', response)
      return response.json();
    })
    .then( (jobs) => {
      console.log('Actions - fetchJobs - received jobs: ', jobs)
      dispatch(receiveJobs(jobs))
    })
    .catch( (error) => {
      console.warn('Actions - fetchJobs - recreived error: ', error)
    })
  }
}


text:
Q: Is there any reason why the robots were buried and forgotten? If I can remember right, no reason is given in Zelda: Breath of the wild as to why the robots that were used to defeat Ganon 10000 years ago were then buried and forgotten by pretty much everybody.
Did the sheikah from 10000 years ago see the "Ganon hacking everything" plan coming, or was their use done so they just let them get buried over time?

A: While nothing is concrete, it appears that the Sheikah either A: Became outcasts and were feared by the Hylian people or B: Adhered to the royal family's warning, and forgot their creations and left them to be buried.

"Eventually, however, people began to fear Sheikah technology being misused, causing the Sheikah to either become outcasts, or follow the Royal Family's warnings by burying their technology and living much simpler lives."

(The quote came from here)


text:
Q: I'd like to inject Repositories container at Service constructor using typedi I'd like to inject Repositories at my UserService.
But i'm not sure how to do that.
I'm using typescript, typedi and sequelize.
I think, the Service is loaded more fast than loaders.
When I try to inject my Repositories which I set at database loader, the error occur.
The error like this : ServiceNotFoundError: Service with "repositories" identifier was not found in the container. Register it before usage via explicitly calling the "Container.set" function or using the "@Service()" decorator.
So, I checked "userRepo" with console.log and the result was undefined.
I also checked Container.get('repositories') at CreateUser meathod, it loaded collectly. I mean, I can get my Container instance.
I just can't load repositories instance at constructor.
What should I do to load repositories at constructor?
Should I change sequelize to typeorm to load this?
// ** UserService.ts **
import { Inject, Service } from 'typedi';
import { UserRepository } from '../repositories/user.repository';
import { UserCreationAttributes } from '../models/interface/User.interface';
import { User, UserModel, UserStatic } from '../models/User';

@Service()
export default class UserService {
  constructor(@Inject('repositories') private userRepo: UserRepository) {}

  public async CreateUser(userData: UserCreationAttributes): Promise<boolean> {
    try {
      await this.userRepo.create(userData);
      return true;
    } catch (err) {
      console.log(err);
      return false;
    }
  }
}

// ** Database Loader **
import { Sequelize } from 'sequelize';
import config from '../config';
import Logger from './logger';
import { UserStatic } from '../models/User';
import { FeedStatic } from '../models/Feed';
import { CommentStatic } from '../models/Comment';
import { VerificationStatic } from '../models/Verification';
import { initializeModels } from '../models';
import { initializeRepositories, Repositories } from '../repositories';
import { Container } from 'typedi';

export interface Models {
  User: UserStatic;
  Feed: FeedStatic;
  Comment: CommentStatic;
  Verification: VerificationStatic;
}

export default async function loadSequelize() {
  const sequelize = new Sequelize(
    config.database,
    config.databaseUsername,
    config.databasePassword,
    {
      host: config.databaseHost,
      port: config.databasePort,
      dialect: 'postgres',
    },
  );

  try {
    await sequelize.authenticate();
    const models: Models = initializeModels(sequelize);
    const repositories: Repositories = initializeRepositories(models);
    await sequelize.sync({ force: true });

    // This part might be loaded after services were loaded
    Container.set('models', models);
    Container.set('repositories', repositories);

    console.log('load finish');
  } catch (err) {
    Logger.error(err);
  }
}

// ** ./repositories/index.ts **
import { Models } from '../loaders/database';
import { UserRepository } from './user.repository';

export interface Repositories {
  UserRepository: UserRepository;
}
export const initializeRepositories = (models: Models): Repositories => {
  const usersRepository = new UserRepository(models.User);
  const repositories: Repositories = {
    UserRepository: usersRepository,
  };
  return repositories;
};

// ** ./repositories/base.repository.ts **
import { Model, BuildOptions, FindOptions } from 'sequelize/types';
import { IFilter } from './filter/base.filter';

export type RichModel = typeof Model & {
  new (values?: Record<string, unknown>, options?: BuildOptions): Model;
};

export interface IMeta {
  globalCount: number;
  countAfterFiltering: number;
}

export interface IWithMeta<M extends Model> {
  meta: IMeta;
  data: M[];
}

export abstract class BaseRepository<
  M extends Model,
  C extends object,
  F extends IFilter = IFilter
> {
  constructor(public _model: RichModel, private filterFactory: new () => F) {}

  private async getCount(where?: Record<string, unknown>): Promise<number> {
    const count = await this._model.count({ where });
    return count;
  }

  async getAll(params?: FindOptions, filter?: F): Promise<IWithMeta<M>> {
    const { from: offset, count: limit } = filter || {};
    const result = await this._model.findAndCountAll({
      order: [['id', 'ASC']],
      offset: offset,
      limit: limit,
      ...params,
    });

    const globalCount = await this.getCount();
    const countAfterFiltering = ((result.count as unknown) as Record<
      string,
      unknown
    >[]).length;

    return {
      meta: { globalCount, countAfterFiltering },
      data: result.rows as M[],
    };
  }

  async getById(id: string | number): Promise<M> {
    const result = await this._model.findByPk(id);
    return result as M;
  }

  async get(where: Record<string, unknown>): Promise<M> {
    const result = await this._model.findOne({ where });
    return result as M;
  }

  async updateById(id: string | number, data: C): Promise<M> {
    const result = await this._model.update(data, {
      where: { id },
      returning: true,
    });

    const [, models] = result;

    return models[0] as M;
  }

  async deleteById(id: string | number): Promise<void> {
    await this._model.destroy({
      where: { id },
    });
  }

  async create(data: C): Promise<M> {
    const model = await this._model.create(data);
    return (model as unknown) as M;
  }
}

// ** ./repositories/user.repository.ts
import { BaseRepository, IWithMeta, RichModel } from './base.repository';
import { UserModel, UserStatic } from '../models/User';
import { UserCreationAttributes } from '../models/interface/User.interface';
import { IFilter } from './filter/base.filter';
import { UserFilter } from './filter/user.filter';
import { Service } from 'typedi';

@Service()
export class UserRepository extends BaseRepository<
  UserModel,
  UserCreationAttributes,
  IFilter
> {
  constructor(private model: UserStatic) {
    super(<RichModel>model, IFilter);
  }

  async getAllUsers(): Promise<IWithMeta<UserModel>> {
    const users = await this.getAll();
    return users;
  }

  async getOneByFilter({
    email,
    password,
  }: UserFilter): Promise<UserModel | null> {
    const user = await this.model.findOne({
      where: {
        email,
        password,
      },
    });
    return user;
  }

  async getAdminOneByFilter({
    email,
    password,
  }: UserFilter): Promise<UserModel | null> {
    const user = await this.model.findOne({
      where: {
        email,
        password,
        isAdmin: true,
      },
    });
    return user;
  }
}

A: First of all, try to put your initializeRepositories call right after the reflect-metadata call, to test if the execution order will impact. You don't need to call inside the database connection file.
From what I saw at the old docs, to use Container.set to set all of your repos, you need to provide an array containing objects with id for them.
Container.set([{ id: 'userRepository', value: new UserRepository() }])
If you just need to set a single repository:
Container.set('userRepository', new UserRepository())
In both cases above, you use like: Container.get('userRepository');
If you want to keep the reference as repositories your initializeRepositories  method is ok, but the usage must be like:
@Inject('repositories') repositories: { UserRepository: UserRepository};

repositories.UserRepository

If you don't need to set your repositories from that method you can just put a decorator @Service('userRepository') in your UserRepository class and it will work.


text:
Q: Specific Like, Twitter and Pinterest buttons for each image in the gallery? The site I am working on is on WordPress.
I am trying to create a picture gallery now but I would like that each image will have its own URL and social buttons.
It means that you will be able to see an image, like it, see it posted on your wall with the correct thumbnail and redirect to the correct page in the gallery again.
I tried with the simple WordPress gallery and with NextGEN gallery, until now. Unfortunately I didn't get a good result yet.
Here is what I could do with NextGEN until now:
Gallery Main Page
Gallery Image Page
Problems I have there:

*

*When I like an image, the thumb that appears in Facebook is wrong.

*Same about the redirection URL from Facebook that takes me to the main gallery instead of the specific image that I liked.

*Same with Twitter.

This is the code I am using on the image pages:
http://jsbin.com/ujahex/watch
Many thanks!


text:
Q: How to inject a button to a webpage with Chrome Extension I'm using content scripts and I would like to inject a button to a webpage.
This is my manifest.json:
{
  "manifest_version": 2,
  "name": "my extension",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:8000/*"],
        "js": ["script.js"],
        "run_at": "document_end"
      }
  ]
}

This is popup.html:
<html>
  <body>
    <input type="button" id="button" style="display:none;">
  </body>
</html>

And script.js:
document.body.style.backgroundColor = "yellow";
var button = document.getElementById("button");
button.style.visibility = "visible";

When going to http://127.0.0.1:8000 I see the background changes to yellow, however it doesn't find button because it's not part of the webpage served by my local server. It shows this error:
Uncaught TypeError: Cannot read property 'style' of null

What should I do to inject a button on top of the content in http://127.0.0.1:8000 (assuming I don't know its content)?

A: To insert a button, just create it in you content scripts and insert it, you needn't(shouldn't) declare it in popup.html
manifest.json
{
  "manifest_version": 2,
  "name": "my extension",
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"]
      }
  ]
}

script.js
document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);

A: You should add a "run_at": "document_end" in your content_scripts property
In document_end, the script files will then be injected after the DOM is complete. This way the document will be able to find your lost button :)
"content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"],
        "run_at": "document_end"
      }
  ]


text:
Q: C functions invoked as threads - Linux userland program I'm writing a linux daemon in C which gets values from an ADC by SPI interface (ioctl). The SPI (spidev - userland) seems to be a bit unstable and freezes the daemon at random times.
I need to have some better control of the calls to the functions getting the values, and I was thinking of making it as a thread which I could wait for to finish and get the return value and if it times out assume that it froze and kill it without this new thread taking down the daemon itself. Then I could apply measures like resetting the ADC before restarting. Is this possible?
Pseudo example of what I want to achieve:
(function int get_adc_value(int adc_channel, float *value) )

*

*pid = thread( get_adc_value(1,&value); //makes thread calling the function

*wait_until_finish(pid, timeout); //waits until function finishes/timesout

*if(timeout) kill pid, start over //if thread do not return in given time, kill it (it is frozen)

*else if return value sane, continue //if successful, handle return variable value and continue

Thanks for any input on the matter, examples highly appreciated!

A: I would try looking at using the pthreads library. I have used it for some of my c projects with good success and it gives you pretty good control over what is running and when.
A pretty good tutorial can be found here:
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

A: In glib there is too a way to check the threads, using GCond (look for it in the glib help).
In resume you should periodically set a GCond in the child thread and check it in the main thread with a g_cond_timed_wait. It's the same with the glib or the pthread.
Here is an example with the pthread:
http://koders.com/c/fidA03D565734AE2AD9F5B42AFC740B9C17D75A33E3.aspx?s=%22pthread_cond_timedwait%22#L46

A: I'd recommend a different approach.
Write a program that takes samples and writes them to standard output. It simply need have alarm(TIMEOUT); before every sample collection, and should it hang the program will exit automatically.
Write another program that runs that first program. If it exits, it runs it again. It looks something like this:
main(){for(;;){system("sampler");sleep(1);}}

Then in your other program, use FILE*fp=popen("supervise_sampler","r"); and read the samples from fp. Better still: Have the program simply read the samples from stdin and insist users start your program like this:
(while true;do sampler;sleep 1; done)|program

Splitting up the task like this makes it easier to develop and easier to test, for example, you can collect samples and save them to a file and then run your program on that file:
sampler > data
program < data

Then, as you make changes to program, you can simply run it again on the same data over and over again.
It's also trivial to enable data logging- so should you find a serious issue you can run all your data through your program again to find the bugs.

A: Something very interesting happens to a thread when it executes an ioctl(), it goes into a very special kind of sleep known as disk sleep where it can not be interrupted or killed until the call returns. This is by design and prevents the kernel from rotting from the inside out.
If your daemon is getting stuck in ioctl(), its conceivable that it may stay that way forever (at least till the ADC is re-set).
I'd advise dropping something, like a file with a timestamp prior to calling ioctl() on a known buggy interface. If your thread does not unlink that file in xx amount of seconds, something else needs to re-start the ADC.
I also agree with the use of pthreads, if you need example code, just update your question.


text:
Q: Writing data to S3 through Spark Data Frame and in scale - s3 connectivity issue and caused by s3 503 slow down error We are trying to read and write the data to S3 in spark using AWS EMR clusters. And during this process, while we were scaling the execution, we ended up with some issues. When we try to process the same job for one-quarter of data we are not noticing this issue, but when we scale it to run multiple quarters of data in parallel, randomly for one/more quarters of data, we started seeing the spark jobs failing while writing the data to S3. Then we went down further to understand the issue in deeper, that is when we realized that spark is throwing the issue while it is writing the data to S3 and that is caused by S3 503 Slow down the error.
The slow down error will come only when we exceeded the S3 TPS of a given path. And the suggestion from S3 is to add random hash values to s3 path while writing. We tried this using partition by, but we come to know that some hash values(xy, 2 digit hash values) only will perform better. So does anyone come across the similar issue, and if so may I know how you had overcome this issue?
Looking forward!
Krish

A: S3 client should be throttling back on the errors; surprised the EMR one wasn't as the AWS SDK everyone uses does recognise a 503 and will backoff and retry.
There'll probably be a config option to set it (for S3a://, its fs.s3a.attempts.maximum)
If you are using the EMR s3:// connector, you'll have to look for their option


text:
Q: Can some one tell me what i have done wrong I got a question in interview about a man who can take a step back or move double of his current distance . Considering each of them as a single move find minimum moves he can take to reach y from x.
import java.util.*;
import java.io.*;

public class Main
{
    public static int Solve(int x,int y)
    {
        if(x==0)
        {
            return Integer.MAX_VALUE;
        }
        else if(x==y)
        {
            return 0;
        }
        else if(x==1)
        {
            return 1+Solve(x*2,y);
        }
        return Math.min(1+Solve(x*2,y),1+Solve(x-1,y));
    }

    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        int y=sc.nextInt();
        int z=Solve(x,y);
        System.out.print(z);
    }
}

A: This is an infinite loop. At what place will Solve( x * 2, y) ever
stop ?
Assuming all this is in one axis only (1D), since you defined int x and int y. Let's say we have x and y, if y-x is positive, that means we have to go forward. Now if y-x is odd, let's say 7 that means we have to go 8 steps (4*2) ahead, then 1 (1 step) back. Giving us 5 steps. So we have to go
(((y-x) + 1)/2) + 1

So 7+1 = 8, we go 8 steps ahead taking double steps, then 1 more step to come back.
If it is even, then that means we can go straight ahead ! So
(y-x)/2

If y-x is negative, which means we have to go back. Only way is 1 step back (x-1), so that will just be
-(y-x) steps.

You can write the code. I like the recursion aspect for your code, but it's an overkill if it is 1D.

A: Not sure if a recursion-based solution is needed here.
We have two subproblems here:

*

*count moves back when from >= to

*otherwise count moves forward taking into account a case when difference to - from is odd: then 1 extra move forward is needed and 1 step back.

This can be resolved with the help of a ternary operator:
public static int findMoveCount(int from, int to) {
    return from >= to ? from - to : (to - from) % 2 * 2 + (to - from)/2;
}


text:
Q: HTML5: dragover(), drop(): how get current x,y coordinates? How does one determine the (x,y) coordinates while dragging "dragover" and after the drop ("drop") in HTML5 DnD?
I found a webpage that describes x,y for dragover (look at e.offsetX and e.layerX to see if set for various browsers but for the life of me they ARE NOT set).
What do you use for the drop(e) function to find out WHERE in the current drop target it was actually dropped?
I'm writing an online circuit design app and my drop target is large.
Do I need to drop down to mouse-level to find out x,y or does HTML5 provided a higher level abstraction?

A: The properties clientX and clientY should be set (in modern browsers):
function drag_over(event) {
    console.log(event.clientX);
    console.log(event.clientY);
    event.preventDefault();
    return false;
}
function drop(event) {
    console.log(event.clientX);
    console.log(event.clientY);
    event.preventDefault();
    return false;
}

Here's a (somewhat) practical example that works in Firefox and Chrome.

A: To build on top of robertc's answer and work around the issue:

The clientX and clientY are going to be inaccurate proportional to the distance of the cursor from the upper left corner of the element which was dropped.

You may simply calculate the delta distance by subtracting the client coords recorded at dragStart from the client coords recorded at dragEnd. Bear in mind the the element which was dropped still has the exact same position at dragEnd which you may update by the delta distance to get the new left and top positional coordinates.
Here's an demo in react, although the same can be accomplished in plain JS.


text:
Q: Image not filling the entire div I have a div. Inside it, I have an image. The dimension of the image is 540*420. I want the image to completely fill the container div, which is not happening. On the left and right of the image are whitespaces(denoted by pink colour in the image) which I want to remove. Screenshot of my image is:-

My HTML:

            apple pay runs afoul of mcx, a group with a rival product.

Please help.

A: You are using classes col-md-6 and col-sm-6. And these classes contain 15px right and left padding rules:
padding-right: 15px;
padding-left: 15px;

Use width: 100%, height: 100% and object-fit: cover for the img tag, just override padding rules by adding padding: 0 in the styles of div.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

            apple pay runs afoul of mcx, a group with a rival product.


text:
Q: Accept All Cookies via HttpClient So this is currently how my app is set up:
1.) Login Activity.
2.) Once logged in, other activities may be fired up that use PHP scripts that require the cookies sent from logging in.
I am using one HttpClient across my app to ensure that the same cookies are used, but my problem is that I am getting 2 of the 3 cookies rejected. I do not care about the validity of the cookies, but I do need them to be accepted. I tried setting the CookiePolicy, but that hasn't worked either. This is what logcat is saying:
11-26 10:33:57.613: WARN/ResponseProcessCookies(271): Cookie rejected: "[version: 0]      [name: cookie_user_id][value: 1][domain: www.trackallthethings.com][path: trackallthethings][expiry: Sun Nov 25 11:33:00 CST 2012]". Illegal path attribute "trackallthethings". Path of origin: "/mobile-api/login.php"

11-26 10:33:57.593: WARN/ResponseProcessCookies(271): Cookie rejected: "[version: 0][name: cookie_session_id][value: 1985208971][domain: www.trackallthethings.com][path: trackallthethings][expiry: Sun Nov 25 11:33:00 CST 2012]". Illegal path attribute "trackallthethings". Path of origin: "/mobile-api/login.php"

I am sure that my actual code is correct (my app still logs in correctly, just doesn't accept the aforementioned cookies), but here it is anyway:
HttpGet httpget = new HttpGet(//MY URL);
HttpResponse response;
response = Main.httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();

From here I use the StringBuilder to simply get the String of the response. Nothing fancy.
I understand that the reason my cookies are being rejected is because of an "Illegal path attribute" (I am running a script at /mobile-api/login.php whereas the cookie will return with a path of just "/" for trackallthethings), but I would like to accept the cookies anyhow. Is there a way to do this?

A: The issue that you are facing seems to be by design for privacy/security purpose. In general  any resource is not allowed to set a cookie it will not be able to receive. Here you are trying to set the cookie with the path trackallthethings from the resource /mobile-api/login.php which obviously is not working.
Here you have following two options

*

*Set the cookie with the path which is accessible to both the resources (this may be root '/') OR

*Define a custom cookie policy and Registering your own cookie support. Here is related documentation and example.

Hope this helps.

A: Since the API of HttpClient seems to change very fast, here is some working example code for HttpClient 4.5.1 to allow all (malformed) cookies:
class EasyCookieSpec extends DefaultCookieSpec {
    @Override
    public void validate(Cookie arg0, CookieOrigin arg1) throws MalformedCookieException {
        //allow all cookies
    }
}

class EasySpecProvider implements CookieSpecProvider {
    @Override
    public CookieSpec create(HttpContext context) {
        return new EasyCookieSpec();
    }
}

Registry<CookieSpecProvider> r = RegistryBuilder.<CookieSpecProvider>create()
            .register("easy", new EasySpecProvider())
            .build();

CookieStore cookieStore = new BasicCookieStore();

RequestConfig requestConfig = RequestConfig.custom()
            .setCookieSpec("easy")
            .build();

CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCookieStore(cookieStore)
            .setDefaultCookieSpecRegistry(r)
            .setDefaultRequestConfig(requestConfig)
            .build();


text:
Q: Using login session from asp.net in silverlight Is there a way I can use the session created by ASP.NET to authenticate my silverlight app? All I would need is the userID. Then I can call to my WCF RIA service to get roles, etc. If there is a better way to do this, please tell.
But I want to be able to login using html in asp.net. I'm using forms authentication.

A: Since the user authentication context resides on the server and the SL resides on browser, you need to create a service layer in WCF to get these details. The WCF service needs to run in aspNetCompatibilityEnabled mode. Check details here. Once you create such WCF service, you can expose methods on it such as GetLoggedInUser(), GetUserRoles() etc. I believe WCF RIA service make this work easier for you, so you can concentrate on main application logic.

A: If the user id is all you need you can pass it as a custom initialization parameter to the Silverlight plugin. More info on MSDN:
http://msdn.microsoft.com/en-us/library/cc189004%28v=vs.95%29.aspx


text:
Q: EOF error when I try to use 'expect' function from'Pexpect' I'm trying to automate the process of switch between networks in "Cisco AnyConnect", but my code always is terminated with an 'EOF error'.
I've tried a search in API doc for some help and used different expressions like: "Network", "Network:" or "Network.*".
from pexpect import popen_spawn
import pexpect

vpnui = pexpect.popen_spawn.PopenSpawn(r'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe', maxread=2000)
vpnui.expect('Network:')
vpnui.sendline('SomeNetwork')

The error:

Traceback (most recent call last):   File
  "C:\Users\myUser\AppData\Local\Programs\Python\Python36\lib\site-packages\pexpect\expect.py",
  line 111, in expect_loop
      incoming = spawn.read_nonblocking(spawn.maxread, timeout)   File "C:\Users\myUser\AppData\Local\Programs\Python\Python36\lib\site-packages\pexpect\popen_spawn.py",
  line 75, in read_nonblocking
      raise EOF('End Of File (EOF).') pexpect.exceptions.EOF: End Of File (EOF).
During handling of the above exception, another exception occurred:
Traceback (most recent call last):   File
  "C:\Users\myUser\eclipse-workspace\teste\switchGuestWifi.py", line 15,
  in
      vpnui.expect('Network:')   File "C:\Users\myUser\AppData\Local\Programs\Python\Python36\lib\site-packages\pexpect\spawnbase.py",
  line 341, in expect
      timeout, searchwindowsize, async_)   File "C:\Users\myUser\AppData\Local\Programs\Python\Python36\lib\site-packages\pexpect\spawnbase.py",
  line 369, in expect_list
      return exp.expect_loop(timeout)   File "C:\Users\myUser\AppData\Local\Programs\Python\Python36\lib\site-packages\pexpect\expect.py",
  line 117, in expect_loop
      return self.eof(e)   File "C:\Users\myUser\AppData\Local\Programs\Python\Python36\lib\site-packages\pexpect\expect.py",
  line 63, in eof
      raise EOF(msg) pexpect.exceptions.EOF: End Of File (EOF).
  searcher: searcher_re:
      0: re.compile(b'Network:')


text:
Q: Expressing that a food is naturally hot When you want to say that a food, for instance, is naturally hot, what do you call it?
Any help would be appreciated.

A: You can use 'hot' to refer to food that is at a high temperature or that is 'spicy' in taste. It confuses us native english speakers all the time in conversations!
For example - both of these sound very standard:

*

*The nachos just came out of the oven and are very hot.

*The nachos are topped with jalapeños and are very hot.

I recommend using 'spicy' to refer to food that is naturally 'hot' in flavor to avoid confusion.


text:
Q: How to select current date and previous date from a single table? I have a very simple table:
mysql> desc stats;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| entry_id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| entry_date  | date        | NO   |     | NULL    |                |
| show_name   | varchar(40) | NO   |     | NULL    |                |
| month_total | int(11)     | NO   |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+

I want a select statement that will give me the results from the current date as well as the previous day's data in a single statement, so for example, the results would be something like
show_name month_total(Current day) monthly_total(Previous Day)

Is there an easy way to do this within a single sql statement?

A: UPDATED: It makes sense to add entry_date to the output
SELECT c.show_name,
       c.month_total current_month_total,
       p.month_total prev_month_total
  FROM stats c INNER JOIN
       stats p ON p.entry_date = c.entry_date - INTERVAL 1 DAY

Assuming that you have sample data like
+----------+------------+-----------+-------------+
| entry_id | entry_date | show_name | month_total |
+----------+------------+-----------+-------------+
|        1 | 2013-03-07 | Name1     |          10 |
|        2 | 2013-03-08 | Name2     |          20 |
|        3 | 2013-03-09 | Name3     |          30 |
|        4 | 2013-03-10 | Name4     |          40 |
+----------+------------+-----------+-------------+

The output of the query is
+-----------+------------+---------------------+------------------+
| show_name | entry_date | current_month_total | prev_month_total |
+-----------+------------+---------------------+------------------+
| Name2     | 2013-03-08 |                  20 |               10 |
| Name3     | 2013-03-09 |                  30 |               20 |
| Name4     | 2013-03-10 |                  40 |               30 |
+-----------+------------+---------------------+------------------+

Here is a sqlfiddle example
If you need the output for a specific date or for an interval of dates just add a WHERE clause.
For today
...
WHERE c.entry_date = CURDATE();

From 03/09 to 03/10
...
WHERE c.entry_date BETWEEN '2013-03-09' AND '2013-03-10'

A: If by current day you mean today, use SUBDATE and CURDATE functions and a subquery in your select statement:
SELECT
    show_name,
    month_total AS current_day_total,
    (SELECT month_total FROM stats WHERE entry_date = SUBDATE(CURDATE(), 1) LIMIT 1) AS previous_day_total
FROM stats
WHERE entry_date = CURDATE();

see fiddle.
If you want this for everyday and not just the current day, go with join.

A: assuming this test data:
+----------+------------+-----------+-------------+
| entry_id | entry_date | show_name | month_total |
| 1        | 2013-03-07 | test1     |           1 |
| 2        | 2013-03-07 | test2     |          11 |
| 3        | 2013-03-08 | test1     |           2 |
| 4        | 2013-03-08 | test2     |          22 |
| 5        | 2013-03-08 | test3     |         222 |
| 6        | 2013-03-09 | test1     |           3 |
| 7        | 2013-03-09 | test2     |          33 |
| 8        | 2013-03-07 | test1     |           5 |
+----------+------------+-----------+-------------+

If you have multiple entries per day for different names, than this should work well:
SELECT c.show_name, c.entry_date,
       c.month_total current_day_month_total,
       IFNULL(p.month_total,0) previous_day_month_total
  FROM test.stats c LEFT JOIN test.stats p
       ON p.entry_date = c.entry_date - INTERVAL 1 DAY
          AND c.show_name = p.show_name
  GROUP BY c.entry_date, c.show_name;

+-----------+------------+-------------------------+--------------------------+
| show_name | entry_date | current_day_month_total | previous_day_month_total |
| test1     | 2013-03-07 |                       1 |                        0 |
| test2     | 2013-03-07 |                      11 |                        0 |
| test1     | 2013-03-08 |                       2 |                        1 |
| test2     | 2013-03-08 |                      22 |                       11 |
| test3     | 2013-03-08 |                     222 |                        0 |
| test1     | 2013-03-09 |                       3 |                        2 |
| test2     | 2013-03-09 |                      33 |                       22 |
+-----------+------------+-------------------------+--------------------------+

If the there are even multiple entries per day and name than this would combine their values:
(see line one of the result table for test1 - id1:1 + id8:5 = 6)
SELECT c.show_name, c.entry_date,
       c.month_total current_day_month_total,
       IFNULL(p.month_total,0) previous_day_month_total
  FROM (SELECT show_name, entry_date, SUM(month_total) month_total
        FROM test.stats
        GROUP BY entry_date, show_name) c
     LEFT JOIN
       (SELECT show_name, entry_date, SUM(month_total) month_total
        FROM test.stats
        GROUP BY entry_date, show_name) p
     ON p.entry_date = c.entry_date - INTERVAL 1 DAY
     AND c.show_name = p.show_name;

+-----------+------------+-------------------------+--------------------------+
| show_name | entry_date | current_day_month_total | previous_day_month_total |
| test1     | 2013-03-07 |                       6 |                        0 |
| test2     | 2013-03-07 |                      11 |                        0 |
| test1     | 2013-03-08 |                       2 |                        6 |
| test2     | 2013-03-08 |                      22 |                       11 |
| test3     | 2013-03-08 |                     222 |                        0 |
| test1     | 2013-03-09 |                       3 |                        2 |
| test2     | 2013-03-09 |                      33 |                       22 |
+-----------+------------+-------------------------+--------------------------+


text:
Q: sql query in mongoengine I have a document and an embedded document as shown below. And I would like to query the embedded document in mongoengine. In sql, this would be: SELECT A.Nom_PC, B.Intitule from Comptes as A, Vals as B WHERE B.Num = "some value"
class Vals(EmbeddedDocument):
    Num = StringField()
    Intitule = StringField()
    meta = {'allow_inheritance': True}

class Comptes(Document):
    Nom_PC = StringField()
    PC = ListField(EmbeddedDocumentField(Vals))
    meta = {'allow_inheritance': True}

I've tried out some things that didn't work like:
Comptes.objects(Vals__match={ "Num": Num }).aggregate(
       {'$project': {
           'PC': {
               '$filter': {
                   'input': '$PC',
                   'as': 'Vals',
                   'cond': {'$eq': ['$$Vals.Num', Num]}
               }
           }
       }}
   )

A: First off, you really should use
PC = EmbeddedDocumentListField(Vals)

instead of
PC = ListField(EmbeddedDocumentField(Vals))

This is because lists of embedded documents require special considerations.
As to the query:
q = Comptes.objects(PC__Num="some value")

This creates a query for all matching Comptes documents. You can then cherry pick whatever data you wish from each document.
(If, in the future, you need to match on multiple items in an EmbeddedDocument, use the match keyword. See the docs for more info.)
For example:
my_list = []
for doc in q:
    for v in doc.PC:
        if v.Num == "some value":
            my_list.append([doc.Nom_PC, v.Intitule])

For a YouTube vid I made with further details about the EmbeddedDocumentListField: https://www.youtube.com/watch?v=ajwPOyb6VEU&index=6


text:
Q: how to pass a value from a form control to a variable in php html when submit is pressed what I am trying to do is pass a value to a variable depending on which button the user presses. I created a table and delete button with a while loop, however, because of this, all the buttons have the same name and id. how can i pass the specific UserID to a variable when the appropriate button is pressed??
this is my PHP with embedded HTML
<?php
    $servername = "localhost";
    $username = "root";
    $password = "A1128857795!";

    // Create connection
    $conn = new mysqli($servername, $username, $password);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } else{
        echo "Connected successfully";}

    mysqli_select_db($conn,'test_schema');

    $sql = "SELECT * FROM userinfo;";

    $retvalues = mysqli_query($conn, $sql);

    if(!$retvalues)
        {
            die("could not get data: " . mysqli_error());
        }

    print("
");
    echo "<form action='delete.php' method='POST'>";
    echo"
";
    echo"
";
    echo "ID	";
    echo "NAME	";
    echo "GENDER	";
    echo "
";
    while($row = mysqli_fetch_array($retvalues, MYSQL_ASSOC))
    {
            print("
");
            echo "<input type='text' name='id' value='{$row['UserID']}'/>	". " " . "{$row['FirstName']}" . " " . "{$row['LastName']}	" .
                " " . "{$row['gender']}	";
            echo "<input  name='Delete' value='Delete' type='submit'>	";
            print("
");
    }

    echo "
";
    echo "</form>";

When I press any of the buttons, it returns the ID for the last row of the table every time, causing the DELETE statement to always delete the last record from my database.
if(isset($_POST['id']))
    {

        $delUID = $_POST['id'];
        $sql="DELETE FROM userinfo WHERE UserID = $delUID";
        $query = mysqli_query($conn, $sql);
        echo "DELETE FROM userinfo WHERE UserID = $delUID;";
    }
    $conn->close();
?>

Any advice will be welcomed. thank you.

A: You can either use an array in the name of the old school input-button or just use the <button> tag to have different value and caption.
<form method="post">
  <?php for($id = 1; $id <= 3 ; $id++): ?>
    <input type="submit" name="delete_a[<?php echo $id; ?>]" value="Caption of delete button a">
    <button type="submit" name="delete_b" value="<?php echo $id; ?>">Caption of delete button b</button>

  <?php endfor; ?>
</form>
<?php
var_dump($_POST);
?>

With the array version you could even use checkboxes and any submit button to delete multiple rows at once. You are then interested in the keys of the array $_POST['delete_a'].

A: I will think about doing something like this
<?php
$servername = "localhost";
$username = "root";
$password = "A1128857795!";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else{
    echo "Connected successfully";}

mysqli_select_db($conn,'test_schema');

$sql = "SELECT * FROM userinfo;";

$retvalues = mysqli_query($conn, $sql);

if(!$retvalues)
    {
        die("could not get data: " . mysqli_error());
    }

print("
");
echo "<form action='delete.php' method='POST'>";
echo"
";
echo"
";
echo "ID	";
echo "NAME	";
echo "GENDER	";
echo "
";
while($row = mysqli_fetch_array($retvalues, MYSQL_ASSOC))
{
        print("
");// I don't think u need to give user a chance to edit their UserID.. so I kept it in hidden type
        echo "{$row['UserID']}<input type='hidden' name='userid' value='{$row['UserID']}'/>	". " " . "{$row['FirstName']}" . " " . "{$row['LastName']}	" .
            " " . "{$row['gender']}	";
        echo "<input  name='Delete' value='Delete' type='submit'>	";
        print("
");
}

echo "
";
echo "</form>";

Receiving side
if(isset($_POST['Delete']))
{

    $delUID = $_POST['userid'];
    $sql="DELETE FROM userinfo WHERE UserID = $delUID";
    $query = mysqli_query($conn, $sql);
    echo "DELETE FROM userinfo WHERE UserID = $delUID;";
}
$conn->close();

A: @f_anto Has the right idea.
Create your table using query loop but attach a unique link or button to each row.
while($row = mysqli_fetch_array($retvalues, MYSQL_ASSOC)) {
        echo "<input type='text' name='id' value='{$row['UserID']}'/>	"
        . "{$row['FirstName']} " . "{$row['LastName']}	" .
        . "{$row['gender']}	"
        . "	";
}

Then use an AJAX call to do the dirty work.
$(".delete-button").on('click', function(e){
    e.preventDefault();
    var $id = $(this).attr("id");
    $.ajax({
      type: "POST",
      url: "delete.php",
      data: ["id": $id]
  });
});

Or something like that. Light example: https://jsfiddle.net/mcmullen_greg/okvrbfnx/1/


text:
Q: How to handle Salesforce Heapsize limit We are building a sync service for downloading all the objects data via a single call.
If all the data excceed 20000 records, when we use
EncodingUtil.base64Encode(Blob.valueof(JSON.serialize(syncServiceInstance)));

It will show the Heapsize exceed error.
How to handle it?

A: Really, the only thing you can do is try to reduce the heap size.
You could try to construct the JSON string in batches of records instead of passing the whole List.  It might looks something like this:
String s = '';
for(List<My_Object__c> objList : [SELECT ... FROM MY_Object__c]){
   //add serialized list (remove outer {})
   s += StringJSON.serialize(objList).substring(1,s.size()-1);
}
return EncodingUtil.base64Encode(Blob.valueof(s));

After each loop the objects in objList should be garbage collected.
Another way would be to implement paging in your service (assuming you mean a web-service) and only pull down so many records at a time.
Finally, if syncServiceInstance is a list of SObject, then I would recommend just using the Bulk Data API.  It will be way faster and save you from a hacky implementation.


text:
Q: Distribuição log-normal em python Eu estou a tentar ajustar a distribuição log-normal a estes dados mas não sei como descobrir a média, o desvio-padrão e ajustar a curva da distribuição em Python (estou a usar o Jupyter no Anaconda). Já tinha tentado fazer isso com a distribuição normal, mas olhando melhor para o gráfico, parece que o que se ajusta mais aos dados é uma distribuição log-normal em vez de uma normal. Poderiam dizer-me como posso alterar o código e colocar uma distribuição log-normal em vez de normal, se faz favor, para o mesmo conjunto de dados?
#amostra 22A
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
import matplotlib.ticker as tkr
import scipy, pylab
import locale
locale.setlocale(locale.LC_NUMERIC, "de_DE")
plt.rcParams['axes.formatter.use_locale'] = True

df=pd.DataFrame({'frequencia_relativa': {'0-1': 0.282, '1-2': 0.316, '2-3': 0.171, '3-4': 0.068, '4-5': 0.085, '5-6': 0.026, '6-7': 0.026, '7-8': 0.009, '8-9': 0.009, '9-10': 0.0, '10-11': 0.0, '11-12': 0.009}})
df=df.reindex(['0-1', '1-2', '2-3', '3-4', '4-5', '5-6', '6-7',
       '7-8', '8-9', '9-10', '10-11', '11-12'])
plt.rcParams["figure.figsize"] = [15,8]
fig, ax =plt.subplots()
ax.bar(x=df.index, height=df.frequencia_relativa, alpha=0.5, width=0.9)
ax.set_xlabel('Tamanho lateral do triângulo ($\mu m$)', fontsize=22)
ax.set_ylabel('Frequência relativa', fontsize=22)
x_axis = np.arange(0, 10, 0.001)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
#normal com média 2,232 e variância 1.88, conforme planilha
ax.plot(x_axis, norm.pdf(x_axis,2.232,1.888), linewidth=3)
#plt.show()
plt.savefig('output.png', dpi=500, bbox_inches='tight')

A: Sua variável X ocorre no ponto médio das classes, X=[0.5,1.5,2.5, etc...,11.5 ] - a distribuição parece ser log normal com média possivelmente na classe 1.5 nesta escala, porém, se for mesmo log normal, deves procurar a média em Ln(x).
Transforme X em Ln(X); nesta escala a distribuição deve ser normal, mas também estará assimétrica por falta de resolução do histograma (por sub amostragem possivelmente); daí você retira o Ln(média) e o Ln(desvio padrão), gera um outro vetor Ln(X) mais refinado, calcula as frequências relativas usando a distribuição normal padrão em Z (média zero, desvio 1) e leva de volta este vetor para o espaço da sua variável X usando X = exp(Ln(média) + Z * Ln(desvio padrão)).
Seguindo este procedimento encontrei média de 0.67 e desvio de 2.59 em X. Para isso, usei tentativa e erro, uma vez que otimização não levou a bons resultados. Veja que na sua modelagem, a média está na realidade apontando para o desvio padrão.


text:
Q: DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") gives different formats for different users I assumed that ToString("yyyy/MM/dd  HH:mm:ss") will force the string to be formatted with '/', but I can see that every device gets different formats. How can I force it to be saved with '/'?
Good example-

*

*2021/10/06  18:05:53
Strange examples I see in my DB from different users-

*

*2021-10-06 23:48:37

*2021.10.12  12:41:42

*2021. 10. 06  19:17:23  ('.'+ space after)

*2021.10.13  19.18.16
One solution is to replace every -, . and . to /, but this only solves the strange examples I found. What if there are others?

A: / in a format string means "the culture-specific date separator". If you want the literal forward-slash, quote it (and the colons, to avoid the use of a custom time separator):
ToString("yyyy'/'MM'/'dd HH':'mm':'ss")

Alternatively - and probably better - use the invariant culture. Not only will that use / as the date separator, but you won't need to worry about a culture having a different default calendar. (It'll always use the Gregorian calendar, which is presumably what you want.)
Even better, use an ISO-8601 format - you're already using a "slightly unusual for humans" format of year-first, so you might as well go the whole hog and go with the standard format for dates and times.
Sample code:
String text = dateTimeValue.ToString(
    "yyyy-MM-dd'T'HH:mm:ss",
    CultureInfo.InvariantCulture);

This is also the sortable standard date/time format so you can simplify the code significantly:
String text = dateTimeValue.ToString("s");

(That format always uses the invariant culture.)
That's if you really need to format the string at all, though. If you're saving it in a database, I'd advise you to:

*

*Use an appropriate type in the database, e.g. DATETIME

*Store it using a parameter (specifying the value just as a DateTime), not formatted text

If you do both of these, you'll avoid oddities like this.

A: Another solution that I can think of is creating a new function that creates a date
DateTime date= DateTime.UtcNow;
And extracting manually and splitting the date to a few strings (year,month,day,hour,month,seconds)
string year = date.Year.ToString(); string month = date.Month.ToString();...
and building a string out of it in the right format,
string newDate= year + "/" + month + "/" + day + "  "+ hour+":"+ minute+ ":"+seconds;
that way I can be sure it's always one format that I'll decide on

A: How about storing the date as a number, eg unix time - DateTimeOffset.UtcNow.ToUnixTimeSeconds() or (DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds - it's a lot simpler and cheaper to store a number than a string
Also wanted to point out that the only date I've
seen you store so far is UtcNow (as written in your answer) - fire base does appear to have a solution for that in that you can send ServerValue.TIMESTAMP and it will cause fb to store the unix time as the server sees it.
My take away from this (never used fb) is that that's how they store dates so perhaps it makes sense to follow :)


text:
Q: Converting C# Encryption Algorithm to Ruby Hi i have an encryption algorithm in c#, and i need to port it to ruby.
private string Encrypt(string clearText)
{
    string EncryptionKey = "ENC_KEY";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x5, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream()) {
        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
        {
            cs.Write(clearBytes, 0, clearBytes.Length); cs.Close();
        }
        clearText = Convert.ToBase64String(ms.ToArray()); }
    }
    return clearText;
}

As i understand alghorithm generates AES key, and iv and encrypt and return as base 64 string.
I didn't find exact alternative for Rfc2898DeriveBytes and i used PBKDF2 Gem. And here is my ruby method:
def self.encrypt clear_text
  iterations = 1000
  encryption_key = 'EncryptionKey'
  clearBytes = clear_text.encode( 'UTF-16LE' ).bytes.to_a
  enc_bytes = [0x1, 0x2, 0x3, 0x4, 0x5, 0x5, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11]
  salt = enc_bytes.pack('C*')
  derived_a = PBKDF2.new do |p|
    p.password = encryption_key
    p.salt = salt
    p.iterations = iterations
    p.key_length = 32
  end

  derived_b = PBKDF2.new do |p|
    p.password = encryption_key
    p.salt = salt
    p.iterations = iterations
    p.key_length = 16
  end

  key = derived_a.bin_string
  # iV = derived_b.bin_string
  iV_a = iV_a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] # Static iV
  iV = iV_a.pack('C*')

  cipher = OpenSSL::Cipher::AES256.new(:CBC)
  cipher.encrypt
  cipher.key = key
  cipher.iv = iV
  encrypted = cipher.update(clear_text) + cipher.final
  Base64.encode64(encrypted)
end

i have 2 problems in my code. i can't get same value on iv and if i use it as static value, return values doesn't match.
I don't have too many c# experience. What am i missing?

A: It looks like your PBKDF2 generation algorithm has fixed input, so the resulting Key and IV should always be the same.
I just ran the C# code on my machine modified to output the values of the Key and IV. It gave me:
takKsX7IBXq3R0Q5GWgJo/XhhEHDNfRFxSVru12vtU4=
y/lm9eKzBJTMdU+uA6GlXA==

as the Base64 encoded values of the Key and IV respectively. You can just use these values in your Ruby code, that will remove the need to keep generating these using the PBKDF2 gem.
So this Ruby code
clear_text = 'HELLO WORLD'
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.key = Base64.decode64('takKsX7IBXq3R0Q5GWgJo/XhhEHDNfRFxSVru12vtU4=')
cipher.iv = Base64.decode64('y/lm9eKzBJTMdU+uA6GlXA==')
clearBytes = clearText.encode('UTF-16LE')
encrypted = cipher.update(clearBytes)
encrypted << cipher.final
puts Base64.encode64(encrypted)

will output the same thing as Encrypt("HELLO WORLD")

A: For starters, you have different encryption keys
string EncryptionKey = "ENC_KEY";
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x5, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11 });

Which is different from:
encryption_key = 'EncryptionKey'
...
derived_a = PBKDF2.new do |p|
    p.password = encryption_key
    p.salt = salt
    p.iterations = iterations
    p.key_length = 32
  end

If you truly are using the same "everything" you might need to make sure your passphrase is the same before KDF-ing it :)
Also, don't forget to pack your IV in with your ciphertext since you don't want that (or your salt) to be static, encrypt then MAC, all that good stuff :)


text:
Q: Flutter - access attribute in List> i have a varibale named _users of type `List<Map<String,dynamic>> it has an attribute named email that i'm trying to access

I tried accessing it like this but it didn't work
   var emails = _users.map((element) => element["email"]).toList();
          for (String? element in emails) {
            TaggedUsersSingleton.instance.taggedUsers.add(element);
          }
        }

And this is the error that i'm getting
════════ Exception caught by foundation library ════════════════════════════════
The following _TypeError was thrown while dispatching notifications for AnnotationEditingController:
type 'List<dynamic>' is not a subtype of type

A: The resulting mapping is a list of lists. You would want to flatten it. I believe changing the first line to this might do that:
var emails = _users.expand((element) => element["email"]).toList();

Example:
  List<Map<String,dynamic>> _users = [{'email': ['a']},{'email': ['b']},{'email': ['c', 'd']}];
  var emails = _users.expand((element) => element["email"]).toList();
  for (String? element in emails) {
    print(element);
  }

output:
a
b
c
d


text:
Q: Variable number of arguments and recursion in Python I wanted to write a recursive function that takes a variable number of arguments (each argument being an iterable list or set) and returns a set of all concatenated combinations of each argument. I learned how to write functions with a variable number of arguments and I know how to write recursive functions, but I don't know how to put those two together in Python (or if it is even possible).
Here's my code:
def generate_combinations( *args ):
    # returns all combinations of each of the arguments
    if len( args ) == 1:
        return set( args[0] )

    result = set()
    lastdigits = generate_combinations( args[1:] )
    for d in args[0]:
         result.add( d + lastdigits )

if __name__ == '__main__':
    lastDigit = [ '1', '2', '3' ]
    allDigits = [ '4', '5' ]
    print("{}".format( generate_combinations( allDigits, lastDigit )))

Expected output:
14
15
24
25
34
35

The "problem" with my code lies in line 7: lastdigits = generate_combinations( args[1:] ). What I wanted to do here, is to pass all original arguments except the first one to the function (thus creating the recursion). And this is obviously not the way to do that. My question: can this be done, and how?
Ps: I know I can accomplish the same using a list of lists with one argument, but I'm curious is this is at all possible.

A: The requested job is done by these lines :
args = list(args)
args.pop(0)
recursiveCall( *tuple(args) )

Here the implementation of your function was a little buggy ( or I misunderstand your use of set maybe ).
def generate_combinations( *args, **kwargs ):
    print("called with", args)
    #terminate recursion
    if len(args) == 1:
        return list(set(args[0]))

    #recursion
    else:
        result = []
        args = list(args)
        heads = args.pop(0)
        tails = generate_combinations( *args, **kwargs )
        for head in heads:
            for tail in tails:
                result.append(head + tail)
        return result

if __name__ == '__main__':
    allDigits = [ '1', '2', '3' ]
    lastDigit = [ '4', '5' ]
    letters   = [ 'a', 'b' ]
    print("{}".format( generate_combinations( allDigits, lastDigit, letters , Useless='parameter')))

Execution give :
['14a', '14b', '15a', '15b', '24a', '24b', '25a', '25b', '34a', '34b', '35a', '35b']

Hope you enjoy this ;)
Arthur.


text:
Q: Importing Contracts: What to do with contract number? I have a customer who is already using Contracts that wants to import a bunch of their old Contracts.  One caveat is that the Salesforce auto-number for Contracts is prefixed with the current year, so all the old contracts have numbers that make them look like they were created this year.
Anyone know if there is a way to 'fix' the numbers so that they agree with the year they were imported?  Or even if we could make them '0000-####' so we know that they were imported?

A: I faced the same issue with Order Number
From salesforce help link
Modifying Standard Auto-Number Fields
The unique identifiers for solutions, cases, and contracts are standard auto-number fields. Each record is assigned a unique number with a specified format upon creation. You can modify the format and numbering for these auto-number fields.

*

*From Setup, click Customize, select the appropriate tab link, and
then click the Fields link.

*Click Edit next to the name of the field
    in the Standard Fields list.

*Enter a Display Format to control such
    formatting details as the minimum number of leading zeros as well as
    any prefix or suffix for the number. See Custom Field Attributes.
    Format changes do not affect existing records; they are applied only
    to new records.

*Enter the number to be assigned to the next record
        that is created after you save your changes.

*Click Save.


text:
Q: Dump Java heap shortly before OutOfMemoryException?
Possible Duplicate:
Java VisualVM Enable Heap Dump on OOME

I've got an App that crashes because of an OOME. I would like to create a dump file of the heap shortly before the App crashes. I used jdump before to analyse the heap after a few hours of runtime, but nothing suspicious was found. I can run the app in some Eclipse profiler. Is there some way to create a heap dump shortly before a OOME is thrown on a server with a normal (or jdk) installation?

A: You can use -XX:+HeapDumpOnOutOfMemoryError

A: If you really want to dump heap before you run out of memory, you could add a worker thread that periodically polls for memory usage (see freeMemory).  When you start running out of memory, you dump heap.
See https://blogs.oracle.com/sundararajan/entry/programmatically_dumping_heap_from_java for how to dump heap from your application.


text:
Q: Complicated FOR loop nesting. Having trouble cleaning up legacy code I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?
map<Id,SObject> mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property');
map<Id,SObject> mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');

for ( Lease__c l: Trigger.New ) {

    if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {

        lProperties = new List<SObject>{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};

            for ( SObject p: lProperties ) {

                for ( String fm: FieldMap.keyset() ) {

                    if ( p.get(FieldMap.get(fm)) != Null) {
                        l.put(fm,p.get(FieldMap.get(fm)));
                    }

                }
            }
    }
}

A: The idea that nested for loops are bad seems to be a common one, but it is at best an overgeneralization. There are many problems for which a nested for loop is the the most idiomatic solution - iterating over nested containers, for example.
Where you don't want nested for loops is when they represent a needless increase in computational complexity - taking an algorithm from O(n) to O(n * m) complexity by needlessly iterating rather than using containers like Maps and Sets that provide constant-time access and membership checking.
A fairly common example of a bad nested for loop looks like this:
for (Account a : accts) {
    for (Contact c : contacts) {
        if (c.AccountId == a.Id) {
            // Do some work
        }
    }
}

This wastes cycles because it compares every Contact to every Account - an n * m complexity for n total Contacts and m total Accounts. If instead either the user wrote a parent-child SOQL query or precomputed a Map<Id, List<Contact>>, the inner for loop could be optimized to only iterate over the Contacts that belong to a, with no comparison or wasted iterations.
Looking at this code, I don't see that it is wasting much time. It can be lightly optimized, I think, but mostly it can be made clearer.
// This loop cannot be eliminated.
for ( Lease__c l: Trigger.New ) {

    if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {

        // This is pointless, but also largely harmless.
        // The code is creating a *one element list* and then iterating over it;
        // `mapProperyIdBudDetail` is a one-to-one Map.
        lProperties = new List<SObject>{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};
            // So this loop can be removed.
            for ( SObject p: lProperties ) {

                // This loop is idiomatic, but can be slightly optimized in sense.
                // Whether that leads to performance enhancements would have to be benchmarked.
                // You can do `p.getPopulatedFieldsAsMap()` and intersect its keySet
                // with that of FieldMap to get a specific field collection to iterate
                // over and copy to `l`.
                for ( String fm: FieldMap.keyset() ) {

                    if ( p.get(FieldMap.get(fm)) != Null) {
                        l.put(fm,p.get(FieldMap.get(fm)));
                    }

                }
          }
    }
}

A: if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {

This shouldn't be necessary. If it is, I'd consider your map improperly initialized. if the value is null, some changes elsewhere might be necessary.

    lProperties = new List<SObject>{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};

No need to construct a new list, it can be simply:
    lProperties = mapProperyIdBudDetail.get(PropertyMap.get(l.space__c));

        for ( SObject p: lProperties ) {

            for ( String fm: FieldMap.keyset() ) {

                if ( p.get(FieldMap.get(fm)) != Null) {
                    l.put(fm,p.get(FieldMap.get(fm)));
                }

            }
        }

This bit is improperly indented, and could be optimized slightly:
    for ( SObject p: lProperties ) {
        for ( String fm: FieldMap.keyset() ) {
            Object value = p.get(FieldMap.get(fm));
            if (value != Null) {
                l.put(fm,value);
            }
        }
    }

map<Id,SObject> mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property');
map<Id,SObject> mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');

for ( Lease__c l: Trigger.New ) {

    lProperties = mapProperyIdBudDetail.get(PropertyMap.get(l.space__c));
    for ( SObject p: lProperties ) {
        for ( String fm: FieldMap.keyset() ) {
            Object value = p.get(FieldMap.get(fm));
            if (value != Null) {
                l.put(fm,value);
            }
        }
    }
}

A more optimized version would probably use getPopulatedFieldsAsMap (which likely didn't exist when this code was written).

In this case, the nested loops are warranted, because you're checking for all non-null values in a list of objects, so it necessarily needs to go through either one of the lists for each record.