text:
Q: What is a better way to replace IDs in an array with their value counterpart? I have the following array that includes id:
[Key1] => 1
[Key2] => 2, 3

I would like to replace these ids by their respective name from this second array:
[0] => Array
    (
        [ID] => 1
        [Name] => Name1
    )

[1] => Array
    (
        [ID] => 2
        [Name] => Name2
    )

[2] => Array
    (
        [ID] => 3
        [Name] => Name3

The desired output:
[Key1] => Name1
[Key2] => Name2, Name3

I have the following code which works but I know this is not the right way. If anybody could let me know what would be a better way to achieve this, it would be greatly appreciated.
What my code looks like:
$var1 = explode(", ", $array1["Key1"]); // No need to explode in this example but "Key1" sometimes includes more than 1 ID
$var2 = explode(", ", $array1["Key2"]);

$array1["Key1"] = $var1 ; // This row is for the new array generated from "explode" to be a sub-array
$array1["Key2"] = $var2 ; // Same

for ($i = 0; $i < 83; $i++){
    if($array1["Key1"][0] == $array2[$i]["ID"]){
        $array1["Key1"][0] = $array2[$i]["Name"];
    }
    if($array1["Key1"][1] == $array2[$i]["ID"]){
        $array1["Key1"][1] = $array2[$i]["Name"];
    }
// (etc)
    if($array1["Key2"][0] == $array2[$i]["ID"]){
        $array1["Key2"][0] = $array2[$i]["Name"];
    }
    if($array1["Key2"][1] == $array2[$i]["ID"]){
        $array1["Key2"][1] = $array2[$i]["Name"];
    }
// (etc)

}

$var1 = implode(", ", $array1["Key1"]);
$var2 = implode(", ", $array1["Key2"]);

$array1["Key1"] = $var1 ;
$array1["Key2"] = $var2 ;

A: You need to nest some loops. Here is a sample that should work:
//Processing Array
$arrayOne = array(
    "Key1"  =>  "1",
    "Key2"  =>  "2, 3");

//Lookup Array
$arrayTwo = array(
    array(
        "ID" => "1",
        "Name" => "Name1"),
    array(
        "ID" => "2",
        "Name" => "Name2"),
    array(
        "ID" => "3",
        "Name" => "Name3"));

var_dump($arrayOne);

//Loop through all values in our original array
foreach($arrayOne as &$arrValue) {
    //Split the value in the original array into another temporary array
    //if there are multiple values.
    $valueArray = explode(", ", $arrValue);
    $outputArray = array();
    foreach($valueArray as &$myValue) {
        //Now do a lookup to replace each value
        foreach($arrayTwo as &$lookupValue) {
            //Find a match
            if($myValue==$lookupValue["ID"]) {
                $myValue = $lookupValue["Name"];
                //We found the value we want, so let's break out of this loop
                break;
            }
        }
        //Append the value
        array_push($outputArray, $myValue);
    }
    //Convert back to string
    $arrValue= implode(", ", $outputArray);
}

var_dump($arrayOne);

There are improvements you could possibly make to this code if your incoming data was always sorted, but I imagine that is just the case for your sample above.

A: I have an approach to do this. You can make a try if you wish see here at:- https://eval.in/839823. I am using array_column to map the key=>value pair and then simple used foreach.
<?php
$main = ['Key1' => 1,'Key2' => '2, 3'];

$match = [
    [
        'ID' => 1,
        'Name' => 'Name1'
    ],

    [
        'ID' => 2,
        'Name' => 'Name2'
    ],
    [
        'ID' => 3,
        'Name' => 'Name3'
    ]
 ];

$final_array=[];
$mapped = array_column($match, 'Name', 'ID');
foreach($main as $k=>$v){
   $r = explode(',',$v);
    if(count($r)>1){
       $final_array[$k] = $mapped[$r[0]]. ", ".$mapped[intval($r[1])];
    }else{
       $final_array[$k] = $mapped[$r[0]];
    }
}
print '
';
//print_r($mapped);
print_r($final_array);
print '
';

Output :
Array
(
    [Key1] => Name1
    [Key2] => Name2,Name3
)

Edit : As per comment of Josh Maag,

My code will only work if he only has a maximum of 2 values in Key2.
  If Key3 contains "4,5,6" this code will leave the 6 untouched.

<?php

 $main = ['Key1' => 1,'Key2' => '2,3','Key3' => '4,5,6'];

    $match = [
        [
            'ID' => 1,
            'Name' => 'Name1'
        ],

        [
            'ID' => 2,
            'Name' => 'Name2'
        ],
        [
            'ID' => 3,
            'Name' => 'Name3'
        ],
        [
            'ID' => 4,
            'Name' => 'Name4'
        ],
        [
            'ID' => 5,
            'Name' => 'Name5'
        ],
        [
            'ID' => 6,
            'Name' => 'Name6'
        ]
     ];

    $final_array=[];
    $mapped = array_column($match, 'Name', 'ID');
    foreach($main as $k=>$v){
       $r = explode(',',$v);
        if(count($r)>1){
           $final_array[$k] =  implode(',',array_map(function($key) use ($mapped){ return $mapped[$key]; }, array_values($r)));
        }else{
           $final_array[$k] = $mapped[$r[0]];
        }
    }

    print '
';
    print_r($mapped);
    print_r($final_array);
    print '
';
    ?>

See demo See here https://eval.in/839939

A: Just extract the ID and Name into a single-dimension and use it as search and replace parameters. We need to modify the IDs to search for and turn them into a pattern /\b$v\b/ where \b is a word boundary, so that 1 won't replace the 1 in 164 for example:
$replace = array_column($array2, 'Name', 'ID');
$search  = array_map(function($v) { return "/\b$v\b/"; }, array_keys($replace));

$array1 = preg_replace($search, $replace, $array1);

A: The core function that should be used for this task is preg_replace_callback().  Why?  Because it is uniquely qualified to handle this operation in a single function call.  It seems a tragedy to not use php functions for their designed purpose.
Beyond preg_replace_callback(), only array_column() is needed to prepare the $array2 data as a simple lookup array.
Code: (Demo)
$array1=["Key1"=>"1","Key2"=>"22, 4, 123"];
$array2=[["ID"=>"1","Name"=>"Name1"],["ID"=>"22","Name"=>"Name22"],["ID"=>"123","Name"=>"Name123"]];
$lookup=array_column($array2,'Name','ID');  // generate array: keys = IDs, vals = Names

$result=preg_replace_callback('/\d+/',function($m)use($lookup){return isset($lookup[$m[0]])?$lookup[$m[0]]:"*{$m[0]}*";},$array1);
var_export($result);

Output:
array (
  'Key1' => 'Name1',
  'Key2' => 'Name22, **4**, Name123',
)

There is no need to run any preparations (excluding $lookup) using additional loops or function calls.
This pattern will match all full ID numbers from each element in $array1 and process them individual.  Each numeric match is sent to the anonymous callback function to receive its customized replacement string -- delivered by the $lookup data.
As an additional consideration, I have included an asterisk-wrapped replacement when an ID is not found in $lookup.


text:
Q: ImportError: No module named build_lib I'm trying to run the pip install command in this way: pip install pyverdict --upgrade, but I get the following error: ImportError: No module named build_lib. How can I resolve this?
More detailed error:
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting pyverdict
  Using cached https://files.pythonhosted.org/packages/81/be/c7f5803f599fa74b26ac9b2be385f19f14ce573540371f1f2c1c59a51a80/pyverdict-0.1.3.1.tar.gz
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-hBPHyv/pyverdict/setup.py", line 21, in <module>
        from build_lib import build_and_copy
    ImportError: No module named build_lib
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-hBPHyv/pyverdict/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bi Publisher empty page when using tables in PDF output RTF template defines a table that has a header row and and a single content row.
The content row has a Field that contains a for loop like this to populate the rows based on a XML data file:
<?for-each:row_MYDATA?>
...
...
<?end for-each?>

The issue happens when the table grows past the end of the page and overflows to the next page. The next page is as expected and contains the extra data just fine, but a page before the table beginning gets inserted and it's empty.
A text diagram of the issue if the table exceeds a single page:
| Empty page  |

| Table begins|

| Table cont. |

Expected:
| Table begins|

| Table cont. |


text:
Q: Help to understand the validness of relation in a model In my assignment I have the following question:
Find a model $M$ with domain $\{a, b, c, d\}$ so that:

$M\vDash R(\overline{a},\overline{b})\land R(\overline{b},\overline{a})\land\neg Q(\overline{d})$
$M\vDash\forall x(P(x)\to Q(x)),$
$M\vDash\forall x(R(x,x)\to P(x))$,
$M\vDash\forall x\exists y (R(x,y))$

where $R^M$ is a transitive relation.
What I struggle to understand here is how the negation of $Q$ can be true with the input $\overline{d}$, however later it is expected that for all $x$, if $P(x)$ is true, it implies that $Q(x)$ too shall be true (according to the truth table for implication).
How I interpret this is that $x$ can be everything in the domain, so either $a, b, c\text{ or }d$, but since the NEGATION of $Q$ with  $\overline{d}$ as input is true, isn't there a contradiction here?
How is the negation (of this relation $Q$) meant to be understood here?

A: There is no contradiction. The idea is that $P$ must be false for $d$.
Consider the following interpretation in the domain $\{a,b,c,d\}$:
\begin{align}
R^M &= \{(a,b), (b,a), (a,a), (b,b), (c,c), (d,c)\} \\
P^M &= \{a,b,c\} \\
Q^M &= \{a,b,c\} \\
\end{align}
It is immediate to prove that $R^M$ is transitive and that the structure $M$ (where each $x \in \{a,b,c,d\}$ is the interpretation of the constant $\overline{x}$) satisfies the four axioms.


text:
Q: Pandas raises error index contains duplicate entries, can not reshape Trying to append data to the dataframe but error raises

index contains duplicate entries

I want data in csv file basically they show me error in these line:
df = df.pivot(index=['v1','v2','v3'], columns='image', values='link').reset_index().fillna('')

Code:
import requests
from bs4 import BeautifulSoup
import pandas as pd
baseurl='https://twillmkt.com'
headers ={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}
r =requests.get('https://twillmkt.com/collections/denim')
soup=BeautifulSoup(r.content, 'html.parser')
tra = soup.find_all('div',class_='ProductItem__Wrapper')
productlinks=[]
for links in tra:
    for link in links.find_all('a',href=True)[:1]:
        comp=baseurl+link['href']
        productlinks.append(comp)
data=[]
u=[]
k=[]
w=[]
n=[]
for link in productlinks:
    r =requests.get(link,headers=headers)
    soup=BeautifulSoup(r.content, 'html.parser')
    up = soup.find('div',class_='Product__SlideshowNavScroller')
    for e,pro in enumerate(up):
        t=pro.find('img').get('src')
        data.append({'image':'Image '+str(e)+' UI','link':t})
        dup = soup.find_all('div',class_='OptionSelector list-options')
        for ro in dup:
            m=[k.text.strip() for k in ro.find_all('button')]
            variant1=m[0]
            variant2=m[1]
            variant3=m[2]
            data.append({'image':'Image '+str(e)+' UI','link':t,'v1':variant1,'v2':variant2,'v3':variant3})

df = pd.DataFrame(data)
df.image=pd.Categorical(df.image,categories=df.image.unique(),ordered=True)
df = df.pivot(index=['v1','v2','v3'], columns='image', values='link').reset_index().fillna('')
df.to_csv('yt.csv')
```

A: What happens?
One reason for duplicates is you are appending information to data you may not need:
data.append({'image':'Image '+str(e)+' UI','link':t})

cause you also append:
data.append({'image':'Image '+str(e)+'UI','link':t,'v1':variant1,'v2':variant2,'v3':variant3})

But main issue is you are using index=['v1','v2','v3'] to build the index, but this is not a combination that is still unique.
How to fix?

*

*Skip this line data.append({'image':'Image '+str(e)+' UI','link':t})

*Add also the id of the product data.append({'id':t.split('=')[-1],'image':'Image '+str(e)+' UI','link':t,'v1':variant1,'v2':variant2,'v3':variant3})

*Use id to build a unique index index=['id','v1','v2','v3']
Example
import requests
from bs4 import BeautifulSoup
import pandas as pd
baseurl='https://twillmkt.com'
headers ={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}
r =requests.get('https://twillmkt.com/collections/denim')
soup=BeautifulSoup(r.content, 'html.parser')
tra = soup.find_all('div',class_='ProductItem__Wrapper')
productlinks=[]
for links in tra:
    for link in links.find_all('a',href=True)[:1]:
        comp=baseurl+link['href']
        productlinks.append(comp)

data=[]

for link in productlinks:
    r =requests.get(link,headers=headers)
    soup=BeautifulSoup(r.content, 'html.parser')
    up = soup.find('div',class_='Product__SlideshowNavScroller')
    for e,pro in enumerate(up):
        t=pro.find('img').get('src')
        dup = soup.find_all('div',class_='OptionSelector list-options')

        for ro in dup:
            m=[k.text.strip() for k in ro.find_all('button')]
            variant1=m[0]
            variant2=m[1]
            variant3=m[2]
            data.append({'id':t.split('=')[-1],'image':'Image '+str(e)+' UI','link':t,'v1':variant1,'v2':variant2,'v3':variant3})

df = pd.DataFrame(data)
df.image=pd.Categorical(df.image,categories=df.image.unique(),ordered=True)
df = df.pivot(index=['id','v1','v2','v3'], columns='image', values='link').reset_index().fillna('')
df

`


text:
Q: Tried to synchronously call function {promiseMethodWrapper} from a different thread This is the first time I'm trying the bridging of react-native and a native iOS app.
In my react-native iOS project, I've created a swift file (that created a bridging header) and in that swift file I've created a sample method to test first:
import Foundation

@objc(MyModule)
class MyModule: NSObject {

  @objc
  func testFunctionWithPromiseResolve(frame: Frame,
                                 resolver resolve: @escaping RCTPromiseResolveBlock,
                                 rejecter reject: @escaping RCTPromiseRejectBlock) {

    var resp = [String:Any]() //Init Dictionary

    resp.updateValue(frame, forKey: "frame");
    resolve(resp);

  }

  @objc
  static func requiresMainQueueSetup() -> Bool {
    return true
  }

}

In the bridging header file I have imports only:
#import "React/RCTBridgeModule.h"
#import <VisionCamera/FrameProcessorPlugin.h>. //from react-native-vision-camera
#import <VisionCamera/Frame.h> //from react-native-vision-camera

Then I created an objective-c file named MyModule.m and in it, I've added:
#import <Foundation/Foundation.h>
#import "React/RCTBridgeModule.h"

@interface
RCT_EXTERN_MODULE(MyModule, NSObject);
RCT_EXTERN_METHOD(testFunctionWithPromiseResolve:
                  (Frame *)frame
                  resolver:(RCTPromiseResolveBlock *)resolve
                  rejecter:(RCTPromiseRejectBlock *)reject);

@end

Then in react-native, I have a Home.js where I'm going to access this method.
import React from 'react';
import { Text, StyleSheet, ScrollView, NativeModules } from 'react-native';
import { Camera, useCameraDevices, useFrameProcessor } from 'react-native-vision-camera';

import 'react-native-reanimated'

function Home(props) {

    const devices = useCameraDevices();
    const device = devices.back;

    const { MyModule } = NativeModules;

    const frameProcessor = useFrameProcessor((frame) => {

        'worklet';

        let res = MyModule.testFunctionWithPromiseResolve(frame);
        console.log(res);

        // .then((res) => {
        //     console.log(res);
        // }).catch((e) => {
        //     console.log(e);
        // })

    })

//... My other code is just UI-related in which I'm calling the frameProcessor in <Camera... using its prop frameProcessor={frameProcessor} as per react-native-vision-camera documentation.

As per my understanding, we handle a Promise with then and catch as I assume this is what we'll be getting from RCTPromiseResolveBlock but that was not working so I just simply tried console.log(res); and it prints undefined.
The error I'm getting is:
Tried to synchronously call function {promiseMethodWrapper} from a different thread.

Possible solutions are:
a) If you want to synchronously execute this method, mark it as a Worklet
b) If you want to execute this method on the JS thread, wrap it using runOnJS

reanimated::REAIOSErrorHandler::raiseSpec()
    REAIOSErrorHandler.mm:18
reanimated::ErrorHandler::raise()::'lambda'()::operator()()
decltype(static_cast<reanimated::ErrorHandler::raise()::'lambda'()&>(fp)()) std::__1::__invoke<reanimated::ErrorHandler::raise()::'lambda'()&>(reanimated::ErrorHandler::raise()::'lambda'()&)
void std::__1::__invoke_void_return_wrapper<void, true>::__call<reanimated::ErrorHandler::raise()::'lambda'()&>(reanimated::ErrorHandler::raise()::'lambda'()&)
std::__1::__function::__alloc_func<reanimated::ErrorHandler::raise()::'lambda'(), std::__1::allocator<reanimated::ErrorHandler::raise()::'lambda'()>, void ()>::operator()()
std::__1::__function::__func<reanimated::ErrorHandler::raise()::'lambda'(), std::__1::allocator<reanimated::ErrorHandler::raise()::'lambda'()>, void ()>::operator()()
std::__1::__function::__value_func<void ()>::operator()() const
std::__1::function<void ()>::operator()() const
invocation function for block in vision::VisionCameraScheduler::scheduleOnUI(std::__1::function<void ()>)
F14F0161-E0DE-3D9C-851E-AD12F95A3073
F14F0161-E0DE-3D9C-851E-AD12F95A3073
F14F0161-E0DE-3D9C-851E-AD12F95A3073
F14F0161-E0DE-3D9C-851E-AD12F95A3073
F14F0161-E0DE-3D9C-851E-AD12F95A3073
_pthread_wqthread
start_wqthread

I've worklet defined in the useFrameProcessor.
UPDATE:
I've updated the obj-c method to:
@objc(testFunctionWithPromiseResolve:resolver:rejecter:)
  func testFunctionWithPromiseResolve(_ frame: Frame,
                                 resolver resolve: @escaping RCTPromiseResolveBlock,
                                 rejecter reject: @escaping RCTPromiseRejectBlock) {...

and the in JS I did:
let module = NativeModules.MyModule;

const frameProcessor = useFrameProcessor((frame) => {

        'worklet';
        //let module = NativeModules.MyModule; //didnt work either
        console.log(module.testFunctionWithPromiseResolve(frame));

    })

But I get the same error:

A: Luckily I found the problem.

*

*Custom Frame Processor Plugins need to be completed according to the document, the document address is Creating Frame Processor Plugins, native-side customize code that you need to use the VISION_EXPORT_FRAME_PROCESSOR export definition plugin, and using RCT_EXTERN_MODULE and RCT_EXTERN_METHOD will fails.

*You need to export custom plug-in methods on the js side, the document address is Expose your Frame Processor Plugin to JS, as follows:

import type { Frame } from 'react-native-vision-camera'

/**
 * Scans QR codes.
 */
export function scanQRCodes(frame: Frame): string[] {
  'worklet'
  return __scanQRCodes(frame)
}

but now ,this will be __scanQRCodes:
module.exports = {
  plugins: [
    [
      'react-native-reanimated/plugin',
      {
        globals: ['__scanQRCodes'],
      },
    ],

you have to restart metro-bundler for changes in the babel.config.js file to take effect.
3: you must be restarted project to take effect.
My code is as follows:
I customized a Ojective-C frame Processor Plugins named MyModuleFrameProcessPlugin.m, the code is implemented as follows:
#import <VisionCamera/FrameProcessorPlugin.h>
#import <VisionCamera/Frame.h>

@interface MyModuleFrameProcessPlugin : NSObject
@end

@implementation MyModuleFrameProcessPlugin

static inline id myCustomPlugin(Frame* frame, NSArray* arguments) {
  CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(frame.buffer);
  NSLog(@"myCustomPlugin: %zu x %zu Image. Logging %lu parameters:", CVPixelBufferGetWidth(imageBuffer), CVPixelBufferGetHeight(imageBuffer), (unsigned long)arguments.count);

  for (id param in arguments) {
    NSLog(@"myCustomPlugin:   -> %@ (%@)", param == nil ? @"(nil)" : [param description], NSStringFromClass([param classForCoder]));
  }

  return @{
    @"myCustomPlugin_str": @"Test",
    @"myCustomPlugin_bool": @true,
    @"myCustomPlugin_double": @5.3,
    @"myCustomPlugin_array": @[
      @"Hello",
      @true,
      @17.38
    ]
  };
}
VISION_EXPORT_FRAME_PROCESSOR(myCustomPlugin)
@end

Create a new js plugin named ExamplePlugin.ts, the code is as follows:
/* global __myCustomPlugin */
import type { Frame } from 'react-native-vision-camera';
declare let _WORKLET: true | undefined;
export function cusPlugin(frame: Frame): string[] {
  'worklet';
  if (!_WORKLET) throw new Error('my_custom_plugin must be called from a frame processor!');

  // @ts-expect-error because this function is dynamically injected by VisionCamera
  return __myCustomPlugin(frame, 'hello my_custom_plugin!', 'parameter2', true, 42, { test: 0, second: 'test' }, ['another test', 500]);
}

The babel.config.js file is as follows:
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'react-native-reanimated/plugin',
      {
        globals: ['__myCustomPlugin']
      }
    ]
  ],
};

The plugin import code is as follows:
import {cusPlugin} from './ExamplePlugin';

The calling code is as follows:
  const frameProcessor = useFrameProcessor((frame) => {
    'worklet';
    const value = cusPlugin(frame);
    console.log(`Return Values: ${JSON.stringify(value)}`);
  }, []);
  //Use in Camera is  frameProcessor={frameProcessor}

I tested my code and it is ok, I hope it can help you.


text:
Q: Creating a haskell function that returns the sum of the squares in a list of lists of ints? I'm currently working on a small practice question for a haskell course I have. It asks the following:

Write a Haskell function called sumSquareMax which takes a list of lists of Ints as a parameter,
  finds the maximum of each sub-list and returns the sum the squares of those maximums.

I've figured out how to do it using individual lines of code in the win hugs compiler but I really want to make it a simple function with parameters. What I have so far is as follows:
sumSquaresMax :: [[Int]] -> Int
sumSquaresMax x
    let maxes = map maximum x
    let squares = map (^2) maxes
    let finalSum = sum squares

So if I were to run sumSquaresMax [[4,2,5],[6,2],[2],[-6,4,1]] first it would map the maximum of the lists: [5,6,2,4] then, it would square each of these numbers and then sum the squares leading to my answer.
How would I go about "printing" finalSum? I know this is not even close to being correct but I'm not entirely sure where to go from here. Any help is greatly appreciated!

A: You should only have one let statement in your example function if I understand your example. (While you can have multiple let statements, this isn't how you do it). let gives you the ability to define functions within a function, things that are one-off pieces of code you won't use elsewhere.
When you use let, you have to also include in to provide the actual return value of the function.
You are also missing the = sign for defining your function body.
Here's what I think you're trying to do:
sumSquaresMax :: [[Int]] -> Int
sumSquaresMax x =
    let maxes = map maximum x
        squares = map (^2) maxes
    in sum squares

A: you actually have it there - all you have to do is replacing names:
sumSquaresMax x
= sum squares
= sum (map (^2) maxes)
= sum (map (^2) (map maximum x))
= sum . map (^2) . map maximum $ x
= sum . map ((^2) . maximum) $ x

so overall:
sumSquaresMax = sum . map ((^2) . maximum)

example:
Prelude> let sumSquaresMax = sum . map ((^2) . maximum)
Prelude> sumSquaresMax [[4,2,5],[6,2],[2],[-6,4,1]]
81


text:
Q: Vue Pinia function is undefined in onMounted when unit test is ran I have a component and a Pinia store which contains a state and some actions. The code works perfectly fine in browser and in E2E (cypress) tests, but fail on unit tests. I'm using vue-testing-utils and vitest.
The store function can be called fine from the unit test when the button is clicked, but if the function is in the mounted or main script, it fails the test
src/components/UsersComponent.vue

<template>

Status: {{ usersStore.status }}

    <button @click="changeStatus()">Change Status</button>

</template>

src/stores/users.store.js
import { defineStore } from 'pinia'
import { usersAPI } from '@/gateways'

export const useUsersStore  = defineStore({
  id: 'users',
  persist: true,

  state: () => ({
    status: 'ready',
  }),

  getters: {},

  actions: {
    resetStatus() {
      this.status = 'ready'
    },
    changeStatus() {
      this.status = 'loading'
    },
  },
})

src/components/tests/UsersComponent.spec.js
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'

import UsersComponent from '@/components/UsersComponent.vue'
import { useUsersStore } from '@/stores/users.store'

const wrapper = mount(UsersComponent, {
  global: {
    plugins: [createTestingPinia({ createSpy: vi.fn() })],
  },
})
const usersStore = useUsersStore()

describe('UsersComponent', () => {
  it('store function is called', async () => {
    // arrange
    const spy = vi.spyOn(usersStore, 'resetStatus')
    const button = wrapper.find('button')

    // act
    await button.trigger('click')

    // assert
    expect(spy).toHaveBeenCalled()
  })
})

The unit tests return 2 different error. The first is a console log when the function tries to run in onMounted() and the second is what vitest returns.
stderr | unknown test
[Vue warn]: Unhandled error during execution of mounted hook
  at <UsersComponent ref="VTU_COMPONENT" >
  at <VTUROOT>

 FAIL  src/components/__tests__/UsersComponent.spec.js [ src/components/__tests__/UsersComponent.spec.js ]
TypeError: usersStore.resetStatus is not a function
 ❯ src/components/UsersComponent.vue:16:14
     16|
     17| <template>
     18|

       |  ^
     19|
Status: {{ usersStore.status }}

     20|     <button @click="changeStatus()">Change Status</button>

I know this example is a little basic and doesn't really serve a purpose, but I'm wondering how I can have store functions inside the onMounted() (or similar places) without it breaking all my unit tests.

A: Maybe this can be useful to you:
describe('UsersComponent',  () => {
  it('changeStatus function is called', async () => {
    const wrapper = mount(UsersComponent, {
      mounted: vi.fn(), // With this you mock the onMounted
      global: {
        plugins: [createTestingPinia({
          initialState: { // Initialize the state
            users: { status: 'ready' },
          }
        })]
      }
    })

    // Spy the method you call...
    const spy = vi.spyOn(wrapper.vm, 'changeStatus');

    wrapper.vm.changeStatus()

    expect(spy).toHaveBeenCalled()
    expect(spy).toHaveBeenCalledTimes(1)
  })
})


text:
Q: Count within the aggregate SUM() I have a table with 1000 rows. Columns exist are ID, DBID, TalkTime.
I am doing:
SELECT DBID, SUM(TalkTime)
FROM Incoming_Calls
GROUP BY DBID

This condenses down to approximely 18 rows.
I want to know how I can count the number of records present within each grouping. So for example DBID 105 has a sum of 526 which is made up of 395 records, DBID 104 has a sum of 124 made up using 241 of the records during the grouping.
Any ideas?
Using Microsoft SQL Server 2012.

A: Then use COUNT()
SELECT DBID,
       COUNT(*) TotalRows,
       SUM(TalkTime) TotalTalkTime
FROM   Incoming_Calls
GROUP  BY DBID

*

*TSQL Aggregate Function

A: Select DBID, SUM(TalkTime), COUNT(TalkTime) TalkTimeCount
FROM Incoming_Calls
GROUP BY DBID

OR, If you want to include null values count then you can you this
Select DBID, SUM(TalkTime), @@ROWCOUNT
FROM Incoming_Calls
GROUP BY DBID


text:
Q: How can I monitor cli commands on one machine and execute them on another in real time? I'm trying  to make a highly available topology, by executing all of the cli commands that have been executed from one machine to another - Doing this will syncronize their configurations. Therefore, if the first machine breaks or something else happens to it, I can make a failover to the second one that will have the same configuration due to this monitoring & executing.
To make it easier I'm only working with root user on both machines.
I am familiar with the history command in linux, but that way I will have to create my own scripts for monitoring and then executing the commands via ssh. Is there a service/project that can do such a thing, if not is there a easier way?
How can I make that happen in real time?

A: Apply configuration to both with your automation solution of choice. The commands are well defined as playbooks or recipes. Test going from a blank operating system image to a working, tested application. Excellent at repeating identical tasks on the test and production environments.
Backup data and operating system at a frequency to meet your desired recovery point objective. Test restores, obviously.
Or, shared storage clusters, where the important data is really on one set of LUNs failed over between hosts, are still a thing. Tend to be tricky to set up, however.
Interesting idea to record shell history and replay it. Tricky to capture in practice however, how are you going to replay an interactive editor session? What if some important configuration is done by a less-privileged not-root user? What happens if the network between them is partitioned, how does it track what commands have been run on each node?


text:
Q: WPF ListBox SelectionBox I have a DataTemplate for my WPF ListBox:
<DataTemplate DataType="{x:Type local:LogEntry}" x:Key="lineNumberTemplate">
  <Grid IsSharedSizeScope="True">
    <Grid.ColumnDefinitions>
      <ColumnDefinition SharedSizeGroup="Index" Width="Auto"/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <Grid Cursor="/LogViewer;component/Template/RightArrow.cur">
      <Rectangle Fill="{Binding Path=LineNumbersBackgroundColor, ElementName=LogViewerProperty}" Opacity="0.4" />
      <TextBlock Grid.Column="0" Margin="5,0,5,0" Style="{StaticResource MyLineNumberText}" x:Name="txtBoxLineNumbers" />
    </Grid>
    <TextBlock Grid.Column="1" Margin="5,0,0,0" Style="{StaticResource MyTextEditor}" />
  </Grid>
</DataTemplate>

Is it possible that the selection box begins not at the beginning (MyLineNumberText) but at MyTextEditor? Sorry I don't know how to describe it in the right way.

A: Yes, it is possible. You have to modify the style of the listbox. If you are using Blend this is easy. Otherwise you could get the style for Listbox and ListboxIten here: http://msdn.microsoft.com/en-us/library/cc278062(v=vs.95).aspx
Copy the style to your project and then change the style acordingly.


text:
Q: Having trouble sending form information to server I am using Angular framework, and I am still trying to figure things out... I am using Restangular to post
For reference:
feedback: Feedback; (feedback class)
feedbackCopy = null; (to be used to check for form entry before posting to server)
feedbackForm = FormGroup;

I am working on putting together a form that will take input information, and post it to the server.
onSubmit(){
//store form values in feedback object
this.feedback = this.feedbackForm.value;
//log object to console
console.log(this.feedback);
//give feedback info to feedback class to be stored in object
this.feedbackCopy.push(this.feedback);
this.feedbackCopy.save().subscribe(feedback => { this.feedback = feedback; console.log(this.feedback)})
//reset for to empty values
this.feedbackForm.reset({
  firstname: '',
  lastname: '',
  telnum: '',
  email: '',
  agree: false,
  contacttype: 'None',
  message: ''
});

}
Above is the code for the Submit function that is supposed to post the information to the server. It stops at the
this.feedbackCopy.push(this.feedback);

line and says that .push is not a function
ERROR TypeError: this.feedbackCopy.push is not a function
at ContactComponent.onSubmit (contact.component.ts:122)

Am I missing something obvious here?

A: *

*feedbackCopy needs to be an array for "this.feedbackCopy.push(this.feedback);" to avoid error.

*feedbackCopy needs to be a ngx-restangular object for
"this.feedbackCopy.post()..." to avoid error.

You need to prepare feedbackCopy as a right type (i.e., restangular) before calling onSubmit()


text:
Q: setBitmapImage is not working in panasonic and one plus after image compression This is the method where i'm setting the bitmap to imageView. This works properly for all the devices except oneplus and panasonic devices. It will show blank when i set the bitmap to imageView in oneplus and panasonic devices and the bitmap is not null. we thought android version might be the issue, but it worked fine for other devices with the same version.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

// start the image capture Intent
startActivityForResult(intent, REQUEST_CAMERA);

ImageView chatImageSendView;

private void onCaptureImageResult(Intent data) {

    ImageCompression imageCompressione = new ImageCompression(ChatWithImageActivity.this);
    String compressImagePath = imageCompressione.compressImage(fileUri.getPath());
    destination = new File(compressImagePath );

    Bitmap bmp = null;
    try {
        bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri);
    } catch (IOException e) {
        e.printStackTrace();
    }

    ExifInterface exifCamera = null;
    try {
        exifCamera = new ExifInterface(fileUri.getPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    int orientationCam = exifCamera.getAttributeInt(ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_UNDEFINED);

    Bitmap bmRotatedCam = rotateBitmap(bmp, orientationCam);

    if (bmRotatedCam != null) {
        chatImageSendView.setImageBitmap(bmRotatedCam);
    }
}

This class we are using for image compression.
public class ImageCompression {

    private Context context;
    private static final float maxHeight = 1280.0f;
    private static final float maxWidth = 1280.0f;

    public ImageCompression(Context context){
        this.context=context;
    }

    public String compressImage(String imagePath) {
        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

    float imgRatio = (float) actualWidth / (float) actualHeight;
    float maxRatio = maxWidth / maxHeight;

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;
    options.inDither = false;
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {
        bmp = BitmapFactory.decodeFile(imagePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    if(bmp!=null)
    {
        bmp.recycle();
    }

    ExifInterface exif;
    try {
        exif = new ExifInterface(imagePath);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
        } else if (orientation == 3) {
            matrix.postRotate(180);
        } else if (orientation == 8) {
            matrix.postRotate(270);
        }
        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
    } catch (IOException e) {
        e.printStackTrace();
    }
    FileOutputStream out = null;
    String filepath = getFilename();
    try {
        out = new FileOutputStream(filepath);

        //write the compressed bitmap at the destination specified by filename.
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return filepath;
}

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;

    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }

    return inSampleSize;
}

public String getFilename() {
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Medcync/ImageSent");

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        mediaStorageDir.mkdirs();
    }

    String mImageName="IMG_"+ String.valueOf(System.currentTimeMillis()) +".jpg";
    String uriString = (mediaStorageDir.getAbsolutePath() + "/"+

mImageName);;
        return uriString;

    }
}

Below method is used to rotate the image
public Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

    Matrix matrix = new Matrix();
    switch (orientation) {
        case ExifInterface.ORIENTATION_NORMAL:
            return bitmap;
        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
            matrix.setScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.setRotate(180);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.setRotate(90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.setRotate(90);
            break;
        case ExifInterface.ORIENTATION_TRANSVERSE:
            matrix.setRotate(-90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.setRotate(-90);
            break;
        default:
            return bitmap;
    }
    try {
        Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return bmRotated;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        return null;
    }
}


text:
Q: Main Looper queued unexecuted runnables I'm trying to run a unit test on my RecyclerView. For my first test, I want to see if the RecyclerView is displayed.
@RunWith(RobolectricTestRunner::class)
class WordListFragmentTest {

    // Executes task sin the Architecture component in the same thread.
    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    private lateinit var scenario: FragmentScenario<WordListFragment>

    private lateinit var viewModel: MainViewModel

    val word = Word("Word")

    @Before
    fun setup() {
        viewModel = mock(MainViewModel::class.java)

        scenario = launchFragment(
            factory = MainFragmentFactory(viewModel),
            fragmentArgs = null,
            themeResId = R.style.Theme_Words,
            initialState = Lifecycle.State.RESUMED
        )

    }

    @Test
    fun `recyclerView displayed`() {
        onView(withId(R.id.recyclerView))
            .check(matches(isDisplayed()))
    }

After running the test I get the following error.
java.lang.Exception: Main looper has queued unexecuted runnables. This might be the cause of the test failure. You might need a shadowOf(getMainLooper()).idle() call.

This appears to be related to LiveData observer that submits the list in the fragment. If I comment out the submit function the test will run.
The Fragment.
class WordListFragment(private val viewModel: MainViewModel) : Fragment() {

    ...

    private fun submitList() {
        viewModel.wordList.observe(viewLifecycleOwner, {
            it?.let {
                rvAdapter.submitList(it)
            }
        })
    }
}

MianViewModel
class MainViewModel @Inject constructor(
    var repository: IWordRepository,
    @IoDispatcher var ioDispatcher: CoroutineDispatcher
) : ViewModel() {

    var wordList: LiveData<List<Word>> = repository.allWords
    ...
}

This link states Robolectric will default to LooperMode.LEGACY behavior, but this can be overridden by applying a @LooperMode(NewMode) annotation to a test package, test class, or test method, or via the 'robolectric.looperMode' system property. I'm still experiencing the same error when I run my test.


text:
Q: number of Parenthesizations for fixed number of "()" pairs Say we'd like to count the number of different parenthesizations of n pairs of brackets but having a fixed number of "()" pairs. How do we count these.
ex:
for n = 3. i.e 3 pairs of parenthesizations, if we want number of parenthizations with k = 2 pairs of "()"
the number of ways is 3.
()(())
(())()
(()())
for n = 4,k = 2, it will be 6
((()()))
()((()))
(())(())
(()(()))
((()))()
((())())

A: I'm pretty sure this is A001263, a.k.a. the Narayana numbers, and that the formula is
T(n,k) = C(n-1,k-1) C(n,k-1)/k with 1<=k<=n

One interpretation of A001263 is that T(n,k) is the number of Dyck n-paths with exactly k peaks, and you can interpret each Dyck step as either ( or ) and each peak as ().


text:
Q: How can I avoid setTimeout and redundant getEntityRecord calls in a block editor sidebar? I've been struggling with getCurrentUser, getEntityRecord, and editEntityRecord and am wondering how I should be using them.
It's for a sidebar that submits a prompt to OpenAI and then returns it. It shows the result as well as the previous 10 prompts and results.
Here's the complete code, below. It's doing this in a PluginSidebar in the block editor/Gutenberg:

*

*When page loads, load history (with useEffect)

*When a new result is received, update history

*When the panel is closed and re-opened, state is lost, so load history again

History in this case is stored in user meta; I wanted it to be unique to each user.
There are a number of odd things that it seems like may be because I'm doing something wrong:

*

*When useEffect() calls getHistory(), it has to run inside a setTimeout() or it'll fail on initial page load

*getCurrentUser() caches its results so I have to use getEntityRecord() instead to handle #2 and #3 above

*But getEntityRecord() results are undefined (even inside a subscribe() with isResolving()) on page load, so at that time I have to use getCurrentUser instead

*warmUpEntityRecord() has to run on initial page load, or subsequent calls will fail

This is probably confusing to read; I know it's confusing to me!
The code works, but it must be unnecessarily complex and hacky. Do you know the correct way of handling these issues? Any and all advice welcome.
import { useState, useEffect } from '@wordpress/element';
import { useSelect, useDispatch, subscribe } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import Compose from './compose';
import History from './history';

export default function AiWriter() {
    const [historyItems, setHistoryItems] = useState([]);
    const [resultLoading, setResultLoading] = useState(false);
    const [historyLoading, setHistoryLoading] = useState(true);

    const apiKey = fjSidekick.openaiApiKey; // eslint-disable-line no-undef
    const apiURL = 'https://api.openai.com/v1/completions';
    const numberOfHistoryItems = 10;

    const isResolving = useSelect((select) => {
        return select('core/data').isResolving;
    }, []);

    const getCurrentUser = useSelect((select) => {
        return select('core').getCurrentUser;
    }, []);

    const getEntityRecord = useSelect((select) => {
        return select('core').getEntityRecord;
    }, []);

    const { editEntityRecord, saveEditedEntityRecord } = useDispatch('core');

    // This prevents editEntityRecord from failing with an "undefined" error on its first call
    const warmUpEditEntityRecord = async () => {
        await getEntityRecord('root', 'user', 1, {});
        await editEntityRecord('root', 'user', 1, {});
        await saveEditedEntityRecord('root', 'user', 1);
    };

    // Why do I have to use getCurrentUser() as a fallback on page load?
    const getHistory = async () => {
        setHistoryLoading(true);
        const currentUser = await getCurrentUser();

        // Returns undefined on page load, even with isResolving()
        const updatedUserRecord = await getEntityRecord(
            'root',
            'user',
            currentUser.id
        );

        if (updatedUserRecord) {
            // On panel re-open and history refresh
            setHistoryItems(updatedUserRecord.meta?.fj_sidekick_history?.items);
            setHistoryLoading(false);
        } else {
            // On page load
            const unsubscribe = subscribe(() => {
                const isResolvingCurrentUser = isResolving(
                    'core',
                    'getCurrentUser'
                );
                if (!isResolvingCurrentUser) {
                    unsubscribe();

                    setHistoryItems(currentUser.meta.fj_sidekick_history.items);
                    setHistoryLoading(false);
                }
            });
        }
    };

    // This works fine thanks to the warm-up function
    const addHistoryItem = async (prompt, newResult, length) => {
        const currentUser = await getCurrentUser();
        const meta = (currentUser && currentUser.meta) || [];
        const history = (meta && meta.fj_sidekick_history) || null;
        const items = (history && history.items) || [];
        const newItems = [...items, { prompt, result: newResult, length }];

        while (numberOfHistoryItems < newItems.length) {
            newItems.shift();
        }

        const newMeta = {
            ...meta,
            fj_sidekick_history: {
                ...history,
                items: newItems,
            },
        };

        await editEntityRecord('root', 'user', currentUser.id, {
            meta: newMeta,
        });
        await saveEditedEntityRecord('root', 'user', currentUser.id);

        getHistory();
    };

    // No problems here
    const updateHistory = async (prompt, length) => {
        setResultLoading(true);

        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: 'Bearer ' + apiKey,
            },
            body: JSON.stringify({
                model: 'text-davinci-002',
                prompt,
                temperature: 0,
                max_tokens: length,
            }),
        };

        const response = await fetch(apiURL, requestOptions);
        const data = await response.json();
        const newResult =
            data && data.choices && data.choices[0]
                ? data.choices[0].text.trim()
                : __('No result', 'fj-sidekick');

        setResultLoading(false);

        addHistoryItem(prompt, newResult, length);
    };

    // Here lies weirdness
    useEffect(() => {
        warmUpEditEntityRecord();
        setTimeout(() => {
            getHistory();
        }, 0);
    }, []);

    // History items are shared between the two sections of the sidebar
    return (
        <>
            <Compose
                historyItems={historyItems}
                historyLoading={historyLoading}
                updateHistory={updateHistory}
                resultLoading={resultLoading}
            />
            <History
                historyItems={historyItems}
                historyLoading={historyLoading}
            />
        </>
    );
}


text:
Q: An Embedded the twitter timeline in not working in IBM Client 9.0.0 I used the HTML Code provided by Twitter  (https://publish.twitter.com/).
The given code is like
Tweets by TwitterDev
this code is embedded in an XPages and the XPages is displayed in XPinc
For some IBM Notes client (seems only the version 9.0.0), the timeline is not loaded.
With the 9.0.1+ version of the IBM Notes client, it works well.
Any idea ?

A: the pb was not due to the version of the Notes Client.
The Xpages was opened from a local replica.
The proxy congifuration did not allow to open the external websites (plateform.twitter.com) and the localhost (127.0.0.1) used for running the Xpages.
Changing the proxy setting in the location document by setting do not use proxy for localhost ip address solved the pb.


text:
Q: How to implement independent component in Javascript? I've implemented simple todo list http://jsfiddle.net/tw9p9sw3/ with possibility add/remove todo's.
    (function (todoApp) {
    'use strict';

    todoApp.todoItemValue = '';

    function _appendListNode() {
        var listNode = document.createElement('li');
        listNode.className = 'list-group-item';
        listNode.appendChild(document.createTextNode(todoApp.todoItemValue));
        listNode.appendChild(_createRemoveItemButton());
        todoList.appendChild(listNode);
    }

    function _createRemoveItemButton() {
        var removeButtonNode = document.createElement('a'),
            removeButtonLabel = 'Remove';

        removeButtonNode.className = 'badge';
        removeButtonNode.appendChild(document.createTextNode(removeButtonLabel));

        return removeButtonNode;
    }

    function _addItem() {
        todoApp.todoItemValue = document.getElementById('todoInput').value;
        _appendListNode();
        document.getElementById('todoInput').value = '';
    }

    function _removeItem() {
        var nodeToRemove = this.parentNode;
        this.parentNode.parentNode.removeChild(nodeToRemove);
    }

    function _addEventHandlers() {
        document.getElementById('todoListForm').addEventListener('submit', function (event) {
            event.preventDefault();
            _addItem();
        });

        /*
         * Used delegated event cause todo list is not static,
         * so we don't need to add events for remove buttons each time after DOM of todo list have changed
         */
        document.getElementById('todoList').addEventListener('click', function (event) {
            if (event.target && event.target.nodeName === 'A') {
                event.preventDefault();
                _removeItem.call(event.target);
            }
        });
    }

    todoApp.init = function () {
        _addEventHandlers();
    };

}(window.todoApp = window.todoApp || {}));

//////////////////////////////////////////////////////////
// INITIALIZATION
//////////////////////////////////////////////////////////
document.onload = todoApp.init();

The question is how to re-make this todo list as independent component so for example I could inject/instanciate it twice on the same page and there should be no conflicts between todo list instances.

A: Basically you need to create TodoList class, so you can create instances of this class, as suggested in coments use OO programming.
Here is code:
var TodoListComponent = (function () {
    'use strict';

    var todoListTemplate =  '
' +
        '
' +
        '
' +
        '<form role="form" class="todoListForm">' +
            '
' +
                'Add todo item' +
                '<input type="text" class="form-control todoInput" required>' +
            '
' +
            '<button type="submit" class="btn btn-success">Submit</button>' +
        '</form>' +
    '
' +
    '
' +
        '
' +
            '
Todo list
' +
       '
' +
   '
' +
   '
' +
   '
';

    function TodoList() {

        this.initialize = function() {
            this.$el = $(todoListTemplate);
            this.todoItemValue = '';
            this._initEvents();
        }

        this._initEvents = function() {
            var self = this;

            this.$el.find('.todoListForm').on('submit', function (event) {
                event.preventDefault();
                self._addItem();
            });

            /*
             * Used delegated event cause todo list is not static,
             * so we don't need to add events for remove buttons each time after DOM of todo list have changed
             */
            this.$el.find('.todoList').on('click', function (event) {
                if (event.target && event.target.nodeName === 'A') {
                    event.preventDefault();
                    self._removeItem.call(event.target);
                }
            });
        }

        this._appendListNode = function () {
            var listNode = $('
');
            listNode.addClass('list-group-item');
            listNode.text(this.todoItemValue);
            listNode.append(this._createRemoveItemButton());
           this.$el.find('.todoList').append(listNode);
        }

        this._createRemoveItemButton = function () {
            var removeButtonNode = $(''),
                removeButtonLabel = 'Remove';

            removeButtonNode.addClass('badge');
            removeButtonNode.text(removeButtonLabel);

            return removeButtonNode;
        }

        this._addItem = function() {
            var input = this.$el.find('.todoInput');
            this.todoItemValue = input.val();
            this._appendListNode();
            input.val('');
        }

        this._removeItem = function() {
            var nodeToRemove = this.parentNode;
            this.parentNode.parentNode.removeChild(nodeToRemove);
        }

         this.render = function() {
             return this;
         }

        this.initialize();
    }

    return TodoList;
}());

//////////////////////////////////////////////////////////
// INITIALIZATION
//////////////////////////////////////////////////////////

var todoList1 = new TodoListComponent();
var todoList2 = new TodoListComponent();

$('body').append(todoList1.render().$el);
$('body').append(todoList2.render().$el);

And jsfiddle link: http://jsfiddle.net/tw9p9sw3/10/
This works, but what if you want to use data, send items somewhere or else, then you probably will get it via DOM which is bad and messy.
Try to use Backbone where DOM used only for representation, and data is held by Javascript.
Here is example:
http://backbonejs.org/docs/todos.html


text:
Q: How to update an index with new variables in Elasticsearch? I have an index 'user' which has a mapping with field of "first", "last", and "email". The fields with names get indexed at one point, and then the field with the email gets indexed at a separate point. I want these indices to have the same id though, corresponding to one user_id parameter. So something like this:
function indexName(client, id, name) {
  return client.update({
    index: 'user',
    type: 'text',
    id: id,
    body: {
      first: name.first
      last: name.last
    }
  })
}

function indexEmail(client, id, email) {
  return client.update({
    index: 'user',
    type: 'text',
    id: id,
    body: {
      email: email
    }
  })
}

When running:
indexName(client, "Jon", "Snow").then(indexEmail(client, "jonsnow@gmail.com"))

I get an error message saying that the document has not been created yet. How do I account for a document with a variable number of fields? And how do I create the index if it has not been created and then subsequently update it as I go?

A: The function you are using, client.update, updates part of a document. What you actually needs is to first create the document using the client.create function.
To create and index, you need the indices.create function.
About the variable number of fields in a document type, it is not a problem because Elastic Search support dynamic mapping. However, it would be advisable to provide a mapping when creating the index, and try to stick to it. Elastic Search default mapping can create you problems later on, e.g. analyzing uuids or email addresses which then become difficult (or impossible) to search and match.


text:
Q: How can we pass image variables in jinja2/weasyprint python the problem is that i am trying to create an image variable in python using jinja2 and weasyprint and then, i want to pass that image variable in my HTML template (html_out).
I was successful in creating the image variable and it appears in my variable explorer. But passing it to the HTML template by including it in my dictionary was only trouble.
#this is my image variable
art_work = Image.open('D:/Course/report-automation/Huaweii.png')

#this is my dictionary

template_vars = {"title": title, "start_date": start_date, "end_date": end_date, "price": price,
                 "total_Impressions": total_impressions, "art_work": art_work, "total_Clicks": total_clicks,
                 "cpm":cpm, "percentage_mobile": percentage_mobile}

below is the html template with my variable holder:

        {{ art_work }}

A: To display image you should use  tag. Also, just pass the src of image in dictionary.


text:
Q: Are Hamiltonian trajectories geodesics on the cotangent bundle? Suppose we have a Hamiltonian dynamics on a phase space, whose base space is also a Riemannian manifold. I was wondering if the Hamiltonian trajectories are whether geodesics or only locally geodesics on the cotangent bundle? Thanks!

A: A short answer is yes, but we need some more restriction on the Hamiltonian we are choosing.  See: https://en.wikipedia.org/wiki/Geodesics_as_Hamiltonian_flows .


text:
Q: ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled I am trying to access url mentioned in the code through python, when I set verify=False I am getting error "ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled.".
When I set verify=True I am getting Max retries exceeded with url: /api/search/users?employeesOnly=true&pid=g453942*&surname=y*&name=x* (Caused by SSLError(SSLError(9, '[SSL] PEM lib (_ssl.c:4044)')))
But same url I can access through browser without any issue (I have imported my certificate).
Any Idea why this is happening, I have absolutely no clue.
from flask import Flask

app = Flask(__name__)

import requests
import os
from OpenSSL import crypto

@app.route("/abc")
def home():
    url = 'https://myurl.com/api/search/users?employeesOnly=true&pid=g453942*&surname=y*&name=x*'
    pkcs12_filename = r"C:\Users\user16\Downloads\certificate_TEST2.p12"
    pkcs12_password = 'pass123'

    p12 = crypto.load_pkcs12(open(pkcs12_filename, 'rb').read(), pkcs12_password.encode())

    # PEM formatted private key
    k = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())

    key_path = os.path.join(os.getcwd(), "myKey.key")
    cert_path = os.path.join(os.getcwd(), "myCert.crt")
    fkey = open(key_path, 'wb')
    fkey.write(k)
    fkey.close()

    # PEM formatted certificate
    c = crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())
    fcert = open(cert_path, 'wb')
    fcert.write(c)
    fcert.close()

    result = requests.get(url, verify=False, cert=(key_path, cert_path))

    return result

app.run(debug=True)

A: When the file is in local, why not use lunix command to extract key and crt,
then use the below code
> import json
import requests

clientCrt = "cc.crt"
clientKey = "ck.key"
url = "https://example.com/api"
payload = { "someId": "myID" }
certServer = 'cs.crt'
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), verify=certServer,
                  headers=headers, cert=(clientCrt, clientKey))
print(r.status_code)
print(r.json())


text:
Q: How to write a Map object to a file I want to write to a file from a Map object.  Here is my attempt.
try {
    stuMap.put(student.getId(), student);
    Path file = Paths.get("student.txt");  // to create the file
    Files.write(file, stuMap, Charset.forName("UTF-8"));  // try to save in the file
    /*  fileReaderWriter.createFileIn_NIO(stuMap);*/
    try {
        fileReaderWriter.createFileIn_NIO(stuMap);
    } catch (IOException ex) {
        System.out.println("file not saved");
    }
    return true;
} catch (Exception ex) {
    System.out.println("not stored in Map");
    return false;
}

How do I make this work?

A: You can use tools like Jackson to write java maps out as json and read it in as map. As others have mentioned, this is only one possible way.
Full working Read/Write Example
@Test
public void loadMapFromFileAndSaveIt(){
    Map<Object, Object> map = loadMap("map.json");
    map.put("8", "8th");
    map.remove("7");
    save(map,"/path/to/map2.txt");
}

private Map<Object, Object> loadMap(String string) {
    ObjectMapper mapper = new ObjectMapper();
    try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("map.json")) {
        return mapper.readValue(in, HashMap.class);
    }catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private void save(Map<Object, Object> map,String path) {
    try (PrintWriter out = new PrintWriter(path)) {
        out.println(toString(map));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public String toString(Object obj) {
    try (StringWriter w = new StringWriter();) {
        new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
        return w.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

If the file map.json on your classpath contains
{
 "1":"1th",
 "2":"2th",
 "3":"3th",
 "4":"4th",
 "5":"5th",
 "6":"6th",
 "7":"7th"
}

The code above will modify it and write it to a file /path/to/map2.txt that will contain
{
  "1" : "1th",
  "2" : "2th",
  "3" : "3th",
  "4" : "4th",
  "5" : "5th",
  "6" : "6th",
  "8" : "8th"
}

A: There is concept in java for saving state of object and retrieve it back later called 'Serialization'.
To Write Object
File fileToSaveObject=new File("path");
Object objectToSave=new Object();

FileOutputStream fileOut = new FileOutputStream(fileToSaveObject);
ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(objectToSave); // It will save 'objectToSave' in given file

out.close();
fileOut.close();

To Read Object
File fileToReadObject=new File("path");
Object objectToRead;

FileInputStream fileIn = new FileInputStream(fileToReadObject);
ObjectInputStream in = new ObjectInputStream(fileIn);

objectToRead= (Object) in.readObject();  // It will return you the saved object

in.close();
fileIn.close();

A: Just use org.apache.commons.io.FileUtils
import org.apache.commons.io.FileUtils;

yourMap.forEach((key, value) -> {
    FileUtils.writeStringToFile(
            outputFile, key + ", " + value + "\n", true);
});

A: A simple variant to solve the problem is to use Gson library:
    String str = new Gson().toJson(yourMap);
    File file = new File(fileName);
    try(FileOutputStream stream = new FileOutputStream(file)) {
        file.createNewFile();
        stream.write(str.getBytes());
    }catch (IOException e){
        System.out.println("can't write to file");
    }


text:
Q: how to display submenu in the sidebar using HTML, css and Js I need a help, I am making a web page in which I need to create a responsive sidebar with sub menu.
So far I have done the html and css part I also have added a js to it but still it is not working also I want to add the responsiveness to this so that when the user click a hamburger menu it opens the sidebar and when user click beside the sidebar it close it (I want to close my sidebar on clicking beside it and not by using cancel button). To be more precise I am crating a clone of myntra website in mobile view.
below is my code please help if you can thank you.
html:

                                Men

                                        Topwear

                                                T-shirts

                                                Casual Shirts

                                                Formal Shirts

                                                Sweatshirts

                                                Jackets

                                                Rain Coats

                                        Indian & Festival Wear

                                        Bottomwear

                                        innerwear & Sleepwear

                                        Plus Size

                                        Footwear

                                Women

                                Kids

                                Home & Living

                                Beauty

                        Myntra Studio

                        Myntra Mall

                        Myntra Insider

                        Gift Cards

                        Contact Us

                        FAQs

                        Legal

CSS:
.sidebar .sidebar-ul {
    background-color: #fff;
    border-bottom: 1px solid #eaeaec;
    margin-bottom: 5px;
    padding-bottom: 5px;
}

.sidebar .image-signUp-box{
    position: relative;
}

.sidebar .sidebar-signup {
    position: absolute;
    bottom: 14%;
    right: 18%;
}

.sidebar .login-link {
    font-size: 12px;
    color: #ff3f6c;
    font-weight: 500;
    text-transform: uppercase;
    text-decoration: none;
}

.sidebar-ul > ul {
    display: flex;
    flex-direction: column;
    padding: 0;
}
.sidebar-ul .item-link {
    font-size: 14px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    color: #3e4152;
    text-decoration: none;
}

.sidebar .sidebar-ul .toflex {
    display: flex;
    justify-content: space-between;
    padding: 14px 20px;
}

.sidebar .user-specific-links {
    background-color: #fff;
}

.sidebar .specific-list {
    display: flex;
    flex-direction: column;
    padding: 0;
}

.sidebar .specific-item a {
    display: block;
    color: #282c3f;
    padding: 14px 20px;
    text-decoration: none;
}

.sidebar .drop-list a {
    font-weight: 400;
}
 ul.drop-list {
            display: none;
        }

        ul.drop-menu-list {
            display: none;
        }

Javascript:
var mainDrop = document.getElementsByClassName("menu-items");
            var i;

            for (i = 0; i < mainDrop.length; i++) {
                mainDrop[i].addEventListener("click", function () {
                    this.classList.toggle("active");
                    var mainDropContent = this.children(".drop-list");
                    if (mainDropContent.style.display === "block") {
                        mainDropContent.style.display = "none";
                    } else {
                        mainDropContent.style.display = "block";
                    }
                });
            }


text:
Q: Fatal Exception at AnroidRuntime after releasing new update After updating for a new release of my app I'm getting this error crash repeatedly on the opening of the app and nothing else. This crash happening after few seconds of the opening of the app.
Error Log:
E/AndroidRuntime: FATAL EXCEPTION: Thread-3
Process: com.company.app, PID: 13304
java.lang.NoSuchMethodError: No direct method <init>(Lorg/apache/http/c/c;Lorg/apache/http/conn/scheme/SchemeRegistry;)V in class Lorg/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager; or its super classes (declaration of 'org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager' appears in /system/framework/org.apache.http.legacy.boot.jar)
    at com.a.g.c.c(Unknown Source:54)
    at com.a.g.c.a(Unknown Source:4)
    at com.a.e.b.a(Unknown Source:0)
    at com.a.e.b.b(Unknown Source:23000)
    at com.a.d.b.c(Unknown Source:5000)
    at com.a.d.b.b(Unknown Source:0)
    at com.a.d.b.a(Unknown Source:4000)
    at com.a.c.f.a(Unknown Source:12000)
    at com.a.c.f$1.run(Unknown Source:4)
    at com.a.a.b.b.a(Unknown Source:8)
    at com.a.e.a(Unknown Source:51031)
    at com.a.e.a(Unknown Source:0)
    at com.a.e$4.run(Unknown Source:1000)
    at com.a.e.o(Unknown Source:31)
    at com.a.e.a(Unknown Source:45000)
    at com.a.c.a(Unknown Source:20)
    at com.a.c.b(Unknown Source:27000)
    at com.a.c$1.run(Unknown Source:7)
    at com.a.a.b.c.run(Unknown Source:8)
    at com.a.a.b.d.run(Unknown Source:2000)

This error is showing in Logcat not getting on Crashlytics.
What are the main causes of this happening and how to solve this problem?

A:
What are the main causes of this happening and how to solve this problem?

This is due to your apache classes are stripped by your proguard obfuscation step. Try to add -keep options for those apache classes. E.g.
-keep class org.apache.http.** { *; }


text:
Q: Self sizing label I'm working on chat. So I stopped where I should do self-sizing labels to display text.
I tried to make my label as:
messageLabel.frame = CGRectMake(0, 0, self.chatScrollView.frame.size.width - 90, CGFloat.max)
messageLabel.sizeToFit()

messageLabel.frame.origin.x = (self.chatScrollView.frame.size.width - self.messageX) - messageLabel.frame.size.width
                        messageLabel.frame.origin.y = self.messageY

but my label didn't appear at all. If I make some exact height of my label for example 100 and comment line
 //messageLabel.sizeToFit()

so the whole label code:
let messageLabel: UILabel = UILabel()
messageLabel.text = self.messageArray[i]
messageLabel.frame = CGRectMake(0, 0, self.chatScrollView.frame.size.width - 90, CGFloat.max)
messageLabel.backgroundColor = UIColor.groupTableViewBackgroundColor()

messageLabel.numberOfLines = 0
messageLabel.lineBreakMode = .ByWordWrapping
messageLabel.sizeToFit()

messageLabel.textAlignment = .Left
messageLabel.font = UIFont(name: "Apple SD Gothic Neo", size: 20)
messageLabel.textColor = UIColor.grayColor()

messageLabel.layer.zPosition = 20
messageLabel.frame.origin.x = (self.chatScrollView.frame.size.width - self.messageX) - messageLabel.frame.size.width
messageLabel.frame.origin.y = self.messageY
print(self.messageArray[i])
print("label origin \(messageLabel.frame.origin.x, messageLabel.frame.origin.y)")
self.chatScrollView.addSubview(messageLabel)
self.messageY += messageLabel.frame.size.height + 30

let width = self.view.frame.size.width

self.chatScrollView.contentSize = CGSizeMake(width, self.messageY)
self.chatScrollView.bringSubviewToFront(messageLabel)

Edit #1

*

*Label definitely has text (print statement proofs it)

*Label origin is on the screen area (second print statement proofs it)

Question: How I can fix it (or how I can make my label appear and be self-sizing label)?

A: I found the solution!
I just put my
messageLabel.text = self.messageArray[i]

right under the
let messageLabel: UILabel = UILabel()

so my label appeared!


text:
Q: Javascript / Jquery Validation on required fields I searched a lot but couldn't find an answer for my question.
Firstly, i would like to have a submit button which will be disable if all the required fields are not filled.
I found some example if all the fields are filled but i have required and not required ones So,
I need to find if the required ones are filled or not.
I am currently out of ideas of how to make it happen.
Just in case , i am using play framework 2.1.x with Scala.
Cheers,
Ilgün

A: This should work:

My submit Button:
<input type="submit" class="btn btn-primary" value="Submit" id="form-submit" onclick="return myConfirm();" />

A: Here is a simple example:
First you can identify the required fields with a class of required:
<form id="myForm">
    *<input type="text" class="required" />

    *<input type="text" class="required" />

    <input type="text" />

    <input type="text" />

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

Initially disable your submit button:
var submitButton = $("#myForm input[type='submit']").attr("disabled", true);

Then use jQuery to loop through your inputs everytime one changes, and check if there are values in them. If they all have a value then enable the submit button, if not disable it:
    $("#myForm input.required").change(function () {
        var valid = true;
        $.each($("#myForm input.required"), function (index, value) {
            if(!$(value).val()){
               valid = false;
            }
        });
        if(valid){
            $(submitButton).attr("disabled", false);
        }
        else{
            $(submitButton).attr("disabled", true);
        }
    });

Please see this jsFiddle with a simple example of what you are describing using jQuery.

A: This is just some basic stuff with plain HTML/JS to show a possible way of input validation:
HTML:

      <form id="form">
        <input class="form-input" data-required="true" type="text" />
        <input class="form-input" data-required="true" type="text" />

        <input class="form-input" data-required="false" type="text" />
        <input class="form-input" data-required="false" type="text" />

        <input id="form-submit" type="submit" disabled />
      </form>

JS:
    $(document).ready(function() {
      // on input change:
      $(".form-input").on('change', function() {
        // hide the input (not neccessary)
        $("#form-submit").hide();
        // enable it
        $("#form-submit").removeProp("disabled");

        // check all inputs
        $.each(".form-input", function() {
          // read element values
          var required = $(this).data("required");
          var empty = ($(this).val() == "" || $(this).val() == null)
          // if element is required but empty:
          if (required && empty) {
            // disable submit button
            $("#form-submit").prop("disabled", "disabled");
          }
        }

        // now the submit button is enabled if all required inputs are filled
        // and it is disabled if at least one required input is empty

        // after hiding it: make the button visible again (not neccessary)
        $("#form-submit").show();
      }
    });


text:
Q: Present UIAlertController in UITableViewCell on Presented View Controller I want to show UIAlertController from UITableViewCell class.
While searching I found that UIApplication.shared.keyWindow?.rootViewController?.present doing this will display it.
Which works in the case if the opened ViewController is under NavigationController because my rootViewController is a NavigationController and the view under which the cell is being presented.
So how can I present UIAlertController in UITableViewCell which is presented.

A: I think you have to make a variable in cell Class, and you have to assign those class to that variable which implements cell.
then in cell on any action you just call alert like code below:
var fromViewController : UIViewController?

@IBAction func accessoryBtnTapped(_ sender: UIButton){

    let alert = UIAlertController(title: "Alert!", message: "It's Alert From Cell", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(okAction)

    fromViewController?.present(alert, animated: true, completion: nil)
}

A: You need to implement the delegate pattern.
Create a protocol implemented by your controller and assign a weak reference from this controller to your cell.
then use something like cell.delegate.didPerformAction()
The cell is a View, and it should not be responsible for presenting anything.


text:
Q: The difference between git pull & git fetch What is the main difference between following git commands?
git fetch --all
git pull origin repo1
git merge repo1

A: First, git pull is not meant to, nor supposed to, "overwrite local file contents".  It's just shorthand for run two Git commands, with the second command being git merge by default:

*

*The first command is git fetch (with certain arguments), and that never overwrites any files.

*The second command is under your control (to a large extent).  The default git merge does not mean overwrite my files: it means merge my commits.1  The other main option, git rebase, does not mean overwrite my files: it means rebase my commits.

Note that the common denominator here is the word commits.  Understanding that Git is about commits is one of the keys to using Git.  Git is not about branches, though Git uses branch names to find commits.  Git is not about files either, although commits contain files.  Git is really all about the commits.
What this means is that you need to learn what commits are and do for you.  There are a lot of articles and web tutorials about this, including many of my existing StackOverflow answers; find and read some of them.  Don't just blindly try various Git commands: learn what commits are, what a repository is, and how Git uses commits.  Learn how branch names help Git locate commits, and how branch names are specific to each repository copy.
Meanwhile, let's look at these three commands:

git fetch --all

If you're a Git beginner, I recommend that you never use --all here.  It's not that it is harmful, it's that beginners think it means all branches, and it doesn't.  The git fetch command means:

*

*call up some other Git repository;

*have them list out all their branch names and commit hash IDs;

*use this information to get, from the other Git repository, all their commits; and

*use that to update all our own (local) remote-tracking names to remember their branch names.

This updates no branches at all, because our branches are local to our own Git repository.  It does, however, obtain all commits from all of their branches.2  This works well because we don't need branches to find commits.  While Git (and we) use branch names to find commits, we can have Git use other names—remote-tracking names, in this case—to find commits, too.  We just don't want to make our own commits this way.

git pull origin repo1

This means:

*

*Using the name origin, call up a Git.  Get commits from them, as with git fetch origin repo1.  This first step explicitly limits the update from origin to the commits that are find-able, in that other Git, using the branch name repo1.  This does not go to some repository repo1; it goes to the repository named origin.

*If all of that has succeeded, run the second Git command to incorporate any new commits obtained from their Git, using their name repo1 (our origin/repo1), into the current branch, whatever that branch may be.
As always, this second command is under your control: you must choose, before seeing what commits you get, whether you will use git merge or git rebase to incorporate those commits.  Then you have your Git run git fetch to get those commits, and immediately—with no chance to check whether this is a good idea now—run that second command.3

git merge repo1

This means: use the name repo1 to locate a specific commit, and merge that into my current branch.  This usually makes sense if you have your own branch named repo1 and it is time to incorporate the commits that your Git will find on your repo1 into whatever branch you are on now.
Note that it does not matter where you got those commits, only that they are now findable by your name repo1.  If you don't have the name repo1 as a branch name, this command won't do anything useful.4  If you have origin/repo1 as a remote-tracking name, you could run git merge origin/repo1: that will use your remote-tracking name to locate the final commit in the sequence, just as git merge repo1 tries to use your (local) branch name to locate the final commit in the sequence.
It's important to realize that all of these things are really just Git's way to locate some commit.  When you use git fetch, you're getting commits from some other Git repository, and adding them to your Git repository.  This updates your remote-tracking names so that you can locate these commits.  Merging combines the work on some commit(s) with work on other commit(s): it does not overwrite files, but rather combine work.

1This is an overstatement, because git merge is quite complicated.  Sometimes there are no commits to merge, and sometimes Git can "cheat" and do a fast-forward operation instead of a merge; and, rarely, there's no shared history between your commits and their commits, which makes merging unwise, and modern Git will refuse to do that by default.  But in many common cases, it does mean merge commits, and in the cases where Git can use --ff-only instead of --no-ff, you can use --no-ff to force it to make a real merge.  Whether that's what you want is another question entirely.
2The exception here is when your local Git is configured as a single-branch clone.  In this case, git fetch obtains and updates only one of the other Git's branch information, so that you only update one remote-tracking name in this Git.  Adding --all does not help here: if you have a single-branch clone and want to convert it to an all-branch clone, see How do I "undo" a --single-branch clone?
3I tend not to like to do this since sometimes it's not a good idea, depending on what came in.  There are ways to fix things up after the fact, but I like to run git fetch myself, then look at what that did, and only then run git merge or git rebase, or maybe not run either of those.  But many people like the convenience of fetch-then-immediate-second-command, and there's nothing wrong with that.
4Again, this is a bit of an overstatement.  For instance, if you add repo1 as a remote, the bare name repo1 is shorthand for repo1/HEAD, if that name exists.  After git remote add repo1 <url> and git fetch repo1, you'll have commits obtained from whatever Git repository responds to Internet phone-calls at the specified URL.  They presumably have a HEAD and if you have had Git set up your repo1/HEAD as a symbolic reference to whatever branch name they have as their HEAD, using git remote set-head repo1 --auto for instance, you'll now be able to merge that.  I recommend that beginners avoid this kind of deeper magic: if you want to merge their foo branch, use git fetch repo1 followed by git merge repo1/foo, or—if you really like git pull—use git pull repo1 foo.

A: If you always want your server version to reflect a commit from your repo, it's probably better to use git reset instead of git pull - that way you never invoke merge functionality, but instead set all of the files to exactly what they are in the commit you reset to. For example:
git fetch origin master
git reset --hard FETCH_HEAD


text:
Q: iphone - TapGesture on UIWebView conflicts with the link clicking I have a UIWebView loaded html string with url links inside. if I click the url links, an internal home-made browser will launch to open that link.
I added a UITapGestureRecognizer to the UIWebView so if the user taps anywhere on the UIWebView, the UIWebView will become larger and open a fuller html string.
I set the - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizerto return YES, so the UITapGesture works on the UIWebView without problem.
but a problem occurs when I click on a link inside the UIWebView. clicking on a link will invoke two operations: one is opening the browser for link and the other is to enlarge the UIWebView.
This conflicting is not what I want.
I want two cases separated, i.e., if a user click a link on the UIWebView, then browser will open for that link; if a user tap on the UIWebView where no url links exist, the UIWebView is enlarged.
How can I solve that by make two actions co-exist but no conflicting?
Thanks

A: I know this question is old, but I've spent a few hours on Google and Stack Overflow, and I thought it might help someone who comes across this question in the future. Hopefully this is the correct way to solve this problem.
I solved this problem by writing some JavaScript code to determine if a link was clicked. My solution was based on this answer on Stack Overflow. There's a JavaScript function that gets the list of all links in the UIWebView, and their boundaries using getBoundingClientRect(). Then the function CGRectContainsPoint() tells us if the given UITouch object is within the links bounding rectangles.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    BOOL retVal = YES;

    //Check if a link was clicked
    NSString *js = @"function f(){ var a = document.getElementsByTagName('a'); var retVal = new Array(); for (var idx= 0; idx < a.length; ++idx){ var r = a[idx].getBoundingClientRect(); retVal[idx] = '{{'+r.left+','+r.top+'},{'+r.width+','+r.height+'}}'; } return retVal.join(';'); } f();";
    NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:js];

    NSArray *linkArray = [result componentsSeparatedByString:@";"];
    CGPoint touchPoint = [touch locationInView:self.webView];
    for ( NSString *linkRectStr in linkArray ) {
        CGRect rect = CGRectFromString(linkRectStr);
        if ( CGRectContainsPoint( rect, touchPoint ) ) {
            NSLog(@"Link Clicked");
            retVal = NO;
            break;
        }
    }

    return retVal;
}

Hopefully using JavaScript in this way doesn't cause too much of a performance hit. Especially when it has to be recalculated every tap.

A: You can implement your UIWebView's delegate's -webView:shouldStartLoadWithRequest:navigationType method. Return NO when you don't want the link to open.


text:
Q: Variable binding error in angular component Thanks.
I figured it out.
I am just learning Angular and am working with a tutorial that doesn't seem to have the error I am getting.
I am using Angular 12 and the tutorial is using Angular 10.
I have a component that has a variable in the selector in the .html file. I have the variable defined in the .ts file of the component. But I am getting an error that says the variable (dep) that is not known. If I take out the variable from the selector - it works fine. It is set up the same as the tutorial.
Not sure what I am missing.
The error I am getting when I save the file in Visual Studio Code is:

Here is the code code in the html where the selector is:

If I remove the highlighted code ([dep]="dep"), it compiles fine.
And the code in the .ts file is:

Thanks.

A: app-add-edit-dep needs to define dep as @Input like this
@Input() dep: any;


text:
Q: Calabash how to use wildcards in Ruby methods? Trying to figure out how to use the Predicate syntax in Ruby methods ...
Docs introduce the wildcard but forget to mention how to exactly use them in a query (or Ruby) so for a Calabash noob this is difficult. I tried this in Calabash iOS console:
query("* {text CONTAINS 'foo'}"

didn't work!
query("* marked:{text CONTAINS 'foo'}"

didn't work!
In Ruby it becomes more puzzling:
check_element_exists("* marked:# CONTAINS 'sometext'")

No go!
Can some Calabash genius enlighten me?

A: The different samples you have posted all seems to be doing different things. I think it will be easier to help if you have a more concrete example of what you want to query for and what your view contains.
You have probably been by the Xamarin page
Grabbing a piece from one of my own files I have used it like this in a similar check
res = element_exists "* {text LIKE '*foo*'}"


text:
Q: Documentation not working when compiled to jar I'm creating my own package for java with some useful classes. In a lot of them I have added some documentation. It works great when while editing the source files (I'm working with VS Code) however it does not show up when only referencing the compiled jar library. Also, when ctrl-clicking onto a class it says it failed to load the sources and just generated a template. The actual code however is running just fine.
Can someone help me? I put quite some work into the documentaion and it would be a shame to not be able to use it. By the way: I used the jar compiler from the java projects extension.

A: To make the document be shown when hovering over it, you should put the doc text after the label Description and use the command javadoc to generate API information, then pack it as JAR.
Here is a demo project:
/**
 * Description: This is a demo project for printing "helloworld"
 * Program Name: App
 * Date: 2020-12-16
 * @author Molly Wang
 * @version 1.0
 */
public class App {

    /**
     * member variable
     */
    public int age;

    /**
     * main method
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        System.out.println("Hello, World!");
    }
}

Run the following command in terminal. Pay attention to enter the folder of .java file.

*

*javadoc App.java

*jar cvfe App.jar App .\

*Add the jar to Referenced Libraries;

*Test: when you quote App and hover over it, the description will be displayed. As a result, you put your document after the Description so that the java extension catch and show them.


text:
Q: How to run tnftpd without root on OS X? I'm trying to run tnftpd on OS X, which is NetBSD's FTP server and used to be OS X's FTP server. I built and installed it from Apple's sources. Unfortunately, it seems that I cannot run the server without root privileges. These have been my approaches so far to get the server to work without root privileges:

*

*I've tried changing the port number via the -P option, to ensure
that it uses no privileged ports.

*I've tried fiddling with config files, such as ftpd.conf and
ftpusers.

*I've also tried the -r option (which disallows root privileges once a
user logs in).

All of these attempts have been to no avail.
Some examples to illustrate my attempts:
$ ftpd -lnD  # exit code is 0, but `ps' shows no server running

$ ftpd -lnDr # supposed to drop root privileges, but same as above

$ # let's try running on a different port...
$ ftpd -lnDr -P 50001 # exit code still 0, but no dice

However, if I try something like this (this is a scenario where I have no custom configurations in place):
$ sudo ftpd -lnD
Password:
$ ps aux | grep -i ftpd
root            21998   0.0  0.0  4298888    720   ??  Ss   10:41PM   0:00.00 ftpd -lnD

I have no problems.
How can I run the tnftpd server without root privileges? Is it even possible?

A: According to the man page tnftpd(8)
                                                            ... The server
 uses the TCP protocol and listens at the port specified in the ``ftp''
 service specification; see services(5).

and a scan through ftpd.conf(5) shows no obvious means to fiddle with the listen port (as opposed to the data port, which is different) so let's see if we can modify the services file, which is probably a bad idea.
$ sudo perl -i.oops -pe 's/^(ftp\s+21)/${1}21/' /etc/services
$ grep 2121 /etc/services
ftp              2121/udp     # File Transfer [Control]
ftp              2121/tcp     # File Transfer [Control]
scientia-ssdb   2121/udp    # SCIENTIA-SSDB
scientia-ssdb   2121/tcp    # SCIENTIA-SSDB
nupaper-ss      12121/tcp   # NuPaper Session Service
nupaper-ss      12121/udp   # NuPaper Session Service
$

And with this horrible, horrible kluge effected we now start ftpd... (this is on a 10.11.6 system which has ftpd installed by default under /usr/libexec)
$ /usr/libexec/ftpd -lnDr -P 50001
$

And it is running as not-root at the not-21 port:
$ pgrep -lf ftpd
35258 /usr/libexec/ftpd -lnDr -P 50001
$ lsof -P -p 35258 | grep 2121
ftpd    35258 jhqdoe    4u   IPv4 0x817b7cd1effd8d7f       0t0      TCP *:2121 (LISTEN)
ftpd    35258 jhqdoe    5u   IPv6 0x817b7cd1effa3107       0t0      TCP *:2121 (LISTEN)
$

Whether this works or not I dunno; do you really need FTP?
To undo this change, sudo mv /etc/services.oops /etc/services


text:
Q: RDF, Triples, and Semantic Web in everyday apps Vague, uninformed questions:
1: Why do nearly 100% of app developers, app development communities and literature (books, tutorials, etc) take for-granted that you want to express data using either a relational database or a key-value store?
2: Why isn't everybody using "Triple" data structures?
3: Aren't Triples applicable to every problem that relational databses and key-value stores, and aren't Triples at least as easy to work with in every case?

A: Triples can represent any other data structure. But this doesn't necessarily make them easier to work with. If your problem is table-shaped, then a table data structure will work better. With a graph data structure, you need to think about how to make up tables from triples, and that's extra work.
Solving most problems (especially simple problems where the shape of your data is predictable) doesn't require the flexibility of a graph data structure.

A: *

*Most developers use relational databases and/or key/value stores because they're well known, widely taught, easily available, and adequate to most of what most developers care about doing.

*Most developers see little (if any) reason to use triples, except (possibly) for a few special purposes (and even the latter is somewhat unusual).

*No -- triples aren't particularly easy to use when most people don't understand them or how to use them. Even those developers who do understand them usually don't care about what they provide anyway.

More generally, I think quite a few developers quickly get lost in the inter-tangled mess of RDF, OWL, SKOS, ontologies, reasoning engines, etc. For somebody who's thinking: "but I just want the user's order history" (or whatever), it's all just a bit too much to take in, deal with, etc.

A: I have asked myself the exact same question before. Usually people cite complexity as the problem. That is really a bad habit, because the longer we leave the problem, the worse it will get. Semantic Web is a sophisticated solution to a complex problem. It doesn't get any easier. I think also that making comparisons of simplicity to RDBMS is naive. Most developers nowadays are familiar with ORM and work with abstracted persistence, some never aware of the persistence mechanism. The persistence frameworks for Semantic Web (ORDFM) are not typically as sophisticated or evolved. Having said that, a lot of organisations are moving away from RDBMS and investing in NoSQL solutions of which RDF and SPARQL are in my opinion the best candidates.
A great case study I always point out when people talk about Semantic Web being to complex is the Bart van Leeuwen story:
http://semtechbizsf2012.semanticweb.com/sessionPop.cfm?confid=65&proposalid=4590
If a genuine full time firefighter (who puts out real fires) can use SPARQL and RDF in place of databases and proprietary formats to solve a genuine problem (data accessibility in emergency service), then there is little excuse for the rest of us not to. My point is that its not the technology that is the barrier, it is something else.


text:
Q: the limit of a limit Is the following true in general?
(#):'If $\lim_{x \to a} f(x)$ exists, then there exists some neighbourhood $U$ of $a$ such that for every $y \in U$, $\lim_{x \to y} f(x)$ exists.'
Furthermore, if $f$ is a function such that (#) holds, is the following true?
$\lim_{y \to a}\left(\lim_{x \to y} f(x)\right)$ exists and is equal to $\lim_{x \to a} f(x)$.'

A: The first is not true for example consider
$$f(x)= x \cdot D(x)$$
where $D$ is the Dirichlet Function (the characteristic function of $\mathbb{Q}$.
The second one is true as the composition of the continuous function $x\mapsto x$ with $f(x)$ will be continuous.


text:
Q: Newton Raphson does not converge with certain initial guess  program newton_raphson
    implicit none
    real,parameter::error=1e-4
    integer::i
    real::xo,x1,f,fd
    print*,"Please enter the initial guess !!!"
    read*,xo
    i=1
    10 x1=xo-(f(xo)/fd(xo))
    if(abs((x1-xo)/x1)<error) then
    print*,"root is", x1,"no. of iteration=",i
    else
    xo=x1
    i=i+1
    goto 10
    endif
    end

    real function f(x)
    real::x
    f=cos(x)
    end

    real function fd(x)
    real::x
    fd=-sin(x)

    end

This program works fine when I give 1 as an initial guess, but fails or doesn't show up anything when I give 0 as an initial guess. Is there any mistake with my code.

A: Although the Newton–Raphson method converges fast near the root, its global
convergence characteristics are poor. The reason is that the tangent line is not always an acceptable approximation of the function, so could try to combine your code with bisection method, and this way you can improve the results.


text:
Q: Is there a useable command line profiling tool on OS X? I wanna use something like gprof to profile C/C++ programs on command line. But unfortunately gprof doesn't work on OS X for some reason (that's a known issue).
When I search this topic on internet, almost everyone recommends Instruments.app. As my workflow is entirely in command-line environment, I really don't want to switch to GUI just for some profiling.
So is there currently a usable alternative to gprof on OS X, which is purely command line based?
Edit: More specifically, I want to use the tool to analyze the runtime of each function in my program, to find out the hotspots.

A: There's a command line tool component of Instruments: the instruments command. You typically will want to use Instruments.app to view the resulting trace, though.
Besides that, there are lots of different tools. There's sample for simple time profiling. There's spindump. There's DTrace and a whole suite of ready-made DTrace-based tools. (See man -k dtrace for a list.)
You'll need to be more specific about what exactly you're hoping to investigate about your programs to a get a more specific suggestion.