text:
Q: How do i limit in sql, that if one table row is selected, only corresponding items from another table show? For example, i have two tables with the names of "Clothing" and "Colors"
Now I want to limit, which colors can be chosen when selected a certain item.
Example: I have these two items in Clothing: Pants and Tshirt.
And 3 items in color: Red, Green and Black.
Now when I select Pants, i only want to be able to select the colors red and green. When I select Tshirt, then only black and green.
What I tried is:

*

*Make a table called 'clothing' with the columns ID, name

*Make a table called 'color' with the columns ID, name and clothingID (foreign key)

*Make a table called 'order' with the columns ID, clothingID (foreign key) and colorID (foreign key)
My table 'clothing':
ID: 1; name: pants
ID: 2; name: tshirt
After that i filled my table 'color' with these 4 items:
ID: 1; name: red; clothingID: 1
ID: 2; name: green; clothingID: 1
ID: 3; name: black; clothingID: 2
ID: 4; name: red; clothingID: 2
and now the 'order' table should not be able to e. g. select a red tshirt.
However, it doesn't work. I don't know how to advance as I even have got some redundancies in my 'color' table and also do not know where to search to resolve the issue...

A: Let's say that these are your tables clothing and order:
create table clothing(id int primary key, name varchar(20));
insert into clothing(id, name) values
(1, 'pants'), (2, 'tshirt');

create table color(id int primary key, name varchar(20));
insert into color(id, name) values
(1, 'red'), (2, 'green'), (3, 'black');

Now create another table clothingcolor where you store the combinations of clothing and color that you want to allow:
create table clothingcolor(
  clothingid int,
  colorid int,
  PRIMARY KEY (clothingid, colorid),
  FOREIGN KEY (clothingid) REFERENCES clothing(id),
  FOREIGN KEY (colorid) REFERENCES color(id)
);
insert into clothingcolor(clothingid, colorid) values
(1, 1), (1, 2), (2, 1), (2, 3);

Finally your order table:
create table `order`(
  id int,
  clothingid int,
  colorid int,
  FOREIGN KEY (clothingid, colorid) REFERENCES clothingcolor(clothingid, colorid)
)

contains a composite foreign key that references the table clothingcolor so you can only store clothingid and colorid combinations that exist in the table clothingcolor.
See the demo.

This design is just for guidance.
There are and there will be other issues to be solved if you decide to implement it.

A: First of all u should do a join table (with clothingID and colorID as foreign key and primary key) for these 2 entities, then u just do a query to select the right thing.
ex:
order: red t-shirt
query:
select * from clothing c1 join clothingColors cc on c1.id = cc.clothingID join on colors c2 on cc.colorID = c2.id where c1.name = "t-shirt" and c2.name = "red"
This query should return null in your case.

A: On the table called 'order' with the columns ID, clothingID, and colorID make the foreign key both clothingID and colorId together.  Right now you have them as separate foreign keys, separately both are valid but as a combination they won't be valid.  You'll need to make a unique index on the color table to have clothingID and colorID.


text:
Q: How to decode bytes NumPy array I am getting an InferenceResponse from an NVIDIA Triton Inference Server that looks like this:
[[b'6.252468:9676' b'6.248357:8707' b'6.226352:10645']
 [b'6.252468:9676' b'6.248357:8707' b'6.226352:10645']
 [b'6.252468:9676' b'6.248357:8707' b'6.226352:10645']
 [b'6.252468:9676' b'6.248357:8707' b'6.226352:10645']]

For some context, the output of the Inference ran by Triton is specified in a config file as follows:
output [
  {
    name: "predictions"
    data_type: TYPE_FP32
    dims: [ 1917, 17 ]
    label_filename: "labels.txt"
  }
]

However, my main question is how can I decode the InferenceResponse to obtain a response that meets the config I passed. I'm not sure what b'6.252468:9676' means.
I have tried to decode the response using .decode('uff-8') but I only get a string conversion, i.e. b'6.252468:9676' decodes as '6.252468:9676'.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Concave Convex $e^{-x}-e^{-2x}$ My main goal is to see here if my discusison on concave/convex is good enough.
Problem
Find the extreme points (max and/or min) for $$f(x)=e^{-x}-e^{-2x}.$$   Also discuss concavity/convexity.
Attempt
Extreme points
Solve $f'(x) = 0   -e^{-x} + 2e^{-2x}  = 0$
Multiply by $-e^{2x}$ and get $e^x - 2  = 0 \quad \Rightarrow \quad e^x  = 2 \quad \Rightarrow \quad x  = \ln(2).$
Then: $f(\ln(2))  = e^{-\ln 2} - e^{-2\ln(2)}  = e^{\ln(2^{-1})} - e^{\ln(2^{-2})} = e^{\ln(\frac{1}{2})} - e^{\ln(\frac{1}{4})}  = \frac{1}{2} - \frac{1}{4}  = \frac{1}{4}.$
There is an extreme point at $\left(\ln(2), \frac{1}{4}\right).$
Second derivative test: $f''(x)  = e^{-x} - 4e^{-2x}.$
$f''(\ln(2))  = e^{-\ln(2)} - 4e^{-2\ln 2}  = e^{\ln(2^{-1})} - 4e^{\ln(2^{-2})}  = e^{\ln(\frac{1}{2})} - 4e^{\ln(\frac{1}{4})}.$
$=  \frac{1}{2} - 4\left(\frac{1}{4}\right)  = \frac{1}{2} - 1  = -\frac{1}{2}.$
In $x_0=\ln(2)$ we have $f'(x_0)=0$ and $f''(x_0)<0.$
Thus, $\left(\ln(2), \frac{1}{4}\right)$ is a maximum point.
Concave/Convex
$f''(\ln(4)) = 0$. And $f''$ is negative to the left of $\ln(4)$, and positive to the right, so $f$ is concave for $x<\ln(4)$ and conve for $f>\ln(4)$.

A:
My main goal is to see here if my discusison on concave/convex is good enough.

Yes, your discussion is very good and very clear.

A: !
$f′′(\ln(4))=0$
$f′′$ is negative to the left of $\ln(4)$
 and positive to the right


text:
Q: php/Laravel - codepath is reached no matter the value of the conditional expression I created a helper class named UuidHelper with a function named IsValidUuid that returns a bool value. I'm type-hinting it to return a bool.
public static function IsValidUuid($uuid) : bool {
    ...
}

I'm testing my code on a Homestead Vagrant box.
$isValid = \UuidHelper::IsValidUuid($employee_uuid);

if ($isValid)
    dd($isValid);

The dd() works as intended here, returning true, but when I negate the $isValid in the if() statement (this is the only change I'm making) like so:
if (!$isValid)
    dd($isValid);

The dd() now returns false. Why is the value of $isValid changing when I negate the expression in the if() statement? And why is the dd() running in both cases? This code path should not be reached.
Just for kicks I also tried the following instead of the NOT operator:
if ($isValid == false)

with the same results.
Thanks for any help

A: Make sure you're not calling the function multiple times - one of them might be passing in a bad UUID.


text:
Q: Angular production build once and deploy to multiple sites Angular 10+. Is it possible to achieve the below?
Deploy the dist direclty to multiple sites, some under subsite/folder.

*

*site1.com

*site2.com/portal

*site3.com/a/b

I prefer not to run ng build for each site to set each base-href explicitly.
(Currently it works if I just use ".")
Avoid copying font/image from asset folder to the root
Currently the build will duplicate the asset folder item at root (with hashed file name). And when index page loads, the files are not loaded from asset folder.
https://github.com/angular/angular-cli/issues/6599
Due to the subsites above, I can't set absolute path like url("/asset"). Neither can I import/set a path variable at runtime.
Question
What would be a good solution than building individual artifacts for each site?

A: Following steps could help you as to build once and deploy to multiple sites.
At first add a configuration file, app-config.json, in the src folder and put the following.
{
    "url" : "http://site1.com"
}

Then make sure the configuration file is added to the dist folder. So, in the angular.json file you need to add the path to your configuration file to the assets array in the build configuration.
 ...
 "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/app-config.json"
            ],
 ...

Now create a configuration service with a call to get configuration data from app-config.json file.
@Injectable({
  providedIn: 'root'
})
export class ConfigService {

  private configuration: AppConfig;

  constructor(
    private httpClient: HttpClient
  ) { }

  setConfig(): Promise<AppConfig> {
    return this.httpClient
      .get<AppConfig>('./app-config.json')
      .toPromise()
      .then(config => this.configuration = config);
  }

  readConfig(): AppConfig {
    return this.configuration;
  }
}

Then use APP_INITIALIZER to invoke the method retrieving configuration data. So app.module.ts will be like below.
const appInitializerFn = (configService: ConfigService) => {
  return () => {
    return configService.setConfig();
  };
};

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: appInitializerFn,
      multi: true,
      deps: [ConfigService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now inject ConfigService into the app.component.ts to call readConfig() method.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  config: AppConfig;

  constructor(private configService: ConfigService) {}

  ngOnInit(): void {
    this.config = this.configService.readConfig();
  }
}

and in app.component.html put the following just to check what was set in the configuration file.
<div>{{ config | json }}</div>

Hence your application will be capable to resolve configuration data at runtime.


text:
Q: Star pattern is not executing I am printing a star pattern of 100 asterisks using while loop, in which a new line has to be printed after every 10 asterisks, that makes it 10 lines of 10 asterisks. However, my conditions in loops are not working I guess.
Here's the code:
#include <stdio.h>

int main(
{
    int i = 1, rem, j = 0;
    char str = 'x';
    while (i <= 100)
    {
        printf("%c", str);
        while (j * 10 <= 100)
        {
            printf("\n");
            j++;
        }
        i++;
    }
}

A: This way it will work
#include<stdio.h>
int main()
{
  int i=1,rem,j=0;
  char str='*';
  while(i<=10)
  {
    j = 0;
    while(j*10<100)
    {
      printf("%c",str);
      j++;
    }
    printf("\n");
    i++;
  }
}

Or just reduce the code to this
#include<stdio.h>
int main()
{
  for (int i = 1; i <= 100; i++) {
    printf("*");
    if (i % 10 == 0) // if i / 10 reamainder is 0 -> every 10th iteration
      printf("\n");
  }
}

A: Right now you have a loop from from 1 to 100, and one from 0 to 10 (since j*10<=100 is just j<=10). That means the body of the inner loop is run (100-1+1) * (10-0+1) = 1100 times, when you want just 100 stars.
You want to output 10 rows. And for each row, you want to output 10 columns. So you want two nested loops from 0 to 9, one of the rows, and one for the columns.
#include <stdio.h>

int main(void) {
    char ch = '*';
    int row = 0;
    while (row < 10) {
        int col = 0;
        while (col < 10) {
            printf("%c", ch);
            ++col;
        }

        printf("\n");
        ++row;
    }
}

The code would be cleaner if we wrote those while loops using the for (;;) syntax.
#include <stdio.h>

int main(void) {
    char ch = '*';
    for (int row = 0; row < 10; ++row) {
        for (int col = 0; col < 10; ++col) {
            printf("%c", ch);
        }

        printf("\n");
    }
}

A: it is overcomplicated:
void print(int numstars, int linelen)
{
    for(int star = 0; star < numstars; star++)
    {
        if(!(star % linelen)) printf("\n");
        printf("*");
    }
    printf("\n");
}

because you need to print CR only after printing linelen number of stars the modulo % is the best way to check it.
https://godbolt.org/z/Un7DYN


text:
Q: Explain this SQL Script to create user and assign role I need to create an SQL User: and came across this script:
CREATE USER [Username] FOR LOGIN [Domain\Username]
EXEC sp_addrolemember N'DatabaseRole', N'Username'

at this link:
Creating a user, mapping to a database and assigning roles to that database using SQL scripts
Can someone explain this script to me:

*

*what is [Domain\Username]?

*[Username] = The userName I want,

*what is sp_addrolemember?

*What is N'DatabaseRole',?

*What shall I put as N'Username'? The username same as [Username]?

A: 1: [Domain\Username] is for the windows Active Directory-user for that domain.
Example: Say you have an AD/Domain/Computer called StackOverFlow, that would be the Domain, and then your username is Awan, that makes it StackOverFlow\Awan
2: Correct, this is the username you want you just insert your username there (within the brackets)
Example [Awan]
3: sp_addrolemember is a function that adds the user with a specific role. (dbo and such)
4: N'DatabaseRole' is a numeric text where you write in what role your user is supposed to have. An example is db_owner, which makes the user able to create tables, delete tables, alter tables, and so on.
5: Exactly, you just put for example N'Awan' instead of N'Username'
Otherwise you can create a user from SSMS ( http://msdn.microsoft.com/en-us/library/aa337562.aspx )

A: As you are using WINDOWS server you can only create user for users who have access on windows server.

*

*SERVERNAME\USERNAME E.g. TEMP_SERVER\Ashutosh

*Uknow this

*This Sp is basically sets roles for a user.
4&5. http://msdn.microsoft.com/en-us/library/ms187750.aspx
Below is a way to do it in GUI
http://msdn.microsoft.com/en-us/library/aa337562.aspx
Regards
Ashutosh Arya

A: *

*[Domain\Username] is a format of windows authentication logon name; you use it to log on to things, one of them is SQL Server

*[Username] = The userName I want - I hope so, it should exist on your domain, or if Domain is computer name, then it has to exist on your computer

*sp_addrolemember is a stored procedure that assigns a role to your user; roles can be e.g. database level roles like db_owner, db_datareader, db_datawriter...

*Look at 3.

*If I have user MyUser on MyComputer, I would put MyComputer\MyUser; If I have user MyUser on MyDomain, I would put MyDomain\MyUser


text:
Q: Getting 'Cannot read properties of undefined (reading 'classList')' and I don't know why...? I'm trying to make a pagination and to achieve that I created a function createButtons() that dynamically creates buttons and displays them in a specific div .pagination-btns. And within that function, I created another function hideButtons() that takes the array of created buttons as parameter and then hides all the buttons except for five of them by adding a classlist of .hide. Unfortunately, when hideButtons() is called up console throws this error ''Cannot read properties of undefined (reading 'classList')'. I don't why this is happening. Plz, help me resolve this issue.
Here's the code:-

const totalBtn = 99;
const paginationBtns = document.querySelector('.pagination-btns');

createButtons();

function createButtons() {
  document.querySelector('.prev-btn').disabled = true;
  for (i = 1; i < totalBtn; i++) {
    var btn = document.createElement('button');
    btn.innerText = `${i}`;
    btn.classList.add('page-btn');
    btn.classList.add('btn-style');
    var id = document.createAttribute('data-id');
    id.value = `${i}`;
    btn.setAttributeNode(id);
    paginationBtns.appendChild(btn);
  }
  const pageBtns = document.querySelectorAll('.pagination-btns button');
  hideButtons(pageBtns);
};

function hideButtons(btn) {
  for (var i = 1; i < totalBtn; i++) {
    if (i > 4) {
      btn[i].classList.add('hide');
    }
  }
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'League Spartan', sans-serif;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  row-gap: 50px;
}

.pagination-btn-container {
  display: flex;
  justify-content: center;
  align-items: center;
  column-gap: 10px;
}

.btn-style {
  font-size: 14px;
  font-weight: 600;
  padding: 15px 30px;
  color: #000;
  background-color: lightgray;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  outline: none;
  transition: 0.2s;
}

.hide {
  display: none;
}

.prev-btn:disabled {
  opacity: 0.5;
}

.next-btn:disabled {
  opacity: 0.5;
}

  <button type="button" class="prev-btn btn-style">prev</button>

  <button type="button" class="next-btn btn-style">next</button>

A: Your loop starts at 1 you end when you get to 99 so you are one short.

const totalBtn = 99;
const paginationBtns = document.querySelector('.pagination-btns');

createButtons();

function createButtons() {
  document.querySelector('.prev-btn').disabled = true;

  // changed
  for (var i = 0; i < totalBtn; i++) {

    var btn = document.createElement('button');

    // changed
    btn.innerText = `${i + 1}`;

    btn.classList.add('page-btn');
    btn.classList.add('btn-style');
    var id = document.createAttribute('data-id');

    // changed
    id.value = `${i + 1}`;

    btn.setAttributeNode(id);
    paginationBtns.appendChild(btn);
  }
  const pageBtns = document.querySelectorAll('.pagination-btns button');
  hideButtons(pageBtns);
};

function hideButtons(btn) {

  // changed
  for (var i = 0; i < totalBtn; i++) {

    if (i > 4) {
      btn[i].classList.add('hide');
    }
  }
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'League Spartan', sans-serif;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  row-gap: 50px;
}

.pagination-btn-container {
  display: flex;
  justify-content: center;
  align-items: center;
  column-gap: 10px;
}

.btn-style {
  font-size: 14px;
  font-weight: 600;
  padding: 15px 30px;
  color: #000;
  background-color: lightgray;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  outline: none;
  transition: 0.2s;
}

.hide {
  display: none;
}

.prev-btn:disabled {
  opacity: 0.5;
}

.next-btn:disabled {
  opacity: 0.5;
}

  <button type="button" class="prev-btn btn-style">prev</button>

  <button type="button" class="next-btn btn-style">next</button>


text:
Q: Как найти php.ini который читает Docker? При попытке связаться с mysql бд с помощью
$this->pdo = new PDO($dsn, $this->user, $this->password, $opt);
Происходит ошибка Fatal error: Uncaught PDOException: could not find driver. В phpInfo стоит
PDO drivers         sqlite

Как я понял, нужно прописать расширение mysql в файле php.ini, но я никак не могу его найти. phpInfo выглядит так :

Подскажите, как найти php.ini?
P.S. Докер на Windows

A: А где и как вы делаете? Вообще php.ini лежит в папке своей версии А где и как вы делаете? Вообще php.ini лежит в папке своей версии, например в ubuntu это /etc или /var/shared не помню точно, кажись в etc... В той же Ubuntu версию можно узнать 'php -v'
Но подозреваю, что вы просто не в ту папку его распаковали, или что-то такое, на сколько я понимаю докеру не нужно указывать эту информацию


text:
Q: Is there a way I can add a scrollbar to an overflow-x  at the top instead of or as well as the bottom? I have

   ...
   ...

This places a scroll bar at the bottom of my table. Is there a way that I could have this appear at the top of the table instead of or as well as the bottom ? Note that although I didn't use this I do have jQuery available if I need to use that. If anyone knows of the most well used jQuery scrollbar solution I would also like to know which to have a look at.
Note I'm using IE9 and above. Also I did see an answer out there but that's over 2 1/2 years old so I'm hoping some new way might have come up that I could use.

A: Well, the scrollbar's position is determined by the browser which inherits it from the operation system. There's no way you can move that sidebar.
You can however create something that functions as a scrollbar!

*

*jQuery Tiny scrollbar

*jQuery Custom content scroller

*jQuery jScrollPane

*jQuery Nanoscroller (doesn't support horizontal scrolling)

There are a vast amount of plugins so there's absolutely no need to write your own.

A: This can't be done only with CSS and HTML....add JS and below is your answer :
Source : horizontal scrollbar on top and bottom of table
JSFiddle
HTML

CSS
.wrapper1, .wrapper2 {
  width: 300px;
  overflow-x: scroll;
  overflow-y:hidden;
}

.wrapper1 {height: 20px; }
.wrapper2 {height: 200px; }

.div1 {
  width:1000px;
  height: 20px;
}

.div2 {
  width:1000px;
  height: 200px;
  background-color: #88FF88;
  overflow: auto;
}

JS
$(function(){
  $(".wrapper1").scroll(function(){
    $(".wrapper2").scrollLeft($(".wrapper1").scrollLeft());
  });
  $(".wrapper2").scroll(function(){
    $(".wrapper1").scrollLeft($(".wrapper2").scrollLeft());
  });
});


text:
Q: Check if second array has any string from first array I am trying to find if second array has any string from the first one.
Not sure what I am doing wrong
const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];

const search = ["test@domain1.com", "test@tomato2.com"];

const myFunc = () => {
  return search.some((r) => domainAlertList.includes(r));
};

console.log(myFunc());

It returns false instead of true

A:

const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];

const search = ["test@domain1.com", "test@tomato2.com"];

const myFunc = () => {
  return domainAlertList.some((r) => {
      return search.some(t => t.includes(r))
  });
};

console.log(myFunc());

A: There are many ways to approach this. One of them could be the indexOf() method.
let str = "test@domain1.com";
str.indexOf('domain1') !== -1 // true
source

A: You have to map through the second array too like this
const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];

const search = ["test@domain1.com", "test@tomato2.com"];

const myFunc = () => {
  return search.some((r) => domainAlertList.some(domain=>{domain.includes(r)});
};

console.log(myFunc());

A: You can iterate and use array filter function.

const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];
const search = ["test@domain1.com", "test@tomato2.com"];

let r = []
domainAlertList.forEach(i => {
  r.push( search.filter(i1 =>  i1.includes(i)) )
})
newArr = r.map((a) => {
  if(a.length != 0) {
    return a
  }
}).filter((a) => a);
console.log(newArr)

A: const domainAlertList = ["@domain1", "@domain1", "@carrot3"];

const search = ["test@domain1.com", "test@domain1.com"];

const myFunc = () => {
  return domainAlertList.some((domain) =>
    search.some((email) => email.includes(domain))
  );
};

console.log(myFunc());


text:
Q: Angular: TextArea losing focus each times textarea model gets update I am using Socket.io for brodcasting change to all it subscribers when a data on textarea gets updated but the problem I am having is that when the data gets updated and the textarea is in focus state it loses all it focus. I just want to update the textarea only when it is in blur state and never on focus state.
I tried writing this but it doesnot works
<textarea ng-model-options="{ updateOn: 'blur'}"  ng-model="value.note"></textarea>

A: Found an Alternate solution
<textarea ng-blur="saveNote(value)" ng-model="value.note" ></textarea>

In controller

app.controller('testController', function($scope){
    $scope.persistedValue = '';
    $scope.saveNote = function(value){
       var note = value.note;
       if(note !== $scope.persistedValue){
         //Only save if persistentValue is different from note value

       }
    }
});


text:
Q: Shopify Admin API not working on Google hosted server but works on localhost My Shopify Admin API not working on Google hosted server but works on localhost. I wonder what am I missing.
I got my order data on localhost but when I upload the code to google server it doesn't work.
I am working on a private app for my shop.
no luck trying to make this works.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const Shopify = require('shopify-api-node');

const shopify = new Shopify({
  shopName: 'tinyrabbithole',
  apiKey: 'your-api-key',
  password: 'your-app-password'
  // accessToken: ""
});

shopify.on('callLimits', limits => console.log(limits));
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.getData = functions.https.onRequest((req, res) => {

shopify.order.list({ limit: 5 })
    .then( orders => {
    console.log(orders);
    return res.status(200).send(orders);
 })
    .catch( err => {
    console.log(err);
    return res.status(303).send(err);
 })
});

    { RequestError: getaddrinfo ENOTFOUND tinyrabbithole.myshopify.com tinyrabbithole.myshopify.com:443
    at ClientRequest.req.once.err (/user_code/node_modules/shopify-api-node/node_modules/got/index.js:182:22)
    at ClientRequest.g (events.js:292:16)
    at emitOne (events.js:101:20)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1025:8)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  name: 'RequestError',
  code: 'ENOTFOUND',
  host: undefined,
  hostname: 'tinyrabbithole.myshopify.com',
  method: 'GET',
  path: '/admin/orders.json?limit=5',
  protocol: 'https:',
  url: undefined }

A: I'll drop this as an answer instead of leaving it in the comments. If you see a getaddrinfo ENOTFOUND error, first make sure you are on the right payment plan. The free tier doesn't allow outgoing API calls.


text:
Q: Sed for parsing I have file:
"data_personnel": [
    {
        "id": "1",
        "name": "Mathieu"
    }
],
"struct_hospital": [
    {
        "id": "9",
        "geo": "chamb",
        "nb": ""
    },
    {
        "id": "",
        "geo": "jsj",
        "nb": "SMITH"
    },
    {
        "id": "10",
        "geo": "",
        "nb": "12"
    },
    {
        "id": "2",
        "geo": "marqui",
        "nb": "20"
    },
    {
        "id": "4",
        "geo": "oliwo",
        "nb": "1"
    },
    {
        "id": "1",
        "geo": "par",
        "nb": "5"
    }
]

How to use sed for for to have all the values of geo in struct_hospital? (chamb, jsj, , marqui, oliwo, etc ..)
The file can be in any form. With tabs, everything on a line, etc ..

A: As pointed out by Sundeep, it makes more sense to use a proper JSON parser.
But if you are looking for a one-time quick and dirty solution, then this might do:
sed -n '/^"struct_hospital"/,/^]/s/^.*"geo"\s*:\s*"\([^"]*\)"\s*,\?.*$/\1/p' input.txt

Sample output:
chamb
jsj

marqui
oliwo
par

Explanation:

*

*/^"struct_hospital"/,/^]/ - only consider lines between struct_hospital and the closing bracket.

*s/.../\1/p search and replace; only print the first capturing subpattern of every matching line

*^.*"geo"\s*:\s*"\(.*\)"\s*,\?.*$ matches the geo lines; captures the value following the colon

In case the input spans a single line, you can use another sed invocation as a preprocessor to insert line breaks:
sed 's/]\|,/\n&/g'

This makes the full command:
sed 's/]\|,/\n&/g' input.txt | sed -n '/^"struct_hospital"/,/^]/s/^.*"geo"\s*:\s*"\([^"]*\)"\s*,\?.*$/\1/p'


text:
Q: Datatable installation from github failing to find the version I have uninstalled and re-installed the latest version of datatable from the repo
16:42:49/seirdc2.March8.in $sudo pip3 install 'datatable==0.10.1'
Successfully installed datatable-0.10.1

Let's see the version:
import datatable as dt
print(f'datatable version={dt.__version__}')

Um oops !
Traceback (most recent call last):
  File "/git/corona/python/pointr/experiments/python/datatable.py", line 18, in <module>
    import datatable as dt
  File "/git/corona/python/pointr/experiments/python/datatable.py", line 19, in <module>
    print(f'datatable version={dt.__version__}')
AttributeError: module 'datatable' has no attribute '__version__'

But why?

Note: I have seen other strangeness with this package: e.g. not finding Frame - though not consistently.

A: It appears that the problem has nothing to do with datatable. Look at the traceback:
Traceback (most recent call last):
  File "/git/corona/python/pointr/experiments/python/datatable.py", line 18, in <module>
    import datatable as dt
  File "/git/corona/python/pointr/experiments/python/datatable.py", line 19, in <module>
    print(f'datatable version={dt.__version__}')
AttributeError: module 'datatable' has no attribute '__version__'

Doesn't it strike you as suspicious that you have line 18 "calling" line 19? I mean, how could it be? Here's how:
When you name your script datatable.py and then do import datatable, then instead of importing the actual module from site-packages, it imports the "module" datatable.py instead. Basically, the file imports itself. And the way python manages imports, is that it creates a "stub" module in the sys.modules first (in order to prevent infinite recursions during imports). In your case, the module tries to import itself, so the stub module is fetched instead -- and then when you try to print its __version__ variable, turns out it doesn't exist.
You can verify this by printing dt.__file__ instead, which should show the location of the file that is being imported.
Needless to say, all this is not specific to datatable in any way; for example if you created a file numpy.py and then tried to import numpy, you'd run into same problems.


text:
Q: img tag without src attribute but with class attribute gives a random display I just come across one question in stackoverflow where user want to give an icon in html, but not using

but, using class like

And css class is
.iconClass{
              background:url('smiley.gif')!important;
          }

I tried this, but this works for me, but wierd thing is that, the image is getting repeated till the width and height specified. Why this is happening, and how to solve it?

A: The reason why it happens is because background is a composite property which includes background-color, background-image, background-repeat, background-position, background-attachment. It means that when you set background alone without specifying background-repeat you simply overwrite previously defined rule, it just falls back to default value which is repeat. To fix it you should explicitly provide it:
.iconClass{
     background-repeat: no-repeat;
}

A: background repeat is by default set to repeat. You should set:
.iconClass{
   background-repeat: no-repeat;
}

or :
.iconClass{
              background:url('smiley.gif')!important no-repeat;
          }


text:
Q: Converting an integer in String form to char octets I need some help with a Java program.
I am trying to take a String containing an integer and convert it to a more compact storage format, namely, a couple of octet chars that will be printed into a file. When the file is read, it should be able to take the chars and combine their values to get the original int back. Is there a way to do this? Or am I misunderstanding something?

A: Use Integer.toOctalString(Integer.parseInt([String Value])). This will give you a octal string.
To get back the integer, use Integer.parseInt([Octal string],8);

A: Try
Integer.valueOf(yourstring)

A: You could use
public static String toHexString(int i)

and
 public static int parseInt(String s, int radix)

with a radix of 16 as a way of "compressing" your string to hexadecimal.
Alternatively you could just use the serialization methods on the integer itself if the file is a binary one.

A: to convert string to int use
int i = Integer.parseInt(String)

the most compact way to save int to a file is in binary representation
java.io.DataOutputStream.writeInt(i);

read it back as
int i = java.io.DataInputStream.readInt();

A: So you have a String that really contains an int like "12345" and you want to write it compactly in a file.
First, you convert the string to an int:
int value = Integer.valueOf(string);

Then you either convert it to a byte array with a ByteBuffer:
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(value);
byte[] result = b.array();

Or you simply write it in a file:
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(value);

Edit: Since you still have difficulties, here is a complete example:
public class Snippet {

  public static void main(String[] args) {
    int value = Integer.parseInt("1234567890");

    ByteBuffer b = ByteBuffer.allocate(4);
    b.putInt(value);
    byte[] result = b.array();

    System.out.println(result.length);  // 4
    System.out.println(Arrays.toString(result)); // [73, -106, 2, -46]
  }
}


text:
Q: terminal - having "$" instead of MyComputer:~ me$ Right now in my MacOS X terminal I have MyComputer:~ me$ before all the commands.
In some videos I saw they have just $ - that's much less clutter, how is it done?

A: This text is printed by your shell, and it's called a prompt.
Your shell is probably bash. The prompt is set in bash's initialisation file, which is .bashrc in your home directory. Specifically, the prompt is set by the PS1 variable. Its value can contain escape sequences that are replaced by some value when the prompt is displayed. For example, MyComputer:~ me$ results from a prompt setting like
PS1='\h:\w \u\$ '  # host name colon working directory space user name dollar space

Try adding the following line at the end of your .bashrc (create it if it doesn't exist):
PS1='\$ '

If this doesn't change anything, it's because you have a login shell and no proper .bash_profile. See Difference between .bashrc and .bash_profile for an explanation. Short story: create a .bash_profile containing
if [ -r ~/.profile ]; then . ~/.profile; fi
case "$-" in *i*) if [ -r ~/.bashrc ]; then . ~/.bashrc; fi;; esac


text:
Q: Passing a double pointer to a function as reference - c I'm having hard times trying to pass the reference of double pointer to a function.
I have this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_ROWS 2
#define MAX_COLS 2

int main(void){
    int i=0,lenght=0,maxColumns=0,j=0,k=0,maxRows=0,maxColumns2=0;
    int **columnVect;
        /*lengthOfPtr gives me the columns that i need. */
    if((lenght=(lengthOfPtr(ptrMessage)))<=3){
        maxColumns=1;
        maxColumns2=2;
    }else{
        maxColumns=lenght/2;
        maxColumns2=maxColumns;
    }
        /* Allocating Memory for the double pointer. */
    columnVect=malloc(maxColumns2 * sizeof(int*));
    if(columnVect == NULL){
        fprintf(stderr, "Memory error.\n");
        exit(0);
    }

    for(i = 0; i < maxColumns2; i++){
        columnVect[i] = malloc(maxRows * sizeof(int));
        if(columnVect[i] == NULL){
            fprintf(stderr, "Memory error.\n");
            exit(0);
        }
    }

    // Do something that fills columnVect[i][j]

        /* Passing the double pointer to messageVector */
    messageVector(&columnVect,maxColumns);
return 0;
}

int messageVector(int ***columnVect,int maxColumns){
        /* Allocating Memory for the triple pointer. */
    columnVect=(int ***)malloc(sizeof(int **));

   //Do something here . . .

return messageVector;
}

If i run the program gives me: (lldb)
In:
3 start
libdyld.dylib`start:
0x7fff88b447e0:  nop
Anyone could tell me how to do this in the correct way?  Thanks!

A: Ok, although I do not quite understand what you are trying to accomplish with the messageVector function, I think your question is a legitimate one, thus I'll try to give you some insight.
First of all, there is another issue with the code you have presented in the main function. If malloc fails while you're allocating maxColumns2 rows, you exit without freeing any previously allocated rows.
Please note that I have deliberately swapped the wording of maxColumns2 and maxRows, because in a general context it does a bit more sense. Conceptually, you start by allocating rows of int pointers, and then for each row you allocate columns of int.
So, you may try something like this instead...
/* Allocating Memory for the double pointer. */

columnVect = malloc( maxRows * sizeof(int *) );
if ( columnVect == NULL ){
    fputs( "Memory error.\n", stderr );
    exit(0);
}

for (int i=0; i < maxRows; i++)
{
    columnVect[i] = malloc( maxColumns2 * sizeof(int) );
    if ( columnVect[i] == NULL )
    {
        fputs( "Memory error.\n", stderr );
        for (int j = i-1; j > -1; j--)
            free( columnVect[j] );
        free( columnVect );
        columnVect = NULL;
        exit(0);
    }
}

The inner loop (using the j counter) walks from the last successfully allocated row towards the 1st one, freeing them up on the way. After that, columnsVect is also gets free'ed (that is, the memory reserved for the int pointers before the outer loop) and it's set to NULL.
I'm probably nitpicking here, since most modern operating systems will free up any memory allocated by your program after it terminates, but it's a good habit to always free the memory you have allocated. For one thing, it helps when debugging your code. It also protects you from creating memory leaks in the future, if you need to embed your current code into a larger project (a library for example).
Now, regarding passing the reference of a double pointer into a function, a nice and simple example imho would be a function that frees up the memory reserved for that pointer, and setting the pointer to NULL. Something along these lines:
void free_int2d( int ***int2d, int nrows )
{
    int i;

    if ( nrows < 1 ) {
        printf( "*** warning: %s() failed, no memory freed\n", __func__ );
        return;
    }
    if ( !int2d || !*int2d )
        return;

    for (i=0; i < nrows; i++) {
        if ( (*int2d)[i] )
            free( (*int2d)[i] );
    }

    *int2d = NULL;
}

Hopefully it is self-explanatory, but just in case let me point out a few things.
The main one is to write *int2d whenever you want to express your original double pointer inside the function (that is, the rows of int pointers).
The other one is that when you want to express the i'th row, you write (*int2d)[i]. You have to explicitly enclose the 1st dereference inside parenthesis... the 2nd dereference is done implicitly via the [ ] notation.
Finally, as an example of passing by reference a double pointer to this function, here is the inner loop of the original code, rewritten using this free_int2 function...
for (int i=0; i < maxRows; i++)
{
    columnVect[i] = malloc( maxColumns2 * sizeof(int) );
    if ( columnVect[i] == NULL )
    {
        fputs( "Memory error.\n", stderr );
        free_int2d( &columnVect, i );
        exit(0);
    }
}

It is substantially simplified, thus more readable. free_2d( &columnVect, maxRows ) should also get called on successful termination of the program (for the reasons I explained above).
EDIT
For performance reasons, you may consider pre-allocating a buffer for mallocing the columns, and reallocate it as needed (perhaps by doubling its size). But this yields to a bit more complicated code.


text:
Q: How to cast implementation instance to interface without specifying generic argument (the implementation knows it)? I have an interface:
public interface IA<T>
{
     T fce1(float[] data);
     byte[] fce2(T arg);
}

and I have its implementation which specifies certain T (so the implementation do not need anything else):
public class A : IA<float>
{
   public float fce1(float[] data)
   {
       return 1f;//data processing
   }

   public byte[] fce2(float arg)
   {
       return BitConverter.GetBytes(arg);//some kind of serialization
   }
}

Class A is in a.dll and I want to get it and call the fce2(fce1()) (so there should be no uknown argument or type. I want to do something following:
var data = File.ReadAllBytes("a.dll")
var assembly = Assembly.Load(data);
var expTypes = assembly.GetExportedTypes();

foreach (var d in assembly.GetExportedTypes())
{
     var obj = Activator.CreateInstance(d);
     if (obj is IA)
     {
          var kernel = obj as IA;
          kernel.fce2(fce1());
     }
}

The purpose is to run fce1 as one Task later and fce2 as a second Task when fce1 provides result (this is simplyfied situation).
I tried this with .NET 4.7
I know it could be done to return the object from fce1 and then cast inside fce2 the object to desired type and process it? But is this the only way? I want to avoid casting.

A: Using the dynamic type, the methods invocation could be made (only the first call takes a long time, then it is quite efficient.
float[] testingPacket = new float[6250000];
dynamic instance = null;

foreach (var d in assembly.GetExportedTypes())
{
    instance = Activator.CreateInstance(d);
}
int L = 0;
for (int i = 0; i < L; ++i)
{
    dynamic result1 = instance.fce1(testingPacket);
    byte[] buffer = instance.fce2(result1) as byte[];
}

The higher the L is the duration period of the for cycle is closer to the duration of object casting and direct declaration using as IA. Thx.


text:
Q: State Variable Filter - Unexpected High Frequency Behavior I am designing a voltage-controlled state variable filter for use in a modular synthesizer. Its function is to produce low-pass, band-pass, and high-pass responses for a given audio input signal. Corner frequency and resonance (Q) are determined by LM13700 amplifier bias currents, which are controlled by external voltages.
Here is the circuit I'm simulating and breadboarding. Resonance control is simplified in this schematic, and signal ac-coupling and output buffering is not shown.

Behavior of the simulation and breadboard prototype is as-expected for normal control voltage and signal input frequencies in the range of <1Hz to 20KHz.
Out of curiosity I simulated the circuit to 100MHz and found that, in the 50KHz-200KHz range, gain starts increasing. This is most visible in the low-pass output. The frequency at which gain increases is independent of Q and corner frequency, and seems to be determined entirely by the op amps used for U6 and U7. Responses for TL072 and LT1022 show a 180-degree phase shift at different frequencies, leading me to believe this is non-ideal op amp behavior.

I am not too concerned since the circuit functions properly in its intended application, but would like to understand why this is happening.
Question:
Is non-ideal op amp behavior the cause of this high frequency behavior? If so, what parameters are relevant?

A: The shown problems at higher frequencies are typical for all inverting opamp applications. Here, the last stage is an inverting integrator circuit with capacitive feedback.
What happens as a result of high frequencies at the input of the last stage?
There are 3 major effects:
(a) The open-loop gain of the opamp drops continuously so that the circuit cannot work properly anymore,
(b) the impedance of the feedback element (capacitor) is reduced continuously and
(c) there is, therefore, a rising part of the input signal that arrives at the output node using a "wrong" way: Directly through the capacitor. This current, which is NOT driven by the amplifiers output node, causes a rising output voltage across the finite output resistance of the opamp. It is even worse, because this finite output resistance is not constant but goes high with rising frequencies.
As a result, the ouput signal goes high with the frequency because of this unwanted effect (parasitic portion of the input arrives the output node with an even increasing characteristic).

A: Here is the output impedance of a 1uA Idd opamp, the MCP6031.
The opamp has plenty of drive strength---Iout is 50mA.
But the opamp has only 10,000 Hz UnityGainBandWidth, hence attempting any performance near or above 10,000 Hz is doomed to failure.
Additionally, the opamp's output impedance at 10Khz is 100,000 ohms; the opamp
(consuming only 1uA for the internal FETs) simply cannot charge and discharge any capacitors at high frequencies.
Your example has the same challenges. The opamp's Rout (Zout) starts rising as soon as your frequency is above the -3dB of the OPEN LOOP RESPONSE. For many opamps, that frequency is 10Hz or close.
Walt Jung (of Analog Devices, et al as consultant) wrote of the failure of active filters at higher frequencies, many decades ago. His example: to achieve
40dB stop-band rejection at 1MHz, the opamp needs UGBW of at least 100MHz.


text:
Q: Collecting tikZ drawings in a box Please is it possible to collect tikz picture in the following way? I get \box40=\hbox(0.0+0.0)x0.0 []. I would even prefer a \vbox, but I get a worse outcome.
\makeatletter
\newbox\tempbox
\newbox\mainbox
\def\collecttikzpicture{\@testopt\@collecttikzpicture{}}
\def\@collecttikzpicture[#1]{%
  \global\setbox\tempbox=\hbox\bgroup\begin{tikzpicture}[#1]%
}
\def\endcollecttikzpicture{%
  \end{tikzpicture}\egroup
  \setbox\mainbox=\hbox{\unhbox\mainbox\unhbox\tempbox}%
}

\begin{collecttikzpicture}[remember picture,overlay]
  \draw [cyan,fill=yellow]
  (0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

\showbox\mainbox
\makeatother

A: You need to collect your main box outside the environment group:
\def\endcollecttikzpicture{%
  \end{tikzpicture}\egroup
  \aftergroup\collectbox
}

\def\collectbox{\setbox\mainbox=\hbox{\unhbox\mainbox\unhbox\tempbox}}

Note, that this makes the \mainbox contain the picture, it still has zero size because of the overlay option passed to the tikzpicture. If you remove that the box attains the natural dimensions of the square.

As you said you would prefer a vbox:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\makeatletter
\newbox\tempbox
\newbox\mainbox
\def\collecttikzpicture{\@testopt\@collecttikzpicture{}}
\def\@collecttikzpicture[#1]{%
  \global\setbox\tempbox=\hbox\bgroup\begin{tikzpicture}[#1]%
}
\def\endcollecttikzpicture{%
  \end{tikzpicture}\egroup
  \aftergroup\collectbox
}

\def\collectbox{\setbox\mainbox=\vbox{\unvbox\mainbox\box\tempbox}}
\makeatother

\begin{collecttikzpicture}[remember picture]
  \draw [cyan,fill=yellow]
  (0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

\begin{collecttikzpicture}[remember picture]
  \draw [cyan,fill=blue]
  (0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

\begin{collecttikzpicture}[remember picture]
  \draw [cyan,fill=green]
  (0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

[[[\box\mainbox]]]

\end{document}


text:
Q: F#: Error FS0030: Value restriction I am new to programming and F# is my first language.
Here are the relevant parts of my code:
let rec splitArrayIntoGroups (inputArray: string[]) (groupSize: int) (hashSetOfGroups: HashSet<string[]>)=
    let startIndex = 0
    let endIndex = groupSize - 1

    let group = inputArray.[startIndex .. endIndex]
    let nextInputArray = inputArray.[groupSize .. inputArray.Length - 1]

    hashSetOfGroups.Add(group) |> ignore
    splitArrayIntoGroups nextInputArray groupSize hashSetOfGroups

let hashSetOfGroups = new HashSet<string[]>()

splitArrayIntoGroups urlArray 10 hashSetOfGroups

urlArray is an array of almost 3200 URLs.
When I try to run the code in F# interactive, I receive the following error message:

Program.fs(119,1): error FS0030: Value restriction. The value 'it' has
  been inferred to have generic type
      val it : '_a     Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to
  be generic, add a type annotation.

What went wrong, and what changes should I make?

A: As it stands, the code will loop indefinitely.  What is the exit condition?  As @Petr points out, what does the function return?
Below is a version which exits and returns unit when the inputArray is empty:
let rec splitArrayIntoGroups (inputArray: string[]) (groupSize: int) (hashSetOfGroups: HashSet<string[]>)=

    match inputArray with
    | [||] -> ()
    | _ ->
        let startIndex = 0
        let endIndex = groupSize - 1
        let group = inputArray.[startIndex .. endIndex]
        let nextInputArray = inputArray.[groupSize .. inputArray.Length - 1]

        hashSetOfGroups.Add(group) |> ignore
        splitArrayIntoGroups nextInputArray groupSize hashSetOfGroups

Rather than using a mutable set, a more idiomatic way would be to use the F# Set type and then pass a new version to each recursion, like this:
let rec splitArrayIntoGroups2 inputArray groupSize hashSetOfGroups =

    match inputArray with
    | [||] -> hashSetOfGroups
    | _ ->
        let startIndex = 0
        let endIndex = groupSize - 1
        let group = inputArray.[startIndex .. endIndex]
        let nextInputArray = inputArray.[groupSize .. inputArray.Length - 1]

        let newSet = Set.add group hashSetOfGroups
        splitArrayIntoGroups2 nextInputArray groupSize newSet

Btw, the logic as it stands appears to be buggy re the index logic. If I try the following:
let urlArray = [| "a"; "b"; "c"; "d" |]
let result = splitArrayIntoGroups2 urlArray 10 Set.empty

then I get an IndexOutOfRangeException.
Did you mean something like this instead?
let rec splitArrayIntoGroups3 inputArray startIndex groupSize hashSetOfGroups =

    let maxIndex = Array.length inputArray - 1
    if startIndex > maxIndex  then
        hashSetOfGroups
    else
        let endIndex = min (startIndex + groupSize - 1) maxIndex
        let group = inputArray.[startIndex .. endIndex]
        let newSet = Set.add group hashSetOfGroups

        let nextStartIndex = endIndex + 1
        splitArrayIntoGroups3 inputArray nextStartIndex groupSize newSet

let urlArray = [| "a"; "b"; "c"; "d"; "e"  |]
let result = splitArrayIntoGroups3 urlArray 0 2 Set.empty

Note that this final version works with arrays of any type, not just string arrays.


text:
Q: Wait until page is fully loaded and then reading its content with urllib2/3 I am opening a webpage with urllib2 and reading its content and then passing it's content to BeautifulSoup and then scraping..
But what I want to first load the page fully or for a specfic time set and then read its content.
I have tried method like time.sleep(sec) but these are not working I am getting the same content either i read it instent or wait(sleep) for 10/15sec.
and when I am entering script line by line inot python shell then I am getting different result.
I am using urllib2 and python2.7. Also I tried to find a solution but everyone suggesting to use another module. Is this not possible with Urllib2 or urllib3?
Or Do I have to use another module like requests?
please suggest


text:
Q: Using ASP.NET Core 3.1 with Node.js? I have read that NodeServices have been deprecated for ASP.NET Core 3.1. Is it still possible to use Node.js to build my JavaScript files into the dist folder in wwwroot?

A: According to the NodeServices package, it allows you to "invoke Node.js modules at runtime in ASP.NET Core applications" (emphasis my own). This is reiterated in more detail on the GitHub ReadMe:

This NuGet package provides a fast and robust way to invoke Node.js code from a .NET application (typically ASP.NET Core web apps). You can use this whenever you want to use Node/NPM-supplied functionality at runtime in ASP.NET.

That's entirely independent of the ability to e.g. precompile, minimize, or move JavaScript files at build time.
Build Time Tasks
You don't—and won't—need NodeServices in order to download npm package dependencies via:

*

*The command prompt on your local workstation,

*From Visual Studio's built-in integration, or

*From a task on your build server (e.g., the npm task on Azure Pipelines).

Likewise, to precompile, minimize, and move client-side dependencies from their source directory to their distribution directory, you can (continue to?) use tools like Gulp.js, Grunt, or WebPack, which are each build systems that operate on top of Node.js.

Important: The critical distinction here is that you don't need to call these tools at runtime from your .NET application. You are incorporating the output from your Node.js build tools into your .NET application, but you aren't executing Node.js code as part of your .NET application.

The one exception to this is if you're using NodeService to dynamically perform these build tasks at runtime. For example, if your application is configured with the UseWebpackDevMiddleware() then that will no longer work. In that case, you would need to migrate to a build process that occurs prior to (or during) deployment.
Webpack
If you are using UseWebpackDevMiddleware(), then I'd recommend looking into configuring Webpack locally. That should be a pretty seamless transition. You can run it manually via the Webpack CLI, use a Visual Studio extension, or potentially even integrate it into your build process. Personally, I run it manually on my development server, then integrate it into my Azure Pipelines build process.
Alternatively, if you really want to maintain "just in time" build support for Webpack files, you can look into using the Webpack dev server in conjunction with ASP.NET Core, as discussed in Best way to integrate webpack builds with ASP.NET Core 3.0?.


text:
Q: Gmail Script - Labels Adding and Removing Labels I'm close to getting this to what I want to do, but having a couple issues.

*

*My addLabel and removeLabel command is impacting all my labels, not just the ones I'm trying to target by identifying a specific subject line. How can I target this change to be only the subject lines I want?

*Somehow my Process1 function is running more times than the number of emails it should be identifying (ie if there are two "Flagged" emails, it will produce three entries in my spreadsheet)

Any help or clean up of this would be greatly appreciated!
Thanks,
function getemails() {

var label = GmailApp.getUserLabelByName("Flagged");
var Nlabel = GmailApp.getUserLabelByName("Logged");
 var threads = label.getThreads();
     for (var i = 0; i < threads.length; i++) {

 var messages=threads[i].getMessages();

     for (var j = 0; j < messages.length; j++) {

   var message=messages[j];
   var subject = message.getSubject();
       if(subject=="test4")

   threads[i].removeLabel(label);
   threads[i].addLabel(Nlabel);

   process1(message);
 }
 }

   function process1(message) {

 var body =message.getPlainBody();
 var label = GmailApp.getUserLabelByName("Flagged");
 var id = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 var ss = SpreadsheetApp.openById([id]);
 var sheet = ss.getActiveSheet();
 sheet.appendRow([body]);

}

  }

A: As sugested by @Cooper. I don't believe your conditional is enclosing the functions you need it to. Check your line 14:

if (subject == "test4")

You should use curly brackets "{" & "}" after the if conditional, as stated in the documentation I link below to enclose any instructions that you want the program to execute only if the condition is met.

Reference:

*

*if ... else statement documentation.


text:
Q: How to remove list of objects from another list of Objects I have two lists json, one called subscribers and the other called following.
following:
{
  0: { id: "u0", username: "user0", avatar: "user0.png" },
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  2: { id: "u2", username: "user2", avatar: "user2.png" },
  3: { id: "u3", username: "user3", avatar: "user3.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" },
  5: { id: "u5", username: "user5", avatar: "user5.png" }
}

subscribers:
{
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" }
}

I want to remove the subscribers from the following, [ following - subscribers = remaining list of following ].
How can I delete them depend on the id property in each object in both list?

A: If your keys line up with your ids:
f = {
  0: { id: "u0", username: "user0", avatar: "user0.png" },
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  2: { id: "u2", username: "user2", avatar: "user2.png" },
  3: { id: "u3", username: "user3", avatar: "user3.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" },
  5: { id: "u5", username: "user5", avatar: "user5.png" }
}

s = {
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" }
}

for( i in s ){
  delete f[i]
}

A: Using lodash is quite helpful:
_.pullBy(following, subscribers, 'id')

A: One way of doing this is using Array.prototype.reduce on follower's keys (or values) to create a new object based on entries that do not appear in subscribers:

let followers = {
  0: { id: "u0", username: "user0", avatar: "user0.png" },
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  2: { id: "u2", username: "user2", avatar: "user2.png" },
  3: { id: "u3", username: "user3", avatar: "user3.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" },
  5: { id: "u5", username: "user5", avatar: "user5.png" }
}

let subscribers = {
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" }
}

followers = Object.keys(followers).reduce((acc, current) => !Object.values(subscribers).some(sub => sub.id === followers[current].id) ? {...acc, [current]: followers[current]} : acc, {})
console.log(followers)

Or you can iterate followers' keys and delete "duplicates" instead:

let followers = {
  0: { id: "u0", username: "user0", avatar: "user0.png" },
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  2: { id: "u2", username: "user2", avatar: "user2.png" },
  3: { id: "u3", username: "user3", avatar: "user3.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" },
  5: { id: "u5", username: "user5", avatar: "user5.png" }
};

let subscribers = {
  1: { id: "u1", username: "user1", avatar: "user1.png" },
  4: { id: "u4", username: "user4", avatar: "user4.png" }
};

Object.keys(followers).forEach(current => {
  if (Object.values(subscribers).some(sub => sub.id === followers[current].id)) {
    delete followers[current];
  }
});
console.log(followers);


text:
Q: LARAVEL - eloquent get relation with null ids I am working on some eloquent query. So the idea is that I have 2 models, let's call it Files and Pricing. Files hasMany so in pricings table I have file_id field. But I have default prices in pricings table which has file_id = null. I want to get files with pricing and also with these default prices which has file_id = null. The most important thing is that I would like to handle it with eloquent, because of some other relations that pricings table have. So I have an idea that in File model I am getting related pricing and default prices and then merge them. But I can't perform the query in an eloquent model to get default prices which have file_id = null. I want to get something like that:
public function filePricing()
{
  return $this->hasMany(Pricing::class);
}

public function defaultPricing()
{
  return Pricing::where('file_id', null);
}

public function pricing()
{
 return $this->defaultPricing()->merge($this->filePricing());
}

So in the controller, I would like to do:
File::with('pricing', 'pricing.[myNextRelation]')->get();

Or maybe anyone has a better idea to achieve it?


text:
Q: Set isolation level in Spring Boot I use Java, Spring Boot, CrudRepository and Postgresql.
How can set the isolation level in a CRUD Repo in Spring Boot or how can I set the isolation level in whole Spring Boot application.

A: Spring creates proxies for all the classes annotated with @Transactional – either on the class or on any of the methods. The proxy allows the framework to inject transactional logic before and after the method being invoked – mainly for starting and committing the transaction.
If the transactional bean is implementing an interface, by default the proxy will be a Java Dynamic Proxy. This means that only external method calls that come in through the proxy will be intercepted – any self-invocation calls will not start any transaction – even if the method is annotated with @Transactional.

Isolation:
DEFAULT: Use the default isolation level of the underlying database.
Read Uncommitted: Allows dirty reads
Read Committed: Does not allow dirty reads
Repeatable Read: If a row is read twice in the same transaction, the result will always be the same
Serializable: Performs all transactions in a sequence

You should refer this Question for more Details.
For Overview Here Here Here


text:
Q: Cache Isolation Level Warning on Parent Entity After adding a second persistence unit and changing my application's data sources to XADataSource (MySQL), I'm now getting a confusing warning in the glassfish log about isolation levels on my parent entity:
WARN  o.e.p.s.f.j.ejb_or_metadata : Parent Entity BaseEntity has an isolation
level of: PROTECTED which is more protective then the subclass Contact with
isolation: null so the subclass has been set to the isolation level PROTECTED.

After some research, I think that this isolation level warning message is coming from EclipseLink's caching mechanism.  But I am not specifying an isolation level anywhere in my app, so it appears that something in my configuration has triggered the BaseEntity class to have an isolation level of 'PROTECTED'.  The documentation is silent on what might cause it to be automatically assigned to that level -- see user guide.
Minor testing with a single user has shown that the application seems to work as expected, but this warning message doesn't make me feel comfortable rolling it out to the masses.
Can anyone shed some light into this message?  Are my concerns valid?

A: The cache implementation here is just trying to sync the isolation level of parnet and child entity. But i think you should override the default protective isolation level. Because "Serializeable" isolation level is the one which is most protective and has poor performance. You can use Read Committed or Repeatable Read levels, depending upon your requirements.

A: This is just a warning about cache isolation, it has nothing to due with database isolation, so you can just ignore it.
For more info on cache isolation see,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Shared_and_Isolated
It is odd if you have not done any caching configuration though.  By default everything should be SHARED, to get something as PROTECTED you must have disabled aching for a related entity, such as using @Cacheable(false)?

A: After some research, I discovered that this warning had nothing to do with using the XADataSource.  I had earlier began some exploration into EclipseLink's Multitenancy, and it turned out that this was the culprit.
Referring to http://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant#Persistence_Usage_for_Multiple_Tenants:

When using this architecture there is a shared cache available for regular entity types but the Multitenant types must be PROTECTED in the cache so the MULTITENANT_SHARED_EMF property must be set to true.

FYI -- In reviewing the code, there are 3 other cases in ClassDescriptor.initializeCaching() in which the cache isolation is downgraded to PROTECTED:

*

*If the entity has a DatabaseMapping marking it as non-cacheable.

*If the entity has a ForeignReferenceMapping that doesn't have an isolation level of shared.

*If the entity has a AggregateObjectMapping that doesn't have an isolation level of shared.


text:
Q: Aligning a shapefile to raster and assign values to overlay, then return as array? My goal is to align a shapefile to a raster basemap, and assign 1 to the cells that overlap and 0 to the ones that don't, eventually returning an array that contains lat, lon, time, and the binary variable (1/0).
Here's the plan: 1) create raster of region from array, 2) rasterize polygon shapefiles, 3) align rasterized shapefiles with base raster, 4) pixels that overlap will be assigned 1 and those that don't will be 0, 5) convert rasters to array.
I've been able to do steps 1 & 2 (see code below), but I've been stuck on step 3 for a long time. How do I align the two rasters?
You can find the files here:
https://www.dropbox.com/sh/pecptfepac18s2y/AADbxFkKWlLqMdiHh-ICt4UYa?dl=0
Here's the code I used to create a flat grid of BC as basemap:
import gdal, osr
import numpy as np

#define parameters
#units = km
grid_size = 5
BC_width  = 700
BC_length = 1800

def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):

    cols = array.shape[1]
    rows = array.shape[0]
    originX = rasterOrigin[0]
    originY = rasterOrigin[1]

    driver = gdal.GetDriverByName('GTiff')
    outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Byte)
    outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
    outband = outRaster.GetRasterBand(1)
    outband.WriteArray(array)
    outRasterSRS = osr.SpatialReference()
    outRasterSRS.ImportFromEPSG(4326)
    outRaster.SetProjection(outRasterSRS.ExportToWkt())
    outband.FlushCache()

def main(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
    reversed_arr = array[::-1] # reverse array so the tif looks like the array
    array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,reversed_arr) # convert array to raster

if __name__ == "__main__":
    array = np.zeros([int(BC_length/grid_size),int(BC_width/grid_size)])  #140x360
    for i in range(1,100):
        array[i] = 100
    rasterOrigin = (-139.72938, 47.655534) #lower left corner of raster
    newRasterfn = '/temp/test.tif'
    cols = array.shape[1] #shape of an array (aka # of elements in each dimension)
    rows = array.shape[0]
    originX = rasterOrigin[0]
    originY = rasterOrigin[1]
    pixelWidth = 5
    pixelHeight = 5

Here's the code I used to rasterize polygon shapefiles
import ogr, gdal, osr

output_raster = '/testdata/poly.tif'

shapefile = "/testdata/20180808.shp"

def main(shapefile):

    #making the shapefile as an object.
    input_shp = ogr.Open(shapefile)

    #getting layer information of shapefile.
    shp_layer = input_shp.GetLayer()

    #pixel_size determines the size of the new raster.
    #pixel_size is proportional to size of shapefile.
    pixel_size = 0.1

    #get extent values to set size of output raster.
    x_min, x_max, y_min, y_max = shp_layer.GetExtent()

    #calculate size/resolution of the raster.
    x_res = int((x_max - x_min) / pixel_size)
    y_res = int((y_max - y_min) / pixel_size)

    #get GeoTiff driver by
    image_type = 'GTiff'
    driver = gdal.GetDriverByName(image_type)
    #passing the filename, x and y direction resolution, no. of bands, new raster.
    new_raster = driver.Create(output_raster, x_res, y_res, 1, gdal.GDT_Byte)

    #transforms between pixel raster space to projection coordinate space.
    new_raster.SetGeoTransform((x_min, pixel_size, 0, y_min, 0, pixel_size))

    #get required raster band.
    band = new_raster.GetRasterBand(1)

    #assign no data value to empty cells.
    no_data_value = -9999
    band.SetNoDataValue(no_data_value)
    band.FlushCache()

    #main conversion method
    gdal.RasterizeLayer(new_raster, [1], shp_layer, burn_values=[255])

    #adding a spatial reference
    new_rasterSRS = osr.SpatialReference()
    new_rasterSRS.ImportFromEPSG(4326)
    new_raster.SetProjection(new_rasterSRS.ExportToWkt())
    return output_raster

I'm doing everything in Python as I don't have access or funding to paid GIS software. I'm totally new to geospatial data processing... not sure if I'm taking the right approach. Any help would be amazing.

A: Checkout 'rasterio.mask.mask' from the rasterio library. I think it will help.


text:
Q: What should I store/ Not store in TFS and how? I'm trying to set up a TFS server for our small dev team, and since this is fairly new to me I have a couple of questions.
1) We are developing ASP.Net websites for internal use (intranet etc), these websites currently are not saved with visual studio solutions, they get saved basically as they are on the server and we just update them using Visual Studio by doing file > open website.
So my first question is should I save these as solutions in TFS? What would the benefit of this be?
Im coming from a background of developing WPF applications and have always seen everything saved with a solution in TFS.
2) What should we store in our TFS repository (and what should we exclude)?
At the moment I am storing source code & Documentation but is it really appropriate to store things like installers for VS plugins / small applications or should this kind of thing all be placed on a server someplace?

A:
So my first question is should I save these as solutions in TFS? What

Yes, you could create a solution containing the different ASP.NET web applications.

would the benefit of this be?

Your source code will be version controlled

What should we store in our TFS repository

Source code, third party assemblies that your ASP.NET applications might require, script files, basically everything that allow to get your site up and running. Documentation should also be stored along with the project. Same stands for installers (the source code only, not the MSI) if those installers allow to deploy the ASP.NET application on the live servers.

and what should we exclude

Compiled assemblies, but they are automatically excluded by TFS anyway.


text:
Q: When using cx_freeze, what files have to be updated to update the application? I want to implement an autoupdater in my Python application. This is no problem with the source version; Python doesn't care at all that the script it's running is trying to overwrite itself.
Windows, however, does care if an EXE tries to overwrite itself. My question is, does my EXE even have to overwrite itself? Or is the EXE just an interpreter, and I only have to overwrite library.zip?
If it does, is there any alternative to starting an updater application and shutting down the main EXE?

A: The cx_Freeze exe is compiled along with cx_Freeze, so in most cases you can safely leave it alone and just update library.zip. However, you should make sure that you prepare your updates using the same version of cx_Freeze that you froze the application with originally, in case it expects specific things about the files around it.
Also, the exe gets stamped with a version number relating to your application (you can see it in the file properties). If you don't replace it, that version number won't change.
If you do need to replace the exe, I believe the trick is to copy it to a temporary folder and re-run from there, so that it can replace the original. You can also look into update frameworks like Esky, which aim to handle these kinds of details for you. I haven't used that, so I don't know how well it works.


text:
Q: Send emails using gmail after Oauth 2.0 in MVC Application I want to send email over google/gmail from my mvc application after oauth.
I am using mvc 4. My application will ask for authorize this app for oauth.
Then I want to send email to other user from the application.
If you help me through code and step to do, that will be great.

A: You can Use Postal which is very handy and easy to use ,to send emails
Controller
dynamic email = new Email("Email");
email.To = UserName;
email.FirstName = FName;
email.LastName = LName;
email.Send();

Then in your View Email
@{
Layout = null;
}

To: @ViewBag.To
From: Example lolcats@website.com
Subject: blah blah

Hello @ViewBag.FirstName,

Your Text.........
This is auto generated email please do not reply.

Edited
Please add your smtp credentials in web.config
<system.net>
<mailSettings>
  <smtp deliveryMethod="Network" from="example@gmail.com">
    <network defaultCredentials="false" host="smtp.gmail.com" port="587" enableSsl="true" userName="example@gmail.com" password="1234567" />
  </smtp>
</mailSettings>
</system.net>

This is very simple. Just give a try
Hope this helps!

A: I have made lots of work out. and Finally.... I have resolved my problem.
In C#, there is no any direct SMTP and Oauth lib. So you need to work manually.
Make Oauth2 access using api and get access "offline".
Then Refer this link SMTP and Oauth


text:
Q: How do I access active IWorkbenchWindow in BundleActivator's start method? In my BundleActivator's start method, I need to access the active IWorkbenchWindow to add an IPartListener to it. However, when the start() method is called,
Workbench.getInstance().getActiveWorkbenchWindow()

returns null.
I tried adding a IWindowListener to Workbench.getInstance(), but a window open event is never fired. Only a window activated event is fired when I switch to another program and back to eclipse.
How do I add the IPartListener properly?

A: Workbench is an internal class and you should not be using it (Eclipse API Rules of Engagement). Internal classes may be changed without notice (Workbench in fact was completely rewritten between Eclipse 3 or 4).
The official way to get the IWorkbench interface is:
IWorkbench workbench = PlatformUI.getWorkbench();

However this may also return null if it is called too early in the Eclipse startup.
It is not usual to add a part listener in an activator, usually this is done in a view or editor part initialization or in a command handler or action.

A: I found a way to do it:
final IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().asyncExec(new Runnable() {
   public void run() {
     IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
     if (window != null) {
       // do something
     }
   }
 });

(from Eclipse documentation)


text:
Q: Spark Hbase inserts too many connections open I'm trying to perform inserts to Hbase after parsing some text and the code works fine but i think it can be organized for better performance. in the below im opening a connection in a loop and i would like to know how i may be able to open a single connection and use it for all inserts. i think i would need to the connection to a function for this to happen.
def extractInfo(fp:String) = {
val p:Parser = new AutoDetectParser()
val fs = FileSystem.get(new java.net.URI("XXXXXXXXXX"), new Configuration())
val inputPath:Path = new Path(fp)
val is:InputStream = fs.open(inputPath)
val handler:BodyContentHandler = new BodyContentHandler(-1)
val metadata:Metadata = new Metadata()
try{
p.parse(is, handler, metadata, new ParseContext())
is.close()
val hand = handler.toString()
val gson = new Gson
val jsonTree = gson.toJsonTree(metadata)
val metaNode = jsonTree.getAsJsonObject().getAsJsonObject("metadata")
val jsonString = gson.toJson(metaNode)
if (hand.trim().isEmpty()){
println("no Text extracted", inputPath)
} else {
println("Success")
}
val fname = "ABC"
val configuration: Configuration = HBaseConfiguration.create()
configuration.set("hbase.zookeeper.quorum", "XXXX")
configuration.set("hbase.zookeeper.property.clientPort", "XXXX")
configuration.set("zookeeper.znode.parent", "/hbase-XXX")
configuration.set("hbase.client.keyvalue.maxsize", "0")
val principal = System.getProperty("kerberosPrincipal", "XXXXX")
val keytabLocation = System.getProperty("kerberosKeytab", "XXXXXXXXX")
UserGroupInformation.setConfiguration(configuration)
UserGroupInformation.loginUserFromKeytab(principal, keytabLocation)
val connection = ConnectionFactory.createConnection(HBaseConfiguration.create(configuration))
val admin = connection.getAdmin
val hTable:HTable = new HTable(configuration, "XXXXXXXXX")
val g = new Put(Bytes.toBytes(fname))
g.add(Bytes.toBytes("txt"),Bytes.toBytes("text"),Bytes.toBytes(hand))
hTable.put(g)
val m = new Put(Bytes.toBytes(fname))
m.add(Bytes.toBytes("data"),Bytes.toBytes("info"),Bytes.toBytes(jsonString))
hTable.put(m)
hTable.close()
fs.close()
}
catch {
case e : Throwable => {
println(e.printStackTrace)
}
}
}

object App {
def main(args : Array[String]) {
val fnames = "/X/X/XXXXX.XXX"
fnames.foreach{x => extractInfo(x) }
}
}

A: in spark, if you are updating Hbase from executors not driver, then create connection per executor, so connection will be reused in the same executor. this way you can same connection creation time overhead, but create table object per thread because hbase table object is not thread-safe(check out Hbase client official document).
and of course, close table and connection whenever you are done.
// this object will make connection reside on executor side not Driver
// and serve as a singleton per executor JVM, which makes connection shared between executor threads, connection is thread-safe!
object HbaseHandler {
  var connection: Option[Connection] = None

  def put(put: Put): Unit = {
    if(connection.isEmpty) {
      val conn = ConnectionFactory.createConnection(HBaseConfiguration.create(configuration))

      connection = Some(conn)
    }

    connection.get.<do some stuff>
    val table = ...
    try {
      table.put(put)
    } finally {
      table.close()
    }
  }
}

...

rdd.foreach (
  row => {
    val put: Put = <generate put object>
    HbaseHandler.put(put)
  }
)

=========== as in the code example above =========
object Hbase {
  private var hbaseConnection: Option[Connection] = None

  private def connection: Connection = {
    if(hbaseConnection.isEmpty) {
      hbaseConnection = Some(ConnectionFactory.createConnection(HBaseConfiguration.create(configuration)))
    }

    hbaseConnection.get
  }
  def extractInfo(fp: String) = {
    val p: Parser = new AutoDetectParser()
    val fs = FileSystem.get(new java.net.URI("XXXXXXXXXX"), new Configuration())
    val inputPath: Path = new Path(fp)
    val is: InputStream = fs.open(inputPath)
    val handler: BodyContentHandler = new BodyContentHandler(-1)
    val metadata: Metadata = new Metadata()
    try {
      p.parse(is, handler, metadata, new ParseContext())
      is.close()
      val hand = handler.toString()
      val gson = new Gson
      val jsonTree = gson.toJsonTree(metadata)
      val metaNode = jsonTree.getAsJsonObject().getAsJsonObject("metadata")
      val jsonString = gson.toJson(metaNode)
      if (hand.trim().isEmpty()) {
        println("no Text extracted", inputPath)
      } else {
        println("Success")
      }
      val fname = "ABC"
      val configuration: Configuration = HBaseConfiguration.create()
      configuration.set("hbase.zookeeper.quorum", "XXXX")
      configuration.set("hbase.zookeeper.property.clientPort", "XXXX")
      configuration.set("zookeeper.znode.parent", "/hbase-XXX")
      configuration.set("hbase.client.keyvalue.maxsize", "0")
      val principal = System.getProperty("kerberosPrincipal", "XXXXX")
      val keytabLocation = System.getProperty("kerberosKeytab", "XXXXXXXXX")
      UserGroupInformation.setConfiguration(configuration)
      UserGroupInformation.loginUserFromKeytab(principal, keytabLocation)
      val admin = connection.getAdmin
      val hTable: HTable = new HTable(configuration, "XXXXXXXXX")
      val g = new Put(Bytes.toBytes(fname))
      g.add(Bytes.toBytes("txt"), Bytes.toBytes("text"), Bytes.toBytes(hand))
      hTable.put(g)
      val m = new Put(Bytes.toBytes(fname))
      m.add(Bytes.toBytes("data"), Bytes.toBytes("info"), Bytes.toBytes(jsonString))
      hTable.put(m)
      hTable.close()
      fs.close()
    }
    catch {
      case e: Throwable => {
        println(e.printStackTrace)
      }
    }
  }
}

object App {
  def main(args : Array[String]) {
    val fnames = "/X/X/XXXXX.XXX"
    fnames.foreach{x => Hbase.extractInfo(x) }
  }
}


text:
Q: JQuery -How to fadeOut instead of Sliding up? I have 2 sections called .about-us and .price-list. With 2 buttons that activates them .prices and .about-us-btn. The 2 sections both are hidden by default with JQuery and have a .slideToggle event for each, if one is visible though, it'll slide up if I click the other button for it.
Now I figured, instead of sliding back up, they can do a fadeOut event. It works, but only if   the .price-list is visible first, then click on .prices. (both sections are in the same position, but only one are visible when I click a button). If .about-us is visible first, then if I click on the .prices button, the .about-us will slideUp instead of fading out.
Will anyways. Hope you understand and can help me out!. Heres my JQuery Code:
$(document).ready(function(e){
  // Price-list & About-us are hidden by Javascript
  $("aside.price-list, aside.about-us").hide();
  // Create a slide for the price-list
    $("button.prices").click(function(){
      $("aside.about-us").fadeOut(300);
      $("aside.price-list").slideToggle(300);
  });
  // Create a slide for the about-us
    $("button.about-btn").click(function(e){
        $("aside.about-us").slideToggle(300);
        $("aside.price-list").fadeOut(300);
    });

});

A: Looks like you are trying to create jQuery Accordian effect. The following link should help you.
http://docs.jquery.com/UI/Accordion

A: Instead of .slideToggle() you should use .slideUp() and .slideDown() explicitly here (since you don't know what state they're in initially, like this:
$(function() {
  $("aside.price-list, aside.about-us").hide();
  $("button.prices").click(function() {
    $("aside.about-us").fadeOut(300);
    $("aside.price-list").slideDown(300);
  });
  $("button.about-btn").click(function() {
    $("aside.about-us").slideDown(300);
    $("aside.price-list").fadeOut(300);
  });
});

Or, if you wanted to completely fade each out before the slide happened on the other, use the .fadeOut() callback, like this:
$(function() {
  $("aside.price-list, aside.about-us").hide();
  $("button.prices").click(function() {
    $("aside.about-us").fadeOut(300, function() {
      $("aside.price-list").slideDown(300);
    });
  });
  $("button.about-btn").click(function() {
    $("aside.price-list").fadeOut(300, function() {
      $("aside.about-us").slideDown(300);
    });
  });
});


text:
Q: Jest not recognising JQuery Object ($) I have used JavaScript to created a simple web application to measure how much time I spend on different projects.
I want to test the code with Jest and this works fine until I try to test a function that contains the JQuery object ($).
This is the error message I get:
ReferenceError: $ is not defined

The answers I have found online tells me that I need to add a jQuery dependency in my global object, which I have done. Below is my package.json file:
"jest": {
    "setupFiles": ["PathToSetupFile/setup-jest.js"],
    "type": "module"

and my setup-jest.js:
import $ from 'jquery';
global.$ = global.jQuery = $;

I am now met with a new error message:
SyntaxError: Cannot use import statement outside a module

I cannot find any further information on how to fix this. A few resources tell me I need to update my jest.config.js file but this file does not exist anywhere in my node modules.

A: I thought it would be helpful to start completely from the beginning and therefore address a much wider scope but never the less provide the exact answer to your problem at the end of my response here.
In PowerShell CD to your project folder
Install the jest node modules locally into your project folder using
npm install --save-dev jest

Install jest globally so you can use it as a CLI command
npm install jest -g

This installs Jest globally i.e. to your user profile %APPDATA%\npm location
Ensure %APPDATA%\npm is in your user profile environment PATH variable (in Windows settings, "Edit Environment variables for your account")
Check in your PowerShell console that it is in your path using $Env:PATH. (If your %APPDATA%\npm path still isn't showing then restart the PowerShell window, if the terminal is inside VSCode then you will have to restart VSCode so that the terminal inherits the new environment)
In order to import jquery you will need to a) install jquery and b) define a setup file for jest which is referenced in jest.config.js created using jest --init in your project folder.
Install jquery -
npm install --save-dev jquery

Generate jest.config.js -
jest --init

The following questions will help Jest to create a suitable configuration for your project
√ Would you like to use Typescript for the configuration file? ... no
√ Choose the test environment that will be used for testing » jsdom (browser-like)
√ Do you want Jest to add coverage reports? ... yes
√ Which provider should be used to instrument code for coverage? » v8
√ Automatically clear mock calls, instances, contexts and results before every test? ... yes
✏  Modified your\project\folder\package.json
  Configuration file created at jest.config.js
If you don't specify the jsdom (browser-like) test environment then running code under test that uses jquery will yield an error of "jQuery requires a window with a document"
But this means the 'jest-environment-jsdom' must now be installed
(As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.) -
npm install --save-dev jest-environment-jsdom

Edit jest.config.js
Change
   // setupFiles: [],
To
   setupFiles: [ './jest.setup.js' ],

N.B. the "./" prefix is required otherwise jest will state it cannot find the jest.setup.js file.
The create jest.setup.js in your project folder and add the following -
const $ = require('jquery');
global.$ = global.jQuery = $;

Node uses the CommonJS module system (https://nodejs.org/en/knowledge/getting-started/what-is-require/)
so the above syntax is required to work with Node.js


text:
Q: How can I loop through numbered variables in javascript I have data that is being returned from a JQuery .ajax function as an array.
Now the fields in that array are named & numbered i.e part1, part2, part3, etc.
I have some code below that I thought may loop through it but it returns NaN.
for (var a = 1; a <= 9; a++) {
newtext += '
' + (exploded[0].part + a) + '
';
}

I couldn't get any of the sugegstions to work so I did this instead.
var h = new Array();
h[1] = exploded[0].part_1;
h[2] = exploded[0].part_2;
h[3] = exploded[0].part_3;
h[4] = exploded[0].part_4;
h[5] = exploded[0].part_5;
h[6] = exploded[0].part_6;
h[7] = exploded[0].part_7;
h[8] = exploded[0].part_8;
h[9] = exploded[0].part_9;

I know it is a bit long winded but when I am dealing with multiple songs also I can loop them all with the array keys.

A: Try it this way:
for (var a = 1; a <= 9; a++) {
    newtext += '
' + (exploded[0]['part_' + a]) + '
';
}

A: You can iterate/loop through the items of array like this. You should use the property 'length' of array variable which tells how many items an array have...
var myStringArray = ["part1", "part2", "part3"];
for (var i = 0; i < myStringArray.length; i++) {
    alert(myStringArray[i]);
    //Do something
}

A: Make sure you array exploded has 10 elements becuase the index of an array start with Zero so for 9 elements you can write the code like this
   for (var a = 0; a <= exploded.length; a++) {
        newtext += '
' + (exploded[a].part + a) + '
';
        }
    alert(newtext);

Modified Response to access the propery dynamically ---------
    var newtext='';
            alert('hi');
    var exploded= {"title":"Cornerstone","firstline":"","keysignature":"C","copyright":"","part_1":"sandeep","part_2":"","part_3":"","part_4":"","part_5":"","part_6":"","part_7":"","part_8":"","part_9":"","ref":"2"};
    var prop='';
    var newhtml='';

    for (var a = 1; a <= 9; a++) {
        prop='part_' + a;

        newhtml+='
' + (exploded[prop]) + '
';
    }
    alert(newhtml);

A: What about the following:
var array=["part1", "part2", "part3"];
html=array.map(function(o){ return '
'+o+'
' }).join("")
console.log(html);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fmap


text:
Q: Inserting and removing text into a textbox on a SHEET in Libreoffice calc BASIC As I can't solve my problem I'd like to ask someone more experienced.I created simple dialog (4 fields) to let the user enter few data. After clicking "Submit" button those data should be inserted into textboxes put ON THE SHEET (not on any dialog). How to refer to those sheet texboxes in code to insert those data? Other thing is deleting those data after clicking other button "Clear". Suppose it will be similar to inserting but how this piece of code should look like?
Thanks in advance.

A: The trick is to create a com.sun.star.drawing.TextShape object and add it to the Draw Page of the target sheet. The following works for me. You should be able to assign it to the appropriate button on your dialog.
Sub InsertTextBox()

    Dim oDocument As Object
    oDocument = ThisComponent

    If oDocument.SupportsService("com.sun.star.sheet.SpreadsheetDocument") Then

        Dim sText As String
        sText = "Blah,blah, blah!"

        Dim oPosition As New com.sun.star.awt.Point
        oPosition.X = 1000
        oPosition.Y = 1000

        Dim oSize As New com.sun.star.awt.Size
        oSize.Width = 10000
        oSize.Height = 5000

        Dim oTextShape As Object
        oTextShape = oDocument.createInstance("com.sun.star.drawing.TextShape")

        oTextShape.setPosition(oPosition)
        oTextShape.setSize(oSize)
        oTextShape.setPropertyValue("FillStyle", "SOLID")
        oTextShape.Visible = 1

        ' Give it a name so you can find it again when you want to delete it
        oTextShape.setPropertyValue("Name", "Thingy")

        Dim oDrawPage As Object
        oDrawPage = oDocument.getSheets().getByIndex(0).getDrawPage()

        oDrawPage.add(oTextShape)

        ' Set the string of the text shape AFTER adding it to the
        ' draw page, otherwise the text will not be set.
        oTextShape.setString(sText)

    End If

End Sub

In the above routine the TextShape object was given the name "Thingy". You can obviously give it any name you like, but it should be unique. To delete it, you need to loop through all the objects in the draw page, find the one that is a TextShape and has the name you gave it (in this case "Thingy") and remove it. This can be done as follows:
Sub DeleteTextBox()

    Dim oDocument As Object
    oDocument = ThisComponent

    If oDocument.SupportsService("com.sun.star.sheet.SpreadsheetDocument") Then

        Dim oDrawPage As Object
        oDrawPage = oDocument.getSheets().getByIndex(0).getDrawPage()

        Dim oShape As Object
        Dim i As Long
        For i = (oDrawPage.getCount() - 1) To 0 Step -1
            oShape = oDrawPage.getByIndex(i)
            If oShape.SupportsService("com.sun.star.drawing.TextShape") Then
                If StrComp(oShape.getPropertyValue("Name"), "Thingy") = 0 Then
                    oDrawPage.remove(oShape)
                End If
            End If
        Next i
    End If

End Sub

This will delete all objects of type TextShape and named "Thingy"


text:
Q: Connect Android App with My SQL database stored on the local machine What are the ways in which I could accomplish the above?
The current one I employ uses a JDBC Connector with the app.
 My question is?
In the following steps:
static final String DB_URL = "jdbc:mysql://localhost:3306/mess";
static final String USER = "root";
static final String PASS = "root";

public Connection connection_open(){
    Connection conn=null;
    try{
         Class.forName("com.mysql.jdbc.Driver").newInstance();

         conn = DriverManager.getConnection(DB_URL,USER,PASS);
         System.out.println("\n Connection inside DB = OK");
      }

   catch(SQLException se){
       System.out.println("\n Connection inside DB = failed");
       se.printStackTrace();
      }

    finally {
        if(conn==null)System.out.println("\n Have to return NULL");
             return conn;
        }
}

This always outputs:
Connection inside DB = failed
Have to return NULL

So, in the localhost section of the DB URL, do I have to write the IP of my android phone, which I use to debug?
Is it even possible, that my app connects remotely (assuming I have granted privileges to all IP's)
Please help :)

A: This won't work. First of all, this is wrong:
static final String DB_URL = "jdbc:mysql://localhost:3306/mess";

The localhost will be your android phone and it doesn't have any MySQL database in it.
You should plan a webservice that takes care of all requests to your DB and send the results back to your app.
To access/connect to your webservice, you could use HttpURLConnection.

A: What do you wish to achieve?
Your android app should save and upload data to a central server location?
- If answer is yes, your options are Parse ( which you already tried i guess ) or build your own rest server api quickly. My personal fav is python rest api server on Google App Engine. https://cloud.google.com/appengine/docs/python/
If your android app should save data on the android device and need not communicate to any server then create local instance of sqlite database and store retrieve data from it.
Try this out - http://satyan.github.io/sugar/

A: There are possibilities that you can run mysql database in android .But for that you have to cross compile the mysql source code for arm architecture becoz mobile phones have arm architecture
You can use android ndk or arm gcc compiler for cross compilation. Once you copiled your libs it will generate the .so files (extension in linux ) .You have to add these libs to your project. Then using jni you have to write a c program that will use the mysql functions. like crud operation then using jni then you have to call that native  c program from your java code . this way you can  do this. I did this once. But it is a very tedious and cumbersome task.


text:
Q: Processing data while keeping frozen frontend database online What is the best approach at having a "frontend" database online and working, while processing and generating new data in the back?
I have an scenario that some tables and even whole databases data needs to be manipulated and regenerated. After this processing is done, the new data is promoted to production (frontend). Once the processing is done, all the new data have to be available at once. So it can't be processed online.
I've come up with two different solutions, I'd like feedback on them since I'm not totally happy with either of them:

*

*Work with snapshots while this processing is being performed. Once the processing is finished, re-create the snapshot with the current data and leave the real database ready to process again. This would have the downside of higher IO activity and fragmentation.

*Work with an additional backend server and schema of backup-restore from one server to the other and then back. This would have the downside of network traffic, storage requirements, times and is more complex and prone to have issues. It would also require an additional server (thus, costs).
Environment: SQL Server 2014 Enterprise.
Additionally, I've been looking into Snapshot replication. But I'm not familiar with it. Given the data is not updated often (maybe once or twice a month) it looks like a potential solution as well.


text:
Q: Postgres copy Heroku Production DB to local development DB I have a heroku database, d76mj7ltuqs.
I then have a local database, test_development.
The schema is the same on both of these databases - I want to pull all of the data from my production database and overwrite my local database, so that local is an exact replica of production at the time of pull.
How can I do that in Postgres?

A: Use heroku's "pg:pull":
You'll need to clear your local DB:
rake db:drop

Then collect some information from Heroku:
heroku pg:pull DATABASE_URL test_development

This will connect to the heroku DB, and copy it to the local database.
See Heroku's documentation on pg:pull for more details.

A: clean your local database:
rake db:schema:load

dump your heroku database:
heroku pg:backups:capture -r <**your production git repo name**>
heroku pg:backups:download -r <**your production git repo name**>

load data in your local database
pg_restore --verbose --clean --no-acl --no-owner -h localhost -d <**test database name**> latest.dump

A: this is how i do it, be sure to gzip it as your database grows. also don't export the ACL as you likely don't have the same postgres user on heroku and local accounts. replace  with your specific details.
 pg_dump -h ec2-##-##-##-##.compute-1.amazonaws.com -p <port> -Fc --no-acl --no-owner -o -U <username> <databasename> | gzip > dumpfile.gz
 #<Prompt for Password>
 gunzip -c dumpfile.gz | pg_restore --verbose --clean --no-acl --no-owner -d test_development -U <local_username>

A: This command should do the work:
heroku pg:pull DATABASE_URL database-name --app heroku-app-name

A: Use your terminal to make a local pg_dump and then either psql or pg_restore it into your local database.
Similar method can be found here.

A: If this is a Rails app, you can use the following script to overwrite your local database with the latest dump you've generated on Heroku. If you uncomment the line with heroku pg:backups capture, the script will generate a new snapshot on Heroku before downloading it to your machine.
Note that you shouldn't have to edit the script, since it reads all the configuration from your database.yml file.
#!/usr/bin/env ruby

require_relative '../config/environment'

# Uncomment the line below if you want to generate a new snapshot of the
# Heroku production database before downloading it to the local machine
# `heroku pg:backups capture`

database_dump_file_pathname = Tempfile.new('latest.dump').path
`heroku pg:backups:download --output #{database_dump_file_pathname}`

# Get database config fom database.yml file
database_config = YAML::load_file(Rails.root.join('config', 'database.yml'))
database_name = database_config['development']['database']
database_username = database_config['development']['username']
database_password = database_config['development']['password']

# Overwrite local database with dump
cmd_line_arguments = [
  '--verbose',
  '--clean',
  '--no-acl',
  '--no-owner',
  '--host localhost',
  "-U #{database_username}",
  "-d #{database_name}",
  database_dump_file_pathname
].join(' ')
`PGPASSWORD=#{database_password} pg_restore #{cmd_line_arguments}`

See the Heroku docs on downloading DB backups for details.