text:
Q: STM32 convert an unsigned short array to a float array I have been doing research in google, however I cannot find a solution.
How to convert an unsigned short array to a float array in STM32? I need to perform multiplication between an unsigned short array with a float array. To use FPU and DSP library for STM32F4, the unsigned array is to be converted to floating point first.
There are only libraries converting signed short arrays to float arrays. How to convert an unsigned short array to a float array?

A: By just storing them as float, I'd say:
void uint16_to_float(float *out, const unsigned short *in, size_t num)
{
  for(; num > 0; --num)
    *out++ = *in++;
}

It's up to the compiler to figure out what instruction(s) are best suited for this, but it's a pretty standard operation.


text:
Q: XCODE AppelScript ObjC : set a variable property parent : class "NSObject"

    -- IBOutlets
    property theWindow : missing value
    set value1 to :value number 1

on buttonClick_(sender)
         set the clipboard to value1
    end buttonClick_

I'm very lost with the way Xcode is handling variable. My variable are reported not defined, I figured out that this is actually not the case when I set the variable in a "sender"
but what If I want to use a variable outside a button/sender ? or what if I want to use the same variable in two different buttons.
I have the feeling that what I'm asking not making much sense but hopefully someone will get me there.

A: It's like in Objective-C or Swift:
Either declare a property with a default value:
property value1 : 1

Or declare the property without a value and set the value in a handler:
property value1 : missing value

...

on applicationDidFinishLaunching_(aNotification)
   set value1 to 1
end applicationWillFinishLaunching_

AppleScript code must always run in a handler. Even in a simple compiled script if you write code on the top level of the script the compiler wraps the code in the implicit on run handler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create multiple checkbox handlers in jQuery? I have these 2 checkboxes:
<form action="">
    <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike

    <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>

The events for each checkbox:
jQuery(function () {
$("#carCheckbox").click(function () {
    if($("#carCheckbox").is(":checked")) {
        alert("it works");
    }
})
});

jQuery(function () {
$("#carCheckbox").click(function () {
    if($("#bikeCheckbox").is(":checked")) {
        alert("it works");
    }
})
});

Now what I want to do is create a for or some kind of loop to create event handlers for multiple checkboxes. So far I am stuck at this code:
jQuery(function () {
var infoArray = ["car", "bike"];

for(var i = 0; i < infoArray.length; i++) {
    var id = "#" + infoArray[i] + "Checkbox";

    $(id).click(function () {
        var myCheckbox = "#" + infoArray[i] + "Checkbox;
        if($(myCheckbox).is(":checked")) {
            alert("it works");
        }
    })
}
});

Any help is greatly appreciated.

A: <form action="">
    <input id="bikeCheckbox" class="mybox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike

    <input id="carCheckbox" class="mybox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>

$('#save_value').click(function(){
$('.mybox:checked').each(function(){
     alert($(this).val());
}); });

you try to add class name same for ever check box and used the

A: You don't need to create an array to save all these values and loop these.
And you definitely don't need a function for each checkbox!
Add a class to your checkboxes you want to check, for example :
<form action="">
    <input id="bikeCheckbox" class="mycheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike

    <input id="carCheckbox" class="mycheckbox" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>

Then you can easily loop like this:
jQuery(function () {
    // Whenever any of these checkboxes is clicked
    $("input.mycheckbox").click(function () {
        // Loop all these checkboxes which are checked
        $("input.mycheckbox:checked").each(function(){
            alert("it works");
            // Use $(this).val() to get the Bike, Car etc.. value
        });
    })
});

A: use JQuery's each function
jQuery(function () {
    $(":checkbox").click(function () {
         $(':checkbox:checked').each(function(i){
            alert("it works");
          });
     });
}

A: if you want to do it by some grouping, like if you want to see only in some of the checkbox in a group, you can use the class name like this below
<form action="">
    <input id="bikeCheckbox" class="myCheckBoxGroup" type="checkbox" name="bikeCheckbox" value="Bike">I have a bike

    <input id="carCheckbox" class="myCheckBoxGroup" type="checkbox" name="carCheckbox" value="Car">I have a car
</form>
jQuery(function () {
    $(".myCheckBoxGroup").click(function () {
        $(".myCheckBoxGroup").each(function(){
            if($(this).is(":checked")) {
                alert("this is checked");
            }
        });
    })
});

A: Try this.
<input id="chk_bikeCheckbox"  type="checkbox" onclick='UpdateIdinHF(this);' name="bikeCheckbox" value="Bike">
<input id="chk_carCheckbox" class="mycheckbox" onclick='UpdateIdinHF(this);' type="checkbox" name="carCheckbox" value="Car">

 function UpdateIdinHF(obj) {
        var id = $(obj).attr('id');
        var name = $(obj).attr('name');
        var value = parseInt($(obj).attr('value'));
        var IsChecked = $(obj).is(':checked');

            $('input[id*="chk_' + name + '"]').each(function () {
                if (parseInt($(this).val()) != 0) {
                    if (IsChecked == true) {
                        $(this).attr('checked', 'checked');

                    }
                    else {
                        $(this).removeAttr('checked');

                    }
                }
            });

    }

A: You can try this also

A: You don't need to define classes. Use the following snippet to directly access to the checkbox you have clicked.
$(document).on("click", "input[type='checkbox']", function (e) {
     console.log(e.target);
});


text:
Q: @Inject not working in vue with typescript Am trying to inject a service in vue as follows.
in more-information.component.ts
@Inject('moreInformationService') private moreInformationService: () => MoreInformationService;

in more-information.service.ts
import axios from 'axios';
import { Store } from 'vuex';
export default class MoreInformationService {
  constructor(private $store: Store<any>) {
  }
}

But am getting the following Waring in console and its not working as expected
webpack-internal:///./node_modules/vue/dist/vue.esm.js:629 [Vue warn]: Injection "moreInformationService" not found

found in

---> <MoreInformation> at src/main/webapp/app/MSB/products/more-information/more-information.vue
       <BlankLayout> at src/main/webapp/app/MSB/layouts/BlankLayout.vue
         <App> at src/main/webapp/app/app.vue
           <Root>

A: I forgot to register the service using provide
The following changes fixed my issue,
import MoreInformationService from '@/products/more-information/more-information.service';

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  router,
  provide: {
    moreInformationService: () => new MoreInformationService(store)
  },
  store
});

if there any better option please answer.


text:
Q: Angular file input changes only shows in the first component I have an image component formed from two input types :
1- text input
2- file input

image.html

 <mat-card>
    <mat-card-content>
        Take picture
        <input id="cam" style="display: none;" type="file" accept="image/*" capture="camera" (change)="onSelectFile($event)" />
OR

        Open gallery
        <input id="gallery" style="display: none;" type="file" accept="image/*" multiple (change)="onSelectFile($event)" />
    </mat-card-content>

    <mat-card-header *ngIf="imagesList.length > 0">
        <mat-card-subtitle>Click on image to remove it</mat-card-subtitle>
    </mat-card-header>
</mat-card>

<input type="text"   placeholder="Ex. pat@example.com">

image.ts

  import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-image',
  templateUrl: './image.component.html',
  styleUrls: ['./image.component.css']
})
export class ImageComponent implements OnInit {
  files!: File[];

  imagesMap: Map<string, string> = new Map<string, string>();
  imagesList: string[] = new Array<string>();
  url = "";
  constructor() { }

  ngOnInit(): void {
  }

  onSelectFile(event: any) {
    this.files = event.target.files;
    if (this.files && this.files.length > 0) {

      for (let file of this.files) {
        if (!this.imagesMap.has(file.name)) {

          let url: string = "";
          var reader = new FileReader();
          reader.readAsDataURL(file);

          reader.onload = (event) => {
            //@ts-ignore
            url = event.target.result;
            this.imagesMap.set(file.name, url);
            this.imagesList.push(file.name);
          }
        }
      }
    }
  }

  deleteImage(imageName: string) {
    let indexToRemove = this.imagesList.indexOf(imageName);
    if (indexToRemove != -1) {
      this.imagesList.splice(indexToRemove, 1);
      this.imagesMap.delete(imageName);
      indexToRemove = this.files.findIndex(file => file.name == imageName);
      if (indexToRemove != -1)
        this.files.splice(indexToRemove, 1);
    }
  }
}

The problem is that when I call this component several times or duplicate it from app components ,

app.component.html

<app-image></app-image>
<app-image></app-image>

the image that had been selected from the second or third … component , it always shows in the first one instead, this problem is with inputs of type File , inputs with type text are working fine . Kindly refer to the image below for a clearer view.
Component screenshot
I want to when I  add pictures in the second component (same component but duplicated) , they must shows in the second component . Each duplicated component must be independent from others.
Please can help me to solve this issue.
Thanks

A: That's because of duplicate Id. You have two input with Id of cam and gallery so when you click on second, one browser finds the first element and opens file chooser. It means you basically clicked on first element. don't use this approach, just simply use a template variable
 Open gallery
 <input #file style="display: none;" type="file"
             accept="image/*" multiple (change)="onSelectFile($event)"/>


text:
Q: Can I get missing achievements by replaying missions from the archive? I had some internet connection problems so I have decided to complete some missions offline and I was not credited achievements for these missions. If I want to get these achievements, is going to the archive and completing these certain missions again enough? Or do I have to start the campaign from scratch?
For example, I was not credited an achievement for doing the baneling evolution mission and I really need it for the portrait. I clicked on the Void Seeker which is also needed for a portrait but it shows that I did not click on it.

A: You can get the achievements by replaying the missions from the archive. Don't restart the campaign because, assuming it works the same way as it did in Wings of Liberty, that will kill your ability to use the full mission archive until you complete it again.
And, of course, make sure you stay connected to Battle.net while replaying the missions.
As Raven Dreamer reminded me, anything that requires actions done in-between campaign missions would require restarting the campaign. So, to get the Void Seeker click, you'll have to replay from the beginning up to the point where that's available in the campaign.


text:
Q: searching for a programming platform with hot code swap I'm currently brainstorming over the idea how to upgrade a program while it is running. (Not while debugging, a "production" system.)
But one thing that is required for it, is to actually submit the changed source code or compiled byte code into the running process.
Pseudo Code
var method = typeof(MyClass).GetMethod("Method1");
var content = //get it from a database (bytecode or source code)
  SELECT content FROM methods WHERE id=? AND version=?
method.SetContent(content);

At first, I want to achieve the system to work without the complexity of object-orientation. That leads to the following requirements:

*

*change source code or byte code of function

*drop functions

*add new functions

*change the signature of a function

With .NET (and others) I could inject a class via an IoC and could thus change the source code. But the loading would be cumbersome, because everything has to be in an Assembly or created via Emit.
Maybe with Java this would be easier? The whole ClassLoader is replacable, I think.
With JavaScript I could achieve many of the goals.
Simply eval a new function (MyMethod_V25) and assign it to MyClass.prototype.MyMethod.
I think one can also drop functions somehow with "del"
Which general-purpose platform can handle such things?

A: In Java, you have the OSGi project, which facilitates upgrading and changing modules of your application without touching other modules.
If you don't mind learning something different, the Erlang programming language was designed from the ground up with this type of application in mind.

A: I think any image-based language would support this.  I know Common Lisp does, since it's probably one of the most common ways to deploy Lisp web apps, but I suspect it would work pretty much the same in, say, Smalltalk.

A: Most of dynamic languages have this capability. Take a look at Ruby: you can modify existing methods etc. at runtime. When IronRuby is out, you will be able to do this also in .Net platform.

A: My impression is that right now Erlang is very visible as a language which has this capability.  That said, my father-in-law (a master programmer, in my opinion) has told me that he's implemented hot-swappable code on a somewhat older platform -- assembler for what they now call z/OS (OS/390 before that).
Personally, I've been looking for ways to do this in the Java space, where the vast majority of my professional work is currently done.  In Javaland, the best publicized effort to provide hot-unloading (as far as I know) is the work done by the OSGi Alliance.  That said, this solution necessarily involves some classloader magic because of how some common Java libraries are architected (example: JDBC DriverManager).  If you choose to go down the OSGI route, your code will likely require extensive auditing and testing to ensure that it will be usable with the OSGi architecture.
As an alternative to implementing hot-swappable code, perhaps you could implement a system which appears to have this capability using the potentially simpler mechanism of request queueing.  For example, if you need to hot-swap the piece of your system which processes large, backend requests, why not send these requests through an intermediary which can dispatch them to the backend component if it is running and accumulate them in a queue if the component is down?  This might allow you to upgrade the backend component independently of the rest of your system without redeploying as we say in the industry "the whole shebang".

A: With JavaScript it can be done. Whats amazing is that Google's V8 engine is open source and is easy to implement into any C++ program.
http://code.google.com/p/v8/
Of course you will have to write a bit of a library to have functionality exposed and loading of the script from inside the JavaScript. It will depend on what you are wanting to do.

A:
But one thing that is required for it, is to actually submit the changed source code or compiled byte code into the running process.
  Which general-purpose platform can handle such things?

Erlang was already mentioned, and it uses explicit "synchronization points" where a running routine may explicitly update itself by doing a "self" call using "?MODULE:routine()."
This is another important thing to keep in mind: you don't just need the capability in the VM to replace running code, but the running code also needs a way to respond to such updates and adjust accordingly.
You may also want to look into UpgradeJ which is a language that was specifically designed with this requirement (code hot swapping) mind.

A: Erlang can do everything you are looking for, and it doesn't rely on any bolt-on libraries (unless you count OTP in that category) or coding work-arounds.  It can maintain state (i.e. "values of variables" in imperative-language-speak) across the reload, and does not require transactions to be buffered or retransmitted.  If you write your code in the OTP style then you can have your application programmers write straightforward sequential code that will have some degree of ability to execute in parallel, and to support hot reload, and all this without themhaving to worry about the details of how it's done.  It just works.

A: With .NET this is perfectly implemented via the Managed Extensibility Framework. This framework is introduced in .NET 4. You can build extensible applications. It does what an IoC container could do, although it can do on thing more. It can discover functionality which does not know a priori. Additionally you can update functionality, you do not know that is going to be updated a priori. In other words, it is a framework for modular applications, whether you want to hot swap code chunks and want to provide different functionality, or update already existing.


text:
Q: How do you trigger the duplicate rules before a record is saved on a flow? We have a scenario where we want to prevent users from creating duplicate contacts but want to allow users to be able to create the same contact with same details if its on a different account.
What I have done is created a flow so that it updates the field (Associated_Account__c) before it is saved. My flow will checks if the contact has an account associated
If it does it will add the account id to it
if it doesn't it will add 'No account'.
On my duplicate matching rule I have these conditions set
Email(exact match)
phone (fuzzy match)
Associated Account__c (exact match)
The idea behind this idea is if there are no accounts attached to it they should have 'No Account' and if the phone and email are the same the duplicate rule will flag it and prevent users from creating it.
If there is an account attached to it and because every account has a unique id they should be able to create the contact.
My problem Im having is when i test and try and create the same contacts without an account attached to it the duplicate rule doesn't fire. I am assuming because the field isn't being updated by the flow even though i have it set to update before saving the record.
Am I going about this the correct way or should I have a different approach? I would like to try and code this but I dont know how.
If its simple I would like to have a crack at it.
Thanks


text:
Q: unix timestamp value is getting converted to a scientific format while reading it using pandas I'm trying to read a csv file which has few columns. Some of the columns contains long digits as shown below. Pandas is converting these values into scientific notation.
"85405355309256431514161802018284625587","1","1580459391475",1

If I open the csv using Excel also, they get converted to scientific notation. Is there a way to prevent this and load the data as it is in CSV without converting the values?


text:
Q: How to set up sh script to be ran with Terminal (mac os) by default? I have a sh script (scala compiler). I'm trying to run it from Terminal application: sudo fsc, but it says that the file can't be found. I've set chmod +x, so script should be visible. It's sh script, not bash.
Is it any possible?
UPD: thanks all for the great answers, i really did learn a lot :)
to set up Path properly, everyone can see: http://macosx.com/forums/unix-x11/250180-set-path-environment-variable.html
thx everyone!

A: If the script is in the current directory, you must always prefix its name by "./" which would gave in that case :
sudo ./fsc

Cheers

A: First, if it's in the local directory and not a directly specified in $PATH, you need to preface it with ./ .
Second, once the script is given execute permissions, if it's still not working, try adding #!/bin/sh or whatever the path to the interpreter is at the top.

A: Has sudo been configured with the --wth-secure-path option. If so then it will use a secure path and ignore your path setting altogether.
You can find this out by typing sudo -v when you are already root.
If it is configured with secure path then the only way is to put the command into one of the directorys specifed in secure path or to pass the full pathname as the argument to sudo.


text:
Q: How to add days to date using java DateUtil.addDays(days, date) is there any addDays method in java to add days to a date?
Provide me any solution for this that how to add days to date

A: JDK native date/time handling is pretty poor. The Joda Time library's DateTime is better than java.util.Date class for anything requiring manipulation:
DateTime dt = new DateTime();
DateTime twoDaysLater = dt.plusDays(2);

If you want to create a DateTime from a java.util.Date:
Date nativeDate = new Date();
DateTime dt = new DateTime(nativeDate);

If you need to convert back to a java.util.Date:
Date date = dt.toDate();

A: You can use calendar.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);

A: The closest thing in the JDK is using TimeUnit:
date.setTime(date.getTime() + TimeUnit.DAYS.toMillis(days));

It is interesting to note that (quite unbelievably) Date is not immutable! Just one of many questionable design decisions in the JDK.


text:
Q: Java inheritance; passing a subclass to an abstract method of a superclass Sorry for the title, couldn't come up with anything clearer.
I have the following structure:
public interface Vehicle {...}
public class Car implements Vehicle {...}

then:
public abstract class Fixer {
...
   abstract void fix(Vehicle vehicle);
...
}

and would like to have:
public class CarFixer extends Fixer {
    void fix(Car car) {...}
}

but this doesn't work. Eclipse says: The type CarFixer must implement the inherited abstract method Fixer.fix(Vehicle). Any idea how can I solve this?

A: You can use Generics to solve this:
public abstract class Fixer<T extends Vehicle> {
    abstract void fix(T vehicle);
}

public class CarFixer extends Fixer<Car> {
    void fix(Car car) {...}
}

The problem with your original version is that the fix method allows any type of vehicle, but your implementing class allows only cars. Consider this code:
Fixer fixer = new CarFixer();
fixer.fix(new Bike()); // <-- boom, `ClassCastException`, Bike is a vehicle but not a car

A: You've met the humble home of generics.
Generics provide kind of 'wildcard' type where a class or method can specify that 'we don't really care what type it is, we just need -a- type'.
Generics allow a super class to enforce a specific type in a child class instead of allowing any class that extends a certain class.
This means that you're ultimately enforcing a new highest allowed super-class as the parameter (i.e. Vehicle is no longer the most basic allowable type you can pass to fix(); it's now whatever the subclass says it is, so long as that arbitrary type extends Vehicle).
Common places for generics are container classes (i.e. List, Map, and Set) where the container doesn't really care about what type it tracks, but rather focuses on actually tracking and managing those instances.
Generics consist of one or more type placeholders (in Java, E and T are commonly used but the name doesn't really matter; they usually follow the normal type naming conventions) that are used in place of a specific class or super class.

In your code, you want subclasses to implement methods given their exact relevant types (i.e. a CarFixer would take Cars, a JetpackFixer would take Jetpacks) but you want to enforce that these types extend Vehicle.
In order to enforce this, you have to tell the Fixer class exactly what your subclass wants.
public abstract class Fixer <E extends Vehicle>
{
    abstract void fix(E vehicle);
}

Your subclass then extends Fixer, filling in E with the type it wants.
public class CarFixer extends Fixer<Car>
{
    @Override
    void fix(Car vehicle)
    {
         // ...
    }
}


text:
Q: Lógica de uma implementação de rede neural Olá, Bom Dia
Fiz a implementação de uma rede, e nela se tem a seguinte matriz, onde f(x) é um vetor de entrada (matrix 1,139), a matriz phi que tem dimensão 1,20 (20 devido ao numero de sinais que usei pra treina-la) e w como sendo os pesos que são de dimensão 20,1
for k in range(0,20):
    for item in range(0,139):
        substract += (s[0,item] - phi[0,k])            # phi = 20,20

    mod = np.linalg.norm(substract)

    substract = 0

    if(mod > 0):
        substract = (mod*mod)*math.log10(mod)
        phi_matrix_final.append(substract)
    else:
        phi_matrix_final.append(mod)

    mod = 0
    substract = 0

Sn = 20, devido ao numero de entradas pro treinamento
Problema dessa rede é que ela sempre retorna um valor muito próximo um do outro, já que as respostas deveriam ser entre 0 e 10
Observação: Uso a função r²log(r)

A: Você deve ter uma só entrada na rede, com uma amostra de treinamento de 139 pontos, por isso que phi tem dimensão 1x20 e os pesos, dimensão 20x1.
O que não está claro é por que você tem 139 saídas,
        substract += (s[0,item] - phi[0,k])          # phi = 20,20
                                                     # item varia de 0 a 139, ou seja, são 139 saídas?

O código, eu acho, deveria ser o seguinte, segundo sua equação,
x = [] # 139 amostras
s = [[]] # 139 amostras x 20 saídas esperadas

mod = 0.0 # forçando um erro em phi
modant = 1.0 # forçando um erro em phi

phi = np.zeros((1, 20)) # 1 entrada e 20 saídas

ctr = 0

eta = 0.3 # amortecimento

while abs(1 - mod/modant) > 0.01 and ctr < 10000:
    ctr += 1
    modant = mod

    for item in range(0,139):
        for k in range(0,20):
            phi[0,k] += eta* (x[item] - s[item,k])

        mod = np.linalg.norm(s)
        if mod > 0:
            phi = (mod*mod*math.log10(mod)) @ phi


text:
Q: Can't run npm install on Ubuntu 20.4 server I have a node.js application that I want to run on an Ubuntu 20.4 server, when I try to run the command npm install, I see the following error, I do not have root access on the server, where can this problem be? I have version 6.14.3 of npm and version 14.15.3, how can i deal with this problem?

```
npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generated for lockfileVersion@2. I'll try to do my best with it!

> core-js@2.6.12 postinstall /var/www/site/public_html/node_modules/@nuxt/babel-preset-app/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js@3.10.2 postinstall /var/www/site/public_html/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

> bootstrap-vue@2.21.2 postinstall /var/www/site/public_html/node_modules/bootstrap-vue
> opencollective || exit 0

sh: 1: opencollective: Permission denied

> nuxt@2.15.4 postinstall /var/www/site/public_html/node_modules/nuxt
> opencollective || exit 0

sh: 1: opencollective: Permission denied

> swiper@5.4.5 postinstall /var/www/site/public_html/node_modules/swiper
> echo "Love Swiper? Support Vladimir's work by donating or pledging on patreon:
 > https://patreon.com/vladimirkharlampidi
"

Love Swiper? Support Vladimir's work by donating or pledging on patreon:
 > https://patreon.com/vladimirkharlampidi

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/watchpack-chokidar2/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1334 packages from 697 contributors and audited 1338 packages in 17.59s

102 packages are looking for funding
  run `npm fund` for details

found 58 vulnerabilities (39 moderate, 18 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
```

A: This might have the issue with permission
Try this

sudo npm cache clean
sudo npm install


text:
Q: How to convert a string of integers into a vector full of int's? I know other questions have been asked about this same thing, however, I have used those other resources to come up with what I have now and I am getting an error that I can't seem to figure out. Also, keep in mind that I am a c++ beginner. That being said, I have a very large string filled with integers formatted as follows:
newString = "12 -34 50 2 -102 13 78 9" (the actual string is much larger). I then try to create a function using transform() to convert the string into a vector of int's:
int convertString(){

    istringstream is(newString);
    vector<int> intVector;
    transform(istream_iterator<string>( is ),
              istream_iterator<string>(),
              back_inserter( intVector ),
              []( const string &newString ){ return ( stoi( newString ) ); } );//This is the line indicated in the error!
    for(int x : intVector )
        cout << x << ' '<<endl;

    return 0;
    }

The error that I am getting is That there is an expected expression at the indicated error line...
Any ideas how to fix this?
Thanks in advance and just let me know if anything is unclear!

A: Assuming you're reasonably certain the input contains only properly formatted ints, (or can live with just stopping reading when/if something other than a readable integer is encountered) there's no need for transform here--the istream_iterator itself can handle the conversion perfectly well. You can initialize the vector directly from the iterators, giving code like this:
std::istringstream is(newString);
std::vector<int> intVector { std::istream_iterator<int>(is),
                             std::istream_iterator<int>()};

This would differ from your version in one respect: if you give a string to stoi that it can't convert to an integer, it'll throw an exception--invalid_argument if it contains something like ac; that can't convert to an integer at all, or out_of_range if it contains something like 50 digits, that produce a result that won't fit in the target type.


text:
Q: Get xmltype in field in Oracle column CLOB I have a column CLOB type that contain xml format.
I need to get with a simple query all different type from this field:
Ex. The field contain different types:
First record:
<Message type="New Address" xmlns="http://euroconsumers.org/ecommerce/2009/01/scope/messages"><Customer ...

Second record:
<Message type="Added Email" xmlns="http://euroconsumers.org/ecommerce/2009/01/scope/messages"><Customer ...

Third record:
<Message type="New Order" xmlns="http://euroconsumers.org/ecommerce/2009/01/scope/messages"><Customer ...

I would like to retrieve:
New Address
Added Email
New Order

A: This works for your data:
select xmlquery('/*/@type'
  passing xmltype(<clob column>)
  returning content)
from <your table>;

Demo:
create table t42 (clob_col clob);
insert into t42 values ('<Message type="New Address" xmlns="..."><Customer type="x"></Customer></Message>');
insert into t42 values ('<Message type="Added Email" xmlns="..."><Customer></Customer></Message>');
insert into t42 values ('<Message type="New Order" xmlns="..."><Customer></Customer></Message>');

select xmlquery('/*/@type'
  passing xmltype(t42.clob_col)
  returning content)
from t42;

XMLQUERY('/*/@TYPE'PASSINGXMLTYPE(T42.CLOB_COL)RETURNINGCONTENT)
----------------------------------------------------------------
New Address
Added Email
New Order

Or this:
select xmltype(<clob_column>).extract('/*/@type')
from <your table>;

Demo:
select xmltype(clob_col).extract('/*/@type')
from t42;

XMLTYPE(CLOB_COL).EXTRACT('/*/@TYPE')
-------------------------------------
New Address
Added Email
New Order

Read more about querying XML.


text:
Q: how to add edittext to a linearlayout dynamically at desired positions to the linearlayout in android I am new to android ,Actually   i want to add edittexts to a relativelayout or linearlayout at desired positions on the layout .plz suggest me.
 thanks in advance..

A: Do you really need add an EditText programmatically?
Usually it is enough to hide certain Views and change the visibility programmatically.
<EditText android:id="@+id/view_name"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:visibility="gone"
        />

The three values for visibility are "visible", "invisible" and "gone". "gone" means the EditText is taking no space. "invisible" means that the space it would take is empty.
You can change the visibility the following way:
EditText editText = (EditText) findViewById(R.id.view_name);
editText.setVisibility(View.VISIBLE);


text:
Q: PHP welcome screen echo username I am building a welcome user page - after my user logs in, I want on each page to echo the name of the user. however I am having difficulty, after looking at various forums I have resulted into posting my code in the hope someone may have an idea where I am going wrong.
I have 2 key pages - Login and the Index page.
Login.php page
    <?php
    session_start();
    require("includes/connect.php");
    ?>

    <!DOCTYPE html>

            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Login</title>
            <link rel="stylesheet" type="text/css" href="css/login.css">

            <link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css">
            <link rel="stylesheet" type="text/css" href="css/bootstrap.css">

                <form class="form-signin" role="form" action="login.php" method="post">

Please sign in

                    <input type="text" class="form-control" placeholder="Username" name="username_login" required autofocus>
                    <input class="form-control" type="password"  placeholder="Password" name="user_password" required>
                    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
                    Forgotten password?
                </form>

    <?php

    //if an admin or user session is already in progress then dont let them log in, redirect to 'index.php'
    if (isset($_SESSION['admin']) && ($_SESSION['admin'] == true) || isset($_SESSION['user']) && ($_SESSION['user'] == true)) {
        echo "You are already logged in";
        //if use not logged in then
     }else
        if ( trim($_POST['username_login']) AND trim($_POST['user_password']))
        {
        //if username and password are entered, blank before user fills form
        $usr = (isset($_POST['username_login'])? $_POST['username_login']:null);
        $pwd = (isset($_POST['user_password'])? $_POST['user_password']:null);

        //$usr = mysqli_escape_string($usr); //Prevent against SQL Injection by avoiding "\" being executed
      //  $pwd = mysqli_escape_string($pwd); //Prevent against SQL Injection by avoiding "\" being executed

        if ($usr && $pwd){
            $epwd = $pwd;
            $q = "SELECT * FROM users WHERE UName='$usr' LIMIT 1;";
            $resultset = mysqli_query($conn,$q);
            $rowcount = mysqli_num_rows($resultset);

            if ($rowcount==1){
                while ($userRow = mysqli_fetch_assoc($resultset)){
                    //Get the DB username and password to compare
                    $dataBaseEmail = $userRow['UName'];
                    $dataBasePass = $userRow['Password'];
                    $userGroup = $userRow['UserLevelID'];

                }

            mysqli_free_result($resultset);
            unset($q);

            //Compare DB user and pass to those entered
            if ($usr == $dataBaseEmail && $epwd == $dataBasePass){
                //Now that we know they are activated ect, we can create a session based on their privlidges
                if ($userGroup ==1){ //ADMIN load the console
                    $_SESSION['admin'] = true;
                    //header("Location: admincreateuser.php");
                    echo '
You are an admin user Admin.
';

                    //exit;
                }else{ //Normal User
                    $_SESSION['user'] = true;
                    $_SESSION['user'] = $dataBaseEmail;
                    //header ("Location: index.php");
                    echo '
You are a standard user Standard.
';
                    //exit;
                    }
                }else{//user and pass do not match DB
                    echo '
Incorrect Password, try again
';
                }
            }else{
                echo '
Error: There is no such user registered on the system. Please check the username and password entered.
';
            }
        }
    }
    ?>

Index.php page:

<?php
session_start();
include "includes/header.php";
include "includes/connect.php";
?>

Operating system being used:<?php echo $os?>

Text

<?php echo $os?>
<?php

echo "Hello" .$_SESSION['user'];
?>

Many thanks in advance.

A: You have used $_SESSION['user'] for two purposes, you can rename any one of the $_SESSION array
Try this,
  $_SESSION['user'] = true;
  $_SESSION['userEmail'] = $dataBaseEmail;

instead of
  $_SESSION['user'] = true;
  $_SESSION['user'] = $dataBaseEmail;

And in welcome screen,
if(isset($_SESSION['user'])){
  echo "Hello" .$_SESSION['userEmail'];
}


text:
Q: How to navigate from MasterView's TableViewCell (Xib Cell) to DetailView's TableView I have a master-detail view application in which MasterView's table cell is a Xib cell. I also have two TableViews in DetailViewController placed side by side as shown below:
Master and Detail Views
Now my problem is I am unable to populate DetailView's Table View when I am clicking on Master's TableViewCell. I am pasting my code below:
class MasterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var devarlViewController: DetailViewController? = nil
var objects = [Any]()
var statesList = ["AL", "GA", "AK", "AR", "AZ", "CA", "CO", "CT", "CO"]

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
    // Do any additional setup after loading the view, typically from a nib.
    }

// MARK: - Table View

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return statesList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel!.text = statesList[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    DetailViewController.sharedDetail.selectedState = (self.tableView(tableView, cellForRowAt: indexPath).textLabel?.text)!
    DetailViewController.sharedDetail.selectedCity = ""
}

}
class DetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
static let sharedDetail = DetailViewController()
@IBOutlet weak var CitiesTable: UITableView!

@IBOutlet weak var PlacesTable: UITableView!
var selectedState: String = ""{
    didSet{
        CitiesTable.reloadData()
    }
}
var selectedCity: String = ""
var citiesStates: [String:[String]] = [ "AL": ["Auburn", "Montgomery", "Birmingham"]

]
var placesCities: [String:[String]] = [ "Auburn": ["Dominos", "Pizzahut", "McDonalds"],
                                        "Birmingham": ["iHop", "Coldstone", "WaffleHouse"]
]
var cities: [String] = []
var places: [String] = []
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(tableView == CitiesTable)
    {
        if(selectedState != "")
        {
            cities = citiesStates[selectedState]!
            return cities.count
        }
    }
    else
    {
        if(selectedCity != "")
        {
            places = placesCities[selectedCity]!
            return places.count
        }
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if(tableView == CitiesTable)
    {
      let cell = tableView.dequeueReusableCell(withIdentifier: "citiesCell", for: indexPath)
        cell.textLabel?.text = cities[indexPath.row]
        return cell
    }
    else
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "placesCell", for: indexPath)
        cell.textLabel?.text = cities[indexPath.row]
        return cell
    }
}

}

A: I have added a protocol in masterviewcontroller shown below
protocol MasterSelectionDelegate: class {
   func itemSelected(_ item: AnyObject)
}

then, as splitviewcontroller sits as a rootviewcontroller.
In app delegate or during creation of Split View Controller. I have added below line
masterViewController.delegate = detailViewController

In didSelectRowAtIndexPath of master ViewController I have called it this:
`override func tableView(tableView: UITableView,
 didSelectRowAtIndexPath indexPath: NSIndexPath) {
 let selectedItem = self.arrString[indexPath.row]
 self.delegate?.itemSelected(selectedItem)
}`

Finally you have to implement it in the delegate in detail view controller
func itemSelected(_ item: AnyObject) {
    itemSelected = item as? Array<String>
    tableview.reloadData()
  }


text:
Q: Using if, elif and else in list comprehension in python3 I want to convert a loop-based script containing if, elif and else into a list comprehension but I cannot figure out how to do it.
Here is the script I wrote (it prints the numbers from 1 to 100, but for multiples of 3 it prints 'fizz', for multiples of 5 it prints 'buzz' and for multiples of both 3 and 5 it prints 'fizzbuzz'):
for num in range(1, 101):
    if num % 3 == 0 and num % 5 == 0:
        print('fizzbuzz')
    elif num % 3 == 0:
        print('fizz')
    elif num % 5 ==0:
        print('buzz')
    else:
        print(num)

A: elif is not part of the if-else short-hand, aka if else conditional operator, but you can achieve the same logic by chaining these operators, for example:
if A:
    v = a
elif B:
    v = b
else:
    v = c

turns into
v = a if A else b if B else c

And you can use a conditional operator expression in your list comprehension:
[a if A else b if B else c for something in someiterator]

Note that things can become unreadable quite quickly, for example this may not be recommended in your example:
['fizzbuzz' if num%3 == 0 and num%5 == 0  else 'fizz' if num%3 == 0 else 'buzz' if num%5 == 0 else num for num in range(1, 101)]

A: List comprehension is not the right tool since you want to do something
(print) and not to produce a list.
First, you should replace the "switch" by a function:
def foobar(num):
    if num % 3 == 0 and num % 5 == 0:
        return 'fizzbuzz'
    elif num % 3 == 0:
        return 'fizz'
    elif num % 5 ==0:
        return 'buzz'
    else:
        return str(num) # return a string to have a consistent return type

(You can make a one liner of this function as in @EnzoBnl's answer if you want, but that's not a good idea.). Now, you code looks like:
for num in range(1, 101):
    print(foobar(num))

If you want a list comprehension (a generator here), use:
print("\n".join(foobar(num) for num in range(1, 101)))


text:
Q: Ignoring Android unit tests depending on SDK level Is there an annotation or some other convenient way to ignore junit tests for specific Android SDK versions? Is there something similar to the Lint annotation TargetApi(x)? Or do I manually have to check whether to run the test using the Build.VERSION?

A: An alternative is to use JUnit's assume functionality:
@Test
fun shouldWorkOnNewerDevices() {
   assumeTrue(
       "Can only run on API Level 23 or newer because of reasons",
       Build.VERSION.SDK_INT >= 23
   )
}

If applied, this effectively marks the test method as skipped.
This is not so nice like the annotation solution, but you also don't need a custom JUnit test runner.

A: I've been searching for an answer to this question, and haven't found a better way than to check the version. I was able to conditionally suppress the execution of test logic by putting a check in the following Android TestCase methods. However, this doesn't actually prevent the individual tests from executing. Overriding the runTest() method like this will cause tests to "pass" on API levels you know will not work. Depending on your test logic, you may want to override tearDown() too. Maybe someone will offer a better solution.
@Override
protected void setUp() throws Exception {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        if (Log.isLoggable(TAG, Log.INFO)) {
            Log.i(TAG, "This feature is only supported on Android 2.3 and above");
        }
    } else {
        super.setUp();
    }
}

@Override
protected void runTest() throws Throwable {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        assertTrue(true);
    } else {
        super.runTest();
    }
}

A: I don't think there is something ready but it pretty easy to create a custom annotation for this.
Create your custom annotation
@Target( ElementType.METHOD )
@Retention( RetentionPolicy.RUNTIME)
public @interface TargetApi {
    int value();
}

Ovverride the test runner (that will check the value and eventually ignore/fire the test)
public class ConditionalTestRunner extends BlockJUnit4ClassRunner {
    public ConditionalTestRunner(Class klass) throws InitializationError {
        super(klass);
    }

    @Override
    public void runChild(FrameworkMethod method, RunNotifier notifier) {
        TargetApi condition = method.getAnnotation(TargetApi.class);
        if(condition.value() > 10) {
            notifier.fireTestIgnored(describeChild(method));
        } else {
            super.runChild(method, notifier);
        }
    }
}

and mark your tests
@RunWith(ConditionalTestRunner.class)
public class TestClass {

    @Test
    @TargetApi(6)
    public void testMethodThatRunsConditionally() {
        System.out.print("Test me!");
    }
}

Just tested, it works for me. :)
Credits to: Conditionally ignoring JUnit tests

A: I think @mark.w's answer is the path of least resistance:

You might wanna take a look at SdkSuppress annotation. It has two methods -- maxSdkVersion and minSdkVersion which you could use depending on your need.

for example:
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.KITKAT)
public void testMethodThatRunsConditionally() {
    System.out.print("Test me!");
}

A: I have upgraded answer of @Enrichman for Kotlin modern version. So, this is test runner class:
class ConditionalSDKTestRunner(klass: Class<*>?) : BlockJUnit4ClassRunner(klass) {
    override fun runChild(method: FrameworkMethod, notifier: RunNotifier) {
        // Annotation class could not have a base class of interface, so we can not group them.
        val testOnlyForTargetSDKCode = method.getAnnotation(TestOnlyForTargetSDK::class.java)?.sdkLevel?.code
        val testForTargetSDKAndBelowCode = method.getAnnotation(TestForTargetSDKAndBelow::class.java)?.sdkLevel?.code
        val testForTargetSDKAndAboveCode = method.getAnnotation(TestForTargetSDKAndAbove::class.java)?.sdkLevel?.code

        when {
            // If annotation exists, but target SDK is not equal of emulator SDK -> skip this test.
            testOnlyForTargetSDKCode != null && testOnlyForTargetSDKCode != Build.VERSION.SDK_INT ->
                notifier.fireTestIgnored(describeChild(method))
            // If annotation exists, but test SDK is lower than emulator SDK -> skip this test.
            testForTargetSDKAndBelowCode != null && testForTargetSDKAndBelowCode < Build.VERSION.SDK_INT ->
                notifier.fireTestIgnored(describeChild(method))
            // If annotation exists, but test SDK is higher than emulator SDK -> skip this test.
            testForTargetSDKAndAboveCode != null && testForTargetSDKAndAboveCode > Build.VERSION.SDK_INT ->
                notifier.fireTestIgnored(describeChild(method))
            // For other cases test should be started.
            else -> super.runChild(method, notifier)
        }
    }
}

Enum with exist SDKs in your project:
enum class SdkLevel(val code: Int) {
    SDK_24(24),
    SDK_25(25),
    SDK_26(26),
    SDK_27(27),
    SDK_28(28),
    SDK_29(29),
    SDK_30(30),
    SDK_31(31),
    SDK_32(32)
}

and annotations below:
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class TestForTargetSDKAndAbove(val sdkLevel: SdkLevel)

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class TestForTargetSDKAndBelow(val sdkLevel: SdkLevel)

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class TestOnlyForTargetSDK(val sdkLevel: SdkLevel)

To use it just add ConditionalSDKTestRunner to your base android unit test class:
@RunWith(ConditionalSDKTestRunner::class)
abstract class BaseAndroidUnitTest

and necessary annotation for test to make it actual only for special sdk:
@Test
@TestForTargetSDKAndAbove(SdkLevel.SDK_31)
fun getConnectionInfo_positive_SDK31() {

@Test
@TestForTargetSDKAndBelow(SdkLevel.SDK_30)
fun getConnectionInfo_negative1_SDK30() {

@Test
@TestOnlyForTargetSDK(SdkLevel.SDK_29)
fun getConnectionInfo_negative1_SDK29() {

That's all. Thanks!


text:
Q: Wait until element is clickable Selenium Javascript Bindings I am trying to click a button. For now I am simply trying to click it once and I know it will be there. This button gets loaded in with a bunch of other stuff by some JavaScript, and therefore takes a moment to be clickable. As of now, I am trying to click it in the following way:
const seeMoreBtn = await this.driver.findElement(showMoreBtnPath);
await waitUntilElementClickable(this.driver, seeMoreBtn, ONEMINUTE_TIMEOUT);
await seeMoreBtn.click();

I wrote the waitUntilElementClickable function, as I don't thinks it's a part of the JavaScript bindings. It is defined as follows:
async function waitUntilElementClickable(driver, element, timeout) {
    await driver.wait(until.elementIsVisible(element), timeout);
    await driver.wait(until.elementIsEnabled(element), timeout);
}

When I run my code, I am getting the error
(node:16076) UnhandledPromiseRejectionWarning: ElementClickInterceptedError: Element <button class="btn btn-default btn-sm ng-binding"> is not clickable at point (743,865) because another element <div class="clearfix animate-show ng-isolate-scope ng-hide-add ng-animate ng-hide-animate ng-hide ng-hide-add-active"> obscures it

I can't attach a screenshot because of information on the page, but the driver is automatically scrolling to the element, and the ONEMINUTE_TIMEOUT is not being waited on, so I guess the element is Visible and Enabled.
Any tips on why this click is still being intercepted would be immensely helpful. Thanks! Also, I know that the waitUntilElementClickable function could theoretically double the timeout, it's just not a big deal at the moment.
Update: Quick fix suggested by @Prophet in comments is working for me. I replaced
await seeMoreBtn.click();

with
await this.driver.executeScript("arguments[0].click()", seeMoreBtn);

Big thanks to @Prophet for helping me keep moving on my project.


text:
Q: How do I enter lots of integers in a loop in C/C++? I have this snippet:
printf("\nEnter number of elements: ", MAX);
scanf("%d", &num);
printf("\nEnter %d Elements : ", num);
for (i = 0; i < num; i++)
  scanf("%d", &arr[i]);

I want to enter say, 1000 integers to the arr[i] but how do I do it without entering 1000 numbers manually? I was thinking of using an external file to store the numbers and I just read it there but I don't know how to...

A: There are two simple approaches:
First, you can use a file of numbers:
printf("\nEnter number of elements: ", MAX);
scanf("%d", &num);

FILE *f = fopen("numbers.txt","r");
if (f == NULL){... handle error }
for (i = 0; i < num; i++)
  fscanf(f,"%d", &arr[i]);
fclose(f);

This is fine, but you should, of course, test fscanf for errors (see the documentation of fscanf) and at the same time, you can replace num with waiting for feof(f) signaling the end of file.
Still, on most operating systems, there are shell pipes that can actually make a file an input to a program. For your snippet, you could format your file by placing the number of numbers in the first line and then the input to the second round of scanfs (e.g., the space separated numbers) into the second line.
Then, on Linux,

    cat filename.txt | yourprogram

will behave as if you were inputting the content of file through the keyboard. For Windows, replace cat with type (as far as I remember...)


text:
Q: Jena TDB , see how many triple stored during tdb creation Hi is possible to see the number of triple in storing during tdb creation with java api?
I run the TDB factory with a rar file in turtle , but during the creation of files in my directory i cant see how many triple it has stored. How can i solve this problem?

A: You can access the bulk-loader through java code (to view triples introduced) as follows:
final Dataset tdbDataset = TDBFactory.createDataset( /*location*/ );
try( final InputStream in = /*get input stream for your large file*/) {
    TDBLoader.load( ((DatasetGraphTransaction)tdbDataset.asDatasetGraph()).getBaseDatasetGraph() , in, true);
}

If you have multiple files in your archive (for simplicity, I'll not do rar, but rather a zip), then as per an answer to this question, you can get optimized performance by concatenating the files into a single file prior to passing them to the bulk loader. The improved performance arises from delaying index creation until all triples have been introduced. I'm sure there are other formats that are supported, but I have only tested N-TRIPLES.
The following example utilizes IOUtils from commons-io for copying streams:
final Dataset tdbDataset = TDBFactory.createDataset( /*location*/ );
final PipedOutputStream concatOut = new PipedOutputStream();
final PipedInputStream concatIn = new PipedInputStream(concatOut);

final ExecutorService workers = Executors.newFixedThreadPool(2);
final Future<Long> submitter = workers.submit(new Callable<Long>(){
    @Override
    public Long call() throws Exception {
        long filesLoaded = 0;
        try( final ZipFile zipFile = new ZipFile( /* Archive Location */ ) {
            final Enumeration< ? extends ZipEntry> zipEntries = zipFile.entries();
            while( zipEntries.hasMoreElements() ) {
                final ZipEntry entry = zipEntries.nextElement();
                try( final InputStream singleIn = zipFile.getInputStream(entry) ) {
                    // If your file is in a supported format already
                    IOUtils.copy(singleIn, concatOut);
                    /*(final Model m = ModelFactory.createDefaultModel();
                    m.read(singleIn, null, "lang");
                    m.write(concatOut, "N-TRIPLES");*/
                }
                filesLoaded++;
            }
        }
        concatOut.close();
        return filesLoaded;
    }});

final Future<Void> comitter = workers.submit(new Callable<Void>(){
    @Override
    public Void call() throws Exception {
        TDBLoader.load( ((DatasetGraphTransaction)tdbDataset.asDatasetGraph()).getBaseDatasetGraph() , concatIn, true);
        return null;
    }});

workers.shutdown();
System.out.println("submitted "+submitter.get()+" input files for processing");
comitter.get();
System.out.println("completed processing");
workers.awaitTermination(1, TimeUnit.SECONDS); // NOTE this wait is redundant


text:
Q: .tbl file import request for a .tlh file C++ I'm working in a C++ native project and I need to import a .tbl file
#import  "C:\packages\S...\xx.tlb" raw_interfaces_only, named_guids, no_namespace

But Visual studio 2019 always ask for a .tlh file that I don't have, how can I use tbl file without the tlh file?


text:
Q: How to change hadoop conf directory location? In the exception stack trace I can see that my hadoop configuration is loaded from /etc/hadoop/conf.empty/hdfs-site.xml
How do I change it to /etc/hadoop/conf/hdfs-site.xml ?

A: In principle you can load any bash script before loading the hadoop daemon, e.g. in /etc/init.d/hadoop-hdfs-datanode for datanodes.
You can add towards the top to this init script,
 export HADOOP_CONF_DIR=/etc/hadoop/conf

Also, you can check whether this is overridden by hadoop in /usr/lib/hadoop/etc/hadoop/hadoop-env.sh. A similar file should also be: /etc/hadoop/hadoop-env.sh
Best way is to check, which are the files are getting called when hadoop calls the init script in /etc/init.d/hadoop-hdfs-*

A: You can always set your configuration files from the command line via: (example ls)

hadoop fs -conf configFile.xml -ls ./


text:
Q: How to access discord server channels python I'm trying to build an app that will access discord server channels, and get messages with certain keywords. My problem is, I don't own these servers, and I can't add a bot to it. So I have to use something else to get them. (I am however a part of these servers and have access to said channels).
I looked into oauth, but another answer on SO said it wasn't possible using oauth, so is there a work around?
also how does /guilds/{guild.id}/channels work?

A: To access the channels and read the messages you will need to have a bot in the guild. Discord limits you from getting guild and its info if your bot is not in it.
To my knowledge, there is no workaround but you may want to ask the experts at the Discord developers Discord server.
The /guilds/{guild.id}/channels endpoint is a POST request to get all of a guild's channels. You can see more info on this at the docs.


text:
Q: How can I inject plugins functionalities to the Vuex store using Nuxt without Typescript error? I'm working in a Nuxtjs app with typescript and I've created a custom plugin for Axios that injects some functions to the context. I can use those functions from the store (it works) but, even though I got an error that tells me that the property that I'm using does not exist in the type store. What is the right way to do this? is there any configuration that must be done?
This is the code of the plugin axios.js
export default function ({ $axios, redirect }, inject) {

  $axios.onResponse((response) => {
    if (response.data == null)
      console.log(`Undefined or null data from url ${response.config.url}`)
  })

  $axios.onError((error) => {
    const code = parseInt(error.response && error.response.status)
    console.log('REQUEST ERROR')
    console.log('ENDPOINT:',error.request?.responseURL);

    if(error.response)
      console.log(error.response.data)
    else
      console.log("SIN DATOS")
    if (code === 404) {
      redirect('/404')
    }
  })

  const request = async (
    method = 'get',
    path,
    data = {},
    params = {}
  ) => {
    const config = {
      headers: {
        'Content-Type': 'application/json'
      },
      method: method,
      url: $axios.defaults.baseURL + path,
      data: data,
      params: params
    }

    return $axios(config)
  }

  const get = (path,params) => request(undefined,path,undefined,params)
  const post = (path, data) => request('post',path,data)

  const customAxios = {
      get,
      post
  }

  // Inject to context as $customAxios
  inject('customAxios', customAxios)
}

This is a fraction of a code where I use the plugin, user.ts
//ACTIONS
export const actions: ActionTree<RootState, RootState> = {
  setPhoneLink({ commit }, setPhoneLink: string) {
    commit('setPhoneLink', setPhoneLink)
  },
  setHasSameAddressOfId({ commit }, sethasSameAddressOfId: boolean) {
    commit('setHasSameAddressOfId', sethasSameAddressOfId)
  },
  async login({ commit }, loginBody: LoginBody) {
    return this.$customAxios
      .post('seguridad/login/web/', loginBody)
      .then((response: any) => {
        console.log('RESPONSE OF LOGIN:', response.data)
        commit('setUserData', response.data)
      })
  },

This is the error I get
ERROR in store/user.ts:229:17
TS2339: Property '$customAxios' does not exist on type 'Store<any>'.
    227 |   },
    228 |   async login({ commit }, loginBody: LoginBody) {
  > 229 |     return this.$customAxios
        |                 ^^^^^^^^^^^^
    230 |       .post('seguridad/login/web/', loginBody)
    231 |       .then((response: any) => {
    232 |         console.log('RESPONSE OF LOGIN:', response.data)

A: Store<S> is a defined type in Vuex, so you need to extend it by injecting your custom plugin inside.
You can create vuex.d.ts file that declares Store<S> with your custom axios instance as below:
import type { NuxtAxiosInstance } from '@nuxtjs/axios'

declare module 'vuex/types/index' {
  interface Store<S> {
    $customAxios: NuxtAxiosInstance
  }
}


text:
Q: Clickable Text + Image using TextView in Android How to put an clickable image in between string using a single TextView.

Using SpannableString, I am able to color part of string. But how to add a colored image? Any suggestion would be really appreciated.

A: This is not possible for a single TextView element. TextViews are not meant to contain images in the middle of them.
You can, however, add drawable resources to the top, right/start, left/end, or bottom of a given TextView by leveraging the drawableTop, drawableBottom, etc. attributes.  But again, no way of adding an image in the middle of a TextView by using only one of them.
If you really want that specific effect, I would group a few XML components into any ViewGroup like a ConstraintLayout to get exactly what you want; e.g.
<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_part_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="first part of the text"
                android:textSize="16dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@id/image"/>

            <ImageView
                android:id="@+id/image"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@color/white"
                app:layout_constraintStart_toStartOf="@id/text_part_1"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="@id/text_part_2"/>

            <TextView
                android:id="@+id/text_part_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="first part of the text"
                android:textSize="16dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toEndOf="@id/image"/>
        </androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: pandas drop row if value is not in different dataframe I have two dataframes and want to drop rows from dataframe 'Total' if there is not a matching ID in dataframe 'Student'
DF Total:
    ID     name
0   115    john
1   118    mike
2   34     mac
3   897    sarah

DF Student:
    ID     name
0   34     mac
1   118    mike
2   897    sarah

In this example since ID 115 is not present in the Student df that row would be dropped from df Total and the resulting table would look like this:
    ID     name
0   118    mike
1   34     mac
2   897    sarah

A: one way is to use the .isin() method:
df_total[df_total['ID'].isin(df_student['ID'])]


text:
Q: html seo alternate Мультиязычность сайта Вопрос по поводу мультиязычности сайта. Есть сайт на двух языках. Например, наша базовая страница - http://www.example.com.ua на русском и http://www.example.com.ua/ua/  - на украинском. Переход через кнопку на страницу сайта с другим языком(другой html файл). Этих 3 строк LINK мне будет достаточно для того что бы сайт нормально отображался/индексировался в поске? Или нужно еще что-то добавлять? И правильно ли оформленные ссылок линк исходя из моего примера выше? + НА сколько я понимаю "х-default" заменяет каноникал и должен быть использован только один раз? (тоисть на других страницах нужно будет указать только два тега линк альтернейт без x-default).Спасибо.
например на мейн странице http://www.example.com.ua/, которая на русском языке:
<link rel="alternate" hreflang="ru-UA" href="http://www.example.com.ua/">
<link rel="alternate" hreflang="ua-RU" href="http://www.example.com.ua/ua/">
<link rel="alternate" hreflang="x-default" href="http://www.example.com.ua/">

A: разобрался сам))) спасибо
<link rel="alternate" hreflang="ru-UA" href="http://www.example.com.ua/" />
<link rel="alternate" hreflang="uk-UA" href="http://www.example.com.ua/ua/" />
<link rel="alternate" hreflang="x-default" href="http://www.example.com.ua/ua/" />


text:
Q: Issue while querying on DynamoDB table using GSI I have a DynamoDB table, let us say here: ReportingTable. Its has following keys to uniquely identify items:

*

*reportingtablePrimaryKey - partition key of table.

*merchantId - sort Key of table.

*transactionType-timestamp-index - Global Secondary Index of table containing following attributes.

*

*transactionType - partition key of our GSI. We are always saving four types of values here. [Cancel, Refund, Shipment, MFNShipment]

*timestamp- timestamp in epoch when item came into our system and was saved in dynamodb.

Now, the thing I am trying to achieve is, I am to calculate number of items present in DynamoDB table which lie between two timestamps (start and end timestamp).
For that, I came-up with the approach of using our GSI transactionType-timestamp-index and where for the list of values of transactionType and timestamp range, I will pass the key condition which will read all the records and to overcome returned response limiting issue and I will use lastEvaluatedKey in loop to get the other records till end.
Following is the code I am using:
private static int getNumberOfRecordsFromTable(final AmazonDynamoDB dynamoDBclient, final String tableName,
                                                   final String gsiIndex, final List<String> transactionTypes,
                                                   final long startTimeEpoch, final long endTimeEpoch) {
        int numberOfRecords=0;

        Map<String, AttributeValue> lastEvaluatedKey = null;
        Map<String, AttributeValue> valueMap = new HashMap<>();
        valueMap.put(":transaction_type", new AttributeValue().withSS(transactionTypes));
        valueMap.put(":start_time_epoch", new AttributeValue().withN(String.valueOf(startTimeEpoch)));
        valueMap.put(":end_time_epoch", new AttributeValue().withN(String.valueOf(endTimeEpoch)));

        Map<String, String> nameMap = new HashMap<>();
        nameMap.put("#timestamp","timestamp");
        nameMap.put("#transactionType","transactionType");

        final String conditionExpression = "(#transactionType = :transaction_type) " +
                "AND (#timestamp BETWEEN :start_time_epoch AND :end_time_epoch)";

        QueryRequest queryRequest = new QueryRequest()
                .withTableName(tableName)
                .withIndexName(gsiIndex)
                .withKeyConditionExpression(conditionExpression)
                .withExpressionAttributeNames(nameMap)
                .withExpressionAttributeValues(valueMap)
                .withProjectionExpression("#transactionType, #timestamp")
                .withExclusiveStartKey(lastEvaluatedKey)
                .withConsistentRead(false);

        do {
            int numberOfRecordsFetched=0;

            QueryResult queryResult = dynamoDBclient.query(queryRequest);
            lastEvaluatedKey = queryResult.getLastEvaluatedKey();
            numberOfRecordsFetched = queryResult.getScannedCount();
            queryRequest.setExclusiveStartKey(lastEvaluatedKey);

            numberOfRecords = numberOfRecords + numberOfRecordsFetched;
        } while (lastEvaluatedKey != null);

        log.info("Number of {} type messages fetched :: {}", transactionType, numberOfRecords);

    return numberOfRecords;
}

I am getting the following error:
Exception in thread "main" com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: One or more parameter values were invalid: Condition parameter type does not match schema type (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: FJLJTP7NFVKPTSDF2AJRUL0PTJVV4KQNSO5AEMVJF66Q9ASUAAJG)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1640)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1058)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:3443)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3419)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executeQuery(AmazonDynamoDBClient.java:2318)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.query(AmazonDynamoDBClient.java:2293)
    at com.amazon.gstreporting.mtrschedulercli.scripts.GSTDatabaseRecordsCount.getNumberOfRecordsFromTable(GSTDatabaseRecordsCount.java:231)
    at com.amazon.gstreporting.mtrschedulercli.scripts.GSTDatabaseRecordsCount.countDynamoDBRecords(GSTDatabaseRecordsCount.java:192)
    at com.amazon.gstreporting.mtrschedulercli.scripts.GSTDatabaseRecordsCount.main(GSTDatabaseRecordsCount.java:123)

Could anyone help me in it?

A: The reason I was getting error - I was passing list of transactionType which ideally should been passed one by one into the query.
After, adding one more root for-loop to go over every transactionType I was able to fix it.
Please see the code change for reference:
private static int getNumberOfRecordsFromTable(final AmazonDynamoDB dynamoDBclient, final String tableName,
                                                   final String gsiIndex, final List<String> transactionTypes,
                                                   final long startTimeEpoch, final long endTimeEpoch) {
        int numberOfRecords=0;

        for (String transactionType: transactionTypes) {
            Map<String, AttributeValue> lastEvaluatedKey = null;
            Map<String, AttributeValue> valueMap = new HashMap<>();
            valueMap.put(":transaction_type", new AttributeValue().withS(transactionType));
            valueMap.put(":start_time_epoch", new AttributeValue().withN(String.valueOf(startTimeEpoch)));
            valueMap.put(":end_time_epoch", new AttributeValue().withN(String.valueOf(endTimeEpoch)));

            Map<String, String> nameMap = new HashMap<>();
            nameMap.put("#timestamp","timestamp");
            nameMap.put("#transactionType","transactionType");

            final String conditionExpression = "(#transactionType = :transaction_type) " +
                    "AND (#timestamp BETWEEN :start_time_epoch AND :end_time_epoch)";

            QueryRequest queryRequest = new QueryRequest()
                    .withTableName(tableName)
                    .withIndexName(gsiIndex)
                    .withKeyConditionExpression(conditionExpression)
                    .withExpressionAttributeNames(nameMap)
                    .withExpressionAttributeValues(valueMap)
                    .withProjectionExpression("#transactionType, #timestamp")
                    .withExclusiveStartKey(lastEvaluatedKey)
                    .withConsistentRead(false);

            do {
                int numberOfRecordsFetched=0;

                QueryResult queryResult = dynamoDBclient.query(queryRequest);
                lastEvaluatedKey = queryResult.getLastEvaluatedKey();
                numberOfRecordsFetched = queryResult.getScannedCount();
                queryRequest.setExclusiveStartKey(lastEvaluatedKey);

                numberOfRecords = numberOfRecords + numberOfRecordsFetched;
            } while (lastEvaluatedKey != null);

            log.info("Number of {} type messages fetched :: {}", transactionType, numberOfRecords);
        }

        return numberOfRecords;
    }


text:
Q: How to create a custom Firefox installation? I would like to install a custom version of Firefox on several computers.  I would like to customize Firefox in the following ways:

*

*Set Firefox's language to English.

*Set the language of Firefox's default search engine to English.

*Set Firefox to open new tabs by default (instead of new windows).

*Set Firefox's home page to a particular web site.

*Pre-installed with a PDF viewer.

*Pre-installed with a few additional plugins.

I'd like to simply create a single custom version of Firefox that I can distribute to these other computers, rather than doing all of the setup by hand.  How might I do that?
Edit: I will probably install these on Windows machines but am currently working from a Mac.

A: Found an answer to my own question.  CCK2 - a plugin for creating plugins and modifying Firefox settings, offers a unified solution.  It addresses 2,3,4, and 6.  For 5, Firefox comes with its own default PDF viewer, and for 1, I'd need to select the right version of Firefox.


text:
Q: Time constant of parallel RC circuit I have read about Series RC Circuit and have understood the Time constant concept.
Wikipedia states - "It is the time required to charge the capacitor, through the resistor, from an initial charge voltage of zero to approximately 63.2% of the value of an applied DC voltage, or to discharge the capacitor through the same resistor to approximately 36.8% of its initial charge voltage. "
Since Capacitor is charged through this resistor, the concept of time constant is valid.
But assume a parallel RC Circuit. I was not able to find the formula for time constant of a parallel RC circuit and also not sure whether the concept of time constant in a parallel RC circuit would mean something?
Can someone provide me the formula for Parallel RC Circuit during charging and discharging?
My question is based on the below circuit :

Once the voltage across the sense resistors cross 0.7V, the Transistor Q2203 will turn ON. What role does the C2202 play in combination with the sense resistors?
I have checked and reduced the value of C2202 in simulation and saw that if I decreased the value of C2202, the transistor turns ON quickly for a certain load resistance. If C2202 value is increased, the time taken for the Q2203 to turn ON increases? So, I thought of researching on charging of a parallel RC Circuit and its formulas which I couldn't find?
Please help me to solve my queries in the question.

A: If you apply Norton's or Thevenin's equivalent circuit theory, it'll be apparent that a series RC circuit is no different to a parallel one. The time constant is the same.
In your circuit, R2203, C2202 form a high pass filter. One presumes in that circuit to prevent 'nuisance operation' of the current sense.
Again, in answer to your question, apply Norton/Thevenin circuit analysis. You'll see that the 1.87 ohms is insignificant and the RC time constant of the sense circuit is 1k.10u or 10 milliseconds.

A: C2202 and R2203 form a single-pole low-pass filter.  This sets the minimum rate of change  of current through Q2201, the shunt resistors, and the external load.  Note that rate of change across the cap will be slower than the rate of change across the load because of the gains of the three transistors in series.
The time constants of series and parallel R-C networks are the same.  With a typical series network, resistor to V+ and capacitor to GND, the cap charges up to 63% of V+ in one time constant.  If you maintain the connection for five time constants, the cap will be at 99% of V+.  Now, if the resistor is switched from V+ to GND, the cap will discharge through the resistor.  Again, the voltage across the capacitor will change by 63% in one time constant, only now the voltage is decreasing rather than increasing.
This is because a normal capacitor is symmetrical - charge flows into and out of it with equal facility.


text:
Q: Stealing inside the move constructor During the implementation of the move constructor of a toy class, I noticed a pattern:
array2D(array2D&& that)
{
    data_ = that.data_;
    that.data_ = 0;

    height_ = that.height_;
    that.height_ = 0;

    width_ = that.width_;
    that.width_ = 0;

    size_ = that.size_;
    that.size_ = 0;
}

The pattern obviously being:
    member = that.member;
    that.member = 0;

So I wrote a preprocessor macro to make stealing less verbose and error-prone:
#define STEAL(member) member = that.member; that.member = 0;

Now the implementation looks as following:
array2D(array2D&& that)
{
    STEAL(data_);
    STEAL(height_);
    STEAL(width_);
    STEAL(size_);
}

Are there any downsides to this? Is there a cleaner solution that does not require the preprocessor?

A: How about using template:
template<typename T> inline
void MOVE(T &dst, T &src)
{
  dst = src;
  src = 0;
}

Usage:
MOVE(data_, that.data_);

@Fred, from your comment, if you want to avoid mentioning data member twice, then:
#define STEAL(X) MOVE(X, that.X)

Usage:
STEAL(data_);

A: Initialize your own members to default, and then swap.
array2D(array2D&& that)
{
    data_ = 0;
    height_ = 0;
    width_ = 0;
    size_ = 0;

    this->swap(that);
}

Even cleaner (if your compiler supports it)
array2D(array2D&& that)
: array2D() {
    this->swap(that);
}

A: Here is the recommended pattern:
array2D(array2D&& that)
    : data_(std::move(that.data_)),
      height_(std::move(that.height_)),
      width_(std::move(that.width_)),
      size_(std::move(that.size_))
{
    that.data_ = 0;
    that.height_ = 0;
    that.width_ = 0;
    that.size_ = 0;
}

Naturally if the data members are scalar types, the std::move isn't needed.  But if you're copying this pattern around, it is helpful to include the move anyway so that when the member data aren't scalar, the std::move doesn't get forgotten.
Also if the member data have actual move constructors, then you can simply omit the body:
array2D(array2D&& that)
    : data_(std::move(that.data_)),
      height_(std::move(that.height_)),
      width_(std::move(that.width_)),
      size_(std::move(that.size_))
{
}

And if you want to generalize to types that don't have move constructors, but do have a resource-less default constructed state, you can:
array2D(array2D&& that)
    : data_(std::move(that.data_)),
      height_(std::move(that.height_)),
      width_(std::move(that.width_)),
      size_(std::move(that.size_))
{
    that.data_ = Data();
    that.height_ = Height();
    that.width_ = Width();
    that.size_ = Size();
}

I recommend ordering these statements in the same order they are declared as data members in the array2D class definition.  And I find nothing wrong with the repetition of the initializer list in the body.  It is a necessary and second step.  There is no need to sweep it under the rug.


text:
Q: Powershell question: String to Instance of an Object to use as a filename for export-vapp I am trying to pass a string as a filename to a function. This happens with everything, I am just using vmware powercli as a example. Why am I getting this error:
Here is my powershell code? (Sorry this has been stumping me for hours):
PowerCLI C:\> $BackupDir
c:\temp
PowerCLI C:\> $backupDate
20181225
PowerCLI C:\> $line
myVM
PowerCLI C:\> $ovafilename = $line+"_v"+$backupDate+".ova"
myVM v20181212.ova
......................
......................
......................
... And now here is the problem command. It wont convert my string to a instance object:
PowerCLI C:\> Export-VApp -Destination $BackupDir -VM $line -Format OVA -Name $ovafilename

And this error message appears:
Export-VApp : 12/25/2018 11:20:11 AM    Export-VApp             Object     reference not set to an instance of an object.
At line:1 char:1
+ Export-VApp -Destination $BackupDir -VM $line -Format OVA -Name "$ova ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Export-VApp], ViError
+ FullyQualifiedErrorId :     Client20_NfcLease_RunNfcTask_Error,VMware.VimAutomation.ViCore.Cmdlets.Commands.ExportVApp

However......... if I replace the $ovafilename string, and type it manually it works. Why is this?
PowerCLI C:\> Export-VApp -Destination $BackupDir -VM $line -Format OVA -Name "testfilename.ova"

A: So PowerCLI export-vapp doesnt accept a filename with ( ) or [ ], and so i had i had to replace it with a _ underscrore to fix it


text:
Q: "The program is intended to" - is this an awkward use of the term? From a Memorandum of Understanding template:

The purpose of this MOU is to clearly identify the roles and responsibilities of each party as they relate to the implementation of the United States Department of Agriculture (USDA) Food Stamp Program (FSP). The FSP is intended to help state agencies inform low-income households about the availability, eligibility requirements, applications procedures and benefits for the program. To support this goal, Party A and Party B will conduct food stamp outreach to eligible families as described in their respective Outreach Plan.

Won't native speakers find this use of intended to awkward, since the FSP was intended primarily to provide indigent households with means to obtain food, not to just "inform" them?
Does this use of intended to create an impression of

The sole purpose of the FSP is to help state agencies inform low-income households.

Or does it leave space for other "intentions" of the FSP's authors, such as the actual provision of help?

A: I agree, it's awkward.  It might not be 100% wrong, as we both understand what the sentence is trying to say, but it is weird nonetheless.
A better way to phrase that sentence would be

The FSP has provisions for helping state agencies inform low-income households about the availability, eligibility requirements, applications procedures and benefits for the program.


text:
Q: How Do I Load A Assets Bundle So I have created this object which is supposed to load a game over screen whenever I touch a gameobject. However, when I run it, I get this run time error

Scene 'A' (-1) couldn't be loaded because it has not been added to the
  build settings or the asset bundle has not been loaded. To add a scene
  to the build settings use the menu File->Build Settings...
  UnityEngine.Application:LoadLevel(String)
  NewBehaviourScript:OnCollisionEnter(Collision) (at
  Assets/NewBehaviourScript.cs:10)

Here's my code:
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{
    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name =="Hurt")
        {
            Application.LoadLevel("A");
        }
    }
}

A: It means your scene is missing from the Build Settings.
Go to File-> Build settings then you are given a window, you need to drag and drop all the needed scenes.
That is not related to Asset Bundle.


text:
Q: Converting GO map to struct I was wondering if there is anyway to convert a map into a struct in GO. I came across the package called map structure. However, when i run it, my struct is not getting the values for my map.I have posted relevant bits of my code below
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"

    "github.com/drone/routes"
    "github.com/mitchellh/mapstructure"
)

var Infos = []Info{}

type Info struct {
    Keyy   int    `json:"key"`
    Valuee string `json:"value"`
}

var m map[int]string
var outgoingJSON string
var x map[string]string

func main() {
    m = make(map[int]string)
    x = make(map[string]string)
    mux := routes.New()
    mux.Put("/:key1/:value1", PutData)

    mux.Get("/profile", GetProfile)
    http.Handle("/", mux)
    http.ListenAndServe(":3000", nil)
}
func PutData(w http.ResponseWriter, r *http.Request) {

    key_data := r.URL.Query().Get(":key1")
    value_data := r.URL.Query().Get(":value1")
    key2, err := strconv.Atoi(key_data)
    if err != nil {
        panic(err)
    } else {
        m[key2] = value_data
    }

    for key2, value_data := range m {
        log.Println(key2, value_data)
        log.Println(m)
        x[strconv.FormatInt(int64(key2), 10)] = value_data
        log.Println(x)
        var result Info
        err1 := mapstructure.Decode(x, &result)
        if err1 != nil {
            panic(err1)
        }
        Infos = append(Infos, result)
        //log.Println(key2,value_data)
        //  outgoingJSON, err := json.MarshalIndent(x,"","    ")
        //  if err != nil {
        //  panic(err)
        //    break
        //  }

    }
    w.WriteHeader(204)

    //log.Println(key_data)
}
func GetProfile(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    for _, p := range Infos {

        outgoingJSON, err := json.MarshalIndent(p, "", "    ")
        if err != nil {
            panic(err)
            break
        }
        w.WriteHeader(200)
        fmt.Fprint(w, string(outgoingJSON))
    }
}

I have create a map[int]string first, converted it into map[string]string and then converted it into my struct. Please help. My struct returns 0 as key and null string as value.
Output:
{
    "key": "",
    "value": ""
}{
    "key": "",
    "value": ""

A: MapStructure populates a struct with fields the same name as the keys of the map.  Your example generates zero values ( {Key: 0, Value: ""} because there are no keys in the map x with names Key and Value.
Will the following do what you want?
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"

    "github.com/drone/routes"
)

// Infos is a slice of Info
var Infos = []Info{}

// Info is a Key, Value struct
type Info struct {
    Key   int    `json:"key"`
    Value string `json:"value"`
}

func main() {
    mux := routes.New()
    mux.Put("/:key1/:value1", PutData)

    mux.Get("/profile", GetProfile)
    http.Handle("/", mux)
    http.ListenAndServe(":3000", nil)
}

// PutData puts the new key,values in to Infos
func PutData(w http.ResponseWriter, r *http.Request) {

    keyData := r.URL.Query().Get(":key1")
    valueData := r.URL.Query().Get(":value1")
    key2, err := strconv.Atoi(keyData)
    if err != nil {
        panic(err)
    } else {
        Infos = append(Infos, Info{
            Key:   key2,
            Value: valueData,
        })
    }

    w.WriteHeader(204)

}

// GetProfile displays the Infos
func GetProfile(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    for _, p := range Infos {

        outgoingJSON, err := json.MarshalIndent(p, "", "    ")
        if err != nil {
            panic(err)
            break
        }
        w.WriteHeader(200)
        fmt.Fprint(w, string(outgoingJSON))
    }
}


text:
Q: Orthogonal complement in Hilbert space Let $\,  M := \{ x \in H : L(x) = 0 \}$  where $H$ is a Hilbert Space and $L$ $ \in H^* : L \neq 0 $ . Prove that $ M^\perp$ is a one dimensional space.
$\textbf{Here is my attempt:}$
Fix $L \in H^*$ then we can assume that $\exists! \, w \in H : L(x) = \, \langle \, x \, , \, w \, \rangle $ and so we can rewrite $M$ as $\{ x \in H : \langle \, x \, , \, w \, \rangle  = 0 \} $. From the definition of $M^\perp$ it seems to me trivial that $M^\perp = \{ w\}$.
Am i wrong somewhere? If yes, could you give me some hints?


text:
Q: iOS - Reading from a txt file I am storing level details inside of a text file within my iOS project. The Text File contains the following:
Level1.txt
    LevelNum:1.0
    weaponPickupRate:10.0
    weaponPickupAmount:20
    monsterMinSpeed:8.0
    monsterMaxSpeed:12.0
    monsterRate:1.5
    levelMonsters:10
    goldPerMonster:10

I am reading the text file using the code below:
    fileName = "Level1.txt"
    levelPath = "\(NSBundle.mainBundle().resourcePath!)/\(fileName)"

    var err: NSError? = NSError()
    let s = String(contentsOfFile: levelPath, encoding: NSUTF8StringEncoding, error: &err)

    println(s)

When I run this using the iOS Simulator - iPhone 6, everything works fine and it prints the data from the text file.
When I run this directly on my iPhone 6 it prints nil and does not read the text file.
Why is this?
Cheers
Ryann


text:
Q: Identifying disjoined graphs in JgraphT I have a use case as below. I need to construct a graph from a set of input as below -
SimpleDirectedGraph<String, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class);
g.addVertex("APP");
g.addVertex("CHROME");
g.addVertex("MOZILLA");
g.addVertex("LAPTOP");
g.addVertex("SERVER");
g.addVertex("CHROME_DEV");
g.addVertex("MOZILLA_DEV");
g.addVertex("APP_DEV");

Add edges for Server
g.addEdge("SERVER", "APP");
g.addEdge("SERVER", "CHROME");
g.addEdge("SERVER", "MOZILLA");

Add edges for Laptop
g.addEdge("LAPTOP", "APP_DEV");
g.addEdge("LAPTOP", "CHROME_DEV");
g.addEdge("LAPTOP", "MOZILLA_DEV");

Add Connecting edges between these 2 sets
g.addEdge("CHROME", "CHROME_DEV");
g.addEdge("MOZILLA", "MOZILLA_DEV");

Now i can construct a graph like this and the structure will looks something as below -

But my use starts here. Imagine i have removed the connecting edges from the graph above
g.removeEdge("CHROME", "CHROME_DEV");
g.removeEdge("MOZILLA", "MOZILLA_DEV");

Now my graph is essentially disjoint from each other. How do I find out it is disjoint graphs and how to get both the disjoint graphs. I will have to treat these two disjoint graphs separately here after.

A: What you are looking for is called 'connected components'. Have a look at the ConnectivityInspector.
To test whether your graph is connected:
Graph<String, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class);
ConnectivityInspector ci = new ConnectivityInspector(g);
//Test whether the graph is connected:
ci.isConnected();

You can get the vertices of each of the connected components using:
Set<String> vertexSets = ci.connectedSets();
For each of these sets, you can then create a graph induced on these vertices:
Set<String> vertexSets = ci.connectedSets();
for(Set<String> vertexSet : vertexSets){
    Graph<String, DefaultEdge> subgraph = new AsSubGraph(g,vertexSet);
    //Do something with the subgraph
}

More information on graph connectivity can be found here. For the purpose of your question you could also look into the difference between 'strongly' and 'weakly' connected components.


text:
Q: Vcenter REST API VM info - What measure has been used for disk,cdroms identifier I'm using vcenter REST API to get VM information
On Official documentation, each subresource of VM (such as disk, cdrom, sata_adapter....) has their own identifier.But i'm not sure what standard has been used to make those identifier.
Standard json response for VM information is like this
https://developer.vmware.com/apis/vsphere-automation/latest/vcenter/api/vcenter/vm/vm/get/
you can see there are "key" in json response of disks, cdrom, sata_adapter and etcs....
and this is my real json response.
"disks": {
        "2000": {
            "scsi": {
                "bus": 0,
                "unit": 0
            },
            "backing": {
                "vmdk_file": "[datastore3] test.vmdk",
                "type": "VMDK_FILE"
            },
            "label": "Hard disk 1",
            "type": "SCSI",
            "capacity": 322122547200
        },
        "2001": {
            "scsi": {
                "bus": 0,
                "unit": 1
            },
            "backing": {
                "vmdk_file": "[datastore3] ex1.vmdk",
                "type": "VMDK_FILE"
            },
            "label": "Hard disk 2",
            "type": "SCSI",
            "capacity": 17179869184
        },
        "2002": {
            "scsi": {
                "bus": 0,
                "unit": 2
            },
            "backing": {
                "vmdk_file": "[datastore3] ex.vmdk",
                "type": "VMDK_FILE"
            },
            "label": "Hard disk 3",
            "type": "SCSI",
            "capacity": 21474836480
        }
    },
    "parallel_ports": {},
    "sata_adapters": {
        "15000": {
            "bus": 0,
            "pci_slot_number": 33,
            "label": "SATA controller 0",
            "type": "AHCI"
        }
    },

Anyone knows how to measure those numbers at "key" (2000, 2001, 15000) ?

A: 2000  2:0:0:0
SCSI number (X:X:X:X)
/sys/class/scsi_device/2:0:0:0/


text:
Q: Index page is not rendered with newly saved data I'm using the following technologies and frameworks versions:

*

*Couchbase:  Enterprise Edition 6.0.1 build 2037 ‧ IPv4

*Node: v10.15.3

*Express: v4.16.4

I'm a beginner with this technologies and frameworks.
I'm making a simple app with Node + Express and I'm using Couchbase to save data.
The app is about courses and students, and which student take  which courses and which course has which students.
Everything works fine, I can Save, Delete, looking for details, just I have a small issue:
I save new data (doesn't matter that it is on the course route or on the students route), than my app redirect to the index page and it suppose to show all the courses or students. It shows the previously saved students or courses, but not contains the newly saved student or course. When I refresh the page (F5) than it shows the newly saved student or course.
It has to show the newly saved student or course without refreshing the index page.
here is my code
how I'm saving to the DB and redirecting to the /courses route:
//save new course in the db than redirect to index page
app.post("/courses", function(request, response) {
    var course = new CourseModel({
        "name": request.body.name
    });
    course.save(function(error, result) {
        if(error) {
            return response.status(401).send({ "success": false, "message": error});
        }
        response.redirect("/courses");
    });
});

and this is how the /courses route looks like:
//get all courses and render index page
app.get("/courses", function(request, response) {
    CourseModel.find({}, {load: ["students"]}, function(error, result) {
        if(error) {
            return response.status(401).send({ "success": false, "message": error});
        }
        response.render("courses/index", {results: result});
    });
});

So when I hit the SAVE button, than It should save to the db than redirect to the /courses page, where it should render the index page contains the newly saved course or student but it doesn't. But after refreshing the page the newly saved course or student is there.
So why the newly saved data is not there immediately on the index page? What should I change ?
My Couchbase Server is running locally on my computer with this cluster and bucket settings:
Type: Couchbase
Bucket RAM Quota: 512MB
Cluster RAM Quota: 4.1GB
Replicas: 1
Server Nodes: 1
Ejection Method: Value-Only
Conflict Resolution: Sequence Number
Compaction: Not active

A: try to use 205 status code int the HTTP response, this means reset content but this will be helpful if you're using google chrome browser
cause the rest of the browser handles 205 code like 200 both are a success but without resetting the content
you can have more information about the 205 from this link