text:
Q: Removing gap between columns in splitLayout within dashboardSidebar I'm using the splitLayout() function within a dashboardSidebar() from the shinydashboard package. When I do, there is a significant gap between inputs within my splitLayout().
When I used vanilla shiny, I could control this gap with parameter cellArgs = list(style="padding: 0px") but this seems to have a different effect within a dashboardSidebar().
Question:
How can I control the gap between inputs inside a splitLayout() within a dashboardSidebar()?
Here is a MRE which shows my unsuccessful attempts at using padding
library(shinydashboard)
library(shiny)

sidebar <- dashboardSidebar(width=400,
                            sidebarMenu(
                              menuItem("Default", tabName = "dashboard", icon = icon("dashboard"),startExpanded = T,
                                       splitLayout(cellWidths = c(100,100,100,100),
                                                   textInput("a1",label=NULL,value = 1),
                                                   textInput("a2",label=NULL,value = 2),
                                                   textInput("a3",label=NULL,value = 3),
                                                   textInput("a4",label=NULL,value = 4)
                                       ),
                                       splitLayout(cellWidths = c(100,100,100,100),cellArgs = list(style="padding: 0px"),
                                                   textInput("b1",label=NULL,value = 1),
                                                   textInput("b2",label=NULL,value = 2),
                                                   textInput("b3",label=NULL,value = 3),
                                                   textInput("b4",label=NULL,value = 4)
                                       ),
                                       #see the effect of padding
                                       splitLayout(cellWidths = c(100,100,100,100),cellArgs = list(style="padding: 20px"),
                                                   textInput("c1",label=NULL,value = 1),
                                                   textInput("c2",label=NULL,value = 2),
                                                   textInput("c3",label=NULL,value = 3),
                                                   textInput("c4",label=NULL,value = 4)
                                       )
                              )
                            )
)

body <- dashboardBody(

)

# Put them together into a dashboardPage
ui <- dashboardPage(
  dashboardHeader(title = "Padding demo",titleWidth=400),
  sidebar,
  body
)
server <- function(input, output) {

}
shinyApp(ui,server)

A: your problem is not the padding of the the splitCells - that is working fine. It has more to do with that the inputs also have padding around them. To remove this you can add the following code
body <- dashboardBody(
  tags$head(
    tags$style(
      ".shiny-input-container{padding:0px !important;}"
    )
  )
)

hope this helps


text:
Q: Convert CLR type names to equivalent idiomatic C# aliases (eg System.String => string, Int32 => int) I am parsing some objects and I'd like to dynamically generate some code.
The thing is that when I'm reading types I got things like :
System.String
System.Int32
Boolean

I know it's strictly identical for C# to string, int and bool. But when I'm parsing my object, i got the "System" versions and I want to dynamically generate some code using strings and I want to generate the alias description, can I do it easyly ? (without something like a Dictionary associating typeofs to strings...)

A: I don't know of a way to do this.  However, there are not that many types so if it were me I would probably just write a mapping function.
You can find the list of C# type names here as a starting point:
http://msdn.microsoft.com/en-us/library/86792hfa(VS.71).aspx
Update: here is a reference for C# which includes decimal.  Not sure why that was missing from above link:
http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx

A: string and int are aliases for System.String and System.Int32.
Seems like you can use this to get the Types from strings: http://msdn.microsoft.com/en-us/library/system.codedom.codetypeofexpression.aspx
// Creates a reference to the System.Int32 type.
CodeTypeReference int32typeRef = new CodeTypeReference("System.Int32");

But there is no way to get a string from type so you have to define your own mapping there:
Is there a way to get a type's alias through reflection?

A: Once you compile the code you write in C# it no longer knows it came from C# code, therefore there is no way to automatically get the C# alias without doing exactly what you suggest - create a simple mapping dictionary.
The built in C# types are listed here: http://msdn.microsoft.com/en-US/library/ya5y69ds.aspx
This list is not going to change any time soon, as I shouldn't worry about hard coding this list into your application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically adding new data to view I'm working on the app which should download some data form server (done) and then show then. Same way as for example android market app (searching) works. It also need to be click-able items. I was thinking about using for example linear layout and somehow dynamically creating new textview's Is this a good way to do this? Can anybody provide some examples?

A: I think what you are looking for is a ListView. This widget displays items in a list fashion, you can customize how each row of the list looks and what data you want to display. Google Market probably uses GridView, since they display apps in rows with several columns.
Here is a tutorial on how to use ListView (or for GridView). Plus there are tons of related stuff available in SO.

A: An example:
LinearLayout layout = (LinearLayout) findViewById(R.id.somelayout);
TextView text = new TextView(this);
text.setText("some text");
layout.addView(text);

A: You're telling your story like you need a ListView, which is the view used in the Android market to display apps. You can use this in combination with the setOnItemClickListener method to make them clickable.
On this site, I found this example which would serve your needs.
public class ListviewOnclickExample extends Activity {

private ListView lv1;

/*
 * Instead of putting your test here,
 * load it from the internet in the oncreate method
 */
private String lv_arr[] = { "Android", "iPhone", "BlackBerry",
        "AndroidPeople", "J2ME", "Listview", "ArrayAdapter", "ListItem",
        "Us", "UK", "India" };

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    lv1 = (ListView) findViewById(R.id.ListView01);
    lv1.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, lv_arr));
    lv1.setTextFilterEnabled(true);

    lv1.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position,
                long id) {
            // Do your click stuff here
        }
    });
}

}
The XML file is res/layout/layout.simple_list_item_1.xml and looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView android:id="@+id/ListView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

You can customize your view so it shows more than just one word, a good tutorial to do this can be found here
This Google IO video about listviews is certainly worth watching too if you want to know more about them. For the things you describe the above should be enough.


text:
Q: Conduit: make a Source from another Source I am having source crawling some websites and collects items of type Category from them:
catsSource :: Source IO Category

The next step is to write companies collector (items of type Company). Companies collector needs categories: for each Category on input several companies should be produced, one by one. In other word it should "yield" Company, not [Company].
What do I need for this task? Conduit or tricky source? If source, how it should get categories from catsSource? If conduit how it should pass ("yield") company forward when it is found?
To clear my question here is an attempt (not passing type check):
import qualified Data.Conduit.List as CL

companiesFromCategory cat = [Company "foo", Company "bar"]

companies :: Conduit Category IO Company
companies = CL.fold . (CL.map companiesFromCategory)

A: The solution is to use concatMap:
companies = CL.concatMap companiesFromCategory


text:
Q: HDFS over S3 / Google storage bucket translation layer - how? I'd love to expose a Google storage bucket over HDFS to a service.
Service in question is a cluster (SOLR) that can speak only to HDFS, given I have no hadoop (nor need for it), ideally I'd like to have a docker container that would user a Google storage bucket as a backend and expose it's contents via HDFS.
If possible I'd like to avoid mounts (like fuse gcsfs), has anyone done such thing?
I think I could just do mount gcsfs and setup a single node cluster with HDFS, but is there a simpler / more robust way?
Any hints / directions are appreciated.

A: The Cloud Storage Connector for Hadoop is the tool you might need.
It is not a Docker image but rather an install. Further instructions can be found in the GitHub repository under README.md and INSTALL.md
If it is accessed from AWS S3 you'll need a Service Account with access to Cloud Storage and set the env variable GOOGLE_APPLICATION_CREDENTIALS to /path/to/keyfile.

To use SOLR with GCS, you need indeed a hadoop cluster and you can do that in GCP by creating a dataproc cluster then use the connector mentioned to connect your SOLR solution with GCS. for more info check this SOLR


text:
Q: Tag dispatching/enable_if - I am confused I have the following structs:
struct A
{
}

struct B
{
tuple<string,string>  children{{"test1","test2"}};
}

I would like to create a template function that will overload the << operator on every class having a member variable called children.
If possible- only on tuples named children.
When a class with a children tuple like B is met it should iterate the tuple members and call << on each of them.
Something like:
template<typename RECEIVERTYPE,typename SENDERTYPE>
typename std::enable_if<std::have_children_member<RECEIVER_TYPE>::value, void>::type
RECEIVERTYPE& operator<< (RECEIVERTYPE& streamReceiver, const SENDERTYPE&    streamSender)
    {
        for_each(streamSender.children, [&](const auto& child)
        {
            streamReceiver << child;
        });

        return streamReceiver;
    }

I have tried alot of examples- but I cant really get anything working in visual studio 2015.

A: I would just do this to only match types with a tuple member called children:
template<typename S, typename T,
         std::size_t = std::tuple_size<decltype(T::children)>::value>
  S& operator<<(S& s, const T& t)
  { ... }

And might implement the body like this:
template<typename S, typename T, std::size_t... I>
  void
  print_tuple_like(S& s, const T& t, std::index_sequence<I...>)
  {
    void* unused[] = { &(s << std::get<I>(t))... };
  }

template<typename S, typename T,
         std::size_t N = std::tuple_size<decltype(T::children)>::value>
    S& operator<<(S& s, const T& t)
{
    print_tuple_like(s, t.children, std::make_index_sequence<N>{});
    return s;
}

Or like:
template<std::size_t N, typename S, typename T>
  void
  print_tuple_like(S& s, const T& t, std::false_type)
  { }

template<std::size_t N, typename S, typename T>
  void
  print_tuple_like(S& s, const T& t, std::true_type)
  {
    s << std::get<N>(t);
    print_tuple_like<N+1>(s, t, std::integral_constant<bool, (N+1 < std::tuple_size<T>::value)>{});
  }

template<typename S, typename T,
         std::size_t N = std::tuple_size<decltype(T::children)>::value>
  S& operator<<(S& s, const T& t)
{
    print_tuple_like<0>(s, t.children, std::integral_constant<bool, (N != 0)>{});
    return s;
}


text:
Q: React-Native-Maps not showing on Android Emulator or real device I added react-native-maps in my project and it doesn't showup
I am not able to figure out what I'm doing wrong
Things I have tried:

*

*Test the example app available on the official repo: https://github.com/react-native-maps/react-native-maps

*Followed all the instructions available in the installation guide and also tried many articles guiding through the installation process

Please review the code snippets below and let me know if you need code from any other files that are important to find the issue.
For some people it shows an empty map with white screen and Google logo at the bottom. I have nothing at all. Just blank screen.
Doesn't throw any error while compilation.
code in Maps.js
import React from "react";
import { StyleSheet, View } from "react-native";
import MapView, { PROVIDER_GOOGLE } from "react-native-maps";

const Maps = () => {
  return (
    <View style={styles.container}>
      <MapView
        styles={styles.map}
        provider={PROVIDER_GOOGLE}
        initialRegion={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
      />
    </View>
  );
};

export default Maps;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,

  },
 });

\android\app\build.gradle file
dependencies {
   ...
   implementation(project(':react-native-maps')){
       exclude group: 'com.google.android.gms', module: 'play-services-base'
       exclude group: 'com.google.android.gms', module: 'play-services-maps'
   }
   implementation 'com.google.android.gms:play-services-base:17.2.1'
   implementation 'com.google.android.gms:play-services-maps:17.0.0'
}

\android\build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
        ndkVersion = "20.1.5948944"
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:4.2.1')
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

AndroidManifest.xml (Note: I have my API key and tested with the example project from the github repo and it worked)
<meta-data
     android:name="com.google.android.geo.API_KEY"
     android:value="I_ADDED_MY_KEY"/>

settings.gradle
include ':react-native-maps'
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/lib/android')

package.json
{
  "name": "my-app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@react-native-async-storage/async-storage": "^1.15.9",
    "@react-native-community/checkbox": "^0.5.8",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-navigation/bottom-tabs": "^6.0.7",
    "@react-navigation/drawer": "^5.12.9",
    "@react-navigation/native": "^5.9.8",
    "@react-navigation/stack": "^5.14.9",
    "axios": "^0.21.4",
    "react": "17.0.1",
    "react-dom": "^16.8.0",
    "react-native": "0.64.2",
    "react-native-bootsplash": "^3.2.4",
    "react-native-confirmation-code-input": "^1.0.4",
    "react-native-device-info": "^8.1.3",
    "react-native-extra-dimensions-android": "^1.2.5",
    "react-native-fast-image": "^8.3.7",
    "react-native-gesture-handler": "^1.10.3",
    "react-native-maps": "^0.29.3",
    "react-native-orientation-locker": "^1.3.1",
    "react-native-reanimated": "^2.2.0",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.7.0",
    "react-native-svg": "^12.1.1",
    "react-native-svg-transformer": "^0.14.3",
    "react-native-video": "^5.1.1"
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/runtime": "^7.14.6",
    "@react-native-community/eslint-config": "^3.0.0",
    "babel-jest": "^27.0.6",
    "eslint": "^7.30.0",
    "jest": "^27.0.6",
    "metro-react-native-babel-preset": "^0.66.0",
    "react-test-renderer": "17.0.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

A: You must need to make a width, heigh style for MapView: Copy it:
map: {    width: Dimensions.get('window').width,    height: Dimensions.get('window').height,    },
It working on Emulator, but in real device, I'm not sure.


text:
Q: Repainting a Swing component produce an awful result I "drawed" a component to make a kind of knob as I didn't found a way to have a "round JSlider". I use an antialiasing to obtain a good result. When I press the component with my mouse, I modify the cursor postion and I ask to the component to repaint. And then, the problem appears : the result when I repain is awful !
If I ask to repaint only when I release the mouse, it seems the result keeps correct. But that's more complicated to set the knob value if I don't repaint "continuously" the component when I set it.
The "repaint" method that cause the problem is in the run method, at the end of the class.
Does someone already had this problem ? What kind of solution can be used to solve it ?
Here is the code I'm using :
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Knob extends JPanel implements MouseListener {
int length, originX, originY, centerX, centerY, width, height, diameter, squareLength;
int minorTick, majorTick, xTick, yTick, xCursor, yCursor;
int xMouse, yMouse, xMouseOrigin, yMouseOrigin;
float yDeltaMouse;
double angleOrigin, angleRange, angle;
double angleCursorOrigin;
double angleCursorInitial;
Color backgroundColor, knobColor;
boolean mousePressed;
Thread t;

Knob () {
    System.out.println("Knob");
    angleCursorOrigin=0.5;
    angleCursorInitial=0.5;
    knobColor =new Color(0,255,0,255);
    minorTick=9;
    majorTick=3;

    this.addMouseListener(this);
}

public void paintComponent (Graphics g) {
    width=this.getWidth()/10*10;
    height=this.getHeight()/10*10;

    Graphics2D g2D = (Graphics2D)g;
    System.setProperty("awt.useSystemAAFontSettings", "on");
    System.setProperty("swing.aatext", "true");
    g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    if (width>height) {
        length=height;
    } else {
        length=width;
    }
    centerX=width/2;
    centerY=height/2;

    g.setColor(Color.BLACK);
    squareLength = (int )(length*0.9);
    originX=(width-squareLength)/2;
    originY=(height-squareLength)/2;

    /*
    //-45 = (-(Math.PI)/4)
    angleOrigin= -45;
    // 270 = (3*(Math.PI)/2)
    angleRange=270;
    //g.drawRect(originX, originY, squareLength, squareLength);
    //g.fillArc(originX, originY, squareLength, squareLength, (int)angleOrigin, (int)angleRange);
    for (int i=0; i<minorTick ; i++) {
        angle=((i*angleRange/(minorTick-1))+angleOrigin)-7;
        //System.out.println(angle*360/(2*Math.PI));
        xTick= (int) (centerX+Math.cos(angle)*squareLength/2);
        yTick= (int) (centerY-Math.sin(angle)*squareLength/2);
        //g.drawLine(centerX, centerY, xTick, yTick);
        //g.fillArc(originX, originY, squareLength, squareLength, (int)angle, (int)14);
    }
    */

    angleOrigin=-(Math.PI)/4;
    angleRange=3*(Math.PI)/2;
    g2D.setStroke(new BasicStroke(length/50+1));
    for (int i=0; i<minorTick ; i++) {
        angle=i*angleRange/(minorTick-1)+angleOrigin;
        //System.out.println(angle*360/(2*Math.PI));
        xTick= (int) (centerX+Math.cos(angle)*squareLength/2);
        yTick= (int) (centerY-Math.sin(angle)*squareLength/2);
        //g.drawLine(centerX, centerY, xTick, yTick);
        g2D.draw (new Line2D.Float(centerX, centerY, xTick, yTick));
    }

    backgroundColor = this.getBackground();
    g.setColor(backgroundColor);
    diameter=(int)(length*0.8);
    originX=(width-diameter)/2;
    originY=(height-diameter)/2;
    g.fillOval(originX, originY, diameter, diameter);

    /*
    RadialGradientPaint gp;
    Point2D center= new Point2D.Float(width/2, height/2);
    diameter=(int)(length*0.75);
    originX=(width-diameter)/2;
    originY=(height-diameter)/2;
    float radius=diameter/2;
    float[] dist = {0.7f, 1f};
    Color[] colors = {Color.BLUE, Color.GRAY};
    gp=new RadialGradientPaint(center, radius, dist, colors);
    g2D.setPaint(gp);
    g2D.fillOval(originX,originY,diameter,diameter);
    */
    diameter=(int)(length*0.75);
    originX=(width-diameter)/2;
    originY=(height-diameter)/2;
    g.setColor(Color.GRAY);
    g.fillOval(originX,originY,diameter,diameter);

    diameter=(int)(length*0.6);
    originX=(width-diameter)/2;
    originY=(height-diameter)/2;
    g.setColor(knobColor);
    g.fillOval(originX,originY,diameter,diameter);

    g2D.setStroke(new BasicStroke(length/50+3));
    angle=(2*Math.PI)*(0.75-angleCursorOrigin*0.75)+angleOrigin;
    xCursor= (int) (centerX+Math.cos(angle)*length*0.35);
    yCursor= (int) (centerY-Math.sin(angle)*length*0.35);
    g.setColor(Color.GRAY);
    g2D.draw (new Line2D.Float(centerX, centerY, xCursor, yCursor));

}

@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub
    //System.out.println("Bouton : "+arg0.getButton());

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub
    //System.out.println("Bouton : "+arg0.getButton());
    PointerInfo pointer = MouseInfo.getPointerInfo();
    Point mouseLocation = pointer.getLocation();
    xMouseOrigin = (int) mouseLocation.getX();
    yMouseOrigin = (int) mouseLocation.getY();
    if (arg0.getButton()==MouseEvent.BUTTON1) {
        mousePressed=true;
        t= new Thread(new TrackPosition());
        t.start();
    } else if (arg0.getButton()==MouseEvent.BUTTON3) {
        angleCursorOrigin=angleCursorInitial;
        repaint();
    }
}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub
    mousePressed=false;
    //System.out.println("Mouse released");

    repaint();

}

class TrackPosition implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (mousePressed==true) {
            PointerInfo pointer = MouseInfo.getPointerInfo();
            Point mouseLocation = pointer.getLocation();
            yMouse = (int) mouseLocation.getY();
            yDeltaMouse=(float)(yMouse-yMouseOrigin)/100;
            angleCursorOrigin=angleCursorOrigin+yDeltaMouse;
            yMouseOrigin=yMouse;
            if (angleCursorOrigin >=1) {
                angleCursorOrigin=1;
            } else if (angleCursorOrigin <= 0) {
                angleCursorOrigin=0;
            }
            //This repaint is a problem if I "uncomment" it
            //repaint();
        }

    }

}

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    JFrame frame = new JFrame();
    frame.setSize(300,90);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Knob());
    frame.setVisible(true);

}

}

A: Let's start with the fact that you are not call super.paintComponent before performing in custom painting in your paintComponent method.
See Painting in AWT and Swing and
Performing Custom Painting for more details
Then move onto that fact that your "mouse tracking thread" is overkill and actually isn't required.  Instead you should be using a MouseMotionListener, see How to Write a Mouse Listener for more details.
This will relieve you of the need to convert between local and screen contexts.


text:
Q: Jest issue in Angular - UnhandledPromiseRejectionWarning zone.js Currently trying to execute Jest in Angular. Getting an unhandledpromise error from zoneDelegate. Cannot seem to resolve. Tried to update zone.js to version 11 but that seems to generate new issues.
I've tried adding async to the spec.ts but that does not seem to resolve the issue.
Below my current spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ForOthersDashboardComponent } from './for-others-dashboard.component';

describe('ForOthersDashboardComponent', () => {
  let component: ForOthersDashboardComponent;
  let fixture: ComponentFixture<ForOthersDashboardComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ForOthersDashboardComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ForOthersDashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

And my jest.config
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['<rootDir>/src/'],
  testMatch: ['**/+(*.)+(spec).+(ts)'],
  setupFilesAfterEnv: ['<rootDir>/src/test.ts'],
  collectCoverage: true,
  coverageReporters: ['html'],
  coverageDirectory: 'coverage/my-app',
  globals: {
    'ts-jest': {
      isolatedModules: true,
      astTransformers: {
        before: [
          'jest-preset-angular/build/InlineFilesTransformer',
          'jest-preset-angular/build/StripStylesTransformer',
        ],
      },
    },
  },
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
    prefix: '<rootDir>/'
  })
};

EDIT
The error only seems to occur in spec files which import a module I need. So for example the spec file below. It is trying to load something out of node_modules which cannot be found. I've tried other solutions by setting the modules path but that does not seem to resolve this issue.
import { RequiredModule } from 'required-module-lib';

describe('DashboardComponent', () => {
  let component: DashboardComponent;
  let fixture: ComponentFixture<DashboardComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RequiredModule
      ],
      declarations: [
        DashboardComponent
      ]
    })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(DashboardComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    })
    .catch(err => console.error(err));
  }));


text:
Q: Special LATIN characters as UTF-8 escape sequences in Java constants I need to check Strings in Java that they only contain allowed characters. I need to do it for several different languages. Each of the languages contains a set of special characters that are added to the national alphabet against the basic English alphabet, e.g. in German you have ü, ö etc. I would need to define Java constants containing these special characters for each of the languages in the form of UTF escape sequences so that I can keep my Java file ASCII encoded.
Is there a way where I can get such constants, e.g. download them somewhere or get them from some library or generate them somehow? Any idea? I know I can find the chars somewhere on the net, find the escape sequence for each of the charaters and put it into my source file. Is there some way how to do it with less effort?

A: Each Unicode character has a canonical name, and it is possible to look them up by name:
StringBuilder sb = new StringBuilder();
sb.appendCodePoint(Character.codePointOf("LATIN SMALL LETTER O WITH DIAERESIS"));
sb.appendCodePoint(Character.codePointOf("LATIN SMALL LETTER U WITH DIAERESIS"));
System.out.println(sb);

Output:
öü

Beware casting the return value of codePointOf to a char:
char c = (char) Character.codePointOf("LATIN SMALL LETTER U WITH DIAERESIS");

This will only work for characters in the Basic Multilingual Plane (ones that fit in a single UTF-16 code unit i.e., have a code point less than 65,536).


text:
Q: Polynomial ring and extension field Let $K$ be a field and $p(x) \in K[x]$ a monic irreducible polynomial of degree $n$. Suppose $F/K$ is a field extension, and there exists $u \in F$ which is a root of $p(x)$.
1) Let $K(u)$ be the smallest subfield of $F$ containing both $K$ and $u$. Prove that $K(u) \cong K[x]/(p)$.
2) Deduce that $K(u)=\{a_0+a_1u+\cdots+a_{n-1}u^{n-1}:a_0,a_1,...a_{n-1}\in K \}$
3) Compute $u^{-1} \in K(u)$.
I guess that first one can be shown by fundamental theorem of homomorphism, and the second one by division algorithm, but how to do the third one ?

A: Hint: Let $p(x)=a_0+a_1x+\cdots+a_mx^m$. Since $a_0\ne 0$, we can assume that $a_0=-1$. Then $u(a_1+\cdots+a_mu^{m-1})=1$.

A: Hint $\ $ A root $\alpha$ of a polynomial $\,f(x)\,$ divides its constant term $\,\alpha\mid f(0)$. Over a field, if $\,\alpha\ne 0\,$ then by cancelling $\,\alpha^k$ we may assume that $\,f(0)\ne 0\,$ so $\,f(0)\,$ is a unit, thus so is its factor $\,\alpha.$
Remark $\ $ The above rearrangement of a minimal polynomial to show that a root divides the constant term  is simply a generalization of rationalizing denominators. Indeed a quadratic $\,\alpha\,$ has minimal polynomial $\,f(x) = (x-\alpha)(x-\alpha') = x^2-tx + n,\,$ $\, t = \alpha+\alpha',\,$ $\, n = \alpha\alpha',\,$ hence
rearranging $\,\alpha^2 - t\alpha + n = 0\,$ yields $\,\alpha(t-\alpha) = n,\,$ hence $\,\alpha((t-\alpha)/n) = 1,\,$ therefore $\,\alpha^{-1} = \dfrac{t-\alpha}n = \dfrac{\alpha'}{\alpha\alpha'},\,$ precisely the result of rationalizing the denominator of $\,\dfrac{1}{\alpha}.\,$
The same method works for higher degree algebraic numbers by multiplying the denominator by all other conjugates, i.e. using $\,\alpha\mid \alpha\alpha'\cdots \alpha^{(n)} = N(\alpha),\,$ for $\,N = $ norm. This works because the norm is a nonzero element of a field, hence is invertible. Essentially this exploits the norm homomorphism in order to reduce the problem of  division in $\,K(\alpha)\,$ to the simpler problem of division in $\,K.$  The key idea of the hint is that we can find such a simpler multiple of $\,\alpha\,$ already in the constant term of the minimal polynomial.


text:
Q: 26 hard drive limit on x86 servers, IBM x3650, Dell PE 2950, Dell PE 2850, where is my limitation? This is in regard to mass HDD wiping/testing. The software I use, WipeDrive Pro 5 and 7, both fall victim. I originally thought it was a limitation of the software, but after speaking with the software company, I was told there is no limit but what the machine is limited to. I go through a lot of hard drives and need to verify their integrity and that all data is removed. I have a few expansions hooked to various brands of servers, IBM, HP, Dell. They all limit me to exactly 26 simultaneously see-able, wipeable drives in the software. I just went into the lsi card setup and it shows every drive on each expansion, which totals 32 right now. Is this a limit of the card itself being a 3Gb/s PCI-E, the pci lane, x86 platform, or something entirely different? Could it even be the SAS cable type, SFF 8088 that has 26 pins? I just came across that as I was looking up the cable type. Perhaps thats the max number of simultaneous activity it can process? Any help would be greatly appreciated.

A: There is no such limit.  However, the naming convention in linux is slightly different after the first 26 device names (/dev/sdaa is the next after /dev/sdz).  The hard limit on linux is, if memory serves, 128 SCSI disks (which includes SAS and SATA disks typically), after which you will run out of allocated device numbers.  Anyway, I strongly suspect your vendor's support is in error (at least they should have identified the 128-device limit).
Very few distributions include a /dev which contains device names after /dev/sdz, so if the contents of /dev are not being constructed at runtime (as they commonly are) and a static /dev is set up, it's possible that this might be the cause; if you can get a shell, add a device using mknod /dev/sdaa 65 160 to create a reference to the 27th disk.  You may then be able to operate on it.
The device number is calculated in this way.  The major will be either 8 (first 64 drives) or 65 (last 64 drives).  The minor number increases in increments of 16 per drive, resulting in 16 minor numbers for the same volume; the 0th represents the whole device, and the 1st to 15th represent partitions (only 15 partitions per device are permitted).
You may also want to try a recent livecd of something (ubuntu or gentoo or anything, as long as it is reasonably recent) to see if the devices are detected there.  Also check dmesg to ensure your kernel is actually finding them.


text:
Q: type = interface1 or interface2 , can't make it work Sorry if this question has been already asked, but I only see "what is the difference between interface and type".
So my problem is I'm created a type which say it can be one object/interface or another. A function received it a parameters with this type and it creates a type problem. It's not easy to explain, so a code will be better :
go to Typescript Playground.
I don't understand why my variable aren't reachable with this condition, I even tried to use a type guard but I can't make it work.
type Params = {
    a: string;
} | {
    b: string;
    c: number;
}

function test(params: Params) {
    if (params.a !== undefined) {
        console.log("I want to use a there", params.a)
    } else {
        console.log("otherwise it mean b and c are available", params.b, params.c)
    }
}

test({ a: "ok" })
test({ b : "ok", c : 1337 })

Thanks by advance ;)

A: You need to use a type guard for type narrowing. That is because from your union type Params, it is possible that params.a actually does not exist and is not even accessible. You will find that attempts to access params.b or params.c will give you exactly the same error.
The type guard should be 'a' in params, so that TypeScript can narrow the type on params automatically and infer that, if this condition is satisfied, then params must be of type { a: string }, otherwise, it must be of type { b: string; c: number; }:
function test(params: Params) {
    if ('a' in params) {
        console.log("I want to use a there", params.a)
    } else {
        console.log("otherwise it mean b and c are available", params.b, params.c)
    }
}

See proof-of-concept example on TypeScript Playground.

TypeScript supports 3 different types of type guards:

*

*x in y

*x instanceof y

*x typeof y


text:
Q: Problems with references to objects being dropped in javascript

var a = [],b = [],c = [{}];
b = a;
a = c;
a.push("asd");
console.log("a : " ,a);
console.log("b : " ,b );

In this code, Why is b different from a?
I want b to refer to a.
However, if a refers to c, b no longer refers to a.

A: b refers to what was originally assigned to a, but since you assigned a to c later in your code it is no longer true that a === b.
Your problem might be clearer in this example:

var a = ['Originally a']
var b = ['Originally b']
var c = ['Originally c', {}]
b = a
a = c
a.push('asd')

console.log('a = ', a)
console.log('b = ', b)
console.log('c = ', c)


text:
Q: Помогите сделать стиль кнопки Всем привет, помогите пожалуйста сделать стильно такой кнопки. Начал осваивать HTML и CSS, но с кнопками всегда были проблемы

A:

button{
  color: white;
 border: none;
 padding: 10px 15px;
 background: linear-gradient(to right, #1E8AFA, #298EFF);
 border-radius: 5px;
 box-shadow: 0 0 0 5px #DBEBFF;
}
<button>Показать историю</button>


text:
Q: Find number of combinations of strings This was an interview question I was asked. My answer is below, but I wonder if there is a more efficient way. Possible a combinatorics type function, or is an exhaustive generation + count the only way?
Rules:
Given a character, the next character can be any one of
How many N character combinations can you make?
For example

*

*a -> i,e

*e -> i,o

*i -> a,e,o

*u -> a,e,i,o

*o -> i,u,o
For N = 1 possible string combinations are
a , e, i ,o ,u
for N = 2 possible string combinations are
[ai, ae], [ei ,eo] ,[ia , ie , io],[ua,ue,ui,uo],[oi,ou,oo]
and so on.
I solved it by constructing a tree and then counting the leaves
struct Node {
    Node(char v) : v_(v) {}
    void                     add_child(shared_ptr<Node> n) { children.emplace_back(n); }
    char                     v_ = 0;
    vector<shared_ptr<Node>> children;
};

void add_child(shared_ptr<Node> root, int n, int depth, const map<char, vector<char>> &combo) {
    if (depth == n) return;
    auto ch = root->v_;
    auto it = combo.find(ch);
    for (auto ch : it->second) {
        //printf("Adding to %c to %c\n", ch, root->v_);
        root->add_child(make_shared<Node>(ch));
    }
    ++depth;
    for (auto &child : root->children) { add_child(child, n, depth, combo); }
}

int count_leaf(shared_ptr<Node> root) {
    if (root->children.size() == 0) return 0;
    int sum = 0;
    for (auto &child : root->children) sum += count_leaf(child);
    return sum > 0 ? sum : root->children.size();
}
void password_combination() {
    // Find combos until this depth
    int n = 3;

    map<char, vector<char>> combo;
    combo.insert(make_pair('a', vector<char>{'i', 'e'}));
    combo.insert(make_pair('e', vector<char>{'i', 'o'}));
    combo.insert(make_pair('i', vector<char>{'a', 'e', 'o'}));
    combo.insert(make_pair('u', vector<char>{'a', 'e', 'i', 'o'}));
    combo.insert(make_pair('o', vector<char>{'i', 'u', 'o'}));

    // Create a N depth tree and count leaves
    // Count all children until n = 3;
    auto root  = make_shared<Node>(0);
    int  depth = 0;
    for (auto &c : combo) { root->add_child(make_shared<Node>(c.first)); }
    for (auto child : root->children) { add_child(child, n, depth, combo); }
    printf("%d\n", count_leaf(root));
}

Is there a better way. Critique on the code/bugs, and if there's a c++14 idiomatic way of doing it, even better.


text:
Q: Combine microphone audio and music from application to pipe to a Slack call I wanted to do a little experiment, where I would be able to combine music running in one of my Chrome tabs with the microphone input on a slack call running in the Chrome browser as well, so basically everyone on the call would hear my voice over the background music.
I came across a very good tutorial that sort-of solved my problem but also introduced another one :)
By following the steps described here:

$ pacmd load-module module-null-sink sink_name=virt_mix
$ pacmd update-sink-proplist virt_mix device.description=VirtualMixer
$ pacmd load-module module-loopback sink=virt_mix

and then in pavucontrol app, under Playback, assigning VirtualMixer to the Google Chrome tab which was generating music, and under Recording assigning Monitor of Null Output to the Chrome as well, I basically accomplished what I had in mind. If I play the music and start talking on the micrpohone during the slack call, everyone hears my voice with the music in the background.
However, the problem is now - that I can't hear the music coming from the tab, so the whole point kind of loses the point. Setting Playback to VirtualMixer turns off the music for me, is there a way around this so I can hear it as well ?


text:
Q: Custom options by default Is it possible for each product to make two of custom options so that when you create a product in the tab of Custom option, these two options are the default.
Thanks

A: Not out of the box.

*

*Either you implement some JS to do this when you open the create product area

*or you add an observer for catalog_product_before_save which adds the custom option later. You can base it on an attribute or add another field (with a second observer) to the product form with no linked attribute to define this option should be added or not, so you don't have to delete it after saving

A: If you are not looking for free solution you can use following extension,
   http://www.mageworx.com/advanced-product-options-magento-extension.html
It provide you to create custom option template that can be assigned to all or selected products.


text:
Q: How to knockout a pdf file using iText7 C# src_pdf
I wan to knockout a pdf file using iText7 C# with:
var sourceFPath = @"to_knockout.pdf";
var targetFPath = @"out.pdf";
using (PdfDocument origPdf = new PdfDocument(new PdfReader(sourceFPath)))
{
    var currPage = origPdf.GetPage(1);
    using (PdfDocument destPdf = new PdfDocument(new PdfWriter(targetFPath)))
    {
        var page = destPdf.AddNewPage(new PageSize(100 * 72f / 25.4f, 125 * 72f / 25.4f));
        PdfCanvas canvas = new PdfCanvas(page);
        PdfFormXObject xObject2 = currPage.CopyAsFormXObject(destPdf);
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.SetKnockout(true);
        transGroup.SetIsolated(false);
        xObject2.SetGroup(transGroup);
        canvas.AddXObjectAt(xObject2, 0,0);
    }
}

This doesn't work.
wanted_pdf


text:
Q: How to set page numbers within left/right margins using classicthesis and geometry I'm using classicthesis and the geometry package for the margins. The page numbers are top outer, but should be within ALL of the margins. I've successfully got the page numbers within the top and bottom margins,
What I've tried that doesn't work:
1) I've tried includeall and includeemp in the geometry package -- it shifts the page number successfully but then reduces the text width as if making room for margin notes
2) I tried \marginparwidth 0pt, \marginparsep 0pt to remove space for margin notes and that didn't work either.
Here's a working example:
\documentclass[twoside,openright,titlepage,numbers=noenddot,headinclude, footinclude=true,cleardoublepage=empty,dottedtoc, BCOR=5mm,paper=a4,fontsize=11pt, fontsize=11pt, ngerman,american, ]{scrreprt}

\input{classicthesis-config}
\usepackage[inner=3.5cm, outer=2.5cm, top=2.5cm, bottom=2.5cm,includefoot,includehead]{geometry}

\deftripstyle{pgnumbottomcenter}{}{}{}{}{\pagemark}{}
\pagestyle{pgnumbottomcenter}
\deftripstyle{pgnumtopouter}{}{}{\pagemark}{}{}{}
\renewcommand{\chapterpagestyle}{pgnumtopouter}

\begin{document}

\pagestyle{scrheadings}

\pagenumbering{roman}

\section{hello}
\newpage
\section{what's up}

\end{document}

And a screenshot of the second page, showing what I'd like to achieve:

A: \documentclass[twoside,openright,titlepage,numbers=noenddot,headinclude, footinclude=true,cleardoublepage=empty,dottedtoc, BCOR=5mm,paper=a4,fontsize=11pt, fontsize=11pt, ngerman,american, ]{scrreprt}

\input{classicthesis-config}
\usepackage[inner=3.5cm, outer=2.5cm, top=2.5cm, bottom=2.5cm,includefoot,includehead]{geometry}

\lehead{\mbox{{\small\pagemark\kern2em}\headmark\hfil}}
\rohead{\mbox{\hfil{\headmark}{\small\kern2em\pagemark}}}

\begin{document}

\pagenumbering{roman}

\section{hello}
xxxxxxxxxx\hfill xxxxxxxx

\newpage
\section{what's up}
xxxxxxxxxx\hfill xxxxxxxx

\newpage
\pagenumbering{arabic}
\section{Hello}
xxxxxxxxxx\hfill xxxxxxxx

\newpage
\noindent xxxxxxxxxx\hfill xxxxxxxx

\end{document}


text:
Q: Vue Router 2 use hashbang instead of hash I am about to use prerender.io on my website which is a SPA built on Vue and Laravel. By default vue-router seems to use hash (domain.com/#/page) instead of hashbang (domain.com/#!/page) which seems to be what prerender is requiring.
I have googled a ton on "Change hash to hashbang vue-router 2" and stuff, but I can not find any help. Does anyone here know where I can tweak vue-router to use hashbang?
Thanks in advance!


text:
Q: java.lang.IllegalStateException: failed to analyze: java.lang.reflect.InvocationTargetException Android studio gave error

java.lang.IllegalStateException: failed to analyze:
java.lang.reflect.InvocationTargetException

it was working fine on Windows os and
i imported code to macos and i can't run it anymore
tried changing kotlin version
tried changing gradle version
nothing seems to work
My Gradle file
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
}

android {
    compileSdk 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.nrp.sbja"
        minSdk 21
        targetSdk 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

        dataBinding {
            enabled = true
        }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    def room_version = "2.2.6"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
    implementation "androidx.room:room-rxjava2:$room_version"
    implementation "androidx.room:room-guava:$room_version"
    testImplementation "androidx.room:room-testing:$room_version"

    kapt 'com.android.databinding:compiler:3.1.4'

    kapt "androidx.room:room-compiler:$room_version"

}

apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
'''

project level gradle-
'''
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.3.21'
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        // classpath "com.android.tools.build:gradle:7.1.0-alpha02"
        classpath "com.android.tools.build:gradle:4.1.3"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'

        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.0'
        classpath 'com.google.gms:google-services:4.3.8'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        /* maven {
            url 'http://dl.bintray.com/amulyakhare/maven'
        }*/
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: Please update Moshi to 1.13.0: https://github.com/square/moshi/issues/1368
(Answer from: https://youtrack.jetbrains.com/issue/KT-50768)

A: I had same problem too,
first commented :
id 'kotlin-kapt'

then all its apply to and sync project after that clean and remove comments the


text:
Q: Finding initial speed and angle to hit a known position (parabolic trajectory) I am currently doing a small turn based cannon game with XNA 4.0. The game is very simple: the player chooses the speed and angle at which he desires to shoot his rocket in order to hit another player. There is also a randomly generated wind vector that affects the X trajectory of the rocket. I would like to add an AI so that the player could play against the computer in a single player mode.
The way I would like to implement the AI is very simple: find the velocity and angle that would make the rocket hit the player directly, and add a random modifier to those fields so that the AI doesn't hit another player each time.
This is the code I use in order to update the position and speed of the rocket:
            Vector2 gravity = new Vector2(0, (float)400);   // 400 is the sweet spot value that i have found works best for the gravity
            Vector2 totalAcceleration = gravity + _terrain.WindDirection;
            float deltaT = (float)gameTime.ElapsedGameTime.TotalSeconds; // Elapsed time since last update() call

            foreach (Rocket rocket in _instantiatedRocketList)
            {
                rocket.RocketSpeed += Vector2.Multiply(gravity, deltaT);  // Only changes the Y component
                rocket.RocketSpeed += Vector2.Multiply(_terrain.WindDirection, deltaT);   // Only changes the X component
                rocket.RocketPosition += Vector2.Multiply(rocket.RocketSpeed, deltaT) + Vector2.Multiply(totalAcceleration, (float)0.5) * deltaT * deltaT;

                // We update the angle of the rocket accordingly
                rocket.RocketAngle = (float)Math.Atan2(rocket.RocketSpeed.X, -rocket.RocketSpeed.Y);

                rocket.CreateSmokeParticles(3);
            }

I know that the basic equations to find the final X and Y coordinates are:

*

*X = V0 * cos(theta) * totalFlightTime

*Y = V0 * sin(theta) * totalFlightTime - 0.5 * g * totalFlightTime^2
where X and Y are the coordinates of the player I want to hit, V0 the initial speed, theta the angle at witch the rocket is shot, totalFlightTime is, like the name says, the total flight time of the rocket until it reaches (X, Y) and g is the gravity (400 in my game).
Questions:
What I am having problems with, is knowing where to add the wind in those formulas (is it just adding "+ windDirection * totalFlightTime" in the X = equation?), and also what to do with those equations in order to do what I want to do (finding the initial speed and theta angle) since there are 3 variables (V0, theta and totalFlightTime) and only 2 equations?
Thanks for your time.

A: You can do this as follows:
Assuming there is no specific limit to V0 (i.e. the robot can fire the rocket at any desired speed) and using the substitutions
T=totalFlightTime
Vx=V0cos(theta)
Vy=V0sin(theta)

Choose an arbitrary value for Vx. Now your first equation simplifies to
X=VxT  so T=X/Vx

to solve for T. Now substitute the value of T into the second equation and solve for Vy
Y=VyT + gT^2/2  so Vy = (Y - gT^2/2)/T

Finally you can now solve for V0 and theta
V0 = Sqrt(Vx^2 + Vy^2)  and Theta = aTan(Vy/Vx)

Note that your initial choice of Vx will determine the trajectory the missile will take - if Vx is large then T will be small and the trajectory will be almost a straight line (like a bullet fired at a nearby target) - if Vx is small then T will be large and the trajectory will be an arc (like a mortar round's path). You dis start with three variables (V0, totalFlightTime, and theta) but they are dependent variables so choosing any one (or in this case Vx) plus the two equations solves for the other two. You could also pre-determine flight time and solve for Vx, Vy, theta and V0, or predetermine theta (although this would be tricky as some theta wouldn't provide a real solution.


text:
Q: How to Ensure Unique Records In an SQLite database, I have a table called people that has columns prefix, first_name, middle_name, last_name, and suffix. The full name is the concatenation of all of these columns, separated by spaces. Is there any way to create a constraint that forces the full name to be unique (i.e., no two rows can have the same five values for prefix, first_name, middle_name, last_name, and suffix)?

A: Yes.  Just put a unique constraint/index on all five columns:
create unique index unq_people_name on people(prefix, first_name, middle_name, last_name, suffix);

You do realize, of course, that some people do have identical names.


text:
Q: How to pass state from parent to child in react? How do I pass a state attribute from parent to child? In the following implementation, the Dropdown component has a state "isActive" and I want to access it in the Button component to attach propper styling to it. The Dropdown has to generic as it is supposed to take different sorts of buttons.
<Dropdown items="...">
  <Button active ="false" />
</Dropdown>

Dropdwon.js
...

    constructor(props){
        super(props)
        this.state = {
         isActive: true,
        }
    }

    render (){
        return (

 this.showMenu(event)}>
                    {this.props.children} /* want to set active prop for the child button here */

        );
}

...

A: Aside from the answer I linked, there might be another way of achieving this that I didn't see mentioned.
You can send a function as a children element of your dropdown which will take isActive as a variable :
<Dropdown items="...">
  {isActive => <Button active={isActive} />}
</Dropdown>

Then, is the render function, simply call the function and send your state value as a parameter :
render(){
    return (

 this.showMenu(event)}>
            {this.props.children(this.state.isActive)}

    );
}

A: You have two possibilities:

*

*Lift your Dropdown state and keep it in its parent component;

*Use useContext hook;

The first approach would be better, but it may not be good for your application (I cannot know that). Let me make an example for both cases.

This is an example where I've lifted the isActive state to the parent component.
const ParentComponent = () => {
    const [isActive, setIsActive] = useState(false);

    handleIsActiveChange = (newValue) => {
        setIsActive(newValue);
    }

    <Dropdown isActive={isActive} setIsActive={handleIsActiveChange}>
        <Button isActive={isActive} />
    </Dropdown>
}

const Dropdown = props => {
    // You can use `props.isActive` to know whether the dropdown is active or not.
    // You can use `props.handleIsActiveChange` to update the `isActive` state.
}

const Button = props => {
    // You can use `props.isActive` to know whether the dropdown is active or not.
}

Instead, this exploits the useContext API:
const dropdownContext = React.createContext(null);

const Dropdown = props => {
    const [isActive, setIsActive] = useState(false);

    return (
        <dropdownContext.Provider value={{ isActive }}>
            {props.children}
        </dropdownContext.Provider>
    );
}

const Button = props => {
    const dropdownCtx = React.useContext(dropdownContext);

    // You can use `dropdownCtx.isActive` to know whether the dropdown is active or not.
}

A: <Dropdown >
  <Button isActive={this.state.isActive} />
</Dropdown>

In your button get it with this.props.isActive


text:
Q: Which Icon Editing Software would you recommend for creating icons for apps I once bought a single license of Microangelo for creating icons which served me well in the past, but now I'm helping run up a new Virtual Machine base for our dev team to use and would like to include a decent free icon editor in there.
I'd prefer something that fully supports creating icons for Windows Vista.
For all those of you thinking "Don't let a developer design graphics!" just pretend I said "for our UI Design Team" instead of "Dev Team", lol. ;)

A: That's simple, because it's free, powerfull and supports Vista Icons (256x256): IcoFx
On this site you can find a tool for (animated) cursors, too: AniFx
If you want to pay, I'd suggest a more powerful ones: Axialis Iconworkshop

A: I would use Inkscape to design the icons, and then render them scaled down and convert them  to the final format with Gimp
The benefit of this is you can design the icon once, and produce it in many target sizes effortlessly.
That's what the OpenSource world are doing these days :)  ( We even have Native SVG Icons now )

A: I would recommend Paint.NET, or The GIMP.  They're not specifically for icons, but will do the job and much more.  Also, both free.
EDIT: Paint.NET requires plugin (free).

A: For icons, there's IcoFX.


text:
Q: How to get inheritance to work for parameters inside a closure? protocol Proto {
  associatedtype Entity: NSManagedObject
}

extension Proto {
    func subscribe(completionBlock: @escaping (Entity) -> ())  {
       var helper = Helper()
       helper.subscribe(completionBlock)    //error out
    }
}

class Helper {
   func subscribe(completionBlock: @escaping (NSManagedObject) -> ()){}
}

Even though entity will always be of type NSManagedObject, but it won't let me pass that closure into another function that accepts NSmanagedObject. How to fix?
I can make the code work by doing this:
helper.subscribe(completionBlock as! (NSManagedObject) -> ())

But why do I need to force cast when Entity is of type NSManagedObject? Also are there any risk of it crashing at runtime if I cast like this? Is there ever a scenario if the cast will fail?

A: Okay, so after some back and forth I believe the question amounts to this. Given this function:
func foo(v:UIView, f:(UIView)->Void) {
    f(v)
}

...why is it illegal to pass a (UIButton)->Void into foo as its f parameter?
Well, let's imagine that we could do that. (This is called a reductio ad absurdum proof.) Then we could write this:
let bar : ((UIButton)->Void) = {button in print(button.currentTitle)}
foo(v:UISwitch(), f:bar)

And what would happen? foo would pass a UISwitch into f - legally, because f is typed as taking a UIView, and a UISwitch is indeed a UIView. And we would crash, because a UIView has no currentTitle property.
Do you see the problem? Characterising a function as a (UIButton)->Void gives that function the right, in the eyes of the compiler, to talk to the parameter as if it were a UIButton. But on the outside, f is typed as a function that takes a UIView. So it is legal to pass any UIView into it. Therefore the compiler needs to know that the function being held by f does not think that its parameter is a UIButton, lest it do that very sort of thing.
So the compiler very rightly stops you right at the door and doesn't let you pass bar into foo in the first place. The rule is that function types are contravariant on their parameter types, for passing.


text:
Q: Norm of orthogonal projection operator $P$, if $\text{Im}\,P\subseteq\text{Im}\,Q$, with $Q$ also an orthogonal projection In Rynne & Youngson: Linear Functional Analysis, there is an exercise stated as

Let $\mathcal{H}$ be a complex Hilbert space and let $P$, $Q\in B(\mathcal{H})$ be orthogonal projections. Show that the following are equivalent:

*

*$\text{Im}\,P\subseteq \text{Im}\,Q$;

*$QP=P$;

*$PQ=P$;

*$||Px||\le||Qx||$ for all $x\in\mathcal{H}$;

*$P\le Q$.

The set $B(\mathcal{H})=B(\mathcal{H},\mathcal{H})$ denotes the set of all bounded linear operators from $\mathcal{H}$ to $\mathcal{H}$, and $T\in B(\mathcal{H})$ is an orthogonal projection if $T$ is self-adjoint, and $T^2=T$. The set $\text{Im}\,T$ is the range of $T$, the subspace $T(\mathcal{H})\subseteq\mathcal{H}$.
Now, in order to attempt to show that $3.\Rightarrow 4.$, I use the fact that $P=PQ$, and find that
\begin{align}
||Px||=||PQx||\le||P|| \,||Qx||.
\end{align}
The solution (given in the back of the book) now states that $||P||=1$, so $||Px||\le||Qx||$ follows. But as far as I can tell, the only thing we know about the norm of a general orthogonal projection is that $||P||\le1$, but not necessarily $||P||=1$. And if $||P||\not=1$, then $||Px||\le||Qx||$ doesn't necessarily hold.
Any help in pointing out what I'm missing here would be greatly appreciated!

A: Let $V=P(\mathcal{H})$. If $P$ is not the zero projection, there is $x\in V$, $x\ne 0$. Then $Px=x$, implying $\|P\|=1$.

A: If $P = 0$, then there's nothing to prove, so assume that $P \neq 0$. Then you can find (how?) $0 \neq y \in \mathcal{H}$ such that $Py = y$. What would this imply for the value of $\|P\|$?


text:
Q: Can't log in/out using Devise and JQuery Mobile Im currently trying to adapt my Views to a Mobile Plattform. But i am experiencing some Problems.
I've been using the Gem Mobylette for Mobile-Device-Detection.
Devise for Authentication and JQuery-Mobile for the layout.
Everything works fine so far, but logging in and out makes some Problems.
This is my new.erb.mobile:

Sign in

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

<%= f.label :email %>

  <%= f.email_field :email, autofocus: true %>

<%= f.label :password %>

    <%= f.password_field :password, autocomplete: "off" %>

  <% if devise_mapping.rememberable? -%>

<%= f.check_box :remember_me %> <%= f.label :remember_me %>

  <% end -%>

<%= f.submit "Sign in" %>

<% end %>

If the user trys to submit from a mobile plattform the following error occurs:
ActionView::MissingTemplate (Missing template devise/sessions/create, devise/create, application/create with {:locale=>[:en], :formats=>[:mobile], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in:

i found a fix for this. I simple have to create a create.mobile.erb and redirect manually inside this file like so:

but logging out still does not work.
This is how the generated Code looks like :
Logout

But if i try to logout there is just a spinning circle that appears and no redirection happens.
I really don't know what i am doing wrong and i didn't found a solution for this Problem on the Internet so maybe someone here knows what i am doing wrong.

A: This is a wild shot but lets try it, in your form element add this attribute:
data-ajax="false"

This is because jQuery Mobile by default uses it own way of handling form submition, read more about it here. Basically this attribute will prevent jQuery Mobile from hijacking this feature.

A: Okay, after struggeling with this issue a day or so i finally found the right solution including no manual redirects or ajax stuff:

*

*Add a new Initializer to your config/initializers and add the following lines to it :
ActionController::Responder.class_eval do
  alias :to_mobile :to_html
end

*Register the Mobile Type inside the devise configuration block :
config.navigational_formats = [:"/", "/", :html, :mobile]


text:
Q: volume of a triangular pyramid A point $M_0$ with positive coordinates $(x_0, y_0, z_0)$, $x_0>0$, $y_0>0$, $z_0>0$ is given.
A plane is drawn through this point.
Find the minimal possible volume of a triangular pyramid whose
faces lie in the plane mentioned above and in the coordinate planes.

A: Let the plane equation $\frac{x}{a}+\frac{y}{b}+\frac{z}{c}=1$ then the volume is $\frac{1}{6}abc$, so (Lagrangian multipliers, $abc\to\min$).
$$\begin{cases}
bc-\lambda\frac{x_0}{a^2}=0\\
ac-\lambda\frac{y_0}{b^2}=0\\
ab-\lambda\frac{y_0}{c^2}=0\\
\frac{x_0}{a}+\frac{y_0}{b}+\frac{z_0}{c}=1
\end{cases}$$
$$\begin{cases}
abc-\lambda\frac{x_0}{a}=0\\
abc-\lambda\frac{y_0}{b}=0\\
abc-\lambda\frac{y_0}{c}=0\\
\frac{x_0}{a}+\frac{y_0}{b}+\frac{z_0}{c}=1
\end{cases}$$
Since $\frac{x_0}{a}=\frac{y_0}{b}=\frac{y_0}{c}$ so these three $=\frac{1}{3}$,
$a=3x_0$, $b=3y_0$, $c=3z_0$, $V=\frac{27}{6}x_0y_0z_0$.


text:
Q: I want to show loading during working in react The current code displays only "Done !!!" after end work (about 3 seconds).
I want to display "Done !!!" after "Loading..." first.
import React, { useState, useEffect, useCallback } from "react";

const App = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [workingResult, setWorkingResult] = useState<string>();

    const runWorking = useCallback(async () => {
        // working.... (during about 3 seconds)
        var start = new Date().getTime();
        while (new Date().getTime() < start + 3000);

        return "Done !!!";
    }, []);

    const setWorking = useCallback(async () => {
        setLoading(true);
        setWorkingResult(await runWorking());
        setLoading(false);
    }, [runWorking]);

    useEffect(() => {
        setWorking();
    }, [setWorking]);

    return <div>{loading ? "Loading..." : workingResult}</div>;
};

export default App;

A: you need to use promise constructor while will not work because async function require function that return promise so  try this:
  const runWorking = () =>
    new Promise(resolve =>
      setTimeout(() => {
        resolve("done");
      }, 3000)
    );

const setWorking = async () => {
    setLoading(true);
    setWorkingResult(await runWorking());
    setLoading(false);
}

here a full working example

A: thank you.
i solved that.
const runWorking = () => new Promise(resolve => setTimeout(() => {
    let returnValue:any = [];
    // working...
    resolve(returnValue); }, 1)
 );

    const setWorking = async () => {
setLoading(true);
setWorkingResult(await runWorking());
setLoading(false);
}


text:
Q: Zend Framework Router dynamic routes I bumped into a problem and I can't seem to find a good solution to make it work. I have to make some dynamic routes into a Zend Framework project. I'll explain shortly what my problem is:
I need to have dynamic custom routes that "extend" the default route (module/controller/action/params). The project I'm working for has several partners and the routes have to work with those.
To store the partners I've made a static class and it looks like this.
<?php
    class App_Partner
    {
        static public $partners = array(
            array(
                'name' => 'partner1',
                'picture' => 'partner1.jpg'
            ),
            array(
                'name' => 'partner2',
                'picture' => 'partner2.jpg'
            ),
            array(
                'name' => 'partner3',
                'picture' => 'partner3.jpg'
            )
        );
        static public function routePartners() {
            $partners = array();

            foreach(self::$partners as $partner) {
                array_push($partners, strtolower($partner['name']));
            }
            $regex = '(' . implode('|', $partners) . ')';

            return $regex;
        }
    }

So App_Partner::routePartners() return me a string like (partner1|partner2|partner3) which I use to create the right routes. My goal is to have the custom routes for each partner for every route I have set in the Bootstrap. So if I have a route add-product.html set I want it to work for each partner as partner1/add-product.html, partner2/add-product.html and partner3/add-product.html.
Also, partner1/, partner2/, partner3 should route to default/index/index.
In fact, I made this thing to work using routes like the one below.
<?php
$routeProposal = new Zend_Controller_Router_Route_Regex(
    App_Partner::routePartners() . '?/?proposals.html',
    array(
        'module' => 'default',
        'controller' => 'proposal',
        'action' => 'index',
        'page' => 1
    ),
    array( 1 => 'partner'),
    "%s/proposals.html"
);
$router->addRoute('proposal', $routeProposal);

The problem
The above route works fine if I use a partner in the request URI, but if I don't, I get double slashes like public//proposals.html because of the reverse route set in the route above to be "%s/proposals.html". I can't seem to find a way to avoid this reverse route because I build my urls using the url view helper and if the reverse route isn't set I get an exception stating this.
I also need the routes to work without a partner set, which will be the default way (add-product.html, proposals.html etc).

A: From your description, it seems like you're looking for a zend router chain, where your partner is an optional chain.
Here's a similar question, but using a hostname route : Zend Framework: get subdomain parameter from route. I adapted it to solve your problem, just put the following in your Bootstrap.php to initialize the routing :
protected function _initRoute()
{
    $this->bootstrap('FrontController');
    $router = $this->getResource('FrontController')->getRouter();

    // Default route
    $router->removeDefaultRoutes();
    $defaultRoute = new Zend_Controller_Router_Route(
                    ':controller/:action/*',
                    array(
                        'module' => 'default',
                        'controller' => 'index',
                        'action' => 'index',
                    )
    );
    $router->addRoute('default', $defaultRoute);

    $partnerRoute = new Zend_Controller_Router_Route(
        ':partner',
        array('partner' => 'none'),
        array('partner' => '^(partner1|partner2|partner3)$')
    );
    $router->addRoute('partner', $partnerRoute->chain($defaultRoute));
}

Change as you see fit. In your controllers you will only get a value for the partner parameter if it was actually specified AND valid (you will get a routing error if the partner doesn't exist)...

A: I use a similar process to detech lang, in my route (but with a ini file).
You can use a default value for you partners parameter to make the route working without partner, and add a ? to your regex.
But actually, I don't know how to avoid the double //...
Hope that helps.
EDIT: For your information, here is a simplified version of my route with language:
routes.lang.type = "Zend_Controller_Router_Route"
routes.lang.route = "lang/:language/*"
routes.lang.reqs.language = "^(en|fr|nl|de)?$"
routes.lang.defaults.language = none
routes.lang.defaults.module = default
routes.lang.defaults.controller = index
routes.lang.defaults.action = language


text:
Q: Difference between Get-Help and /? in powershell When I use the command icacls /? it shows me information about the command icacls but when I use the command Get-Help icacls it says command not found. This implies there is some difference between /? and Get-Help in powershell. But what is the difference?

A: As mentioned by Scepticalist and Jereon Mostert in comments, it turns out that Get-Help is used to get information about Powershell cmdlet where as, /? is used to get information about commands which are basically external executable files.


text:
Q: Help formulating a cubic easing equation I have the following piece of code
int steps = 10;
for (int i = 0; i <= steps; i++) {
    float t = i / float(steps);
    console.log( "t  " + t );
}

That out puts numbers in a linear fashion like this { 0, 0.1, 0.2, ..., 0.9, 1.0 } I would like apply the cubic (in  or out) easing equation so the output numbers increase or decrease gradually

UPDATE
Not sure if my implementation if correct but I am getting curve as expected
float b = 0;
float c = 1;
float d = 1;
for (int i = 0; i <= steps; i++) {
    float t = i / float(steps);

    t /= d;

    float e = c * t * t * t + b;

    console.log( "e  " + e );
    //console.log( "t  " + t );
}

A: EasIn Cubic Function
/**
 * @param {Number} t The current time
 * @param {Number} b The start value
 * @param {Number} c The change in value
 * @param {Number} d The duration time
 */
function easeInCubic(t, b, c, d) {
   t /= d;
   return c*t*t*t + b;
}

EaseOut Cubic Function
/**
 * @see {easeInCubic}
 */
function easeOutCubic(t, b, c, d) {
   t /= d;
   t--;
   return c*(t*t*t + 1) + b;
}

Here you can find othere useful equations: http://www.gizma.com/easing/#cub1
Put this code in a while, as you've don before and you will have your output cubic decreasing numbers.

A: You can use code from jQuery Easing plugin:
    http://gsgd.co.uk/sandbox/jquery/easing/
/*
*  t: current time
*  b: begInnIng value
*  c: change In value
*  d: duration
*/

easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t + b;
    return c/2*((t-=2)*t*t + 2) + b;
}


text:
Q: Creating editText beneath drawable programmatically I have an editText: @+id/editText1 which I'd like to instantiate beneath R.drawable.sqwhite after my onClick method
My problem is the drawable isn't created via XML - and I'm not sure exactly how to get my editText1 to appear directly beneath R.drawable.sqwhite
JAVA:
public void onClickAddImage(View v) {
    addNewImageToScreen();
}

public void addNewImageToScreen() {
    int resourceId = R.drawable.sqwhite;
    addNewTextToScreen();
    int m = mImageCount % 3;

    if (m == 1)
        resourceId = R.drawable.sqdrk;

    else if (m == 2)
        resourceId = R.drawable.sqwhite;
    addNewImageToScreen(resourceId);

}

private void addNewTextToScreen() {
    // TODO Auto-generated method stub

    et.setVisibility(View.VISIBLE);
    if (isErase) {
        tx.setText(et.getText().toString());
    } else {
        tx.setText("");
        et.setVisibility(View.GONE);
    }
    isErase = !isErase;
}

public void addNewImageToScreen(int resourceId) {
    if (mLastNewCell != null)
        mLastNewCell.setVisibility(View.GONE);
    et.setVisibility(View.VISIBLE);
    FrameLayout imageHolder = (FrameLayout) findViewById(R.id.image_source_frame);
    if (imageHolder != null) {
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                Gravity.CENTER);
        ImageCell newView = new ImageCell(this);
        newView.setImageResource(resourceId);
        imageHolder.addView(newView, lp);
        newView.mEmpty = false;
        newView.mCellNumber = -1;
        mLastNewCell = newView;
        mImageCount++;

        // Have this activity listen to touch and click events for the view.
        newView.setOnClickListener(this);
        newView.setOnLongClickListener(this);
        newView.setOnTouchListener(this);

    }
}

XML:
<?xml version="1.0" encoding="utf-8"?>
<com.example.project.DragLayer xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:launcher="http://schemas.android.com/apk/res/com.android.launcher"
    android:id="@+id/drag_layer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:weightSum="1.0" >

            <GridView
                android:id="@+id/image_grid_view"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_weight="0.8"
                android:background="@color/grid_background"
                android:gravity="center"
                android:horizontalSpacing="2dip"
                android:numColumns="@integer/num_columns"
                android:stretchMode="columnWidth"
                android:verticalSpacing="2dip" />

            <LinearLayout
                android:id="@+id/bottom_part"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="@android:color/black"
                android:layout_centerHorizontal="true"
                android:layout_weight="0.2"
                android:orientation="horizontal"
                android:weightSum="1.0" >

                <Button
                    android:id="@+id/button_add_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:onClick="onClickAddImage"
                    android:text="Add image" />

                <com.example.project.DeleteZone
                    android:id="@+id/delete_zone_view"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_gravity="center"
                    android:src="@drawable/delete_zone" />

                <FrameLayout
                    android:id="@+id/image_source_frame"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_weight="0.5" >

                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" >

                        <EditText
                            android:id="@+id/editText1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" >

                            <requestFocus />
                        </EditText>

                        <TextView
                            android:id="@+id/textView1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                             android:layout_below="@+id/editText1"
                              android:textColor="@android:color/white"
                            android:text="" />
                    </RelativeLayout>
                </FrameLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</com.example.project.DragLayer>

SCREENSHOT:


text:
Q: Explicit termination method 'close' I am using volley and after a couple of hits below exception is thrown.
The application is crashing showing following error.

E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
                                                                     java.lang.Throwable: Explicit termination method 'close' not called
                                                                         at dalvik.system.CloseGuard.open(CloseGuard.java:180)
                                                                         at java.net.AbstractPlainSocketImpl.create(AbstractPlainSocketImpl.java:103)
                                                                         at java.net.Socket.createImpl(Socket.java:464)
                                                                         at java.net.Socket.getImpl(Socket.java:530)
                                                                         at java.net.Socket.setSoSndTimeout(Socket.java:1194)
                                                                         at com.android.okhttp.Connection.setTimeouts(Connection.java:508)
                                                                         at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:400)
                                                                         at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
                                                                         at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:356)
                                                                         at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:273)
                                                                         at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:474)
                                                                         at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:422)
                                                                         at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
                                                                         at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
                                                                         at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java)
                                                                         at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:99)
                                                                         at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
                                                                         at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
                                                                         at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)

Below is the code snippet
public void processServiceResponseEntity(final String serviceName, final String serviceRequest,
            final int method, final String key, final Map<String, String> queryParams, final Map<String, String> header,
            final Map<String, String> pathVariables)
            throws YaggerCustomException
    {

        DatabaseHandler databaseHandler = new DatabaseHandler(context);
        final User user = databaseHandler.getUserDetails();
        String url = serviceName;

        Log.d(TAG, "URL: " + url);

        StringRequest strReq = new StringRequest(method,
                url, new Response.Listener<String>() {

                    @Override
                    public void onResponse(String res) {
                        Log.d(TAG, "Response: " + res);
                        if (currentObject != null) {
                            currentObject.postYaggerServiceCall(res, key);
                        }
                        // setResponse(res);

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error: " + error.getMessage());
                        showSnackbar(serviceName, serviceRequest, method, key, queryParams, header, pathVariables);
                        currentObject.postYaggerServiceCall(null, key);
                        setError(error.getMessage());
                       // ACRA.getErrorReporter().handleException(new YaggerCustomException(error.getMessage()));
                    }
                }) {

            @Override
            public String getBodyContentType()
            {
                if (getContentType() == null)
                {
                    return "application/json";
                }
                else
                {
                    return getContentType();
                }

            }

            @Override
            public byte[] getBody() throws AuthFailureError
            {
                byte[] byt = null;
                this.getParams();
                if (serviceRequest != null)
                    byt = serviceRequest.getBytes();
                return byt;
            }

            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError
            {
                Map<String, String> oauthHeader = new HashMap<>();
                oauthHeader.put("Content-Type", "application/json");
                if(user != null)
                    oauthHeader.put("Authorization", user.getTokenType() + " " + user.getToken());
                if (header != null && !header.isEmpty()) {
                    oauthHeader.putAll(header);
                }
                oauthHeader.putAll(super.getHeaders());
                return oauthHeader;
            }

            @Override
            public Map<String, String> getParams()
                    throws AuthFailureError
            {
                if (queryParams == null)
                    return Collections.<String, String>emptyMap();
                return queryParams;
            }

            @Override
            public RetryPolicy getRetryPolicy()
            {
                return new DefaultRetryPolicy(AppConfig.DEFAULT_TIMEOUT_MS, AppConfig.DEFAULT_MAX_RETRIES,
                        AppConfig.DEFAULT_BACKOFF_MULT);
            }
        };

        // Adding request to request queue
        strReq.setRetryPolicy(new DefaultRetryPolicy(AppConfig.DEFAULT_TIMEOUT_MS, AppConfig.DEFAULT_MAX_RETRIES,
                AppConfig.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(strReq, key == null ? serviceName : key);

    }

Thanks


text:
Q: count, sorting numbers and filter in tibble Given below data,I try to find the most frequently used bike's data records.I need to find the bikeid that has the highest number of records. Then using the highest bikeid, filter my data for only that bikeid and display only those records.
 library(lubridate)
 library(tidyverse)
 nycbikes18 <- read_csv("data/2018-citibike-tripdata.csv",
 locale = locale(tz = "America/New_York"))
 nycbikes18
 #> # A tibble: 333,687 x 15
 #>    tripduration starttime           stoptime
 #>           <dbl> <dttm>              <dttm>
 #>  1          932 2018-01-01 02:06:17 2018-01-01 02:21:50
 #>  2          550 2018-01-01 12:06:18 2018-01-01 12:15:28
 #>  3          510 2018-01-01 12:06:56 2018-01-01 12:15:27
 #>  4          354 2018-01-01 14:53:10 2018-01-01 14:59:05
 #>  5          250 2018-01-01 17:34:30 2018-01-01 17:38:40
 #>  6          613 2018-01-01 22:05:05 2018-01-01 22:15:19
 #>  7          290 2018-01-02 12:13:51 2018-01-02 12:18:42
 #>  8          381 2018-01-02 12:50:03 2018-01-02 12:56:24
 #>  9          318 2018-01-02 13:55:58 2018-01-02 14:01:16
 #> 10         1852 2018-01-02 16:55:29 2018-01-02 17:26:22
 #> # … with 333,677 more rows, and 12 more variables:
 #> #   start_station_id <dbl>, start_station_name <chr>,
 #> #   start_station_latitude <dbl>, start_station_longitude <dbl>,
 #> #   end_station_id <dbl>, end_station_name <chr>,
 #> #   end_station_latitude <dbl>, end_station_longitude <dbl>,
 #> #   bikeid <dbl>, usertype <chr>, birth_year <dbl>, gender <dbl>

my code and output
top_bike_trips <- nycbikes18%>%group_by(bikeid) %>% filter( tripduration==max(tripduration))
top_bike_trips

# A tibble: 900 x 15
# Groups:   bikeid [900]
tripduration starttime           stoptime
      <dbl> <dttm>              <dttm>
1         2111 2018-01-11 15:33:24 2018-01-11 16:08:36
2        21262 2018-01-12 13:00:26 2018-01-12 18:54:48
3         1804 2018-01-12 17:10:56 2018-01-12 17:41:01
4         2717 2018-01-30 18:03:31 2018-01-30 18:48:49
5         1892 2018-01-19 18:40:06 2018-01-19 19:11:39
6          563 2018-01-31 09:20:28 2018-01-31 09:29:51
7        50545 2018-01-02 17:58:07 2018-01-03 08:00:32
8          475 2018-01-03 18:03:39 2018-01-03 18:11:34
9        30997 2018-01-19 08:43:44 2018-01-19 17:20:22
10        80854 2018-01-19 18:50:43 2018-01-20 17:18:18
# ... with 890 more rows, and 12 more variables:

expected output
top_bike_trips
#> # A tibble: 825 x 15
#>    tripduration starttime           stoptime
#>           <dbl> <dttm>              <dttm>
#>  1          520 2018-01-03 13:06:21 2018-01-03 13:15:01
#>  2          232 2018-01-03 17:01:21 2018-01-03 17:05:14
#>  3          315 2018-01-14 15:08:14 2018-01-14 15:13:30
#>  4          266 2018-01-23 14:57:30 2018-01-23 15:01:57
#>  5          162 2018-01-24 17:01:10 2018-01-24 17:03:53
#>  6          150 2018-01-25 18:26:58 2018-01-25 18:29:29
#>  7          272 2018-01-03 08:49:11 2018-01-03 08:53:43
#>  8          315 2018-01-20 14:06:28 2018-01-20 14:11:44
#>  9          322 2018-01-02 15:43:42 2018-01-02 15:49:04
#> 10          251 2018-01-10 17:48:03 2018-01-10 17:52:14
#> # … with 815 more rows, and 12 more variables:
#> #   start_station_id <dbl>, start_station_name <chr>,
#> #   start_station_latitude <dbl>, start_station_longitude <dbl>,
#> #   end_station_id <dbl>, end_station_name <chr>,
#> #   end_station_latitude <dbl>, end_station_longitude <dbl>,
#> #   bikeid <dbl>, usertype <chr>, birth_year <dbl>, gender <dbl>

I'm not sure how to get the expected output 825,maybe use count() ?

A: library(dplyr)
mtcars %>%
  filter(cyl == names(which.max(table(cyl))))
#                      mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
# Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
# Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
# Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
# Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
# Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
# Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
# Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
# AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
# Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
# Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
# Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
# Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8

From this, it might be enough to try
nycbikes18 %>%
  filter(bikeid == names(which.max(table(bikeid))))

Alternatively, since we have to guess about the data. If instead you mean the bikeid with the highest tripdurations number, then perhaps
nycbikes18 %>%
  filter(bikeid == bikeid[which.max(tripdurations)])

A: Base R solution:
# Calculate the modal bike id: modal_bike_id => character scalar
modal_bike_id <- tail(names(sort(table(bikeid))), 1)

# Subset data set to only contain modal bike id's records: data.frame => stdout(console)
nycbikes18[
  with(
    nycbikes18,
    bikeid == modal_bike_id
  ),
]

A: Using mtcars data as example :
library(dplyr)

mtcars %>%
  count(cyl) %>%
  slice_max(n = 1, n) %>%
  select(cyl) %>%
  left_join(mtcars, by = 'cyl')

#   cyl  mpg  disp  hp drat    wt  qsec vs am gear carb
#1    8 18.7 360.0 175 3.15 3.440 17.02  0  0    3    2
#2    8 14.3 360.0 245 3.21 3.570 15.84  0  0    3    4
#3    8 16.4 275.8 180 3.07 4.070 17.40  0  0    3    3
#4    8 17.3 275.8 180 3.07 3.730 17.60  0  0    3    3
#5    8 15.2 275.8 180 3.07 3.780 18.00  0  0    3    3
#6    8 10.4 472.0 205 2.93 5.250 17.98  0  0    3    4
#7    8 10.4 460.0 215 3.00 5.424 17.82  0  0    3    4
#8    8 14.7 440.0 230 3.23 5.345 17.42  0  0    3    4
#9    8 15.5 318.0 150 2.76 3.520 16.87  0  0    3    2
#10   8 15.2 304.0 150 3.15 3.435 17.30  0  0    3    2
#11   8 13.3 350.0 245 3.73 3.840 15.41  0  0    3    4
#12   8 19.2 400.0 175 3.08 3.845 17.05  0  0    3    2
#13   8 15.8 351.0 264 4.22 3.170 14.50  0  1    5    4
#14   8 15.0 301.0 335 3.54 3.570 14.60  0  1    5    8


text:
Q: Break or User input to separate copying of files? I've looked around and haven't come across anything similar so..
I have several directories of files that need to be unzipped/moved to a specific folder(the same folder). The files that need to be unzipped are in this structure:
  -ZippedfolderA
    -unzipped filename: abc.txt
  -ZippedfolderB
    -unzipped filename: abc.txt
  -ZippedfolderC
    -unzipped filename: abc.txt
  etc..

So you see after they're unzipped they all have the same name, and thus overwrite one another.
Quick notes:

*

*No, I can't change the name after it's unzipped. These files get pulled into DB, and need to stay the name they're given.

*The difference between folders A,B,C is dates. Each folder has different dates. A=yesterday, B=daybeforeyesterday, C=3 days ago, etc.

So far my code unzips, compares dates, and moves the files to where they need to be. But I need to somehow pause the code after each dated folder so the DB can pull in the files in between unzipping. Otherwise the last to get unzipped overwrites the other two. I'm trying to figure out how/where I can use something like Input or Break to wait until the first set is pulled in, then continue to unzip the second folder, wait, then pull in the other folders and so on down the line. Here's my code up to this point...
def files_to_folders(filename):
    if f.endswith(".TXT"):
        ff = f[1:7]
        if ff == yesterday.strftime("%y%m%d"):
           print(ff, f)
           fnew = f[12:] # Change back to [13:]
           os.rename(os.path.join(root,f), os.path.join(root, fnew))
           shutil.copy(os.path.join(root,fnew), wescorpex)
           shutil.copy(os.path.join(root, "DLY"), wescorpex)
        elif ff == daybefore1.strftime("%y%m%d"):
            print(ff, f)
            fnew = f[12:] # Change back to [13:]
            os.rename(os.path.join(root,f), os.path.join(root, fnew))
            shutil.copy(os.path.join(root,fnew), wescorpex)
            shutil.copy(os.path.join(root, "DLY"), wescorpex)
        elif ff == daybefore2.strftime("%y%m%d"):
            print(ff, f)
            fnew = f[11:]# Change back to [13:]
            os.rename(os.path.join(root,f), os.path.join(root, fnew))
            shutil.copy(os.path.join(root,fnew), wescorpex)
            shutil.copy(os.path.join(root, "DLY"), wescorpex)
        elif ff == daybefore3.strftime("%y%m%d"):
            print(ff, f)
            fnew = f[10:]# Change back to [13:]
            os.rename(os.path.join(root,f), os.path.join(root, fnew))
            shutil.copy(os.path.join(root,fnew), wescorpex)
            shutil.copy(os.path.join(root, "DLY"), wescorpex)
    return filename

targets = [(folder, create(folder, destpath)) for folder in destdir]
#Create directories based on ZIP folder
try:
    for dirname, full_path in targets:
        for filename in srcfiles:
            if dirname == filename[0:7]:
                shutil.copy(filename, full_path)

        # Extract all files within folders to new directory root
        for root, dirs, files in os.walk(os.path.join(rootpath, full_path)):
            for files in fnmatch.filter(files,pattern):
                zipfile.ZipFile(os.path.join(root,files)).extractall(root)
                os.remove(os.path.join(root,files))
        #Rename extracted files in new direct root with end of filename
        walkpath = os.path.join(rootpath,full_path)
        for root, dirs, files in os.walk(walkpath):
            for f in files:
                files_to_folders(f)

except(IOError):
    print("there was an error.")
    time.sleep(2)


text:
Q: Which form between solar panel and wind turbines requires less cost in servicing? I found that the average life of a solar panel is about 25 years and that of the the wind turbine is also somewhat close to 25 years.
But the wind turbines require alternator in order to generate electricity which is showing an average life span of 7 years.
One factor does add up to the cost of solar panels which is the cost to clean the panels in order to keep it dust free.
Even after adding that cost to the solar panels it appears that it must be requiring very  less cost in servicing.
I did some research but no proper information was available that after a 7 year time span of the alternator the whole alternator need to be changed or just some parts of it as this will vary the cost of servicing prominently.
If anyone in this community have any information regarding the above mentioned field please share it.

A: Brushless alternators most commonly fail due to 1 of the 6 diodes in the 3 phase bridge from overtemp that may be improved with better cooling.  The peak currents are much higher than the RMS . The battery ESR can be <5 mOhms so the diodes need to be lower at rated current.


text:
Q: I'm having trouble updating state with a select menu As the title suggests, I'm having issues updating state with a select menu. I'm not sure if the trouble is coming from the fact I'm trying to update it from multiple sources?
getSurvivorPerks fetches an array of objects. On page load a random 4 are selected to be displayed, and these four are randomized on each handlesubmit. I would like to be able to manually select the individual perks for perk1, 2, etc with a select menu. As of now, this just results in perk1 getting set to Null. The data does display appropriately in the select menu.
export default function SurvivorRandomizer() {
  const [survivorPerk1, setSurvivorPerk1] = useState({});
  const [survivorPerk2, setSurvivorPerk2] = useState({});
  const [survivorPerk3, setSurvivorPerk3] = useState({});
  const [survivorPerk4, setSurvivorPerk4] = useState({});
  const [perkList, setPerkList] = useState([]);
  const [loading, setLoading] = useState(true);
  const { user } = useUser();

  useEffect(() => {
    const fetchData = async () => {
      const data = await getSurvivorPerks();
      let perks = randomPerks(data);
      setPerkList(data);
      setSurvivorPerk1(perks[0]);
      setSurvivorPerk2(perks[1]);
      setSurvivorPerk3(perks[2]);
      setSurvivorPerk4(perks[3]);
      setLoading(false);
    };
    fetchData();
  }, []);

  const handleSubmit = () => {
    let perks = randomPerks(perkList);
    setSurvivorPerk1(perks[0]);
    setSurvivorPerk2(perks[1]);
    setSurvivorPerk3(perks[2]);
    setSurvivorPerk4(perks[3]);
  };

 if (loading) return
loading...
;
  return (
    <>

          <PerkCard {...survivorPerk1} />
          <select value={perkList.perk} onChange={(e) => setSurvivorPerk1(e.target.value)}>
            <option>Select...</option>
            {perkList.map((perk) => (
              <option key={uuid()} value={perk}>
                {perk.name}
              </option>
            ))}
          </select>

A: The issue here (had my blinders on) is that the value cannot be an object.
 const handlePerkSelect = async (perk, id) => {
    let setPerk = await getSurvivorPerkById(id);
    perk(setPerk);
  };

-------------
          <select onChange={(e) => handlePerkSelect(setSurvivorPerk1, e.target.value)}>
            <option>Select...</option>
            {perkList.map((perk) => (
              <option key={uuid()} value={perk.ID}>
                {perk.name}
              </option>
            ))}
          </select>

This was my solution. There's definitely a better way to do it that doesn't involve making more fetch requests, and I'll likely refactor, but on the off chance this helps someone, I figured I'd share what the issue was.