text:
Q: PinterestSDK CocoaPods not working Has anybody recently successfully used the PinterestSDK CocoaPods?
This is the link I used as reference:
https://developers.pinterest.com/docs/sdks/ios/
I receive the below error:

Pre-downloading: PinterestSDK from
  git@github.com:pinterest/ios-pdk.git
[!] Error installing PinterestSDK [!] /usr/bin/git clone
  git@github.com:pinterest/ios-pdk.git
  /var/folders/2m/87ls355x7_7b50b61d9h3lkr0000gn/T/d20150924-16277-16zcydf
  --single-branch --depth 1
Cloning into
  '/var/folders/2m/87ls355x7_7b50b61d9h3lkr0000gn/T/d20150924-16277-16zcydf'...
Permission denied (publickey).**
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

CocoaPods are installed, dependency added in the created Podfile, other Cocoapods don't return the error.
Does anybody have a workaround?

A: Exactly this line in Podfile helps me to install Pinterest-SDK as Cocoapods:
pod "PinterestSDK", :git => "https://github.com/pinterest/ios-pdk.git"

A: Looks like the Pinterest SDK branch by MIT has been deleted or user specific, you can use a forked version:
pod 'PinterestSDK_5'

This happens when installing pod asks for Github username.


text:
Q: Looking for faster loops for big dataframes I have a very simple loop that just takes too long to iterate over my big dataframe.
value = df.at[n,'column_A']

for y in range(0,len(df)):
    index=df[column_B.ge(value_needed)].index[y]
    if index_high  > n:
        break

With this, I'm trying to find the first index that has a value greater than value_needed. The problem is that this loop is just too inneficent to run when len(df)>200000
Any ideas on how to solve this issue?

A: In general you should try to avoid loops with pandas, here is a vectorized way to get what you want:
df.loc[(df['column_B'].ge(value_needed)) & (df.index > n)].index[0]

A: I wish you have sample data. Try this on your data and let me know what you get
import numpy as np
index = np.where(df[column_B] > value_needed)[0].flat[0]

Then
#continue with other logic

redpajama_set_name: RedPajamaStackExchange


text:
Q: VS Code intellisense not working on a typescript Next.js project with Jest and Cypress, but tests run just fine I am trying to set up a new repository to start a new project using Next.js with typescript, using both Jest and Cypress and it works fine, my tests all pass with no issue, however my VSCode is still indicating some issue, I assume it to be related to intellisense problem?
Problem seen in my Jest test files:

Problem seen in my Cypress test files:

I have found similar issues but the solutions didn't seem to work here...
I have followed the instructions on how to make them work together, creating 2 tsconfig.json, one in the root directory, one in the cypress directory.
./tsconfig.json:
{
    "compilerOptions": {
        "baseUrl": "./",
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "types": ["jest", "node", "@types/testing-library__jest-dom"]
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules", "cypress"]
}

./cypress/tsconfig.json:
{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "noEmit": true,
        // be explicit about types included
        // to avoid clashing with Jest types
        "types": ["cypress"]
    },
    "include": [
        "../node_modules/cypress",
        "../tsconfig.json",
        "../package.json",
        "./**/*.ts"
    ]
}

./cypress.config.ts:
import { defineConfig } from 'cypress';

export default defineConfig({
    e2e: {
        baseUrl: 'http://localhost:3000/',
    },
});

./jest.config.ts:
import nextJest from 'next/jest';
// Sync object
const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
    dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig = {
    // Add more setup options before each test is run
    setupFilesAfterEnv: ['<rootDir>/support/setupTests.js'], // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
    moduleDirectories: ['node_modules', '<rootDir>/'],
    testEnvironment: 'jest-environment-jsdom',
    modulePathIgnorePatterns: ['cypress'],
};

module.exports = createJestConfig(customJestConfig);

./next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
    eslint: {
        dirs: ['pages', 'public', 'styles', 'cypress', '__tests__', 'support'],
    },
};

module.exports = nextConfig;

./package.json:
{
    "name": "front-end-base-repo",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint",
        "lint:fix": "next lint --fix",
        "format": "prettier --write .",
        "prepare": "husky install",
        "precommit": "lint-staged",
        "cy:open": "cypress open",
        "cy:run": "cypress run",
        "test:cy": "start-server-and-test start http://localhost:3000 cy:run",
        "test:jest": "jest --watch",
        "test:jest:ci": "jest --ci"
    },
    "dependencies": {
        "next": "12.1.6",
        "react": "18.2.0",
        "react-dom": "18.2.0"
    },
    "devDependencies": {
        "@testing-library/jest-dom": "^5.16.4",
        "@testing-library/react": "^13.3.0",
        "@types/cypress": "^1.1.3",
        "@types/jest": "^28.1.1",
        "@types/node": "18.0.0",
        "@types/react": "18.0.12",
        "@types/react-dom": "18.0.5",
        "@types/testing-library__jest-dom": "^5.14.3",
        "@types/testing-library__react": "^10.2.0",
        "@typescript-eslint/eslint-plugin": "^5.28.0",
        "cypress": "^10.1.0",
        "eslint": "8.17.0",
        "eslint-config-next": "12.1.6",
        "eslint-config-prettier": "^8.5.0",
        "eslint-plugin-jest-dom": "^4.0.2",
        "husky": "^8.0.1",
        "jest": "^28.1.1",
        "jest-environment-jsdom": "^28.1.1",
        "lint-staged": "^13.0.1",
        "prettier": "^2.7.0",
        "start-server-and-test": "^1.14.0",
        "ts-node": "^10.8.1",
        "typescript": "4.7.3"
    }
}

Here is a link to the whole repository to check all the configuration, I have tried on another computer and I had the same issue with VSCode showing the error in the editor, but all the tests run fine.
What I have found so far:

*

*Having /// <reference types="cypress" /> at the top of my cypress tests file seems to solve the issue, but adding /// <reference types="jest" /> on my jest files doesn't work.

*Having a ./cypress/cypress.d.ts file with a single line /// <reference types="cypress" />  solves the issue for cypress tests, VS Code do not show any more errors, but having a similar file for jest ./jest.d.ts or ./tests/jest.d.ts with /// <reference types="jest" /> doesn't solve the issue for my jest files, also tried adding other types like /// <reference types="@types/testing-library__jest-dom" />

*Adding "typeAcquisition": { "include": ["cypress"] } and
"typeAcquisition": { "include": ["jest"] } to the cypress and jest
tsconfig.json files doesn't change anything.

Current State
I have edited the file at ./cypress/support/e2e.ts to include /// <reference types="cypress" /> which solves the issue for Cypress test files, but I still got the VSCode errors showing up for Jest test files

A: I faced a similar problem. It is a good idea to set your computer's path variable.
How to do it:
1)Go to environment variables (search it on your computer)
2)Then go to path
3)Then edit it and add address of your compiler

A: For Cypress, add this to /cypress/support/e2e.ts, it will effectively give Cypress type info and intellisense to all tests.
/// <reference types="cypress" />

For problems with Jest expect
Remove "**/*.ts", "**/*.tsx" from the base tsconfig.json include list.
This entry should refer to types not source files.
{
  "compilerOptions": {
    ...
    "types": ["jest", "node", "@types/testing-library__jest-dom"]
  },
  "include": ["next-env.d.ts"],
  "exclude": ["node_modules", "cypress"]
}

index.test.tsx
expect(heading).toBeInTheDocument(); // intellisense: const expect: jest.Expect

A: You might be missing a couple things, namely:

*

*typescript transformer for jest (I recommend ts-jest since you already have ts-node).

*Configuring jest to use the transformer

If you go with ts-jest, then all you need to do is add the transform configuration option:
In package.json
"jest": {
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  }
}

OR In jest.config.ts
const customJestConfig = {
  preset: 'ts-jest'
}


text:
Q: ssh command is showing no such file or directory when executing within shell script I am trying to run a script in remote machine using ssh.
sshpass -p "" ssh abc@remote.com "bash -s" <  path/file.sh

When I execute this command normally, It is executing.
But when i put this into another shell script and executing it then it showing
no such file or directory

I tried putting #!/bin/bash in the top of code also.
But no use. Please can anyone help me?

A: Actually second time it runs on your local machine not on remote machine try following
ssh abc@remote.com "cd /home && ls -l"


text:
Q: How to add an array as row to DataGrid? In my program I have varying number of columns, so I've created universal input window for that which returns an array of strings

Now I want to add inputted data to DataGrid, but don't know how
Default DataGrid Add method supports only adding an object, so if I adding an array it just add spaces.

                InputWindow iw = new InputWindow(inputs.ToArray());
                if (iw.ShowDialog() == true)
                {
                    try
                    {
                        var strings = iw.GetInputs();
                        ActiveDataGrid.Items.Add(strings);
                    }
                    catch (ArgumentException ex)
                    {
                        Debug.WriteLine($"{ex.Message} from InputWindow");
                    }
                }

Strings from InputWindow returns correctly
How can I add these values corresponding to my varying number of columns?

A: You might consider creating a generic class that only contains string fields. Then feed your array to the class, and then feed the class object to the data grid.

A: I assume you mean you want to add 1 value from your array to each column for each item in the array. The simplest way to do this would be to create a DataRow for each input array formatting it according to how ever many items are in the array.
    DataRow row = dataGrid.NewRow();
    foreach (var item in array)
    {
            dataGrid.Columns.Add(item);
            row[item] = item;
    }
    dataGrid.Rows.Add(row);
    dataGrid.Import.Row(row);

This would work if your plan is to process the array items one at a time and you would clear the DataGrid after each import but if that is not the case you are going to need to create some amount of generic DataColumns then enumerate through the array and columns as much as necessary to place one item in each column.


text:
Q: how can i extract using regex in java I need to extract the extract this string as 2 document  example   test(s): testing
one is example and the other is testing ...please tell me how can i extract it...

A: You can use String.split() method to split the function to split words from sentence.
Example.
String sentence = "example tests(s): testing";
String[] words = sentence.split(" ");

for (String word: words) {
   system.out.println(word);
}

Found the example here: http://blog.codebeach.com/2008/03/split-string-into-words-in-java.html

A: Generally, you want to first come up with a pattern to match your input. Once you do that, and if the pattern doesn't do it already, simply put (...) brackets around the pattern that matches the part you're interested in. This creates what is called capturing groups.
With java.util.regex.Matcher, you can get what each group captured using the group(int) method.
References

*

*regular-expressions.info/Brackets for Capturing, Repeating a Capturing Group vs Capturing a Repeated Group

Example
Given this test string:
i have 35 dogs, 16 cats and 10 elephants

Then (\d+) (cats|dogs) yields 2 match results (see on rubular.com)

*

*Result 1: 35 dogs

*

*Group 1 captures 35

*Group 2 captures dogs

*Result 2: 16 cats

*

*Group 1 captures 16

*Group 2 captures cats


text:
Q: Getting message NDSolve::ndnum when solving my initial value problem I am eagerly learning Mathematica and trying to solve a initial value problem using NDSolve as follows. I'm running into the message NDSolve::ndnum.
ClearSystemCache;
ClearAll["Global`*"];

(*Saturation pressure (Pa) as function of Temperature (K) *)

psatR134a[T_] :=
  Module[{a = -33.7906321345355, b = 0.206544045004122,
   c = 4.03064679080556, d = 4780.59948872221, p}, p = (a + b*T)^c + d]

(*Saturation Temperature (K) as function of pressure (Pa) *)

tsatR134a[p_] :=
 Module[{a = -732.46, b = 13.733, c = 0.51826, d = 177.01, T},
  T = (a + b*Sqrt[p])^c + d]

dqdt[T_, p_, q_] :=
 Module[{A1 = 0.0859, A2 = 0.0566, B1 = 9.14 , B2 = -8.3,
   Tcri = 374.21(*K*), pcri = 4059.48*^3 (*Pa*), Ea := 7332.69 (*J/
   mol*), R := 8.3144 (*J/K.mol*), qt},
  qt = ((A1*(p/pcri) + A2)*Exp[-Ea/R/T]*(1. + (1. - Exp[-1.5*p/p])) +
      Exp[B1*(tsatR134a[p]/Tcri) + B2]*(1 - tsatR134a[p]/T))*(qR134a[
       T, p] - q)]

qR134a[T_, p_] :=
 Module[{q0 := 2.2 (*kg/kg*), Ea := 7332.69 (*J/mol*), n := 1.29,
   R := 8.3144 (*J/K.mol*), qs},
  qs = q0*Exp[-(R*T/Ea*Log[psatr134a[T]/p])^n]]

tOutlet[tIn_, tp_, aR_, uH_, mdot_, cp_] :=
 Module[{tAirOut}, tAirOut = tp + (tIn - tp)*Exp[-uH*aR/mdot/cp]]

tOutlet[298.15, 285.5760375366, 6.25, 15, 0.0851, 1006.6]

(* 289.785 *)

ClearAll[tads, tevap, mR134a, qa, var, vars, eqns, ics]

vars := {tads[t], tevap[t], mR134a[t], qa[t]};

eqns := Module[
   {

    mads = 10,
    cpads = 1375,
    cpR134a = 1400,
    mRr134a = 10,
    hgR134a = 420*^3,
    Qst = 325*^3,
    mHXE = 1.958,
    cpE = 910,
    mdotAir = 0.0851,
    cpAir = 1006.6,
    tAirIn = 298.15,
    uAir = 15,
    areaE = 6.25,
    },
   {

    (mads*cpads + qa[t]*cpR134a)*tads'[t] == Qst*mads*qa'[t],
    qa'[t] == dqdt[tads[t], psatR134a[tevap[t]], qa[t]],
    mR134a'[t] == -mads*qa'[t],
    (mHXE*cpE + mR134a[t]*cpR134a)*tevap'[t] == -hgR134a*mads*qa'[t] +
       mdotAir*
       cpAir*(tAirIn -
         tOutlet[tAirIn, tevap[t], areaE, uAir, mdotAir, cpAir])
    }
   ];

ics := {tads[0] == 303.15, tevap[0] == 303.15, mR134a[0] == 10,
   qa[0] == 0.05}

s = NDSolve[{eqns, ics}, vars, {t, 0, 300}]

During evaluation of this last line, I receive the message,

NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`. >>

I got the solution in Fortran as below.
Your help is greatly appreciated.

A: Function psatr134a is missing. If it is given as a Exp, then a solution can be obtained.
As pointed out by @xzczd in the comments, if psatr134a changed to psatR134a, a solution can be obtained.
ClearSystemCache;

ClearAll["Global`*"];

(*Saturation pressure (Pa) as function of Temperature (K)*)

psatR134a[T_?NumericQ] :=
 Module[{a = -33.7906321345355, b = 0.206544045004122,
  c = 4.03064679080556, d = 4780.59948872221, p}, p = (a + b*T)^c + d]

(*Saturation Temperature (K) as function of pressure (Pa)*)

tsatR134a[p_?NumericQ] :=
 Module[{a = -732.46, b = 13.733, c = 0.51826, d = 177.01, T},
 T = (a + b*Sqrt[p])^c + d]

dqdt[T_?NumericQ, p_?NumericQ, q_?NumericQ] :=
 Module[{A1 = 0.0859, A2 = 0.0566, B1 = 9.14, B2 = -8.3,
 Tcri = 374.21(*K*), pcri = 4059.48*^3 (*Pa*), Ea = 7332.69 (*J/mol*),
 R = 8.3144 (*J/K.mol*), qt},
 qt = ((A1*(p/pcri) + A2)*Exp[-Ea/R/T]*(1. + (1. - Exp[-1.5*p/p])) +
  Exp[B1*(tsatR134a[p]/Tcri) + B2]*(1 - tsatR134a[p]/T))*(qR134a[
   T, p] - q)]

  qR134a[T_?NumericQ, p_?NumericQ] :=
  Module[{q0 := 2.2 (*kg/kg*), Ea := 7332.69 (*J/mol*), n := 1.29,
  R := 8.3144 (*J/K.mol*), qs},
  qs = q0*Exp[-(R*T/Ea*Log[psatR134a[T]/p])^n]]

 tOutlet[tIn_?NumericQ, tp_?NumericQ, aR_?NumericQ, uH_?NumericQ,
 mdot_?NumericQ, cp_?NumericQ] :=
 Module[{tAirOut}, tAirOut = tp + (tIn - tp)*Exp[-uH*aR/mdot/cp]]

 tOutlet[298.15, 285.5760375366, 6.25, 15, 0.0851, 1006.6]

 ClearAll[tads, tevap, mR134a, qa, var, vars, eqns, ics]

 vars = {tads[t], tevap[t], mR134a[t], qa[t]};

 {mads = 10, cpads = 1375, cpR134a = 1400, mRr134a = 10,
 hgR134a = 420*^3, Qst = 325*^3, mHXE = 1.958, cpE = 910,
 mdotAir = 0.0851, cpAir = 1006.6, tAirIn = 298.15, uAir = 15,
 areaE = 6.25}; eqns = {(mads*cpads + qa[t]*cpR134a)*tads'[t] ==
 Qst*mads*qa'[t],
 qa'[t] == dqdt[tads[t], psatR134a[tevap[t]], qa[t]],
 mR134a'[t] == -mads*qa'[t], (mHXE*cpE + mR134a[t]*cpR134a)*
 tevap'[t] == -hgR134a*mads*qa'[t] +
 mdotAir*cpAir*(tAirIn -
   tOutlet[tAirIn, tevap[t], areaE, uAir, mdotAir, cpAir])};

ics = {tads[0] == 303.15, tevap[0] == 303.15, mR134a[0] == 10,
 qa[0] == 0.05}

 s = NDSolve[{eqns, ics}, vars, {t, 0, 300}]


text:
Q: How to use $_SERVER['REQUEST_URI'] Is there any difference between typing:
<?php echo $_SERVER[REQUEST_URI] ?>

or
<?php echo $_SERVER['REQUEST_URI'] ?>

or
<?php echo $_SERVER["REQUEST_URI"] ?>

?
They all work... I use the first one.
Maybe one is faster than the other?

A: The first one is wrong - you're actually looking for a constant REQUEST_URI that doesn't exist.  This will generate a notice-level warning.
There's no difference between the other two.

A: There is a difference between single and double quotes in PHP string handling. A string enclosed in double quotes will be evaluated for embedded variables and escape characters (e.g. \n); a string enclosed in single quotes won't (or not as much).
So, for example,
$hello = "world";

echo "Hello $hello!\n";
echo 'Hello $hello!\n';
echo 'Done';

will output

Hello world!Hello $hello!\nDone

In situations where you have no escape characters or embedded variables, it is slightly more efficient to use single quotes as it requires less processing of the string by the runtime. However, many people (me included) prefer to use double quotes for all strings to save confusion.

A: Without quotes PHP interprets the REQUEST_URI as a constant but corrects your typo error if there is no such constant and interprets it as string.
When error_reporting includes E_NOTICE, you would probably get an error such as:

Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in <file path> on line <line number>

But if there is a constant with this name, PHP will use the constant's value instead. (See also Array do's and don'ts)
So always use quotes when you mean a string. Otherwise it can have unwanted side effects.
And for the difference of single and double quoted strings, see the PHP manual about strings.

A: As a caveat to Gumbo's answer the third representation - double quotes - actually makes PHP look for variables inside that string. Thus that method might be a little slower (although in a string of 11 characters it'll be negligible - it's better practice not to make PHP do that however).

A: When PHP comes across plain strings being used as array keys it checks if there is a constant with that name and if there isn't it defaults it back to an array key. Therefore, not using quote marks causes a slight performance hit and there is a possibility that the result will not be what you expect.

A: $_SERVER[REQUEST_URI]

is syntatically incorrect and AFAIK will not run on a default installation of PHP5. The array index is a string so it needs to be passed on strings. I know PHP4 converted undefined constants to strings inside the square brackets but it's still not good practice.
EDIT: Well unless you define a constant called REQUEST_URI, which you haven't in your example script.
$_SERVER['REQUEST_URI']

is the standard method and what you should be using.
$_SERVER["REQUEST_URI"]

also works and while not wrong is slightly more work for the PHP interpreter so unless you need to parse it for variables should not be used. (and if you need to do so, you need to rethink that part of your program.


text:
Q: Почему не парсится конкретные id. Python Подскажите, пожалуйста почему не парсятся конкретные id?
Код:
tag = links_match.find_all('div', {'id' : re.compile('g.*')})

При запуске [].
Если на этом же сайте собирать любые другие id, то все ок. Пробовал собирать и маской и по точному вхождению, все равно [] на выходе.
Полный код:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

html_open = urlopen('https://www.myscore.ru/snooker/').read()
links_match = BeautifulSoup(html_open, "lxml")

tag = links_match.find_all('div', {'id' : re.compile('g.*')})
print(tag)

with open('links_match_myscore.txt', 'w') as f:
    for item in tag:
        url = item.get('id')
        f.write('\n' + '\n' + str(url))

A: Проблема в том, что эта страница уже изменена (вероятно она генерируется динамически), а ваши значения атрибута id уже не существуют.
Посмотрите, я немножко изменил часть вашей программы:
tag = links_match.find_all('div', {'id' : re.compile('g.*')})

with open('links_match_myscore.txt', 'w') as f:
    for item in tag:
        url = item.get('id')
        print(url)

и получил значения

lsadvert-background
project-debug
lsadvert-right_zone_2
userSettings
lsid-remember-login-form-content

Все эти значения имеют букву g, но нет там значений типа g15_xxxxxxxx.


text:
Q: Divisibility problem. In line written squares of natural numbers from 1 to 2012. How many of these numbers have a remainder when divided by 17, which is divisible by 3?

A: Hint:  make a list of the squares of the numbers $0$ through $16$ and compute the remainder on dividing by $17$.  See how many and which ones they are.  There are $\lfloor \frac {2102}{17} \rfloor=118$ complete cycles and a bit.


text:
Q: Conics and conics of the form $ax^2+by^2+c=0$ The problem of finding rational points on conics is usually discussed (for example in the book of Silverman and Tate) for conics of the form $ax^2+by^2+c=0$.
I assume that those conics are in bijection with all conics, in general of the form $ax^2+by^2+dxy+ex+fy+c=0$, through some natural transformation I haven't been able to think of.
Can someone give me any hints, or point me to a reference?
Note: I'm only interested in conics over the rational.

A: Alright, I will switch to Lehman's notation; here we have a quadratic form in three variables $x,y,z$ written as
$$ g(x,y,z) = a x^2 + b y^2 + c z^2 + r yz+szx + t xy. $$
At the end, you would want to set $z=1$ and set the mess to zero.
Set
$$ \Delta = 4ab - t^2 $$ and
$$ \delta = 4 a c - s^2.  $$
Then
$$ 4 a \Delta g = \Delta \left(2ax + ty + sz \right)^2 + \left( \Delta y + (2ar -st) z \right)^2 + \left( \Delta \delta -  (2ar -st)^2 \right) z^2  $$
Lehman's discriminant for the ternary form is
$$ 4abc + rst - a r^2 - b s^2 - c t^2, $$
or
$$
\frac{1}{2} \det
\left(
\begin{array}{rrr}
2a & t & s \\
t & 2b & r \\
s & r & 2c
\end{array}
\right)
$$
Another way to write the conclusion is
$$ 4 a \Delta g = \Delta \left(2ax + ty + sz \right)^2 + \left( \Delta y + (2ar -st) z \right)^2 + 4a \left(4abc + rst - a r^2 - b s^2 - c t^2 \right) z^2  $$
I do not see that there is anything particularly natural about this. It is just repeated completing the square, introducing coefficients so that there is not a giant denominator.


text:
Q: how to install geopandas properly tried most of the solutions around but still could not install geopandas properly on my device.
some of the errors ım getting

*

*ERROR: Failed building wheel for fiona

*ERROR: Command errored out with exit status 1:Check the logs for full
command output. FileNotFoundError: Could not find module 'geos_c.dll'
(or one of its dependencies). Try using the full path with
constructor syntax.

*A GDAL API version must be specified. Provide a path to gdal-config
using a GDAL_CONFIG environment variable or use a GDAL_VERSION
environment variable.

it is trying to find older version over and over for the packages but at the end, geopandas is not getting installed.
tried in different users and text editors.

A: It was a mess for me to succed installing geopandas too. I had to create a new environment (check how here), install manually part of geopandas dependencies, like pandas, shapely and fiona, and then install geopandas (version 0.10.2) through pip (it wasn't available at conda).
I know other people who managed to install it just followin this video tutorial instructions, after downgrading Python from 3.9 version to a lower one.
Good luck!


text:
Q: Struggling to get my animations to work on my first game I am trying to make my first game and have been struggling to get my animations to work.
I have been following along with a YouTube course and when it came to coding the animations on Unity i cannot seem to get it to work.
Please can someone who understands coding and Unity have a look at the following screenshots and help me out.
This is my code for my game:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    private Vector3 input;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Verical"));
        Rigidbody.AddForce(input * moveSpeed);
    }
}

I cannot get the white dot next to my Player Control script to light up and it will not work.
Any help is appreciated, thanks.

A: If you are able to change the script, then this is how I would do it:
Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}
void Update()
{
    float speed = 10f;
    float x = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
    float z = Input.GetAxis("Vertical") * speed * Time.deltaTime;

    rb.AddForce(x, 0f, z);
}

And freeze rotation along the x and a axis to not fall over. You can do this in the rigidbody component.


text:
Q: Mapping a dictionary in Fluent Nhibernate through a secondary key I have a legacy DB which uses a guid to map children to the parent entity.
In my domain layer, I'd prefer to obscure this quirk, so I'd like to have my parent entity look like this:
public class Parent
{
    virtual public int Id {get; protected set; }
    virtual public string ParentContent { get; set; }
    virtual public Guid ReferenceId { get; set; }
    virtual public IDictionary<int,Child> Children { get; set; }
}

public class Child
{
    virtual public int Id { get; protected set; }
    virtual public Parent { get; set; }
    virtual public string ChildContent { get; set; }
}

The parent would then map each Child.Id to Child in the Children dictionary. The Child mapping works fine, but I can't seem to find a reasonable mapping for the parent.
A field named ParentReferenceID exists in both Parent and Child tables, so I've attempted to map this with something like this:
        mapping.HasMany<Broker>(x => x.Children)
            .Table("Child")
            .KeyColumn("ParentReferenceID")
            .Inverse()
            .AsMap<long>(index=>index.Id,val=>val.Type<Broker>());

Unfortunately, this produces an error:
The type or method has 2 generic parameter(s), but 1 generic argument(s) were provided. A generic argument must be provided for each generic parameter.
To simplify my problem, I started by trying Bag semantics, replacing the Parent's IDictionary with an IList.  This was mapped using something like:
  mapping.HasMany<Broker>(x => x.Brokers)
     .Table("Child")
     .KeyColumn("ParentReferenceId")
     .Inverse()
     .AsBag();

That produces the more obvious exception,
    System.Data.SqlClient.SqlException: Operand type clash: uniqueidentifier is incompatible with int
Unfortunately, I can't seem to figure out the right way to tell it to join on the ReferenceID field. What's the right way to do that? I'd prefer the dictionary, but I'd be reasonably happy if I could even get the bag to work.
For clarity, I'm using a build of Fluent that is bundled with a recent SharpArchitecture pulled from git. The Fluent dll is marked version 1.0.0.594, but if a more recent build would help, I'm flexible.

A: Further digging has led me to a solution for the Bag case, though the dictionary is still giving me a bit of trouble.
The solution requires a patch to Fluent NHibernate's OneToManyPart mapping class. (Hat tip to This bug report: Could not map a one-to-many relationship where the key is not the primary key.
   mapping.HasMany(x => x.Children)
       .Table("Child").KeyColumn("ParentReferenceId")
       .PropertyRef("ReferenceId")
       .Inverse()
       .AsBag();

Theoretically, AsMap should work almost the same way, but for some reason that I'm not entirely clear on, it doesn't work for me. I'll explore that later, but I'm open to suggestions.


text:
Q: How to open a root terminal I am a person that is new to xubuntu using crouton on a chrome book I was wondering how to get the Root terminal open. The reason I want to do this is so I can modify some files that ware left behind by installing wine and removing it
( Yes I used -Remove -Autoremove and -Purge) I can not do this and also I am morbidly curious so I would like access to the root terminal

A: Using your admin account open a terminal with controlaltT and type ...
sudo -i

the will ask for the admin password, and then show a #. Mind that is terribly easy to royally mess up your system when using #.
Mind though this is not required for what you need to do. When you want to remove something you do not own put sudo in front of the command and it will remove it.
If there is anything remaining from deleting wine it should be in /home/$USER/.wine and all the should be needed is to remove that directory.


text:
Q: Resizing 2 dependent bootstrap columns with Angular (2) I have a simple bootstrap layout with 2 column (4:8).

 I want to make the columns resizable in tandem with each other.
After solving the challenge with jQuery I'd like to use AngularJS (preferably 2). I found a sample for a single box (and its source), but wonder what a good Angular2 component approach would be:

*

*create 2 components and use glue code to resize them

*create 1 component with 2 columns (and 2 areas to fill content in)


text:
Q: In TOAD: Is it possible to add custom validation on user/schema field in Toad for Oracle Recently we are seeing security violation as users were sharing credential with other. We would liked to enforce validation on user field so that we can detect the violation before it reaches database
I could see options are available to execute app/action upon connect, but this wont help us as users would've connected to DB using others credentials already. Need to stop the connection if validation fails


text:
Q: Modem software install problem Did an update to Ubuntu 16.04LTS yesterday unfortunately now Ubuntu is giving the messages:

Optus 4G Mobile" contains software intended to be automatically started. Would you like to run it?

and

Oops! There was a problem running this software. Unable to locate program.

Have used terminal to enter as root, navigated to the linux_mbb_install directory i.e. Optus 4G Mobile/linux_mbb_install/ but entering and executing install does not do what is required.
Any suggestions?
Optus E3372 4G USB modem has:
Optus 4G Mobile/HiLink.app
Optus 4G Mobile/linux_mbb_install
Optus 4G Mobile/MobileBrServ
Optus 4G Mobile/ArConfig.dat
Optus 4G Mobile/autorun.sh
Optus 4G Mobile/AutoRun.exe
Optus 4G Mobile/AUTORUN.INF
Optus 4G Mobile/install_linux
Optus 4G Mobile/Startup.ico

Optus 4G Mobile/linux_mbb_install/7zr
Optus 4G Mobile/linux_mbb_install/ArConfig.dat
Optus 4G Mobile/linux_mbb_install/install
Optus 4G Mobile/linux_mbb_install/mbbservice.bin
Optus 4G Mobile/linux_mbb_install/readme.txt


text:
Q: How to track downloads using php I have simple cakephp site. I want to track the downloads of the files in the webroot/files folder.
Is there a way to track it.
I appreciate any help.

A: Have a look at CakePHP's Media views. This will allow you to easily serve files using PHP, allowing you to increment a counter in the database when downloads occur.


text:
Q: Oshin like html template I need to work on a similar design as is used in this website http://www.zaman.ae/, They are  using Oshin template which unfortunately is only available for word press plugin only, how can i create something similar in design as is used for this website.
Any pointer would be of great help or a similar template which i can use for HTML page.

A: Two ways:

*

*Find a structure-similar template for wordpress and edit it
    to ressemble zaman's layout.

*Create your own wordpress template.


text:
Q: How can I change the path for root permanently in solaris sparc? I have edited /etc/profile but the path only gets changed for normal users whereas the change does not reflect for root, how can I make it such that the path also gets changed for root?

A: On Solaris, regular users and root default PATH are defined in /etc/default/login and /etc/default/su in the PATH & SUPATH variables.

A: root uses a different shell from everybody else; or very definitely should: /bin/sh
If you used bash/ksh syntax:
export PATH=${PATH}:/new/path1:/new/path2

...will not work.
PATH=${PATH}:/new/path1:/new/path2
export PATH

This fits /bin/sh syntax


text:
Q: Trigger Power Button Action? for my app i want to stop the screen off function
yes i just want to make it(Screen off function by pressing power button) disable that when user press power but and my app is running then screen must not off will give an toast message is it possible?
Goal :

*

*Disable auto screen timeout.
Done using this

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

used this post
now my first question is when my app will finish() time out will reset or screen will always on
2. Still using this user will be able to make screen off
My second question is
Can i prevent user to do this and instead of screen get off an alert message is shown

A: In your Activity just add the following snippet:
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
        // do nothing but show a warning message
        Toast.makeText(this, "you pressed the power button",Toast.LENGTH_SHORT).show();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

In case the above snippet doesn't work,you can try this then:
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
        //do nothing but show a warning message
        Toast.makeText(this, "you pressed the power button",Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.dispatchKeyEvent(event);
}


text:
Q: When ListView has no data, OnScrollListener's onScroll can not be fired? I need to load more data when user scrolls to near the end of the listview.
When ListView's adapter has no data, OnScrollListener's onScroll can not be fired!
When the ListView's setAdapter be called, the OnScrollListener's onScroll will be called. But when user push the screen and scroll the ListView(which has no data), the OnScrollListener's onScroll has not been call.
When ListView has at least on row, the OnScrollListener's onScroll will be called if user scroll the listview.

A: What I do is call setAdapter just once, in my onCreate method using an ArrayAdapter. I pass in a List which I maintain a reference to. When I want to add more items, I add them to this list. Then I call adapter.notifyDataSetChanged.
In this manner, you can add more items to the end of your list when the user gets to the bottom, and not clear your ListView or set a new Adapter.


text:
Q: Benchmarks for new M1 MacBooks Are there any benchmarks yet for Mathematica 12.1 on the new (13") M1 MacBook Air or (13") M1 MacBook Pro?

A: Mathematica 12.3.1 as of July 2021, supports native Apple M1, my benchmark on a M1 Macbook pro, 16GB is:
{"MachineName" -> "laederlappen",
"System" -> "Mac OS X ARM (64-bit)",
"BenchmarkName" ->
"WolframMark",
"FullVersionNumber" -> "12.3.1",
"Date" -> "July 9, 2021",
"BenchmarkResult" -> 3.147,
"TotalTime" -> 4.398,
"Results" -> {{"Data Fitting", 0.191}, {"Digits of Pi", 0.171},
   {"Discrete Fourier Transform", 0.307}, {"Eigenvalues of a Matrix", 0.453}, {"Elementary Functions", 0.606}, {"Gamma Function", 0.221}, {"Large Integer Multiplication", 0.187}, {"Matrix Arithmetic", 0.145}, {"Matrix Multiplication", 0.302}, {"Matrix Transpose", 0.181}, {"Numerical Integration", 0.322}, {"Polynomial Expansion", 0.048}, {"Random Number Sort", 0.399}, {"Singular Value Decomposition", 0.545},{"Solving a Linear System", 0.32}}}

Update
With a newly reset computer, and a newly reset kernel (completely fresh started mathematica) I wrote a little script to force the benchmark to be done 100 times in a row, in the hopes that the cpu would ramp up some more and give a better result:
Needs["Benchmarking`"]
results = Benchmark[] (*first run to see what it starts with cold*)

things = {};
Do[AppendTo[things, results = Benchmark[]], 100];
data = Table[
"BenchmarkResult" /. things[[i, 1, 6]], {i, 1, Length@things}];
ListLinePlot[data, ImageSize -> Large, Frame -> True, FrameStyle -> Black, GridLines -> Automatic]

Max[data]

(3.22)
Running through rosetta2, I got a max result of ~2.7...there is some improvement, but not the jump to around 3.7 or so I expected.
In this answer a user with a M1 macbook air got a result of 3.2, though they haven't said if that was their first attempt or not...I would find that somewhat strange, being that my machine has active cooling, and an extra core, while theirs has neither...
I would speculate that a different kind of benchmark needs to be developed with different work loads to really push the CPU...things mathematica used to chock on, on my other machines (even my AMD 3800x) my M1 cuts through fine...


text:
Q: What are the ways to put multiple string keys in couchbase in faster way ? I do not see bulkPut() like bulkGet() for couchbase client What are the ways to put multiple string keys in couchbase in faster way ?
I do not see bulkPut() like bulkGet() for couchbase client .

A: For Couchbase Java SDK there is an open enhancement https://issues.couchbase.com/browse/SPY-126 to add this functionality.
However, its possible to do "batch" insert:
// Insert them in one batch, waiting until the last one is done.
Observable
    .from(documents)
    .flatMap(new Func1<JsonDocument, Observable<JsonDocument>>() {
        @Override
        public Observable<JsonDocument> call(final JsonDocument docToInsert) {
            return bucket.async().insert(docToInsert);
        }
    })
    .last()
    .toBlocking()
    .single();

And batch read:
while(true) {
    int docsToLoad = 10;
    Observable
        .range(0, docsToLoad)
        .flatMap(new Func1<Integer, Observable<?>>() {
            @Override
            public Observable<?> call(Integer i) {
                return bucket.async().get("doc-"+i);
            }
        })
        .toList()
        .toBlocking()
        .single();
}

See more on bulk operations
For Node.js client set-multi is suppoerted: http://www.couchbase.com/autodocs/couchbase-node-client-1.2.1/Connection.html#setMulti


text:
Q: reveal.js #+ATTR_REVEAL: :frag - list alignment I have a strange problem when exporting org-mode presentations to HTML via reveal.js:

*

*Topic
+ATTR_REVEAL: :frag appear

*Item 1

*Item 2

*Item 3

aligns the bullet points correct (left)
but if I want to show the items one by one:

*

*Topic
+ATTR_REVEAL: :frag appear

*Item 1
+ATTR_REVEAL: :frag appear

*

*Item 2

+ATTR_REVEAL: :frag appear

*

*Item 3

they get mixed up like this:

*

*Item 1 * Item 2

*

*Item 3

this happens also with "frag roll-in", "frag grow", etc.
when looking into the HTML file, I find no differences
has anyone an idea?

A: Just figured it out:
+ATTR_REVEAL: :frag (appear appear appear...)
does the trick.

A: Expanding on @muteaudio's answer, here is what the "lists can / be fragmented" § should look like in the documentation:
#+ATTR_REVEAL: :frag (roll-in roll-in)
    - Lists can
    - be fragmented.


text:
Q: Calling typeof operator in jQuery Template data tags? Is it possible to call typeof(x) within a data rendering template tag?
${typeof(x)}

Obligatory example jsFiddle
Workaround
I can alias the typeof operator as a custom template function and it works fine, but I would like to avoid that extra level of redirection if I can.
// calling JavaScript
$("#reflectTemplate").tmpl(data, {
    getType: function(itemToCheck) {
        return typeof(itemToCheck);
    }
}).appendTo(".results");

<!--template tag-->
${$item.getType(prop)}

A: What you want is to force the result to be a string. One or both of these should work in most browsers:
${String(typeof(prop))}
${typeof(prop)+''}


text:
Q: JQuery Validator Showing Remote Response I am trying to show the response of the remote rule, possibly in the same place as the other responses. What I want to show is the response the PHP is sending me. I can easily show it in the console.log, but don't know how to show the result underneath the field
$("#conversionForm").validate({

    // Specify the validation rules
    ignore:[],
    rules: {
        "URL[]": {
            required: true,
            minlength: 3,
            pattern: yt,
            remote:  {url:"checkdescription.php",
                type: "post",
                beforeSend: function () {

                },complete: function (response) {
                    console.log(response.responseText); //This is what I would like to show

                   $(this).closest('.form-group').text(response.responseText) // This doesnt work
                },
                onkeyup: false
            }

        }

    },
    messages: {
        "URL[]": {
            required: "
This field is required
",
            pattern: "
Enter a valid URL  of the type https://www.youtube.com/watch?v=ZDO4I5aT0hg
",
            minlength:"
Enter a valid URL
",
            remote:<some invalid message dependent on the php response, too> //help here too
        },
        success: function(e) {

        }
    },

});

Basically I want to customize both error and success messages depending on the php response; if i can only send true or false back, then what other method do you think should i use?
Thank you
Edit: HTML
<form role="form" action="index.php" method="post" id="conversionForm">

                <input type="text" class="form-control" id="youtubeURL-0" name="URL[]" placeholder="Enter your URL here">

            <button type="submit" id="btn-submit" name="submit" >Submit</button>

</form>

After this I add more divs exactly like .row #input-0 with jquery (#input-1, #input-2, etc) (appending them to #to-append). For each input, the remote php returns a different number, i want to show that number somwhere near the input field. Basically, show the validation remote answer


text:
Q: Subtracting values of two maps whenever there is a key match? I'll explain the logic: I am reading a XML file which contain many request and responses in soap format then I'm storing the request and response in two Hash map. In first Hash map I'm storing transaction Id(unique) as key and values as request time,til-name. In second hash map I'm storing transaction Id(unique) as key and values as response time. In both hash map the keys are same but values are different, by using for loop iterating two loops and I need to get the time difference between response time and request time
eg:request time:2020-01-30T11:07:08.351Z and response time:2020-01-30T11:07:10.152Z
public class MapTimeDiff {
public static void main(String[] args) throws ParseException {

File file =new File("C:\\Users\\gsanaulla\\Documents\\My Received Files\\ecarewsframework.xml");
        Scanner in = null;
        String tilname = null;
        String transactionId = null;
        String requesttime = null;
        String responsetime = null;
        Date dateOne = null;
        Date dateTwo = null;
        double timeDiff;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        Map<String,ArrayList<String>> request=new HashMap<String,ArrayList<String>>();
          ArrayList<String> req=new ArrayList<String>();
        Map<String,ArrayList<String>> response=new HashMap<String,ArrayList<String>>();
        ArrayList<String> res=new ArrayList<String>();
        try {
            in = new Scanner(file);
            while(in.hasNext())
                {
                String line=in.nextLine();
                if(line.contains("</S:Envelope>")) {
                    System.out.println(line);

                    tilname=line.split("StartRecord><")[1].split("><")[0].split(":")[1];
                    System.out.println("tilname :: "+tilname);
                    transactionId = line.split("transactionId>")[1].split("<")[0];
                    System.out.println("transactio id :: "+transactionId);
                    requesttime=line.split("sourceTimestamp>")[1].split("<")[0];
                    System.out.println("request time is :: "+requesttime);
                    dateOne = df.parse(requesttime);

                }
                req.add(tilname);
                req.add(dateOne.toString());
                System.out.println("req is==== " +req);
                request.put(transactionId,req);
                System.out.println("request is==== " +request.get(transactionId));
                    if(line.contains("</SOAP-ENV:Envelope>")) {
                        //System.out.println(line);

                          if(line.contains("transactionId"))
                          {
                              responsetime=line.split("sourceTimestamp>")[1].split("<")[0];
                              transactionId = line.split("transactionId>")[1].split("<")[0];
                              System.out.println("responsetime :: "+responsetime);
                              System.out.println("transaction id "+transactionId);
                              dateTwo = df.parse(responsetime);

                          }
                          res.add(dateTwo.toString());
                          System.out.println("res is===== "+res);
                          response.put(transactionId,res);
                          System.out.println("response is===== "+response.get(transactionId));
                        for (Entry<String, ArrayList<String>> entry : request.entrySet()) {
                              for (Entry<String, ArrayList<String>> entry1 : response.entrySet()) {
                             System.out.println("Key = " + entry.getKey() +
                                         ", Value = " + entry.getValue());
                              System.out.println("Key = " + entry1.getKey() +
                                         ", Value = " + entry1.getValue());
                                  if(request.keySet().equals(response.keySet())) {
                                      timeDiff = (dateTwo.getTime() - dateOne.getTime());
                                  }
                          }
                          }
}
      }
        }

           catch (FileNotFoundException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                 }

    }

}

A: I'm not sure if I understood your question correctly but maybe you can do something similiar like the following:
Map<String, List<String>> requests = Map.of("1", List.of("10,13,12"), "2", List.of("8,7,9"), "3", List.of("11"));
Map<String, List<String>> responses = Map.of("1", List.of("9,10,14"), "2", List.of("8,9,6,12"));

for(Map.Entry<String, List<String>> requestEntry : requests.entrySet()) {
    String transactionId = requestEntry.getKey();
    if(responses.containsKey(transactionId)) {
        System.out.println("Transaction Id: " + transactionId);
        for(int i = 0; i < min(requestEntry.getValue().size(), responses.get(transactionId).size()); i++) {
            List<String> requestTimes = asList(requestEntry.getValue().get(i).split(","));
            List<String> responseTimes = asList(responses.get(transactionId).get(i).split(","));
            for(int j = 0; j < min(requestTimes.size(), responseTimes.size()); j++) {
                int requestTime = parseInt(requestTimes.get(j));
                int responseTime = parseInt(responseTimes.get(j));
                System.out.println("Difference: " + abs(requestTime - responseTime));
            }
        }
    }
}

As you can see there are no responses for transactionId 3 so this will be ignored.
If elements in the list for a key differ in size (transactionId 2) the surplus elements will also be ignored.
Transaction Id: 1
Difference: 1
Difference: 3
Difference: 2
Transaction Id: 2
Difference: 0
Difference: 2
Difference: 3


text:
Q: prove command not passing arguments after arisdottle to I'm trying to pass some parameters to a test script through the prove command. Based on some old threads where is option was hashed out, and the content's of my prove's man page (quoted below), using :: before the options should work, but prove is still parsing the test script's option as it's own:

$ prove -v t/040-unit-object-test.t :: --unit 270149
Unknown option: unit

Here the relevant part of the man page:

   Arguments to Tests

  It is possible to supply arguments to tests. To do so separate them
  from prove's own arguments with the arisdottle, '::'. For example

   prove -v t/mytest.t :: --url http://example.com

  would run t/mytest.t with the options '--url http://example.com'.  When
  running multiple tests they will each receive the same arguments.

I tried using sudo to run the option as root, but got the same error.
I am using the Getopt::Long module to get the options, and the options work when I run the test script using plain old perl, but then my SKIP and TODO blocks don't work.
I would rather not have to use the --exec workaround.
I'm running Perl 5.10 on Mac OS 10.6.
The output of prove -V is:

prove v2.64, using Test::Harness v3.25 and Perl v5.10.0

A:  Well, you must have two versions of prove in your $PATH, an old one from 2006 from before App::Prove existed  I suggest you delete that one, and re-install App::Prove


text:
Q: what differences between verbal noun and gerund? some verbs can be used as nouns,so what differences between verbal noun and gerund?
for example:
1.Winning is not everything. (does "win" work?)
2.Please return it after use.(does "using" work?)
3.Walking is a good form of exercise for both young and old. (does "walk" work?)
please give me the reasons,or if both work,any different meanings? thank you!

A:

*

*Winning is not everything. (does "win" work?)

Yes, but as a verb it would need to be in the to-infinitive form: "To win is not everything". It sounds very formal, but sayings like this often are - for example "to know is to understand". As a noun it would be "a win is not everything".

*Please return it after use. (does "using" work?)

"Using" could work, but only as a verb. As this is an instruction or command - the kind you might see on a sign or notice - the strict rules of grammar do not always apply. As a noun, "use" is countable, so if you wanted it to be grammatical rather than instructional you might want to say "after each use".

*Walking is a good form of exercise for both young and old. (does "walk" work?)

"Walk" as a verb doesn't sound right. It would have to be "To walk is good exercise", which may be grammatically correct as in your first question, but it isn't at all idiomatic, I can't imagine anyone saying it. As a noun, it would be "a walk is a good form of excercise.


text:
Q: python function output writing to a file I would like to create output files FileA and FileB which includes output from different function calls. Is it better to pass 'file' as argument to each of appropriate function and append to it? Or is there any other intelligent way to handle it? Thanks!
Output:
FileA contains OutA1, OutA2
FileB contains OutB1, OutB2

(python2.7)

def taskA1_func:

  for lines in :
    yield OutA1

def taskA2_func:

  for lines in :
    yield OutA2

def taskB1_func:

  for lines in :
    yield OutB1

def taskB2_func:

  for lines in :
    yield OutB2

write_to_file_func:
    creates file FileA and FileB

main()

A: As of Python 2.7 (or 3.1 respectively) you can use:
with open('FileA.txt', 'a') as FileA, open('FileB.txt', 'a') as FileB:
    FileA.write('something')
    FileB.write('something else')


text:
Q: How to filter one dataset value with another dataset Table value in SSRS How to filter one dataset table with another dataset Table value in SSRS.

A: Not sure if there is a better way to do this in SSRS 2005, but this should work:

*

*Create dataset A.  This will be your filter dataset.  You should return only one value column.  (If you need multiple values, you'll have to join them)

*Create a new report parameter called ParameterA.  Set both the available values and the default values to the value column result from the dataset A.  Set the parameter to Hidden (I think Internal might be a better choice..try it out)

*Create a second dataset B.  Add ParameterA as a parameter to dataset B, called @parameterA.

*In your query, use the parameter like this:

SELECT blah blah WHERE valueColumn IN (@parameterA)

This should do what you're looking for.  It's not pretty, but it should work.

A: To filter second dataset, like Master/Details you need to use subreport, place second dataset in subreport and filter it by subreport parameter. Subreport, when placed on the report can have parameter value from the field of the first dataset.


text:
Q: How to fill dataframe value based on row:column position key-value? Suppose I have a dataframe
id   0   1   2

001  0   0   0
003  0   0   0
007  0   0   0

and a dataframe of {id:column} , for example
id   col
001   2
007   0

How can I put value in dataframe to become
id   0   1   2

001  0   0   1
003  0   0   0
007  1   0   0

I think using apply / applymap with list comprehension is the way but still cannot figure out.

A: IIUC you can crosstab and update:
df = pd.DataFrame({'id': {0: 1, 1: 3, 2: 7}, 0: {0: 0, 1: 0, 2: 0}, 1: {0: 0, 1: 0, 2: 0}, 2: {0: 0, 1: 0, 2: 0}})
df2 = pd.DataFrame({'id': {0: 1, 1: 7}, 'col': {0: 2, 1: 0}})

df = df.set_index("id")

df.update(pd.crosstab(df2["id"], df2["col"]))

print (df.reset_index())

   id    0  1    2
0   1  0.0  0  1.0
1   3  0.0  0  0.0
2   7  1.0  0  0.0


text:
Q: How to set a delay to a function? I know this question can be answered in many ways but I need someone to do this for me. I want my animation to do its thing and then a random number pops up? Right now I have 2 functions in one click (I need that). I'm new to this and a simple formula would be great! Can anyone help, if you can it would be appreciated! Thank you!
THIS IS ALL THE CODE!

startbtn = function() {
  $('.wheel').addClass('animated-wheel');
  setTimeout(setRandom('random') {}, 6000);
}

function getRandom() {
  var values = [1, 15, 30, 45];
  return values[Math.floor(Math.random() * values.length)];
}

function setRandom(id) {
  document.getElementById(id).innerHTML = getRandom();
}

function refresh() {
  location.reload();
};
.number {
  text-align: center;
  color: white;
  font-size: 78px;
}

.wheel {
  width: 200px;
  height: 100px;
  left: 600px;
  top: 300px;
  background: green;
  position: relative;
}

.animated-wheel {
  -webkit-animation: myfirst4s 2;
  -webkit-animation-direction: alternate;
  animation: myfirst 4s 2;
  animation-direction: alternate;
}

@-webkit-keyframes myfirst {
  0% {
    background: green;
    left: 600px;
    top: 300px;
  }
  33% {
    background: black;
    left: 600px;
    top: 0px;
  }
  66% {
    background: red;
    left: 600px;
    top: 650px;
  }
  100% {
    background: black;
    left: 600px;
    top: 0px;
  }
}

@keyframes myfirst {
  0% {
    background: green;
    left: 600px;
    top: 300px;
  }
  33% {
    background: green;
    left: 600px;
    top: 300px;
  }
  66% {
    background: black;
    left: 600px;
    top: 0px;
  }
  100% {
    background: red;
    left: 600px;
    top: 650px;
  }
}

<!DOCTYPE html>

<title>The Wheel!</title>

  <button onclick="startbtn();setRandom('random');">Start</button>
  <button onclick="refresh()">Reset</button>

A: There are tons of more elegant way but here is correction of your error:
setTimeout(function(){
    setRandom('random')
}, 6000);

A: You had a syntax error in your setTimeout():

startbtn = function() {
  $('.wheel').addClass('animated-wheel');
  setTimeout(function() {
    // Remove animation class
    setRandom('random');
    $('.wheel').removeClass('animated-wheel');
  }, 6750);
}

function getRandom() {
  var values = [1, 15, 30, 45];
  return values[Math.floor(Math.random() * values.length)];
}

function setRandom(id) {
  document.getElementById(id).innerText = getRandom();
}

function refresh() {
  location.reload();
};

<!DOCTYPE html>

<title>The Wheel!</title>

  <button onclick="startbtn();">Start</button>
  <button onclick="refresh()">Reset</button>

Hope this helps,


text:
Q: jQuery function doesn't exit after return I have this jQuery code part:
$.each(myArray, function(index, val) {

  if (val == "Test" ) {

     console.log("FOUND")
     return

  }

});

console.log("DEBUG")

I get both logs:
"FOUND" and "DEBUG"
But I would like to exit the function directly after the value was found.
I guess that my "return" only exit the loop, but not the whole function.
Is there any solution that I can exit the loop and exit the function in one line?


text:
Q: Typescript changes type of Map value I am newbie in TS and need some help. I've got really weird behavior of TS. I try to make a map of arrow functons and then call them by their name. Look at this
const first = (x: string): string => x.toUpperCase();
const second = (x: number): number => x ** 2

type FirstType = typeof first;
type SecondType = typeof second;

type MyUnion = FirstType | SecondType;

const handlers = new Map<string, MyUnion>();
handlers.set('first', first);
handlers.set('second', second);

// here myHandler has this type, as predicted:
// MyUnion | undefined
const myHandler = handlers.get('first');
if (myHandler) {
    // but here myHandler somehow has this type:
    // (x: never) => string | number

    // that's why i got this error
    // Argument of type 'number' is not assignable to parameter of type 'never'.(2345)
    const a = myHandler(10)

    // Argument of type 'string' is not assignable to parameter of type 'never'.(2345)
    const b = myHandler('asd')

}

Could enybody explain what's going on here? Why TS has changed type of the value of the map?

A: That's because your map returns a function whose only parameter is an intersection of all the possible types, and number & string have no overlap, hence the never.
The reason why it's invalid is because it assumes you will call the returned handler with a parameter whose type is valid for all of the registered handlers.
You could eventually do a discriminated union to allow this:
Playground
interface StringHandler {
  type: 'string';
  handler: (x: string) => string;
}

interface NumberHandler {
  type: 'number';
  handler: (x: number) => number;
}

type HandlerUnion = StringHandler | NumberHandler

const handlers = new Map<string, HandlerUnion>();
const first: StringHandler = {
  type: 'string',
  // Notice x is already inferred as a string
  handler: x => x.toUpperCase(),
}
const second: NumberHandler = {
  type: 'number',
  // Notice x is already inferred as a string
  handler: x => x ** 2,
}

handlers.set('first', first);
handlers.set('second', second);

const myHandler = handlers.get('first');
if (myHandler) {
  // This check ensures the handler is a StringHandler thanks to the discriminant "type" property
  if (myHandler.type === 'string') {
    myHandler.handler('asd')
  }
  // This check ensures the handler is a NumberHandler thanks to the discriminant "type" property
  if (myHandler.type === 'number') {
    myHandler.handler(10)
  }
}

A: The map has nothing to do with it; the issue is with your MyUnion type:
declare const foo: MyUnion;
foo(0);
//  ^
// Argument of type 'number' is not assignable to parameter of type 'never'.

When you union two TypeScript functions, the compiler doesn't know what the actual type of your parameters will be at runtime; without more information, it can only choose a type that satisfies all possibilities. In the case of your union, that type is never since number and string have no overlap.
Consider this example where the two function types do overlap:
interface Pet {
  name: string
}

interface Dog extends Pet {
  breed: string
}

declare function getBreed(d: Dog): string
declare function getPetType(p: Pet): string
declare const fn: typeof getPetType | typeof getBreed;
declare const p: Pet;
declare const d: Dog;

fn(d); // ok
// type hint:
//  const fn: (d: Dog) => string
fn(p);
// ^
//  Argument of type 'Pet' is not assignable to parameter of type 'Dog'.

Playground.
Here, Dog was the only type that satisfies both Pet and Dog.
This is related to the concept of contravariance.


text:
Q: How to run ajax in certain time interval in Magento2 I have added ajax to show a text which is fetched from my scope config(The value is given in the store->configuration). In my controller I am getting the value using scope config and used echo in it.
In my ajax function, I am using the url of my controller to print the data in html div tag. I want to make the ajax function running all the time, so that if I change the value the ajax has to update the text automatically without any action.

A: use https://www.w3schools.com/jsref/met_win_settimeout.asp
setTimeout(function(){ callAjaxRequest(); }, 3000);

A: "If I change the value" according to this use the onChange jquery function to get it to work. Now if this is coming from store config (I guess not too much data) you can save all values into JS variable using block or helper and use it using the onChange function which will be faster compare to ajax calls.


text:
Q: Optional with Lombok custom build method says non-static variable cannot be referenced Given the following code.
@Getter
@Builder(builderClassName = "Builder", buildMethodName = "build")
public final class BusinessEvent implements BusinessPayload {
  private String action, duration, outcome, provider, trackId, sequence;
  @lombok.Builder.Default private Optional<String> brand, vin, externalTrackId, code = Optional.empty();
  @lombok.Builder.Default private Optional<BusinessEventError> eventError = Optional.empty();

  static class Builder {
    BusinessEvent build() throws MissingRequiredValueException {
      // Custom validation
      return new BusinessEvent(action, duration, outcome, provider, trackId, sequence, brand, vin, externalTrackId, code, eventError);
    }
  }
}

I get the error

java: non-static variable eventError cannot be referenced from a
  static context

Somehow Optional values are not handled correctly by lombok in this case? I see the same problem in all my builders. This is not shown as an issue by intellij plugin but only when I try to build.
I know you should not use optional as field values but in this case it make the API much clearer and the builder will not get serialized anyways, we have DTOs for that.

A: To sum up what you want to do:

*

*you want a builder generated by lombok

*you want default values assigned in the builder using @Default

*you want custom validation inside the build method

This does not seem to work. Neither with Optional, nor with other objects. Seems to be a limitation in lombok.
The fact that it is not recognized by IntelliJ as an error does not mean that it is supposed to work. But your compilation fails. This is a real issue.
Consider the following code, without the @lombok.Builder.Default annotation:
@Getter
@Builder(builderClassName = "Builder", buildMethodName = "build")
public final class BusinessEvent {
    private String action, duration, outcome, provider, trackId, sequence;
    private Optional<String> brand, vin, externalTrackId, code = Optional.empty();
    private Optional<Object> eventError = Optional.empty();

    static class Builder {
        BusinessEvent build() {
            if (brand == null) {
                throw new RuntimeException("brand not set");
            }
            // Custom validation
            return new BusinessEvent(action, duration, outcome, provider, trackId, sequence, brand, vin, externalTrackId, code, eventError);
        }
    }

    public static void main(String[] args) {
        BusinessEvent eventWithBrand = BusinessEvent.builder().brand(Optional.of("brand")).build();
        // will throw exception
        BusinessEvent event = BusinessEvent.builder().build();
    }
}


text:
Q: Check list of tuples where first element of tuple is specified by defined string This question is similar to Check that list of tuples has tuple with 1st element as defined string but no one has properly answered the "wildcard" question.
Say I have [('A', 2), ('A', 1), ('B', 0.2)]
And I want to identify the tuples where the FIRST element is A. How do I return just the following?
[('A', 2), ('A', 1)]

A: Using a list comprehension:
>>> l = [('A', 2), ('A', 1), ('B', 0.2)]
>>> print([el for el in l if el[0] == 'A'])
[('A', 2), ('A', 1)]

A: Simple enough list comprehension:
>>> L = [('A', 2), ('A', 1), ('B', 0.2)]
>>> [(x,y) for (x,y) in L if x == 'A']
[('A', 2), ('A', 1)]

A: You could use Python's filter function for this as follows:
l = [('A', 2), ('A', 1), ('B', 0.2)]
print filter(lambda x: x[0] == 'A', l)

Giving:
[('A', 2), ('A', 1)]


text:
Q: Persistent authentication filter logging in; not propagating to JSP I've been working on a "Remember Me?"-style persistent authentication system, but after successfully authenticating and logging in the user, my JSPs do not reflect that the user is logged in until the next page request or refresh is processed. The cookie used for this is being written, and the database is being updated. Checking the login state of the user object within the Filter method indicates that the user object is being properly loaded. After refreshing or navigating to a different page, the page shows that the user is logged in.
Why does the successful login not show up on the first page?
Is there something obvious that I'm not doing here, that would prevent changes to the session data from within a Filter from being propagated to the JSP? Is this a limitation that needs to be overcome by a forced refresh?
This is written for a Java EE 5 and Struts 1.x site rendering to JSPs, using a custom Java EE Filter class as the entry point for automatic login. The filter is installed first in the chain, and mapped to "/*" in my web.xml.
My filter method implementation looks like this:
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    if (!isPersistentAuthEnabled()) {
        chain.doFilter(req, resp);
        return;
    }
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    HttpSession session = request.getSession(false);

    SessionStore store = null;
    if (session != null) {
        store = (SessionStore)session.getAttribute("sessionStore");
    }

    User user = null;
    if (store != null) {
        user = store.getUser();
    }

    if (user == null || user.isLoggedIn()) {
        // Skip authentication if no user object in session, or if already logged in.
        chain.doFilter(req, resp);
        return;
    }

    PersistentAuthenticationManager manager = null;
    try {
        manager = new PersistentAuthenticationManager();
    } catch (Exception e) {
        LOG.warn("skipping");
        chain.doFilter(req, resp);
        return;
    }

    try {
        manager.authenticateUser(user, request, response); // Authenticates based on cookie and DB store
        if (user.isLoggedIn()) {
            LOG.debug("success"); // this is being logged correctly
        }
    } catch (Exception e) {
        LOG.warn("failure");
    }
    chain.doFilter(req, resp);
}

The relevant code in the JSP is as follows (mapping the taglib jstl-core.tld to the c prefix):
<c:choose>
    <c:when test="${sessionStore.user.loggedIn}">
        <!-- Not shown: Display welcome message -->
    </c:when>
    <c:otherwise>
        <!-- Not shown: Click here to log in -->
    </c:otherwise>
</c:choose>

I've tested this on Chrome and IE so far, and the same thing happens on both. My idea for a fix would be to force a refresh by redirecting the user to the same page, but I fear that might have some ill effects, such as if that were to hit the Struts action handlers for certain requests (ie. posting things) before submitting a redirect, among other doubts. Is there some other way to handle this scenario?
EDIT: Since I believe I can safely assume users won't be submitting any forms or processing delicate actions on their first access of the site, I'm going to go with an automatic refresh via AJAX verification from the JSP which sets up the login prompt. I've discovered that the filter in question doesn't run when a plain JSP (such as the index page) is requested; it only appears to run when a Struts action is invoked. I was confused because an AJAX action on the homepage of this particular site was authenticating the user, and NOT the index.jsp request; I determined this by logging the URL of the request from within the filter. I'll describe the process in an answer.

A: As it turns out, the filter that I've set up for persistent authentication appears to only run when a Struts action is invoked; as such, it wasn't running on the index page of my site (among other pages), but in my case was instead authenticating when an AJAX call to a Struts action from the index page was processed. I've tested this for other non-Struts pages, and it appears that none of them pass through the filter I've implemented.
The way I've solved this was by placing code into my login check JSP which invokes a Struts action via AJAX (thus triggering the filter in the background); the action returns JSON which indicates whether or not the user is logged in. If logged in, the AJAX response handler then shows the user an overlaid notification for a brief time, then refreshes the page, showing the correct contents as if the user were logged in.
The relevant portion of the JSP which displays the login prompt (updated):
<c:choose>
    <c:when test="${sessionStore.user.loggedIn}">
        <!-- Not shown: Display welcome message -->
    </c:when>
    <c:otherwise>
        <script src="/path/to/persistentAuth.js"></script>
        <script type="text/javascript">
            checkPersistentAuthAndRefresh();
        </script>
        <!-- Not shown: Click here to log in -->
    </c:otherwise>
</c:choose>

Inside persistentAuth.js:
function checkPersistentAuthAndRefresh() {
    var refreshPage = function () {
        window.location.reload(true);
    };
    $.ajax({
        url: "http://example.com/path/checkPersistentAuth.do",
        dataType: "json",
        success: function (data) {
            if (data.isLoggedIn) {
                showArbitraryDropDownMessage();
                setTimeout(refreshPage, 100);
            }
        }
    });
}


text:
Q: Execute dynamic SQL query stored in text variable using Postrgres plpgsql In the Postgres table named my_table, I want to set all empty strings ('') across all variables to null.  I have the following do-block which fails at the execute line.
I am quite new to plpgsql and do not understand why.
How can I properly execute the command stored in q?
do language plpgsql
$$
DECLARE
  r record;
  q text;
BEGIN
   for r in
        select table_name, column_name
        from information_schema.columns t
        where t.table_name = 'my_table'
  loop
    q := format('UPDATE %s SET %s = NULL WHERE %s = '''';',
                    r.table_name, r.column_name, r.column_name);
    raise notice 'cleaning column: %', q;
    execute q;  -- this line fails
   end loop;
END;
$$;

PS. Any other hints for better code are also welcome :)

A: For a non-text column (say integer id) the query
UPDATE id SET id = NULL WHERE id = ''

will raise an error as you cannot compare integer id to text.
Use cast to text:
...
q := format('UPDATE %I SET %I = NULL WHERE %I::text = '''';',
            r.table_name, r.column_name, r.column_name);
...

As an alternative you can execute the update query only for text columns, e.g.:
...
    select table_name, column_name
    from information_schema.columns t
    where t.table_name = 'my_table'
    and data_type in ('text', 'character varying')
...


text:
Q: Appcelerator / Titanium - Are Javascript variables polluting the global scope in controller files? I'm new to Appcelerator and Titianium Alloy, and I wandering how the global scope works in the controller Javascript files.
It is still best practice to attach all of your variables to a single global object within these files? In a lot of tutorials it seems that they are just declaring variables with quite common names right in the file with no closure of the scope.

A: Put your global variables and functions in your app/alloy.js:
 Alloy.Globals.myModule = require("myModule");

 Alloy.Globals.myFunction = function(e){
     // your logic function
 };


text:
Q: How to change kubelet options in RKE like eviction-hard (nodefs.available,imagefs.available,etc) in Rancher? I read carefully the Kubernetes Documentation here about extending the default 15% of imagefs.available and the others parameters but it doesn't say how to set it, i have installed the RKE (Rancher Kubernetes Engine) with the following configs.
Kubernets Version:v1.17.5
OS: Ubuntu 18.04.4 LTS
Container Runtime: 19.3.9

Btw the documentation doesn't clearly explain how to extend the default eviction so i come here to know if someone can tell me how to extend it .
I also tried kubelet command line but i get this
I0903 09:59:13.143727   31472 plugins.go:100] No cloud provider specified.
W0903 09:59:13.143760   31472 server.go:560] standalone mode, no API client
W0903 09:59:13.148508   31472 container_manager_linux.go:912] CPUAccounting not enabled for pid: 31472
W0903 09:59:13.148527   31472 container_manager_linux.go:915] MemoryAccounting not enabled for pid: 31472
W0903 09:59:13.579594   31472 server.go:474] No api server defined - no events will be sent to API server.
I0903 09:59:13.579620   31472 server.go:647] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
F0903 09:59:13.581308   31472 server.go:274] failed to run Kubelet: running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false. /proc/swaps contained: [Filename                           Type            Size    Used    Priority /dev/md0                                partition      16758780       9846712  -2]

Additional Information
Server(Cloud,Bare metal,etc..): Bare Metal
Kubernet installed using: rancher
when i do it by config.yaml with the kuberconfig file provided by rancher it try to do eviction of my containers in docker and not in kubernets containers.
So my command is something like this
kubelet --kubeconfig=/root/.kube/config --config=/root/.kube/config.yaml
E0903 12:29:25.934582   26731 remote_image.go:135] RemoveImage "sha256:8c8e0533fa439319ae0ada18d3a7380d33f14f313ea5dd750ab68a1fde65d909" from image service failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rke-tools:v0.1.56" (must force) - container 2e31fd3c915d is using its referenced image 8c8e0533fa43
E0903 12:29:25.934602   26731 kuberuntime_image.go:120] Remove image "sha256:8c8e0533fa439319ae0ada18d3a7380d33f14f313ea5dd750ab68a1fde65d909" failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rke-tools:v0.1.56" (must force) - container 2e31fd3c915d is using its referenced image 8c8e0533fa43
I0903 12:29:25.934614   26731 image_gc_manager.go:376] [imageGCManager]: Removing image "sha256:2b5329557072f7cd9591670db3814bb54a72aa474ca301f00c8a29597cd32c94" to free 18234790 bytes
E0903 12:29:25.935726   26731 remote_image.go:135] RemoveImage "sha256:2b5329557072f7cd9591670db3814bb54a72aa474ca301f00c8a29597cd32c94" from image service failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "willfarrell/autoheal:latest" (must force) - container 5fb28a06d30d is using its referenced image 2b5329557072
E0903 12:29:25.935746   26731 kuberuntime_image.go:120] Remove image "sha256:2b5329557072f7cd9591670db3814bb54a72aa474ca301f00c8a29597cd32c94" failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "willfarrell/autoheal:latest" (must force) - container 5fb28a06d30d is using its referenced image 2b5329557072
I0903 12:29:25.935758   26731 image_gc_manager.go:376] [imageGCManager]: Removing image "sha256:0a3db21bc2b49b5cddea7ead8b99387ab37a332b71f0b016e1983587bb7d24af" to free 421267928 bytes
E0903 12:29:25.937276   26731 remote_image.go:135] RemoveImage "sha256:0a3db21bc2b49b5cddea7ead8b99387ab37a332b71f0b016e1983587bb7d24af" from image service failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "linuxserver/plex:latest" (must force) - container 8ca7a3b6202b is using its referenced image 0a3db21bc2b4
E0903 12:29:25.937295   26731 kuberuntime_image.go:120] Remove image "sha256:0a3db21bc2b49b5cddea7ead8b99387ab37a332b71f0b016e1983587bb7d24af" failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "linuxserver/plex:latest" (must force) - container 8ca7a3b6202b is using its referenced image 0a3db21bc2b4
I0903 12:29:25.937307   26731 image_gc_manager.go:376] [imageGCManager]: Removing image "sha256:7aab9b2c0cd6d39e03815bf3429be845257a016c3a3f5fd9e22b1ec5c3e9f329" to free 291526564 bytes
E0903 12:29:25.938673   26731 remote_image.go:135] RemoveImage "sha256:7aab9b2c0cd6d39e03815bf3429be845257a016c3a3f5fd9e22b1ec5c3e9f329" from image service failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rancher-agent:v2.4.3" (must force) - container 9eb5c8663b7d is using its referenced image 7aab9b2c0cd6
E0903 12:29:25.938693   26731 kuberuntime_image.go:120] Remove image "sha256:7aab9b2c0cd6d39e03815bf3429be845257a016c3a3f5fd9e22b1ec5c3e9f329" failed: rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rancher-agent:v2.4.3" (must force) - container 9eb5c8663b7d is using its referenced image 7aab9b2c0cd6
W0903 12:29:25.938733   26731 eviction_manager.go:430] eviction manager: unexpected error when attempting to reduce inodes pressure: wanted to free 9223372036854775807 bytes, but freed 0 bytes space with errors in image deletion: [rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "portainer/portainer:latest" (must force) - container 6193548811df is using its referenced image 2869fc110bf7, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/coreos-etcd:v3.4.3-rancher1" (must force) - container fd5c341853c0 is using its referenced image a0b920cf970d, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/hyperkube:v1.17.5-rancher1" (must force) - container 640e1d162e1e is using its referenced image ff99d966b0ee, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "hawkinzzz/dngele:latest" (must force) - container c16369f9385b is using its referenced image f3eb38637bfa, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "pyouroboros/ouroboros:latest" (must force) - container c0e2abfb3104 is using its referenced image 6bde18e83f41, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "linuxserver/emby:beta" (must force) - container 3def488e8543 is using its referenced image 95d10324f024, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "physk/rclone-mergerfs:latest" (must force) - container 9affc85735a1 is using its referenced image 80e6bae8490b, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rancher:latest" (must force) - container 549b67e38726 is using its referenced image ddb8c914dee4, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rke-tools:v0.1.56" (must force) - container 2e31fd3c915d is using its referenced image 8c8e0533fa43, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "willfarrell/autoheal:latest" (must force) - container 5fb28a06d30d is using its referenced image 2b5329557072, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "linuxserver/plex:latest" (must force) - container 8ca7a3b6202b is using its referenced image 0a3db21bc2b4, rpc error: code = Unknown desc = Error response from daemon: conflict: unable to remove repository reference "rancher/rancher-agent:v2.4.3" (must force) - container 9eb5c8663b7d is using its referenced image 7aab9b2c0cd6]
I0903 12:29:25.951254   26731 eviction_manager.go:355] eviction manager: must evict pod(s) to reclaim inodes
I0903 12:29:25.951274   26731 eviction_manager.go:373] eviction manager: pods ranked for eviction: canal-l29wx_kube-system(421796dc-24b3-4bcb-97f3-f61e36665c05)
E0903 12:29:25.951289   26731 eviction_manager.go:575] eviction manager: cannot evict a critical pod canal-l29wx_kube-system(421796dc-24b3-4bcb-97f3-f61e36665c05)
I0903 12:29:25.951297   26731 eviction_manager.go:396] eviction manager: unable to evict any pods from the node

Kind regards

A:
The kubelet has the following default hard eviction threshold:
memory.available<100Mi nodefs.available<10% nodefs.inodesFree<5%
imagefs.available<15%

As per official Rancher page:
You can add additional arguments/binds/environment variables via the Config File option in Cluster Options. For more information, see the Extra Args, Extra Binds, and Extra Environment Variables in the RKE documentation or browse the Example Cluster.ymls.
Look in the full example how you can configure kubelet options:
kubelet:
      # Base domain for the cluster
      cluster_domain: cluster.local
      # IP address for the DNS service endpoint
      cluster_dns_server: 10.43.0.10
      # Fail if swap is on
      fail_swap_on: false
      # Set max pods to 250 instead of default 110
      extra_args:
        max-pods: 250

Here you can add smth like below or whatever you exactly need.
eviction-hard: "nodefs.available<1%,imagefs.available<1%"
eviction-soft-grace-period: "nodefs.available=30s,imagefs.available=30s"
eviction-soft: "nodefs.available<1%,imagefs.available<1%"

Frankly speaking im not sure if you can change RKE's kubelet on flight, but for sure you can create cluster from scratch with required options.


text:
Q: How to get JButton below the JTextFields I have created a GridLayout for my GUI to show 6 rows and 4 columns. I am trying to get the two buttons I have "Calculate" and "Exit" to show in the 6th row. I only have two pane.add of four for row 5 (which is the weight label and textfield). I'm just trying to get the calculate and exit buttons to be on their own row. I tried to do pane.add(); to fill the gap and couldn't get it to work. What am I missing so that I can get the buttons on their own row?
basically I have
    pane.setLayout(new GridLayout(6, 4));

    pane.add(score1L);
    pane.add(score1TF);
    pane.add(weight1L);
    pane.add(weight1TF);
    pane.add(score2L);
    pane.add(score2TF);
    pane.add(weight2L);
    pane.add(weight2TF);
    pane.add(score3L);
    pane.add(score3TF);
    pane.add(weight3L);
    pane.add(weight3TF);
    pane.add(score4L);
    pane.add(score4TF);
    pane.add(weight4L);
    pane.add(weight4TF);

    pane.add(weightAvgL);
    pane.add(weightAvgTF);

    pane.add(calculateB);
    pane.add(exitB);

A: Possible options:

*

*Add empty JLabels to fill in any gaps.

*Use mixed layouts -- nest JPanels, each using its own layout and add components to them. For example, the overall JPanel could use BorderLayout. The textfields/labels could be in a GridLayout or GridBagLayout using JPanel added BorderLayout.CENTER to the main JPanel. The JButtons could be held in their own GridLayout using JPanel that is then added BorderLayout.PAGE_END to the main JPanel.

*Use a layout manager that allows for more complex layouts such as a GridBagLayout, or better perhaps, a 3rd party layout manager such as MigLayout.

*Perhaps the best of all --use a JTable to hold your data grid, add it to a JScrollPane, and then place your buttons below the JScrollPane.


text:
Q: Msg 8120 - Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause select sum(orderinfo.orderamount) as total, userinfo.username
from orderinfo
left join userinfo on orderinfo.userid = userinfo.userid
group by orderinfo.userid
order by total desc

Table orderinfo:
userid
orderamount

Table userinfo:
userid
username

I will need to search for top 10 most buy users with their names.
But I got this error:

Msg 8120, Level 16, State 1, Line 1
Column 'userinfo.username' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I am using SSMS. I must be doing something wrong...please help
Thanks

A: You cannot aggregate by the userid and also select the username.  The quickest fix here would be to aggregate by both the userid and username:
SELECT SUM(oi.orderamount) AS total, ui.username
FROM orderinfo oi
LEFT JOIN userinfo ui ON oi.userid = ui.userid
GROUP BY ui.userid, ui.username
ORDER BY total DESC;


text:
Q: How to check if user needs to re-authenticate using Firebase Authentication I am using Firebase to log in users into my app, but when I am adding the capability to manage their account like changing their email, password and so on. The documentation says that if the user have not recently signed in they need to re-authenticate, but my question is: How can I check if the user have signed in recently or not? According to the docs the error will return FIRAuthErrorCodeCredentialTooOld, but how can I check this?

A: Swift 3
I had to do this yesterday when trying to delete a user. One thing to note is FIRAuthErrorCodeCredentialTooOld is now FIRAuthErrorCode.errorCodeRequiresRecentLogin
What I did was trigger a UIView to ask for log in details if that error is thrown. Since I was using email and password, that's what I collected from the user in my example.
private func deleteUser() {
  //get the current user
  guard let currentUser = FIRAuth.auth()?.currentUser else { return }

  currentUser.delete { (error) in
    if error == nil {
      //currentUser is deleted
    } else {
      //this gets the error code
      guard let errorCode = FIRAuthErrorCode(rawValue: error!._code) else { return }
      if errorCode == FIRAuthErrorCode.errorCodeRequiresRecentLogin {
        //create UIView to get user login information
        let loginView = [yourLoginUIViewController]
        self.present(loginView, animated: true, completion: nil)
      }
    }
}

Once I had the login information I ran this function to reauthenticate the user. In my case I ran it the loginView in the above code if the login in was successful:
func reauthenticateUserWith(email: String, password: String) {
  FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
    if error == nil {
      //display UIView to delete user again
      let deleteUserView = deleteUserView()
      present(deleteUserView, animated: true, completion: nil)
    } else {
      //handle error
      print(error!.localizedDescription)
    }
  }
}

The deleteUserView in my case calls deleteUser() on a button tap from the user. You can also use UIAlertController in place of the custom UIViews, but that's up to you.
Hope this helps.

A: Update for current Swift 5
let user = Auth.auth().currentUser

user?.delete { error in
    if let error = error {
        let authErr = AuthErrorCode(rawValue: error.code)
        if authErr == .requiresRecentLogin {
            // reauthenticate
        }

        // other error
    } else {
        // delete success
    }
}

A: According to the documents, there is currently no way to check FIRAuthErrorCodeCredentialTooOld other than going through the deleting of the account or the other sensitive cases mentioned.
If you are like me and ended up here because you are trying to figure out how to handle removing someone from Auth and removing other user data in Cloud Firestore, Realtime Database, and/or Cloud Storage, then there is a better solution.
Check out the Delete User Data Extension from Firebase to handle this. In short, when a user profile is deleted from Auth, you can use this also to delete data associated with the uid from those other Firebase data storage tools.


text:
Q: Copy different lines of content from text file to clipboard I want to run a batch to copy 2 lines of content from a text file but it does not work. It copies both lines of it. Please review and advise what is the correct way to do it. Thanks.
My text file content is (1st line being proxy server and 2nd line is the exception list)
sample1.scii.com.uu
*.dh;*.gduu;*.uuarg;10.13.*;10.109.*;10.133.*;*.ehr2.com.uu;*.cldpaast1.hu.org.uu;cims-adi-app-cims-dmz-sit.hu.org.uu

My script
clip<%~dp0DH_Proxy.txt
start ms-settings:network-proxy
ping /n 6 localhost>nul 2>&1
clip<<%~dp0DH_Proxy.txt
goto :eof

A: To make it what you want, you would need to use a For /F loop that receives and echoes each line one at a time from your file:
@echo off

for /f usebackq^delims^= %%i in =;(`
find "." ^<"%~dp0\DH_Proxy.txt"`)do =;(
     start "" /b ms-settings:network-proxy
     echo\%%~i|clip & >nul 2>&1 timeout /t 6
    );=

A: It is actually simpler than you think:
type "%~dp0DH_Proxy.txt" | clip


text:
Q: Segmentation fault while creating multiple threads in C I am trying to create 1000000+ threads and have them add and remove elements from a queue.
The queue has a size of 10 elements and when it's full and wants to add an element it waits for a signal from a Condition, same thing goes for when it's empty and trying to remove an element.
The code is working fine when I am creating 100000 threads, but it's giving me a segmentation fault when I try to add one or more zeroes.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define SIZE 10

long NBTHREADS = 1000000;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t notFull = PTHREAD_COND_INITIALIZER;
pthread_cond_t notEmpty = PTHREAD_COND_INITIALIZER;

long sum = 0;

typedef long element;
typedef struct queue{
    element data[SIZE];
    int front, rear;
}queue;

queue CreateQueue(){
    queue q;
    q.front = 1;
    q.rear = 0;
    return q;
}
queue list;

int isEmptyQueue(queue q) {
    return (q.front == (q.rear + 1) % SIZE);
}

int isFullQueue(queue q) {
    return (q.front == (q.rear + 2) % SIZE);
}

int EnQueue(queue *q,element e) {
    q->rear = (q->rear + 1) % SIZE;
    q->data[q->rear] = e;
    return 1;
}

int DeQueue(queue *q) {
    q->front = (q->front + 1) % SIZE;
    return 1;
}

int Front(queue q,element *e) {
    if (isEmptyQueue(q))return 0;
    *e = q.data[q.front];
    return 1;
}

void PrintQueue(queue q){
    element e;
    while(!isEmptyQueue(q) && Front(q, &e)){
        printf("%ld ", e);
        DeQueue(&q);
    }
    printf("\n");
}

void *addToList(void *num)
{
    long number = (long)num;
    pthread_mutex_lock(&lock);
    while(isFullQueue(list))
        pthread_cond_wait(&notFull, &lock);
    EnQueue(&list, number);
    pthread_cond_signal(&notEmpty);
    sum++;
    pthread_mutex_unlock(&lock);
    pthread_exit(0);
}

void *deleteFromList()
{
    pthread_mutex_lock(&lock);
    while(isEmptyQueue(list))
        pthread_cond_wait(&notEmpty, &lock);
    DeQueue(&list);
    pthread_cond_signal(&notFull);
    sum++;
    pthread_mutex_unlock(&lock);
    pthread_exit(0);
}

int main()
{
    list = CreateQueue();
    void *status;
    pthread_attr_t attr;
    pthread_t threads[NBTHREADS];
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    for(long i=0; i<NBTHREADS; i++)
    {
        long err;
        if(i<(NBTHREADS/2))
        {
            err = pthread_create(&threads[i], &attr, addToList, (void*)i);
        }else{
            err = pthread_create(&threads[i], &attr, deleteFromList, NULL);
        }
        if(err){
            printf("\nError Creating Thread...");
            exit(-1);
        }
    }
    pthread_attr_destroy(&attr);
    for(long i=0; i<NBTHREADS; i++)
    {
        long err = pthread_join(threads[i], &status);
        if(err)
            printf("\nFAILED TO JOIN MAIN WITH THREAD %ld", (long)status);
        else
            printf("\nsuccessfully joined");
    }
    printf("\nSum is: %ld", sum);

    PrintQueue(list);
    pthread_exit(NULL);

}

It's giving me this error:
Process returned -1073741571 (0xC00000FD)   execution time : 9.364 s
I am still new to multi-threading and parallel programming.
Maybe I am using the lock in a wrong place?
But the thing is, when I make the NBTHREADS variable 100000 or less, the program is executing fine and returning 0, and the queue is not printing anything (it's empty).
I can't tell where my problem is, help appreciated.

A: There may be other system limitations that prevents 1.000.000 threads but there is (most likely) a stack overflow problem involved.
In main you have:
pthread_t threads[NBTHREADS];

An array with automatic storage duration (often called "a local variable") is on typically systems stored in a fixed size memory block called a stack. If the size of the array exceeds the size of the stack, you have a stack overflow and your program won't work.
On my system 1.000.000 pthread_t is 8.000.000 bytes which is above the (default) stack size for my system. So such a program will fail on my system.
You can do (at least) 3 things:

*

*Put the array variable in global space (kind of ugly solution)

*Allocate the array using malloc

*Increase the stack size if allowed on your system
For solution 1 do:
//long NBTHREADS = 1000000;
#define NBTHREADS 1000000

pthread_t threads_global[NBTHREADS];

int main()
{
    list = CreateQueue();
    void *status;
    pthread_attr_t attr;
    ////pthread_t threads[NBTHREADS];
    pthread_attr_init(&attr);

and update the code to use this new "ugly" variable name
For solution 2 do:
int main()
{
    list = CreateQueue();
    void *status;
    pthread_attr_t attr;
    pthread_t *threads = malloc(NBTHREADS * sizeof *threads);
    assert(threads != NULL);  // Or: if (threads == NULL) exit(1);

For solution 3:
Depends on your system
I would go for solution 2.