Code Bug Fix: React Native: How value is past by onChangeText in this TextInput code?

Original Source Link

This code is suppose to be a generic handler function for multiple TextInputs, to be invoked by onChangeText :

  getHandler= key =>{
    return val =>{
      this.setState({[key]: val})
    }
  }

.

<TextInput
          onChangeText={this.getHandler('phone')}
        />

I don’t understand where the val got its value, it is not defined explicitly anywhere, if val is passed by onChangeText and doesn’t have to be explicitly named in the handler’s props then why the following doesn’t work without the arrow notation:

  getHandler = key => {
      this.setState({ [key]: val });
  };

also the code doesn’t work without a return, why?

//this code also doesn't work without return  
getHandler = key => {
      val => {
      this.setState({ [key]: val });
    };
  };

Entire code here

Assume that you have written the TextInput. You got your onChangeText function. You would call it like

// To avoid cases when no handler function is set
if(typeof onChangeText === "function"){ 
   onChangeText(this.value);
}

In your first case you are passing return value of your getHandler function which is this function (Unnamed):

val =>{
      this.setState({[key]: val})
    }

In other cases you are not returning a function. So when the TextInput‘s onChangeText is not a function it simply ignores whatever you passed into it.

  • It’s handling event binding using the higher-order function, it’s one of the basic ways of writing function.
Tagged : /

Code Bug Fix: R: Create a matrix with randomly generated number of cells with values in each rows and randomly generated values of each of those cells

Original Source Link

For example, to simulate 10,000 values where claims have a compound
Poisson distribution with parameter 1000 and a gamma claims distribution with 750 and 0.25.

Something like :

sapply(rpois(10000,1000), function(n){sum(rgamma(n,shape = 750, scale = 0.25))})

I am not sure about your parametrisation of the gamma r.v.s there is also the rate parameter if you need.

Although I’m not sure, this looks a lot like what a teacher would ask πŸ˜‰

Edit : a list of individual claims can be obtained by :

sapply(rpois(10000,1000), function(n){rgamma(n,shape = 750, scale = 0.25)})

Tagged :

Code Bug Fix: I receive null when I access to another fragment from onDismiss – Android

Original Source Link

I want to refresh the main fragment. So I am using an onDismiss method in DialogFragment to use inside there the method refreshFragment to refresh the mainfragment. I don’t know If this is the best option… But I receive a null object.

This is mi method onDismiss:

 @Override
    public void onDismiss(DialogInterface frag) {
        super.onDismiss(frag);
        this.getChildFragmentManager();
        FragmentManager fm = getActivity().getSupportFragmentManager();
        MyTeamFragment fragm = (MyTeamFragment)fm.findFragmentById(R.id.fragment_my_team_id); //HERE IS NULL
        fragm.refreshFragmnet();

    }

And this is the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.karate_manager.Fragments.MyTeamFragment.refreshFragmnet()' on a null object reference
        at com.example.karate_manager.DialogFragment.AcceptBidRivalDialogFragment.onDismiss(AcceptBidRivalDialogFragment.java:153)

I think you should introduction your fragment class to xml code

android:name="your fragment class"

Tagged : / /

Code Bug Fix: dump ended with error (get phase) => Error: failed to parse json (message: β€œUnexpected token in JSON at position 16832074”)

Original Source Link

I am trying to take elastic search backup with below command but it ended with some error. Could someone please help me here.

elasticdump --limit=10000 --input="http://localhost:9200/source" --output=backup.json --type=data

Logs:

Thu, 14 May 2020 09:52:53 GMT | got 10000 objects from source elasticsearch (offset: 100000)
Thu, 14 May 2020 09:52:53 GMT | sent 10000 objects to destination file, wrote 10000
Thu, 14 May 2020 09:52:56 GMT | Error Emitted => failed to parse json (message: "Unexpected token  in JSON at position 16832074") - source: "{"_scroll_id":"DnF1ZXJ5VGhlbkZldGNoDAAAAAAAVqFRFlRvTWtOeHhaU3dLU1RORzFQUXFQNWcAAAAAAFawQhZNdU5vLUNTdFJSZWRKSTJNdTI5UnBnAAAAAABXrVAWX01ZVUotdUtRNFM4ZWVPVm92bEZ5QQAAAAAAVpvGFjJoMkxzRmNrUWlTQ2pORkZvNGl3WlEAAAAAAFe09xZERXVYQjhqWVQ3U21RWEpHTHV5ZmRnAAAAAABXwyQWVC1vVWhBZjBTdmVwcFVQMnZBSi00QQAAAAAAV7T5FkRFdVhCOGpZVDdTbVFYSkdMdXlmZGcAAAAAAFeshhZEUnFtOTRic1N2MnZ3Z3VNMUNaVktBAAAAAABXtPgWREV1WEI4allUN1NtUVhKR0x1eWZkZwAAAAAAV6KdFktNTU4wTXRGUUtXQ3BNaDR0Mm1PVUEAAAAAAFetURZfTVlVSi11S1E0UzhlZU9Wb3ZsRnlBAAAAAABXwyUWVC1vVWhBZjBTdmVwcFVQMnZBSi00QQ==","took":2114,"timed_out":false,"terminated_early":true,"_shards":{"total":12,"successful":12,"skipped":0,"failed":0},"hits":{"total":86322523,"max_score":1.0,"hits":[{"_index":"nuxeo_live","_type":"doc","_id":"228dedbd-d33c-4e82-84bb-aa43a11d8dd2","_score":1.0,"_source":{"ecm:repository":"default","ecm:uuid":"228dedbd-d33c-4e82-84bb-aa43a11d8dd2","ecm:name":"cc246ac56678c587ebcd7e9b69b48d88_293108.pdf","ecm:title":"cc246ac56678c587ebcd7e9b69b48d88_293108.pdf","ecm:path":"/default-domain/workspaces/fundinfo-lu/cc246ac56678c587ebcd7e9b69b48d88_293108.pdf","ecm:[email protected]":"default-domain","ecm:[email protected]":"workspaces","ecm:[email protected]":"fundinfo-lu","ecm:[email protected]":"cc246ac56678c587ebcd7e9b69b48d88_293108.pdf","ecm:[email protected]":5,"ecm:primaryType":"Idms_file","ecm:parentId":"4976999c-6d57-46c8-9439-f8963b4cdc8e","ecm:currentLifeCycleState":"project","ecm:isCheckedIn":false,"ecm:isProxy":false,"ecm:isVersion":false,"ecm:isLatestVersion":false,"ecm:isLatestMajorVersion":false,"ecm:mixinType":["Versionable","NXTag","Publishable","Commentable","HasRelatedText"],"ecm:tag":[],"ecm:changeToken":"0-0","ecm:acl":["fdsg_tu_fundinfo_importer","IDMS","Administrator","members"],"uid:major_version":0,"uid:minor_version":0,"ifs:ID_CONTENT":["974"],"ifs:ID_TYPE_DOCUMENT":11,"ifs:ID_DELIVERY":894,"ifs:DATETIME_CONTENT":"2019-05-31T00:00:00.000Z","ifs:IS_ARCHIVED":false,"ifs:ID_REGION":["149"],"ifs:ID_LANGUAGE":["2"],"ifs:ID_INSTRUMENT":["36442530"],"ifs:ISIN":["LU0533600846"],"file:content":{"name":"cc246ac56678c587ebcd7e9b69b48d88_293108.pdf","mime-type":"application/pdf","digest":"cc246ac56678c587ebcd7e9b69b48d88","length":293108},"common:icon":"/icons/pdf.png","dc:creator":"fdsg_tu_fundinfo_importer","dc:modified":"2019-06-19T17:09:24.250Z","dc:lastContributor":"fdsg_tu_fundinfo_importer","dc:created":"2019-06-19T17:09:24.250Z","dc:title":"cc246ac56678c587ebcd7e9b69b48d88_293108.pdf","dc:contributors":["fdsg_tu_fundinfo_importer"]}},{"_index":"nuxeo_live","_type":"doc","_id":"72e37cf7-2ea2-4ced-893c-5e9ffab9416b","_score":1.0,"_source":{"ecm:repository":"default","ecm:uuid":"72e37cf7-2ea2-4ced-893c-5e9ffab9416b","ecm:name":"cba31ad08563f2f272ce5ccad1501113_249443.pdf","ecm:title":"cba31ad08563f2f272ce5ccad1501113_249443.pdf","ecm:path":"/default-domain/workspaces/fundinfo-lu/cba31ad08563f2f272ce5ccad1501113_249443.pdf","ecm:[email protected]":"default-domain","ecm:[email protected]":"workspaces","ecm:[email protected]":"fundinfo-lu","ecm:[email protected]":"cba31ad08563f2f272ce5ccad1501113_249443.pdf","ecm:[email protected]":5,"ecm:primaryType":"Idms_file","ecm:parentId":"4976999c-6d57-46c8-9439-f8963b4cdc8e","ecm:currentLifeCycleState":"project","ecm:isCheckedIn":false,"ecm:isProxy":false,"ecm:isVersion":false,"ecm:isLatestVersion":false,"ecm:isLatestMajorVersion":false,"ecm:mixinType":["Versionable","NXTag","Publishable","Commentable","HasRelatedText"],"ecm:tag":[],"ecm:changeToken":"0-0","ecm:acl":["fdsg_tu_fundinfo_importer","IDMS","Administrator","members"],"uid:major_version":0,"uid:minor_version":0,"ifs:ID_CONTENT":["974"],"ifs:ID_TYPE_DOCUMENT":11,"ifs:ID_DELIVERY":894,"ifs:DATETIME_CONTENT":"2019-05-31T00:00:00.000Z","ifs:IS_ARCHIVED":false,"ifs:ID_REGION":["149"],"ifs:ID_LANGUAGE":["1"],"ifs:ID_INSTRUMENT":["41780814"],"ifs:ISIN":["LU0637347302"],"file:content":{"name":"cba31ad08563f2f272ce5ccad1501113_249443.pdf","mime-type":"application/pdf","digest":"cba31ad08563f2f272ce5ccad1501113","length":249443},"common:icon":"/icons/pdf.png","dc:creator":"fdsg_tu_fundinfo_importer","dc:modified":"2019-06-19T17:09:20.725Z","dc:lastContributor":"fdsg_tu_fundinfo_importer","dc:created":"2019-06-19T17:09:20.725Z","dc:title":"cba31ad08563f2f272ce5ccad1501113_249443.pdf","dc:contributors":["fdsg_tu_fundinfo_importer"]}},{"_index":"nuxeo_live","_type":"doc","_id":"9a9f7a78-1b32-48a8-a77d-1bc2d6edceae","_score":1.0,"_source":{"ecm:repository":"default","ecm:uuid":"9a9f7a78-1b32-48a8-a

Tagged :

Code Bug Fix: Eslint rule to ban some import paths

Original Source Link

I have following structure.

.
└── src
    └── pages
        └── Chat
            β”œβ”€β”€ Chat.tsx
            β”œβ”€β”€ index.ts
            └── components
                β”œβ”€β”€ index.ts
                └── AppsBar
                    β”œβ”€β”€ AppsBar.tsx
                    β”œβ”€β”€ AppTile.ts
                    └── index.ts

From Chat.tsx I want to import AppsBar component (each has named exports, and index with export all).

Do it by hand it would look that: import { AppsBar } from './components';. But VSC or WebStorm creates automatic path: import { AppsBar } from '~/pages/Chat/components/AppsBar'; (I have aliases).

Question:
Is there any ESLint rule to force using /. notation when I want access to file from the same level?

You could try adding "typescript.preferences.importModuleSpecifier": "relative" in vscodes user settings or otherwise set baseUrl in your tsconfig.json (see module-resolution)

Tagged : / /

Code Bug Fix: How to filter a svelte store using a dynamic filter

Original Source Link

I have a derived store which has to filter an entries object using HTML selects for the filter. Now I introduced an extra filter store (observable) to force the derived store callback to run when the filter store changes.

But is it possible to trigger the callback in the derived store below without the filter store when the filter changes? Do I need this extra store here?
The below code works fine. I’am curious.

import { writable, derived } from 'svelte/store';
import { entries } from './../stores/entries.js';

export const filter = writable({
  // to update filter use: $filter.kind = ... 
  // or: filter.update(o => Object.assign(o, {kind: .., batchId: ...}));
  batchId: 'all',
  kind: 'all',
});

let list, total;

export const view = derived(
  [filter, entries], 
  ([$filter, $entries], set) => {

    total = 0;

    if ($entries) {
      // filter by HTML selects: kind, batchId
      list = Object.keys($entries.map).sort().reduce((a, key) => {
        if ((['all', $entries.map[key].description.kind].includes($filter.kind))
          && (['all', $entries.map[key].parentId].includes($filter.batchId))) {
            total += $entries.map[key].grossValue;
            a.push($entries.map[key]);
        };
        return a;  
      }, []);
      set({list, total});
    };

    return () => {
      set(null);
    };
  }, null
);

You could extract the logic from the derived store into a function / object you control yourself, with an API to manually trigger an update… But that would not be a good idea. That would break some encapsulation for no benefit and all.

Your writable + derived solution is, IMO, the most straightforward and elegant solution. It explicitly outlines data dependencies, and cleanly separate concerns, with no arcane code involved. It also provides Svelte what it needs to monitor changes, and manages subscriptions automatically for you, with the finest granularity.

This is a nice pattern, and it is perfectly appropriated for your use case. I would keep it like this.

Tagged : / /

Code Bug Fix: react vertical carousel with react-image-gallery

Original Source Link

I am using react-image-gallery

how to auto-play images vertically?

the problem is to view them vertically like below

vertical slider

import ImageGallery from 'react-image-gallery';
function HomePage(props) {
   const imagesFromFolder = [
    {
        original: 'https://picsum.photos/id/1015/1000/600/',
        thumbnail: 'https://picsum.photos/id/1015/250/150/',
    }];

 return (

    <div className="home-page"> <div className="sidenav" style={{ width: "450px" }}>
            <ImageGallery disableThumbnailScroll={false} showThumbnails={true} showNav={false}
                isRTL={false} autoPlay={true} thumbnailPosition="left"
                stopPropagation={true}
                items={imagesFromFolder} />
/>
 </div >
);
 }
export default HomePage;

update
Is there is a way to do that?

Tagged : /

Code Bug Fix: How to create a rating calculator

Original Source Link

I am trying to create this Rating Calculator and has a feature to see how many 5-stars do I need to meet a certain target. Basically it looks like below, and actual will be posted.

Number of Feedbacks: 10

5-star: 9 (5*9 = 45)

4-star: 0

3-star: 0

2-star: 0

1-star: 1 (1*1 = 1)

Total Rating: 4.6 (Basically it’s 9*(5-stars = 45) and 1*(1-star = 1) / 10 feedbacks)

Target Rating: 4.8

The answer is, I need 6(*5-star = 30) feedbacks to get the 4.8 (45 + 1 + 30 = 76 / 16 feedbacks = 4.75 (Roundup to 4.8)

I’m not sure how I will be able to do the computation on how it will add the 5-star that I need to the existing number of feedbacks that I have to reach the 4.8 ratings. Also, this is not the common average computation. Can I kindly ask someone to help me? Thank you so much!

Btw, I’m using Microsoft Visual Studio (VB)

Tagged : /

Code Bug Fix: Abscence of Learning rate and number of iterations in sklearn Linear Regression

Original Source Link

I have found out that neither Linear, nor Lasso, nor Ridge in scikit-learn use learning rate (what we call alpha) or number of iterations.

I want to know how exactly do they implement Linear Regression under the hood without learning rate, considering that it’s at the heart of Gradient Descent?

These methods work by minimizing an objective function, but here’s come the difference between a Linear Regression and a Regularized Regression. On the one hand, Linear Regression fits the optimal coefficients by minimizing the residual sum of squares between the real values and the predicted values, that is, it is minimizing and objective function like ||y – X||^2, where y is your real value and X the predicted one.
For more details of the procedure see Understanding OLS estimation.

On the other hand, Lasso and Ridge Regression incorporates another term that accounts for this coefficients, for example, in Ridge Regression the function to minimize is
||y – X||^2 + alpha * ||w||^2, where alpha is what is normally known as learning rate and w represents the fitted coefficients, see this answer for more details on how the regularization shrinks the coefficients values.

Tagged : / / /

Code Bug Fix: Bad assembly reference in my .net project [RESOLVED]

Original Source Link

I’m reinstalling a server after it has crashed and I’m struggling with an old .net web-service. I’m not sure to have the latest version of source code (it doesn’t compile on my computer in localhost) but I have the version ready to use on production environnement.

The problem is that application doesn’t come with Microsoft.ReportViewer library inside its bin folder (I suppose it was referencing a library on GAC or something)… Anymway, after copied the 4 libraries I need into the bin folder, I have the following error :

Could not load file or assembly ‘Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference.*

How Could I change the assembly version without re-publishing my project from source code ? Can I ? I was thinking about web.config file… but I don’t understand how to do it…

This is my config file

<?xml version="1.0" encoding="utf-8"?>
<!--
  Pour plus d’informations sur la configuration de votre application ASP.NET, rendez-vous sur 
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <appSettings></appSettings>
  <system.web>
    <compilation targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE="Web" /optionInfer+" />
    </compilers>
  </system.codedom>
  <connectionStrings>
    <add name="bdd" connectionString="Data Source=****;Initial Catalog=event_db;User Id=***;Trusted_connection=true; Application Name=WSFacture" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

The assembly I want to use (the file I have copied in /bin/ folder) is 11.0.2802.16

Thanks a lot for helping me : code, source, tutorial… anything will help me πŸ™‚

EDIT : Thanks, this is what i’ve done in my config file :

<dependentAssembly>
        <assemblyIdentity name="Microsoft.ReportViewer.WebForms" publicKeyToken="b03f5f7f11d50a3a" />
        <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.2802.16" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ReportViewer.DataVisualization" publicKeyToken="b03f5f7f11d50a3a" />
        <bindingRedirect oldVersion="10.0.0.0" newVersion="10.0.40219.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ReportViewer.ProcessingObjectModel" publicKeyToken="b03f5f7f11d50a3a" />
        <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.2802.16" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ReportViewer.Common" publicKeyToken="b03f5f7f11d50a3a" />
        <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.2802.16" />
</dependentAssembly>

The error have evoluated… how can I see the dependancies ?

Could not load file or assembly ‘Microsoft.ReportViewer.WebForms, Version=11.0.2802.16, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference.*

EDIT 2 : Following the below comments, I’ve tried several syntaxe but no one is working… So I’ve made a different approach :
– I’ve downloaded the ViewReport (v10) package from NuGet into a .net solution > compile > get the generated .dll > copied them into my bin + remove the bindingRedirect sections from my config file … and it’s working !

Thanks a lot for your help ! It puts me in the right direction πŸ™‚

Tagged : / /