text:
Q: Blob and SAS -- Microsoft Azure Earlier i was getting a blob without using a sas authorization.
But now I want only those users to be able to access a blob who has the sas token.
Lets say i want to access a file at
https://storageaccount.blob.core.windows.net/sascontainer/sasblob.txt

Now i have the SAS token too. So the new url would be
https://storageaccount.blob.core.windows.net/sascontainer/sasblob.txt?sv=2012-02-12&st=2013-04-12T23%3A37%3A08Z&se=2013-04-13T00%3A12%3A08Z&sr=b&sp=rw&sig=dF2064yHtc8RusQLvkQFPItYdeOz3zR8zHsDMBi4S30%3D

What do I do next so that only those with the second link can go and get the "sasblob.txt" file?
What changes do i have to make in the azure portal?
I guess the only change i have to make in the client side is the URL. I need to replace the URl without the sas token with the URl containing the sas token.

A: As long as the blob is private (which can be set at the container level), nobody will have access without the SAS-augmented URI. Even if you kept giving out the public URI, it wouldn't work if the container was marked as private.
Also, in your example, you've created a fictitious sascontainer. Note that shared access signatures work on any blob in any container. You don't need a special designated container.
With a SAS-based URI, it will be a valid URI until such time as the time expires (or you delete the blob). If you wanted more control, such as disabling a URI, you'd need to use a Shared Access Policy. Just something for you to consider looking into. And plenty of documentation on that, should you go that route.


text:
Q: Pb with JavaFx progressbar behavior The very first moment I start a task bound with my progress bar, the latter begins and rewind then restarts, this time according to my counter (as I expected). This unwanted effect is very subtle but visible nevertheless.
Here is my test code below:
private void startButtonEventHandler(ActionEvent event) {
 Service<Void> service = new Service<Void>() {
  @Override
  protected Task<Void> createTask() {

   Task<Void> task = new Task<Void>() {
    @Override
     public Void call() throws Exception {
      for (int i = 1; i <= 10; i++) {
       // Long running task ...
       Thread.sleep(500);
       updateProgress(i, 10);
      }

      return null;
     }
    };

    progressBar.progressProperty().bind(task.progressProperty());
    return task;
   }
  };

  service.start();
}

The progressbar is determinate :
progressBar = new ProgressBar(0.0F);
progressBar.setPrefWidth(200);

Update: I realized that the progressBar starts in undeterminate mode at the beginning and then after the first call to updateProgress() method it switches to the determinate mode. Is that a bug or a feature ?

A: The task's initial progress is -1 (i.e. indeterminate). (This makes sense, since by default the task has no idea how long it will take...) So when you bind the progress of the progress bar to the progress of the task, the progress bar becomes indeterminate.
Just set the progress of the task to 0 when it is created:
protected Task<Void> createTask() {

    Task<Void> task = new Task<Void>() {

        {
            updateProgress(0, 10);
        }

        @Override
        public Void call() throws Exception {
             for (int i = 1; i <= 10; i++) {
                 // Long running task ...
                 Thread.sleep(500);
                 updateProgress(i, 10);
             }

             return null;
        }
     };

     progressBar.progressProperty().bind(task.progressProperty());
     return task;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: what is the problem in my ' index.py' code? I am trying to create a CRUD app using flask and mysql.I try to display to form one for student-login and one for tteacher-login. the form are display by hitting on buuttons "Std-Login" and "Teach-Login".
When I run the code on console it is showing -----
Traceback (most recent call lost):
@app.route('stdLog',methods=['POST','GET']
AssertionError:view function mapping is overwriting and existing endpoint function:home

from flask import Flask,session,render_template,request
import os
import mysql.connector
from flask_bcrypt import Bcrypt

app=Flask(__name__)
# app.secret_key=os.urandom(24)
bcrypt=Bcrypt(app)

mydb=mysql.connector.connect(
 host="localhost",
 user="root",
 password="",
 db="mydatabase"
 )

@app.route('/')
def home():
 return render_template('home.html')

@app.route('/stdLog',methods=['POST','GET'])
def home():
 if request.method=='POST':
  mycursor=mydb.cursor()
  pwHash=bcrypt.generate_password_hash(request.form['password'])
  sql="insert into student (name,password) values (%s,%s)"
  val=(request.form['name'],pwHash)
  mycursor.execute(sql,val)
  mydb.commit()
  print(mycursor.rowcount,"student's record inserted")
 return 'ok'

@app.route('/teacherLog',methods=['POST','GET'])
def teacher():
 if request.method == 'POST':
  mycursor=mydb.cursor()
  pwHash=bcrypt.generate_password_hash(request.form['tpassword'])
  sql="insert into teacher(tname,tpassword) values(%s,%s)"
  val=(request.form['name'],pwHash)
  mycursor.execute(sql,val)
  mydb.commit()
  print(mycursor.rowcount,"teacher's recored Inserted")
 return 'Inserted'

if __name__=='__main__':
 app.run(debug=True)
<!DOCTYPE html>

 <title></title>

 <button onclick="mystd()">Std-Login</button>
 <button onclick="myteach()">Teach-Login</button>

   <form method="post" action="/stdLog" >
     Name:<input type="text" name="name">

     Password:<input type="password" name="password">

     <input type="submit" name="submit" value="std">
    </form>

A: Cause you are overwriting and existing endpoint function: home
Change the route /stdLog fuction to: def home2():  or  def stdLog():
 @app.route('/stdLog',methods=['POST','GET'])
    def stdLog():
        if request.method=='POST':
            mycursor=mydb.cursor()
            pwHash=bcrypt.generate_password_hash(request.form['password'])
            sql="insert into student (name,password) values (%s,%s)"
            val=(request.form['name'],pwHash)
            mycursor.execute(sql,val)
            mydb.commit()
            print(mycursor.rowcount,"student's record inserted")
        return 'ok'

Hope this helps you.


text:
Q: Json.Net JsonConstructor attribute alternative for System.Text.Json In Json.Net we have JsonConstructor attribute in order to instruct deserializer that should use the constructor to create the object.
Is there alternative in System.Text.Json?

A: Looks like this has now been added as of .NET 5.0 Preview 8:
Announcing .NET 5.0 Preview 8
JsonSerializer improvements in .NET 5
Related issue:
JsonSerializer support for immutable classes and structs
Related pull request:
Add [JsonConstructor] and support for deserializing with parameterized ctors

A: Please try this library I wrote as an extension to System.Text.Json to offer polymorphism: https://github.com/dahomey-technologies/Dahomey.Json
Add [JsonConstructor] attribute defined in the namespace Dahomey.Json.Attributes on your class.
public class ObjectWithConstructor
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    [JsonConstructor]
    public ObjectWithConstructor(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

Setup json extensions by calling on JsonSerializerOptions the extension method SetupExtensions defined in the namespace Dahomey.Json.
Then deserialize your class with the regular Sytem.Text.Json API.
JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();

const string json = @"{""Id"":12,""Name"":""foo"",""Age"":13}";
ObjectWithConstructor obj = JsonSerializer.Deserialize<ObjectWithConstructor>(json, options);


text:
Q: Regex to match {@layout=xxx} I am trying to learn the behinds of template system by creating my own and I have hit a bump...
I want to setup my template as follows:
{@layout=layoutname}

{@content}

This is a paragraph

{@endcontent}

But I don't know how to match {@layout= and get the layout name.
I have tried: if (preg_match('/(\{\@layout=[a-z]+\})+/', $string, $matches)) { which works ... kind of. I want to check if there are more then 1 layouts loaded to prevent errors in long files and want to count how many $matches I have and return error if more then 1 match is found but instead of getting all found layouts, it returns the same layout twice:
String used:
{@layout=app}

{@layout=main}

{@content}

{[username]} profile

    Name: {[name]}

    Age: {[age]}

    Location: {[location]}

{@endcontent}

and using that expression I get:
Array ( [0] => {@layout=app} [1] => {@layout=app} )
can someone please help me find my regex?

A: You need to use preg_match_all to get multiple matches in the same string. In this case, you want to check the $matches[1] which will be an array of capture group results. If you have more than one layout, it will have more than one element so if that's the case you know there is more than one layout declaration.
I would also change your regex to /\{\@layout=([a-z]+)\}/ which will capture only the layout name. $matches will look like:
array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(20) "{@layout=layoutname}"
  }
  [1]=>
  array(1) {
    [0]=>
    string(10) "layoutname"
  }
}

So if count($matches[1]) > 1, you know there is more than one layout declaration. Otherwise, $matches[1][0] is your layout name.

A: Thanks to @SebastianProske I have found what I was looking for:
if (preg_match_all('/\{\@layout=([a-zA-Z0-9]+)*\}/', $string, $matches)) {
that is the correct if, that returns also the name and all the matches.
Thank you for your time,
Ares D.


text:
Q: Unable to add a border-bottom in ion-item I want the border of ion-item to touch till the ends.When I write the css class for it, the browser does not apply the styles.

.html
<ion-item class="item-class">
<input type="text" placeholder="Username">
<ion-icon item-end name="people"></ion-icon>
</ion-item>

.css
.item-class {

border-bottom: 1px solid #F1F1F1;

}

You can see the screen-shot below

After adding !important to the border-bottom property in css the result are visible as follows:

When clicking in the input field the bule line is also visible.

A: In side your variable.scss file add this in the android section.
$text-input-md-highlight-color-invalid: transparent;
$text-input-md-highlight-color-valid: transparent;
$text-input-md-show-invalid-highlight: transparent;
$text-input-md-highlight-color: transparent;
$text-input-md-show-valid-highlight: transparent;

Inorder to avoid the item line use this
<ion-item class="item-class" no-line>
(or)
inside your respected scss file
.item-inner {
    padding-right: 8px;
    border-bottom: 1px solid #F1F1F1;
}


text:
Q: Store image width alpha-channel in windows clipboard I'm trying to copy an image to the windows clipboard but windows keeps removing my alpha. This is may latest attempt where i manually create the buffer and copy the BGRA values to the buffer, however still when i read the values later alpha is set to 255. If i copy my image from Paint.NET I get an InteropBitmap with the exact same values but alpha is set correct, so it should be possible. If i save my image to a PNG-file instead of the clipboard alpha is also correct.
var buffer = new byte[width * height * 4];
for (var x = 0; x < width; x++)
{
    for (var y = 0; y < height; y++)
    {
        var pixel = surface[x, y];
        var i = (y * width + x) * 4;
        buffer[i + 0] = pixel.B;
        buffer[i + 1] = pixel.G;
        buffer[i + 2] = pixel.R;
        buffer[i + 3] = pixel.A;
    }
}
Clipboard.Clear();
Clipboard.SetImage(InteropBitmap.Create(
    bounds.Width, bounds.Height,
    96, 96,
    PixelFormats.Bgra32,
    null,
    buffer,
    width * 4));


text:
Q: How do I pass PHP variables to angular js? I have a page where I'm reverse engineering in Angular JS. All the content is being echoed in by a PHP script (bad practice I know, but I'm easing into Angular and just wanted to use it for the onBlur event).
I was trying to figure out how to pass a variable from PHP to Angular. The variable (customer email) wasn't editable so I wanted to put it in a hidden field. The issue is that ng-model doesn't bind to hidden inputs. I needed another solution..

A: I found a great solution here
I ended up not creating a separate init function in my controller but simply did it inline in the ng-init param of a hidden input:
<?php echo $db_unit[$i]['email_id']; ?><input type="hidden" ng-init="customer.email='<?php echo $db_unit[$i]['email_id']; ?>'">

One obvious thing I tripped over was that you have to put the value for customer.email in '' I had it without quotes before that and it didn't work.

A: in this example I am passing the PHP $something variable to angular
ng-init="something='<?php echo $something ?>'"

now from the controller do:
console.log($scope.something);


text:
Q: Unable to use npm request package to meteor app I executed meteor npm install --save request in the command line
I imported the request library in my code import {request} from 'request'
And tried to use it with
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body) // Show the HTML for the Google homepage.
    }
})

However I keep on getting the following error:
undefined is not a function
How do I use the npm request package with my meteor app?

A: The default export from the request package is the object you are looking for. Change your import statement to the following:
import request from 'request';

It may be that you need the low-level functionality from request, however your example could also be accomplished with meteor's HTTP pacakge (which is itself a wrapper around request).
Here's an example:
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

Meteor.startup(() => {
  const resp = HTTP.get('http://www.google.com');
  console.log(resp.content);
});

Note you'll need to run meteor add http for that to work.


text:
Q: Golang: Is a network condition can make a net/http HandleFunc to panic? Think about that I have a critical function, that should run all or nothing.
TakeMoneyFromSomeone()
GiveMoneyToSomeoneElse()

My question is: Can I trust Go that the function will not panicing between line1 & line2 when using `net/http.HandleFunc? (The two function are inside my http handler)
I'm focusing only on networking issues. For example: if the client disconnect, or timeout or too long body, or  anything else. There is any networking issue that can make the server panic between line1, and line2? (Those two lines not using network)
If the answer is no. What happened if I try to ResponseWriter.write to a client that closed the connection. Is it will panic?

A: The HandlerFunc itself doesn't related to any potential networking issues, it just registers handlers to url patterns.
HandlerFunc
With 0 timeouts it will hang not panic. The better way is to use timeouts and handle errors instead of using default timeouts.

More control over the server's behavior is available by creating a custom Server:

s := &http.Server{
    Addr:           ":8080",
    Handler:        myHandler,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())

And you shouldn't apprehend a panic from a built-in libs.
Go By Example:

A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn't occur during normal operation, or that we aren't prepared to handle gracefully.
Note that unlike some languages which use exceptions for handling of many errors, in Go it is idiomatic to use error-indicating return values wherever possible.


text:
Q: How blacklist imports in a specific file with tslint Does TSLint support blacklisting imports in specific files? If yes how can I configure it?

A: I think there is no default rule that can achieve this. But TSLint can be extended with custom rules. Here is a good tutorial on how to create, include and use custom rules https://palantir.github.io/tslint/develop/custom-rules/.
We can start with the existing import-blacklist rule and extend it. To original source can be found at importBlacklistRule.ts
We just need to extend the options to include file-names and have to check the filename. Here a complete listing:
import * as Path from "path";
import * as Lint from "tslint";
import { findImports, ImportKind } from "tsutils";
import * as TS from "typescript";

interface Options {
  imports: string[];
  files: string[];
}

export class Rule extends Lint.Rules.AbstractRule {
  public static FAILURE_STRING =
    "This import is blacklisted, import a submodule instead";

  public apply(sourceFile: TS.SourceFile): Lint.RuleFailure[] {
    return this.applyWithFunction(sourceFile, walk, this
      .ruleArguments[0] as Options);
  }
}

const walk = (ctx: Lint.WalkContext<Options>) => {
  if (ctx.options.files === undefined || ctx.options.imports === undefined) {
    return;
  }

  const fileName = Path.basename(ctx.sourceFile.fileName); // Strip off path
  if (ctx.options.files.indexOf(fileName) === -1) {
    // Could be extended to test for a regex.
    return;
  }

  for (const name of findImports(ctx.sourceFile, ImportKind.All)) {
    if (ctx.options.imports.indexOf(name.text) !== -1) {
      ctx.addFailure(
        name.getStart(ctx.sourceFile) + 1,
        name.end - 1,
        Rule.FAILURE_STRING
      );
    }
  }
};

In the example above I have stripped down the import-blacklist rule to its essentials and added a check for the filename.
const fileName = Path.basename(ctx.sourceFile.fileName); // Strip off path
if (ctx.options.files.indexOf(fileName) === -1) {
    // Could be extended to test for a regex.
    return;
}

In the example, we only check, that the filename without the path must be present in options.files. You could extend this logic to check for a regex or whatever fits your needs.
While including this rule you have to specify the filenames to check and the prohibited imports.
"custom-import-blacklist": [
  true,
  {
    "files": ["Index.ts"],
    "imports": ["xxx"]
  }
]


text:
Q: How to distribute (card game table) dealers across servers in a balanced way? I am currently working on an online card game, similar to blackjack, which will consist of a series of tables where each table has a "dealer" and multiple human players. The dealer (a computer bot) is responsible for dealing and shuffling cards. The tables will be stored in a PostgreSQL database table and it will be possible for a human admin to add/remove/edit tables.
The game will consist of a web front end and a REST/websocket API backend. I will probably use Kubernetes and Nginx as a load balancer for the backend servers.
Onto my question. Let's say I have a single server, I could simply have it read the table list from the database and start a dealer process/thread per table. However, if I have 2 or more servers things start to get more messy.
How do I ensure that the tables are assigned in a balanced way across all servers (e.g. if there is 10 tables and 3 servers, the distribution should be roughly 3-3-4)?
How do I ensure that if a server fails, its tables get reassigned to a live server?
How do I make sure that, when a new server comes online, some existing tables get re-assigned to it so to reduce the workload of the other servers?

A: I assume each state change is forwarded to players via websockets and stored into the database for persistence (just for failure recovery and some stats).
So if for some reason server1 stops working and nginx starts connecting clients of table1 to server2 then it(server2) will have no problems with picking up the state of the game which was serviced by server1 before failure.
You can use hash of URI or parameter to forward all requests related to the same table to specific server.
When nginx sees that server went offline it will stop using it as a pool member and migrate all requests to another server in a consitent way.
Of course when new server comes online existing table will NOT be reassigned to the new server during the game (because you need to keep websocket connection in working state).
But when game ends you can tell clients (via existing websocket connection) to reopen new websocket connection with slightly modified URL thus forcing nginx to re-balance connections between servers.
upstream backend {
    hash $request_uri consistent;
#    hash $arg_table consistent;
    server bj-1.card-games.com max_fails=2 fail_timeout=2s;
    server bj-2.card-games.com max_fails=2 fail_timeout=2s;
    server bj-3.card-games.com max_fails=2 fail_timeout=2s;
}

server {
 location / {
  proxy_pass http://$backend;
 }
}


text:
Q: Using NSDateFormatter in objective-C I would like to convert 2013-07-10T21:48:09.000Z to 10.7.2013 using nsdateformatter.
I've tried going through some tutorial but I can't seem to figure out what to do, How would I correctly do this conversion?
Any help is greatly appreciated.
I tried this but I only get returned a (null)
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:000Z"];
    NSDate *theDate = [dateFormatter dateFromString:stringDate];
    NSLog(@"%@",[dateFormatter stringFromDate:theDate]);

A: First, your date format is wrong -- the second line should be [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"]; -- that is, you need the ss. after the mm: but before the 000Z. This will give you the correct NSDate.
Next, you need to create a new date formatter with the format @"dd.M.yyyy" (or @"d.M.yyyy" if you want to remove the leading zero if the day is a single digit as well) and call stringFromDate: on that for the NSLog.
Just to recap, the whole chunk of code would be
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"];
NSDate *theDate = [dateFormatter dateFromString:stringDate];

NSDateFormatter *printFormatter = [[NSDateFormatter alloc] init];
[printFormatter setDateFormat:@"dd.M.yyyy"];
NSLog(@"%@",[printFormatter stringFromDate:theDate]);


text:
Q: solve the initial value problem $\frac{dy}{dx}=\sqrt{ |y|}$, 0$\frac{dy}{dx}=\sqrt{ |y|},0<y<10$ and $y(0)=0$.  I see that $\sqrt{ |y|}$ is continuous and has a partial derivative w.r.to. y exist and bounded in the given domain. So the ivp has a unique solution but the answer is infinite.

A: How about $y=x^2$?
I got to it just by looking. I ignored the absolute value and thought about polynomials: the square root halve the degree. Differentiation reduce the degree by $1$. If the degree happens to be $2$, then those two things are the same. Of course, $y=0$ is also a solution.

A: This is a standard problem to show the difference of the Peano and Picard-Lindelöf theorems. The general solution is
$$
y(x)=\frac14(x-c)_+^2=\begin{cases}0&0\le x<c\\\frac14(x-c)^2&c\le x\end{cases}
$$
Numerically you get a solution differently from the zero function if you add some small noise in each integration step.


text:
Q: Using symbolic variables in Simulink How do I use symbolic variables in the Simulink block diagram for different blocks? I'd like to run linmod2 and obtain a transfer function in the terms of the symbolic variables.

A: According to John D'Errico, aka woodchips, this likely not possible.  That was my understanding of the way the linmod family of algorithms worked as well.  However, what are you trying to do that you need to get the analytic representation of the model with the symbolic parameter?  There may be other ways to accomplish what you need, please elaborate.


text:
Q: Unable to read the license file `LICENSE` for the spec `GoogleDataTransport (3.2.0)` Unable to read the license file LICENSE for the spec GoogleDataTransport (3.2.0) when pod install Which result in GoogleDataTransport not found when try to build.
Earlier it worked but after I upload project to drive and from my windows computer I push to git and in another mac I cloned the repo and tried. That is the reason this happening.
I have tried cleaning pods, reinstalling updating, deleting podloc, pod directory and .xcworkspace. Non of them worked. I even copied the LICENSE file from another and pasted to GoogleDataTransport directory, nothing worked.

A: I tried lot of things but nothing worked until I do these:
pod deintegrate
pod setup
pod install

in terminal. and open .xcworkspace and Product -> Build
This SO answer helped me for that: How to clear or clean specific pod from the local cocoapods cache


text:
Q: shlock not found I'm trying to use a script for backing up btrfs, and it uses shlock
here is the script:
btrfs-subvolume-backup
now it says i need the inn package, and I've triedn installing it, but still no shlock
according to ubuntu man page shlock should be in inn2 package, which I have also tried with no success.
So where can I find that package to install (64 bit pc) or how to fix the script to have the same functionalaty without shlock

A: According to the Ubuntu Packages index, it could be in the inn or inn2 packages. In both cases, from the list of files, shlock is at:
/usr/lib/news/bin/shlock

Perhaps you need to use the full path, or set the PATH accordingly.


text:
Q: Possible to end a query from within a script if time exceeds x? So we have a schema that holds the view names, and columns for various report queries used in the system.  Some of these views are very old and not very well written, but still get the job done (if slowly).
Anyway, I am writing a script that uses dynamic sql to determine the number of distinct values for each column in the reports. The critical parts of this script which loops through each column for each view is the following lines:
SET @sql = N'SELECT @val=COUNT(DISTINCT [' + @curColumnName + N']) FROM [' + @curViewName + N']'
SET @params = N'@val int OUTPUT'

EXEC sp_executesql @sql, @params, @val=@outputValue OUTPUT

This is working well.  However, as I mentioned before, a few of these views are rather poorly written, and some of the old schema could probably use better indexing, and as a result retrieving the distinct values from the columns takes a very long time, sometimes several hours or even days.
For this reason it's become far less effective to perform this operation, because it will take months to complete for every report.  The thing is, we don't really care what the actual distinct value count is, but really just knowing if there's more than say, 100 distinct values.
So my question is this, is there some way to stop the query once the number of distinct values is over 100 and just return 100, and/or to just cancel the sp_executesql call and then continue the rest of the script if it's taking longer than say, 5 minutes?

A: There is really no way to do what you want before processing the data.  Focusing only on the query, you could do:
SELECT @val = COUNT(*)
FROM (SELECT TOP 100 @curColumnNameFROM
      FROM @curViewName
      GROUP BY @curColumnName
     ) t

It is unlikely that this would have a significant impact on performance.
Sometimes in these cases, you could do:
SELECT @val = COUNT(DISTINCT @curColumnName)
FROM (SELECT TOP 10000 @curColumnNameFROM
      FROM @curViewName
      GROUP BY @curColumnName
     ) t

This can reduce the size of the data and that might be sufficient for some purposes.


text:
Q: disable XQuartz and revert to mavericks's default x server I have installed XQuartz 2.7.5 on Mavericks. After that videos I play with mplayer seems to load on a separate window, all white stuck with only the audio playing. I have disabled Xquartz by disabling /Library/LaunchAgents/org.macosforge.xquartz.startx.plist and /Library/LaunchDaemons/org.macosforge.xquartz.privileged_startx.plist with launchctl.
Iwould like to know how to display the videos as it was playing before. I installed mplayer via brew. Is there a way to direct $DISPLAY to the default x server? Please help.
Thanks

A: Don't disable /Library/LaunchDaemons/org.macosforge.xquartz.privileged_startx.plist.  That will prevent XQuartz.app from launching.
Disabling /Library/LaunchAgents/org.macosforge.xquartz.startx.plist (and relogging) will result in the DISPLAY environment variable not being set and thus automatic launching of XQuartz.app when you run X11 applications, but you can still launch XQuartz.app directly.
There is no default X server.  X11 was removed from OS X in Mountain Lion.  X11.app in earlier versions of OS X was just XQuartz.app with different name.


text:
Q: Jquery - apply method to all elements returned this is probably pretty straightforward but i'm struggling with it - I want to pause all videos I have running in a div container. At the moment, this is what I have:
// Doesn't work
$("#vid").find("video").get().pause();
// Works
$("#vid").find("video").get(0).pause();

What's the best way to apply the pause function to each video element? A for/each loop?

A: $('video','#vid').each(function(){
     this.pause(); //find all videos in #vid and pause them
});

A: $('#vid').find('video').each(function(){
     $(this).pause();
});


text:
Q: Getting original position of listview after filtering with searchview java I have a listview populated with this array
arrayList.add("Adam");
arrayList.add("Bob");
arrayList.add("Bob");
arrayList.add("Charlie");

I then have a searchview which properly filters the adapter based on what the user is typing
String text = textField.getText().toString().toLowerCase(Locale.getDefault());
            adapter.getFilter().filter(text);

If the user types "B", "Bob" and "Bob" are the only items displayed in the     listview. If I click on the top one, the item position is 0. I need to get the original position of that item(which in this case is 1). I am aware that I could take the context of the row and search the arrayList for the first occurrence of the item. I can then get its position in the unfiltered arraylist. (example)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            int i = 0;

            String text = ((TextView) view).getText().toString();

            i = arrayList.indexOf(text);

            if(textLength == 0)
                Toast.makeText(getApplicationContext(), text + " and position is " + position, Toast.LENGTH_SHORT).show();
            else{
                Toast.makeText(getApplicationContext(), text + " and position is " + i, Toast.LENGTH_SHORT).show();
            }

        }
    });

This works regardless of what row I click on, if no filtering has been applied. After filtering, I cannot search the array list for the first occurrence of the row that was selected because there may be more than 1 item with the same text. Also, if I clicked on the second "Bob" (after filtering), it would just return the position of the first "Bob" (which is 1). I understand the problem, I just can't figure out a solution. Is there an efficient way to fix this?

This is just so I can get a proof of concept working. My actual project has multiple array lists. So regardless of their being multiple items in the original array list with the same text (Bob and Bob), the other array lists have different values. That is why I need the original position without searching the array list for the first occurrence of the text. I will not have control of what is in the array list, so I have to account for duplicates.

A: Please try this
public void onItemClick(AdapterView parent, View view, int position, long id) {
parent.getItemAtPosition(position);
* your code *
}


text:
Q: How to get information from an array iteration that uses {{this}} and delete item Meteor Hi guys I have tried this approach to get information from an array of Meteor.users but it's not working and I don't have any idea to solve this problem. Thanks in advance!
Publish users
Deps.autorun(function (handle) {

Meteor.publish('directory', function () {
  if (this.userId) {
  var user = Meteor.users.findOne(this.userId);
  var x = user.profile.x;
  return Meteor.users.find({"profile.x": x});
  } else {
    handle.stop();
  }
});
});

Meteor.users.allow({

  remove:function() {
    var user = Meteor.user();
    var x = user.profile.x;
    if(x === "admin") {
      return true;
    } else {
      return false;
    }
    },
});

Helper:
listTeam: function () {
    var userTeam = Meteor.users.find({}).fetch();
    return _.map(userTeam || [], function(user) { return user.emails[0].address || user._id;});
 },

Template:

{{#each listTeam}}

{{this}}
<button id="deleteTeam" class="button">Delete</button>

{{/each}}

First approach:
'click #deleteTeam': function (event, template) {
    var id = template.data._id;
    Meteor.users.remove({_id:id});

  }

Returns undefined (only in the first item of iteration)
I've tried with jQuery but it's not useful since I just get the email address and the first item only.(I'm not iterating id's and I think this seems not to be a good solution).

A: Inside template event functions you can use this to get the instance data.
Example:
'click #deleteTeam': function (event, template) {
    var id = this._id;
    Meteor.users.remove({_id:id});
}

or alternatively shorter:
'click #deleteTeam': function () {
    Meteor.users.remove({_id: this._id});
}

if you run into further issues, it might be a permissions problem, I recommend using this pattern:
Meteor.users.allow({
  remove: function(userId, doc) {
    var user = Meteor.users.findOne({_id: userId});
    return user ? user.profile.admin : false;
  }
});


text:
Q: How do I create/play audio in C++? I'm pretty new to C++, but have some experience with Python. I wanted to make a program that played certain frequencies based on different conditions, but I soon realized I couldn't even figure out how to play an audio file. From what I found looking for a solution, it seems almost impossible on Mac, and everything I tried copying into Xcode ended up with a bunch of errors. Where should I start with this?

A: I once used SFML for this. Although I did it on Linux, I see that its available for mac as well. You can go through the tutorials here.

A: The problem here is that C++ is just a programming language. The same can be said for python, though Python lives in a different ecosystem of modules and package management which get conflated (rightly or wrongly) as part of the language
C++ doesn't have the same history and the same ecosystem and this is part of the battle you will have when learning it. You don't have pip, you have a nebulous series of frameworks, headers and libraries (some standard, some which need installation) all of which need linked, path-ed or compiled. It is an ecosystem that is unfriendly if you try and approach it like a novice Python programmer. If you approach it agnostically, it is simultaneously very powerful and exceptionally tedious, a combination that tends to polarise developers.
This means that simple answers like Use SFML!, SDL, NSOUND, OpenAL, CoreAudio, AVFoundation, JUCE, &c... are all technically "correct" but massively gloss over large parts of setup, nomenclature and workflow that are just a pip install away with python.
Pontificating aside, if you want to simply

*

*create an array of floating point values

*that represent the samples of sine tone

*then play those samples

*on macOS

Then you are probably best just

*

*creating your array

*writing a .wav

*opening the .wav with afplay
Is that the most open, versatile, DSP orientated, play-from-RAM solution? No, of course not, but it is a solution to the problem you pose here. The alternative and correct answer is an exhaustive list of every major media library, cross-platform and macOS specific, their setup, quirks and minimum working example, which would result in an answer so obtusely long I hope you can sympathise with why it is not best addressed on Stack Overflow.
A Simple CLI App
You can find all the constituent parts of this on SO, but I have tallied-off so many how do I play a sound in C++ questions it has made me realise they are not going away.
The setup for Xcode is to create a Command Line Tool project (Console App for Visual Studio).
Here is a header that will wrap up everything into a playSound function
audio.h
#pragma once

//------------------------------------------------------------------------------
#include <iostream>
#include <fstream>
#include <cstddef>
#include <cstdlib>
#if defined _WIN32 || defined _WIN64
#pragma comment(lib, "Winmm")
#include <windows.h>
#endif
//------------------------------------------------------------------------------

/// <#Description#>
struct WaveHeader
{
    /** waveFormatHeader: The first 4 bytes of a wav file should be the characters "RIFF" */
    char chunkID[4] = { 'R', 'I', 'F', 'F' };
    /** waveFormatHeader: This is the size of the entire file in bytes minus 8 bytes */
    uint32_t chunkSize;
    /** waveFormatHeader" The should be characters "WAVE" */
    char format[4] = { 'W', 'A', 'V', 'E' };
    /** waveFormatHeader" This should be the letters "fmt ", note the space character */
    char subChunk1ID[4] = { 'f', 'm', 't', ' ' };
    /** waveFormatHeader: For PCM == 16, since audioFormat == uint16_t */
    uint32_t subChunk1Size = 16;
    /** waveFormatHeader: For PCM this is 1, other values indicate compression */
    uint16_t audioFormat = 1;
    /** waveFormatHeader: Mono = 1, Stereo = 2, etc. */
    uint16_t numChannels = 1;
    /** waveFormatHeader: Sample Rate of file */
    uint32_t sampleRate = 44100;
    /** waveFormatHeader: SampleRate * NumChannels * BitsPerSample/8 */
    uint32_t byteRate = 44100 * 2;
    /** waveFormatHeader: The number of bytes for one sample including all channels */
    uint16_t blockAlign = 2;
    /** waveFormatHeader: 8 bits = 8, 16 bits = 16 */
    uint16_t bitsPerSample = 16;
    /** waveFormatHeader: Contains the letters "data" */
    char subChunk2ID[4] = { 'd', 'a', 't', 'a' };
    /** waveFormatHeader: == NumberOfFrames * NumChannels * BitsPerSample/8
     This is the number of bytes in the data.
     */
    uint32_t subChunk2Size;

    WaveHeader(uint32_t samplingFrequency = 44100, uint16_t bitDepth = 16, uint16_t numberOfChannels = 1)
    {
        numChannels = numberOfChannels;
        sampleRate = samplingFrequency;
        bitsPerSample = bitDepth;

        byteRate = sampleRate * numChannels * bitsPerSample / 8;
        blockAlign = numChannels * bitsPerSample / 8;
    };

    /// sets the fields that refer to how large the wave file is
    /// @warning This MUST be set before writing a file, or the file will be unplayable.
    /// @param numberOfFrames total number of audio frames. i.e. total number of samples / number of channels
    void setFileSize(uint32_t numberOfFrames)
    {
        subChunk2Size = numberOfFrames * numChannels * bitsPerSample / 8;
        chunkSize = 36 + subChunk2Size;
    }

};

/// write an array of float data to a 16-bit, 44100 Hz Mono wav file in the same directory as the program and then play it
/// @param audio audio samples, assumed to be 44100 Hz sampling rate
/// @param numberOfSamples total number of samples in audio
/// @param filename filename, should end in .wav and will be written to your Desktop
void playSound(float* audio,
               uint32_t numberOfSamples,
               const char* filename)
{
    std::ofstream fs;
    std::string filepath {filename};

    if (filepath.substr(filepath.size() - 4, 4) != std::string(".wav"))
        filepath += std::string(".wav");

    fs.open(filepath, std::fstream::out | std::ios::binary);

    WaveHeader* header = new WaveHeader{};
    header->setFileSize(numberOfSamples);

    fs.write((char*)header, sizeof(WaveHeader));

    int16_t* audioData = new int16_t[numberOfSamples];
    constexpr float max16BitValue = 32768.0f;

    for (int i = 0; i < numberOfSamples; ++i)
    {
        int pcm = int(audio[i] * (max16BitValue));

        if (pcm >= max16BitValue)
            pcm = max16BitValue - 1;
        else if (pcm < -max16BitValue)
            pcm = -max16BitValue;

        audioData[i] = int16_t(pcm);
    }

    fs.write((char*)audioData, header->subChunk2Size);

    fs.close();
    std::cout << filename << " written to:\n" << filepath << std::endl;

#if defined _WIN32 || defined _WIN64
    // don't forget to add Add 'Winmm.lib' in Properties > Linker > Input > Additional Dependencies
    PlaySound(std::wstring(filepath.begin(), filepath.end()).c_str(), NULL, SND_FILENAME);
#else
    std::system((std::string("afplay ") + filepath).c_str());
#endif

}

main.cpp
Your main function could then be something like:
#include <iostream>
#include <cmath>
#include "audio.h"

int main(int argc, const char * argv[])
{
    const int numSamples = 44100;
    float sampleRate = 44100.0f;
    float* sineWave = new float[numSamples];
    float frequency = 440.0f;

    float radsPerSamp = 2.0f * 3.1415926536f * frequency / sampleRate;

    for (unsigned long i = 0; i < numSamples; i++)
    {
        sineWave[i] = std::sin (radsPerSamp * (float) i);
    }

    playSound(sineWave, numSamples, "test.wav");

    return 0;
}


text:
Q: Monitoring CPU Usage Over the Course of a Day? Are there any apps I an install on client machines that will generate a report for me what app used what % of the CPU. We have some machines that are running, at times, VERY slowly. The machine will run really poorly then boom, back up to full speed. There isn't usually enough time to check Task Manager real quickly to see what is running, not to mention the majority of the time there are people using the computer that don't know what the Task Manager is. ;)
It would be really nice to take a look at some logs and see if, maybe, the anti virus is randomly taking alot of CPU for stretches of time. Or another application.
Thanks!
EDIT:
This is for Windows XP. Sorry for the oversight. :)

A: Here are two free CPU meters that seem to fulfill your needs:
Spotlight on Windows

For a busy IT professional, it is
  nearly impossible to diagnose,
  troubleshoot, and resolve every
  component affecting Windows Operating
  System (OS) performance using manual
  methods.  Without a clear view of I/O
  and system activity, you learn of
  performance issues only after problems
  erupt.
With its unique graphical view of the
  Windows OS internals, Quest®
  Spotlight® on Windows empowers you to
  quickly identify and eliminate
  bottlenecks in the Windows
  environment. Displaying the real-time
  flow of data within your Windows OS,
  Spotlight enables you to quickly
  identify and resolve performance
  problems.

SysMetrix (last version from 2006)

SysMetrix is a skinnable clock and metering application. Its purpose is
  to provide system metrics in a variety of interesting, useful, and cool
  ways. It can monitor and report on the hundreds of statistics.

A: This is going to sound a bit wishy-washy, because I don't have an XP system in front of me.
XP has a built in Performance Monitor. I can't recall how to get to it exactly, so you'll need to read the help - but somewhere under Computer Management or the Control Panel.
You can use that to create a graph that monitors dozens of performance items, including the processor time for each nominated process. You may need to spend some time creating graph lines for each process that might be responsible.
Before you start that, you might like to monitor, at an aggregate level, the CPU, page-faults per second, network traffic etc. I often find it isn't the CPU that is peaking, it is the virtual memory dumping to disk that causes my machine to freeze.
I don't have a solution for processes that pop up, consume all the CPU, and then disappear.
Finally, a common war story: Someone installed a CPU-intensive screen-saver on one of our file-servers once. Everyone complained that it was running slowly, but every time I rushed over to look at what it was doing in Performance Monitor, the busy task had just stopped and everything was back to normal... for another 20 minutes. Took a while before it dawned on me.

A: Here's the rest of the details for using perfmon/counter logs to track this down directly:

*

*Right click on My Computer, select Manage

*Expand System Tools-Performance Logs and Alerts-Counter Logs

*Right click on it and select New Log Settings, enter a name and proceed

*Click on the Add Counters button

*Select local computer counters

*Select the Process Object

*Select All instances

*Add at least % Processor Time

*Close the add counters dialog

*Change the interval to something more reasonable between 30sec-5min

*Close and save the configuration, then start it by right clicking or using the toolbar

Personally I would start with a larger time interval and the overall CPU utilization (Processor Object), Disk Utilization, Networking, Some of the core Memory object counters and then add the Process counters that relate to whatever seems to be at the limits of capacity.
When you have captured the incidents you want to analyze you can analyze them manually by loading the files in perfmon (use View Log Data or Ctrl-L to load them).
If you have many machines to check,  download PAL: http://pal.codeplex.com which has different pre-configured counter sets you can import into a Counter Logs configuration, as well as a large number of criteria that it uses to check different specific bottlenecks. More importantly the reports contain pretty specific background information on each type of counter/bottleneck.

A: You could install Nagios agents on Windows computers.
More details here.


text:
Q: Git post-commit hook x central CI system I'm new to git and I am looking at what are the possibilities when integrating it into our CI (Jenkins) environment.
Based on several answers I found here at SO (mainly How to configure Git post commit hook), I understand that it a common wish (or practice) to configure git post-commit hooks to trigger your CI builds, instead of simply relying on SCM polling.
A post-commit hook is triggered when the user runs git commit. Since commiting (in git terminology) means commiting to your local repository, those changes are not yet available in the central repository (i.e., they haven't been pushed).
Assuming you have a central CI server, my question is: what is the use of "triggering your CI build" after commit, if the CI system cannot see those changes yet?

A:
Assuming you have a central CI server, my question is: what is the use of "triggering your CI build" after commit, if the CI system cannot see those changes yet?

There are plenty of workflows to choose from. Trying to include a complete picture here:
# as a new member of your team
git clone https://your-repo your-repo
cd your-repo
git remote add ci-server https://ci-server
git checkout -b my-feature-branch ci-server/master
# code stuff
git add .
git commit -m "lala"
# code stuff
git add .
git commit -m "lala"
# ...
git push my-feature-branch ci-server
# rinse and repeat
git fetch ci-server/master
git checkout my-next-feature ci-server/master

Now, the ci-server reacts to the pushed commits, builds them, perform tests etc, and finally merges the commit to its master, which you as a developer pull/fetch later on (or use as a base for new feature branches as demonstrated above).
That's what I would call a minimal working example. Also see something like gitflow or Atlassians comparison of git branching models


text:
Q: Error creating new Android project with Android Studio I just created a new project Android with Android Studio and I have chosen the minimum SDK 9 (Gingerbread) and the activity NavigationDrawer Activity, once chosen and created the project I get the following error:
Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.android.support:design:26.0.0-alpha1] C:\xxx\xxx\.android\build-cache\bd439271136a9bc6f4bc228104359605401bab70\output\AndroidManifest.xml
    Suggestion: use tools:overrideLibrary="android.support.design" to force usage

And I have not touched anything or modified anything that has created the Android Studio itself and I have updated the SDK with the latest versions.
Any suggestion?
Gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "xx.xx.xx.seguros"
        minSdkVersion 9
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

A: What happening inside it is. The Library support design using the minimum SDK version 14. So you can't use this library if your app minimumSdk version lower than that.
You should use com.android.support:design:25.+ to support minSdkVersion 9.
If you use com.android.support:design:26.0.0-alpha1. You must use minSdkVersion 14
Update your gradle like this.
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
    applicationId "xx.xx.xx.seguros"
    minSdkVersion 14      // Update it to 14
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Hope it helps:)

A: I have found two solutions to eliminate this error, but I don't know which one will be the most correct
I) Downloading the version, for this you have to modify the build.gradle using version 25 instead of 26 as follows:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "xx.xx.xx.seguros"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.+'
    compile 'com.android.support:design:25.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

II) Using tools: overrideLibrary, you have to modify the manifest by adding the following:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="es.uv.lisitt.seguros"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-sdk tools:overrideLibrary="android.support.design, android.support.v7.appcompat,android.support.graphics.drawable, android.support.v7.recyclerview, android.support.v4, android.support.mediacompat, android.support.fragment, android.support.coreui, android.support.coreutils, android.support.compat"/>

     .....
</manifest>

A: apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.0" //change
defaultConfig {
    applicationId "xx.xx.xx.seguros"
    minSdkVersion 14 //change
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }

}

hope it helps


text:
Q: How to get bigger photos' thumbnails in Nautilus? Today I wanted to go through my photos collection but I have realised that it is quite difficult to go through thumbnails in Nautilus as it is using the free space in the window very inefficiently, e.g.

Is there any other option to use it less "padding" , free space between other photos ? Or should I use other window manager to achieve this ?

A: In Nautilus you can right click on a empty area in the folder and select Zoom In or use Ctrl + Mouse scroll wheel to zoom the pictures.
Alternate is to use Thunar

A: I have ended up using nemo as file manager. There has been a new version recently on webupd8
http://www.webupd8.org/2013/10/install-nemo-with-unity-patches-and.html

A: The Control+ (Control key and Plus) and Control- (Control key and dash) should increase/decrease the icon's size, which should be permanent in every folder. This can also be done by pressing the Control key and mouse wheel.
This allow you to have different size icons in each folder as needed.
Additionally you can use the "Arrange Items/Compact Layout" in the context menu (right click) in order to use the folder's space (the right side pane's space) more efficiently.
Good luck!


text:
Q: Issue with jQuery blur I have two elements firstName and lastName. I need to alert some text when focus out both elements. I used the jQuery as below.

$(document).on("blur", "#fName", function(event) {
  alert("First Name lost the focus");
});

$(document).on("blur", "#lName", function(event) {
  alert("Last Name lost the focus");
});

  <input type="text" id="fName" name="firstName" />
  <input type="text" id="lName" name="lastName" />

But the issue here is even If I focus out the first element the second alert also prompting.
What is the issue here?

A:

$(document).on("blur", "#fName", function(event) {
  console.log("First Name lost the focus");
});

$(document).on("blur", "#lName", function(event) {
   console.log("Last Name lost the focus");
});

  <input type="text" id="fName" name="firstName" />
  <input type="text" id="lName" name="lastName" />

It will work fine with "console.log" because on every time alert popups and on clicking it's "ok" button, blur event is definitely going to be call because cursor is still at your input control and you are clicking on button.


text:
Q: What is your workflow for designing "antique" maps? I currently work with ArcGIS 9.3 and have decent competence with Adobe CS4-5 of Photoshop and Illustrator. I'm more than happy to branch out to other software.
Essentially, I'd like to get really good at creating maps that look like old maps with unknown "there be dragons" areas. One project I have in mind is maps of old spice trade routes. I'm thinking of a Art Noveau style like Alphonse Mucha. I get a kick out of imaginative maps that are aesthetically pleasing, simple, and easy to read.
This isn't exactly what I'm looking for, but yes, in this general direction. Map-poster from Conservation GIS 2011 Contest

A: Old Maps Online: Blog has a Workflow for old maps in libraries.
http://blog.oldmapsonline.org/2009/06/elag-workflow-for-old-maps-in-libraries.html
David Rumsey has a huge collection of old maps
http://www.davidrumsey.com/
Map Based Search
http://rumsey.mapranksearch.com/

A: James Fee had a post about some resources to make historical map effects using ArcGIS. A zip file of all the materials including icon and font sets are available.


text:
Q: How to turn a character array into uint8_t I have a server-client application that I'm working on that basically simulates a chat room. This is an assignment for school and the protocol specifications are somewhat strict.
I have a char array which will store all messages from a client.
The client must first send the length of the message as a uint8_t and then the message itself as a char array.
My problem is I need to store the uint8_t value that is sent before the actual message is sent but I can only use the message array to store any information coming from the client.
If I'm not mistaken the char array will not store the uint8_t that gets sent over unless I cast it somehow.
How can I convert the uint8_t to characters and back to uint8_t?
I've tried looking for a similar problem on here but couldn't find an example.
server.c
char msg[100];
recv(clients_sd, msg, sizeof(msg), 0);
uint8_t len; /* store the length of the message here */
char message_received[len];
recv(clients_sd, message_received, sizeof(message_received), 0); /* get and store the message here */

client.c
uint8_t length = 21;
char clients_message[] = "Hi how are you today?";
send(servers_sd, &length, sizeof(length), 0);
send(serers_sd, &clients_message, sizeof(clients_message), 0);

A: If you're on an architecture where uint8_t is a typedef to unsigned char (you most likely are), then simply take the first char and cast it to uint8_t:
length = (uint8_t)(message_received[0]);

It should work.

A: A char is exactly one byte (per definition of the C standard). Unless bytes aren't exactly 8 bits on your system (such systems exist, but I bet you've never used or even seen one), uint8_t and char are exactly the same data type.
char c = 5;
uint8_t u = c;

And if you can do something like that with a data type, then you can just cast pointers as you wish between these two data types:
 char c[] = { 'H', 'e', 'l', 'l', 'o' };
 uint8_t * u = (uint8_t *)c;
 uint8_t x = u[1];
 // x is 101, which is the ASCII char code of 'e'

Actually you can even do that with strings, as a string is also just an array of characters, just one that is NUL terminated.
 char * c = "Hello";
 // "Hello" is in fact just { 'H', 'e', 'l', 'l', 'o', '\0' }
 uint8_t * u = (uint8_t *)c;
 uint8_t x = u[1];
 // x is 101, which is the ASCII char code of 'e'

The only thing you need to be careful is that the C standard does not define if char is signed or unsigned. Unlike integer types that are signed by default and only unsigned if you request so (long vs unsigned long for example), a char may be signed or unsigned by default. So if you need either one, you must use signed char or unsigned char as a data type. In practice that plays no role unless you perform certain math or logic operations on char values (which you probably shouldn't do in modern C code to begin with).
And since there is no way that your message can be bigger than 256 characters (as otherwise the length would not fit into uint8_t) and the length is always exactly one byte, I'd write the code as follows:
uint8_t messageLength = 0;
ssize_t bytesRead = recv(clients_sd, &messageLength, 1, 0);
if (bytesRead == -1) {
     // Handle read error
}
if (bytesRead == 0) {
     // Handle end of stream
}

char message[256];
bytesRead = recv(clients_sd, message, messageLength, 0);
if (bytesRead == -1) {
     // Handle read error
}
if (bytesRead == 0) {
     // Handle end of stream
}
if (bytesRead < messageLength) {
     // Handle truncated message (message too small)
}

And once more, as apparently some people fail to understand my second sentence already: Everything I wrote above it under the assumption, that bytes on your system are 8 bits long. This code is not portable to platforms where bytes have more or less than 8 bits, that's already what my second sentence clearly points out, but that doesn't make my reply wrong. If it wasn't allowed to write C code that is not portable to all existing platforms on earth, 90% of all existing C code would be forbidden. You know the platform you are working with and you know the platforms you are targeting with your app, so it's your responsibility to make sure the code is correct for all these platforms.

A: char can be easily converted to uint8_t, but I don't understand why do you need to store the length in message array. Why can't you store just in variable?
here are your examples of client and server with small changes that I think can be helpful:
server.c
uint8_t len; /* store the length of the message here */
recv(clients_sd, &len, sizeof(len), 0);
char message_received[len];
recv(clients_sd, message_received, len, 0); /* get and store the message here */

client.c
uint8_t length = 21;
char clients_message[] = "Hi how are you today?";
send(servers_sd, &length, sizeof(length), 0);
send(serers_sd, clients_message, length, 0);


text:
Q: Is there a way to break on warnings in Google Chrome? I want to see the warnings in order to do a better debugging of my application which is made in Asp.Net, so it has a lot of code generated in javascript. The problem is that pages reload fast and I can't take a look at the warning messages. I want to know if there is a way to break on warnings in Google Chrome, as in this question is described how to break on errors. Is there a way to do this, or what alternatives do I have?

A: As @Nitsew has already said, preserving the log is a great solution. But just for fun, and because I thought your question was interesting, I decided to work out a solution to do what you asked; cause a debug to occur when warn is used:
function testBreak() {
    console.warn('This is a warning', 1, 2);
    return 1;
}

var oldWarningFunction = console.warn;
console.warn = function () {
    debugger;
    oldWarningFunction.apply(console, arguments);
};

console.log(testBreak());

Essentially, I have monkey-patched the original console.warn to output a debugger statement. When this causes the debug to occur, you will probably need to view the stack trace to see where you were in the code:

Once you click back one on that stack trace, you can see the function that made the call.
This all seems rather silly since you could just write your own debugger statement right in your code where you want them. And one other thing, to whoever may read this and tries it: Do not leave this in your production code

A: If you are just trying to look at the console messages, turning on "Preserve log" might be an easier solution.


text:
Q: Determine if there is an active Microsoft Teams call via the Windows API Is there a function in the Windows API that can be called to determine if there is an active Microsoft Teams call in progress?

A: No.
Microsoft Teams is a 3rd party application, just like contoso.exe. There's nothing built into the system that would allow a client (or the OS, really) to query, whether a Teams (or Contoso) call is currently active.
If you are interested in Microsoft Teams specifically, it offers an API for clients to interact with it. I don't know whether this includes services to query for the current state.
If, on the other hand, you are interested in finding out, whether any given camera or microphone is currently in exclusive use, you can ask the system to open the device for exclusive access, and draw conclusions from the results.


text:
Q: How to pass argument to TestNG listener I have one TestNG file demo.java and one listener for it DemoListener.java
Demo.java
import org.testng.*;
@Listeners(DemoListener.class)
public class Demo{
public static String testName = "DemoName"

@Test(priority = 1)
public void demoTest() {
    Assert.assertEquals(some_value,value, "message");
  }
}

DemoListener.java
import org.testng.ITestListener;
Public class DemoListener implements ITestListener {

@Override
public void onTestSuccess(ITestResult arg0) {
    System.out.println("On test Success:- ");
    // Here I want to access **variable(testName)** declared in Demo class.
    // Or is there anyway that I can pass that variable.
  }
}

Now, I want to access variable testName declared in Demo class in DemoListener class after every test execution. I would have declared it in DemoListener but I have so many class like Demo and each file has different testName.
Appreciate your help!

A: I'm not entirely sure why you're wanting to do this, perhaps a little background would be helpful.
But, to answer the question, you have a few options:

*

*Define the variable in TestNG's XML. If you place it inside the properties construct, it will then be available to System.getProperty().

*Since testName is a public static, you can simply reference Demo.testName inside DemoListener.

I'm slightly confused why you can't simply use ITestResult.getName() though...
EDIT: For clarity, in your Demo.java, in each method, you can do the following:
ITestResult tr = Reporter.getCurrentTestResult();
tr.setName( "whatever name you want to give your test step" );

Then you can do the rest of your test (asserts etc). Later, in DemoListener.java, you're already passed an instance of ITestResult, and you can simply ask it for it's name (the one you set in the above code), by invoking arg0.getName()

A: Got answer of my question, used java reflection. Worked like charm.
I wrote following method in DemoListener class. Thanks to my friend Kailas!
public static void getTestSuiteName(ITestResult arg0){
 Class<?> clazz = arg0.getTestClass().getRealClass(); //Demo class
    Field field = null;
    try {
        field = clazz.getField("testSuiteName");
    } catch (NoSuchFieldException | SecurityException e1) {
        e1.printStackTrace();
    }
    field.setAccessible(true);
    if(String.class.isAssignableFrom(field.getType())) {
        try {
            testSuiteName =  (String) field.get(null); //I can get value of testSuiteName set in Demo class
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}


text:
Q: .htaccess HTTP Expires header doesn't work for some images I have a wordpress website on Apache web server which I have set Image Expires Tags in .htaccess file, this is the code I have put in .htaccess file,
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css A31536000
ExpiresByType text/x-component A31536000
ExpiresByType application/x-javascript A31536000
ExpiresByType application/javascript A31536000
ExpiresByType text/javascript A31536000
ExpiresByType text/x-js A31536000
ExpiresByType text/html A3600
ExpiresByType text/richtext A3600
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType text/plain A3600
ExpiresByType text/xsd A3600
ExpiresByType text/xsl A3600
ExpiresByType text/xml A3600
ExpiresByType video/asf A31536000
ExpiresByType video/avi A31536000
ExpiresByType image/bmp A31536000
ExpiresByType application/java A31536000
ExpiresByType video/divx A31536000
ExpiresByType application/msword A31536000
ExpiresByType application/vnd.ms-fontobject A31536000
ExpiresByType application/x-msdownload A31536000
ExpiresByType image/gif "access plus 1 month"
ExpiresByType application/x-gzip A31536000
ExpiresByType image/x-icon A31536000
ExpiresByType image/jpeg A31536000
ExpiresByType application/json A31536000
ExpiresByType application/vnd.ms-access A31536000
ExpiresByType audio/midi A31536000
ExpiresByType video/quicktime A31536000
ExpiresByType audio/mpeg A31536000
ExpiresByType video/mp4 A31536000
ExpiresByType video/mpeg A31536000
ExpiresByType application/vnd.ms-project A31536000
ExpiresByType application/x-font-otf A31536000
ExpiresByType application/vnd.ms-opentype A31536000
ExpiresByType application/vnd.oasis.opendocument.database A31536000
ExpiresByType application/vnd.oasis.opendocument.chart A31536000
ExpiresByType application/vnd.oasis.opendocument.formula A31536000
ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
ExpiresByType application/vnd.oasis.opendocument.text A31536000
ExpiresByType audio/ogg A31536000
ExpiresByType application/pdf A31536000
ExpiresByType image/png "access plus 1 month"
ExpiresByType application/vnd.ms-powerpoint A31536000
ExpiresByType audio/x-realaudio A31536000
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/x-shockwave-flash A31536000
ExpiresByType application/x-tar A31536000
ExpiresByType image/tiff A31536000
ExpiresByType application/x-font-ttf A31536000
ExpiresByType application/vnd.ms-opentype A31536000
ExpiresByType audio/wav A31536000
ExpiresByType audio/wma A31536000
ExpiresByType application/vnd.ms-write A31536000
ExpiresByType application/font-woff A31536000
ExpiresByType application/vnd.ms-excel A31536000
ExpiresByType application/zip A31536000</IfModule>

However when I check the site on seositecheckup.com for Expire header test, it's still showing some images without "Expires" header.

Is there anything wrong in the code above ? Any help would be appreciated. Thanks!!

A: Those images appear to be data uris. That means they were embedded in the either the html, css or javascript and so were never served directly by Apache. Apache was therefore unable to set expire tags on them. As long as the files those uris came from have the correct expire tags, those assets will expire correctly in a user's browser.
However, If you're interested in scoring highly on their tests then you're out of luck as they advocate using both data uris and expires tags. As far as I can tell these are mutually exclusive.
As long as all of your html, css & js files expire correctly you are expiring these assets correctly.


text:
Q: Is it possible to override / remove background: none!important with jQuery? I have an element which should have a background image, but it's been given the following style in a stylesheet that I'm not able to access/modify:
#an-element li {
  background: none !important;
}

Is it possible to undo that style with jQuery? I've tried to add background: inhert!important with jQuery in two ways: by adding an inline style, and by removing an applied style. Neither work.
Here is a Fiddle illustrating the problem: http://jsfiddle.net/9bJzk/1/
UPDATE: I had the wrong fiddle link, please look again.
UPDATE 2: I cannot edit the stylesheet. I've changed the title to be more clear now. I have to do this with jQuery as I can't control the loading order of the CSS files, but can run jQuery onload.
UPDATE 3: I can't explicitly set the 'kitten' pic (see the fiddle) with a more accurate CSS selector like selector like #an-element .image-list li as some are suggesting as those images are being written out on the fly. The jsFiddle was just an example. To make it clearer still: Can the effects of the background: none be undone with PURE jQuery and NOT editing of any stylesheets. Thanks for sticking with this!

A: Several problems arise in this question.
Problem #1 - css Specificity (how to override important rule).
According to specification - to override this selector your selector should be 'stronger' which mean it should be!important and have at least 1 id, 1 class and something else - according to you creating this selector is impossible(as you can't alter page content). So the only possible option is to put something into element style which (could be done with js). Note: style rule should also have !important to override.
Problem #2 - background is not a single property - it is a set of properties (see specification)
So you really need to know what are exact names of properties you want to change (in your case it would be background-image)
Problem #3 - How to remove rule already applied (to get previous value)?
Unfortunately css have no mechanism to dismiss rule which qualify for an element - only to override with "stronger" rule. So you won't be able to solve this task with just setting value to something like 'inherit' or 'default' cause value you want to see is neither inherit from parent nor default. To solve this problem you have couple of options.
1) You may already know what is the value you want to apply. For example you can find out this value based on selector used. So in this case you may know that for selector ".image-list li" you need  background-image: url("http://placekitten.com/150/50"). If so - just you this script:
jQuery(".image-list li").attr('style', 'background-image: url("http://placekitten.com/150/50") !important; ');

2) If you don't know the value then you can try to alter page content in such a way, that rule you want to dismiss is no longer qualify for element, whereas rule you want to be shown - still qualify. In this case you may temporary remove id from container element. Here is the code:
jQuery("#an-element").attr('id', '');
var backgroundImage = jQuery(".image-list li").css('background-image');
jQuery("#an-element").attr('id', 'an-element');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');

Here is link to fiddle http://jsfiddle.net/o3jn9mzo/
3) As third solution - you may generate element which will qualify for desired selection to find out property value - something like this:
var backgroundImage = jQuery("

").find('li').css('background-image');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');

P.S.: Sorry for really late response.

A: Why does not it work?
Because the background CSS with background:none!important has one #ID
A CSS selector file that contains an #id will always have a higher value than one .class
If you want to work, you need add #id on your .image-list li like this:
#an-element .image-list li {
    display: inline-block;
    background-image: url("http://placekitten.com/150/50")!important;
    padding: 1em;
    border: 1px solid blue;
}

result here

A: div { background: none !important }
div { background: red; }

Is transparent.
div { background: none !important }
div { background: red !important; }

Is red.
An !important can override another !important.
If you can't edit the CSS file you can still add another one, or a style tag in the head tag.

A: Yes it is possible depending on what css you have, you simply just declare the same thing with a different background like this
ul li {
    background: none !important;
}

ul li{
    background: blue !important;
}

But you have to make sure the declaration comes after the first one seeing as it is cascading.
Demo
You can also create a style tag in jQuery like this
$('head').append('');

Demo
You cannot see any changes because it's not inheriting any background but it is overwriting the background: none;

A: Any !important can be overridden by another !important, the normal CSS precedence rules still apply.
Example:
#an-element{
    background: #F00 !important;
}
#an-element{
    background: #0F0 !important; //Makes #an-element green
}

Then you could add a style attribute (using JavaScript/jQuery) to override the CSS
$(function () {
    $("#an-element").attr('style', 'background: #00F !important;');
    //Makes #an-element blue
});

See the result here

A: With a


text:
Q: Using Html in a SQL table and retrieving it in a foreach statement I am having some issues with Html stored in a Sql table.
I am using font Awesome and storing the "i" tags in a table record so that each record may or may not have different set of tags depending on the case.
The problem is Html.DisplayFor does not "Display" it correctly.
In other words it looks like this:

I cannot use Html.Raw because it does not work with Lambda expressions.
Is there a way around this?
The other option I have is to set a int for the records and do if statements to change them and only store the actual font Awesome class in the table.
That to me seems like to much and there has to be a way to do it without doing that.
So something like this:
@if (item.Type = 1)
{

              item.NotificationType)">

 }

Seems silly to me to have to do it that way and for each different item.
Any input would be great. Thanks


text:
Q: How do I rectify the error in mysql-connector where I try to add multiple records at the same time into a MySQL Database? I am trying to add multiple records into a database using mysql-connector-python. I was able to add one record initially but for multiple records, this error has been persistent.
class DataBase:
def __init__(self):
    try:
        self.connection = mysql.connector.connect(host='xx.xxx.xx.xx',
                                                 database='XXX',
                                                 user='XXXX',
                                                 password='xxxx')

    except Error as error:
        print("Failed to connect: {}".format(error))

def store_into_table(self, df):

        mySql_insert_query = """INSERT INTO data ('data_id', 'a', 'b', 'c') VALUES ('%S','%S', '%S', '%S') """
        records_to_insert = df
        cursor = self.connection.cursor()
        cursor.executemany(mySql_insert_query, records_to_insert)
        self.connection.commit()
        print(cursor.rowcount, " Records inserted successfully into data table")

The variable that I am passing to an instance of DataBase is:
data = [('101', 'name_1', '3', 'sample'), ('102', 'name_2', '5', 'sample_1')]

Exception being thrown:
    Traceback (most recent call last):

  File "/Users/dev/anaconda3/envs/sql/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 317, in _batch_insert
    "Not all parameters were used in the SQL statement")

ProgrammingError: Not all parameters were used in the SQL statement

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "<ipython-input-123-44fdf194cd10>", line 1, in <module>
    db.store_into_table(data)

  File "/Users/dev/Detector/database.py", line 30, in store_into_table
    cursor.executemany(mySql_insert_query, records_to_insert)

  File "/Users/dev/anaconda3/envs/sql/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 350, in executemany
    stmt = self._batch_insert(operation, seq_params)

  File "/Users/dev/anaconda3/envs/sql/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 329, in _batch_insert
    "Failed executing the operation; %s" % err)

InterfaceError: Failed executing the operation; Not all parameters were used in the SQL statement

Any clues as to why this isn't working?

A: Try this:
mySql_insert_query = """INSERT INTO data (data_id, a, b, c) VALUES (%s, %s, %s, %s) """


text:
Q: Write to USB PORT C# using LibUsbDotNet C# USB Library I want to write some data to a USB port and receive an answer from it.
I actually used the same
string cmdLine = "@00WD3000C82B*\r";

and sent it to the same machine with the SerialPort object and by using rs235 port.
its do well.. and I got the right answer
using these methods:
omronAX.WriteAction("3000", 200.ToString("0000"));

public void WriteAction(string DM_address, string Data)
{
    write_action(DM_address, Data);
}

private void write_action(string DM_address, string Data)
{
    GotData = "";
    Puredata = "";
    EndCode = "";
    try
    {
        int ErCd = Write_2_port("WD", DM_address, Data);
        if (ErCd != 0) { return; }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private int Write_2_port(string cod_cmd, string Addr, string Data2write)
{
    DReady = false;
    out_data = "";
    end_c = "";

    char cr = Convert.ToChar(13);
    string cmd = "", Dat1 = "", Dat2 = "";
    Mess = "";

    Dat2 = Data2write;
    if (Addr.Trim().Length > 0)
    {
        try
        {
            Dat1 = String.Format("{0:0000}", Convert.ToInt16(Addr));
        }
        catch (FormatException ex)
        {
            Mess = ex.Message;
            return 1;
        }
        catch (OverflowException ex1)
        {
            Mess = ex1.Message;
            return 3;
        }
    }

    int.TryParse(Dat2, out int hex);
    string hexValue = hex.ToString("X");

    cmd = "@" + BakN + cod_cmd + Dat1 + hexValue ;
    string send2port = cmd + Checksm(cmd) + "*" + cr;
    SentCommand = send2port;
    try
    {
        //     if (Sport.IsOpen == false) { Sport.Open(); }
        locking = true;
        Sport.WriteTimeout = 5000;
        Sport.WriteLine(send2port);

        int i = 0;
        while (locking)
        {
            if (i++ == 500)
            {
                throw new TimeoutException("יתכן שיש בעיות תקשורת עם המערכת.");
            }
            Thread.Sleep(10);
        }
        //   T:System.ArgumentNullException:
        //     The str parameter is null.
        //
        //   T:System.InvalidOperationException:
        //     The specified port is not open.
        //
        //   T:System.TimeoutException:
        //     The System.IO.Ports.SerialPort.WriteLine(System.String) method could not write
        //     to the stream.
    }
    catch (TimeoutException ex)
    {
        Mess = ex.Message;
        throw ex;
    }
    catch (Exception ex)
    {
        Mess = ex.Message;
        return 2;
    }
    return 0;
}

for the next code, I try using USB port and write to it the same line...
But I got nothing when I read the answer back and I got (bytesRead = 0)
in my bytesWritten, I got 15...
using System;
using System.Text;
using System.Text.RegularExpressions;
using LibUsbDotNet;
using LibUsbDotNet.Main;

namespace Examples
{
    internal class ReadWrite
    {
        public static UsbDevice MyUsbDevice;

        #region SET YOUR USB Vendor and Product ID!

        public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0590,0x005B);

        #endregion

        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the USB device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                // If this is a "whole" usb device (libusb-win32, linux libusb)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // Remove the exepath/startup filename text from the begining of the CommandLine.
                //string cmdLine = Regex.Replace(Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline);
                string cmdLine = "@00WD3000A11*\r";
                if (!String.IsNullOrEmpty(cmdLine))
                {
                    int bytesWritten;
                    ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 20000000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    byte[] readBuffer = new byte[1024];
                    while (ec == ErrorCode.None)
                    {
                        int bytesRead;

                        // If the device hasn't sent data in the last 100 milliseconds,
                        // a timeout error (ec = IoTimedOut) will occur.
                        ec = reader.Read(readBuffer, 100, out bytesRead);

                        if (bytesRead == 0) throw new Exception("No more bytes!");

                        // Write that output to the console.
                        Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                    }

                    Console.WriteLine("\r\nDone!\r\n");
                }
                else
                    throw new Exception("Nothing to do.");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();

                }

                // Wait for user input.
                Console.ReadKey();
            }
        }
    }
}

I have no idea and I am doing wrong, thanks.

A: I recommend using Usb.Net (https://github.com/MelbourneDeveloper/Device.Net) instead of LibUsb. The problem with LibUsb is that is just wraps WinUSB calls. So, you are deploying an extra C dll (LibUsb) that just points to an existing Windows C DLL. LibUsb is good if you want to keep the code cross platform with Linux, but otherwise, there's not much point.
Here is sample WinUsb code (https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Usb.Net/Windows/WindowsUsbDevice.cs)
    public override Task InitializeAsync()
        {
            Dispose();

            int errorCode;

            if (string.IsNullOrEmpty(DeviceId))
            {
                throw new WindowsException($"{nameof(DeviceDefinition)} must be specified before {nameof(InitializeAsync)} can be called.");
            }

            _DeviceHandle = APICalls.CreateFile(DeviceId, (APICalls.GenericWrite | APICalls.GenericRead), APICalls.FileShareRead | APICalls.FileShareWrite, IntPtr.Zero, APICalls.OpenExisting, APICalls.FileAttributeNormal | APICalls.FileFlagOverlapped, IntPtr.Zero);

            if (_DeviceHandle.IsInvalid)
            {
                //TODO: is error code useful here?
                errorCode = Marshal.GetLastWin32Error();
                if (errorCode > 0) throw new Exception($"Device handle no good. Error code: {errorCode}");
            }

            var isSuccess = WinUsbApiCalls.WinUsb_Initialize(_DeviceHandle, out var defaultInterfaceHandle);
            HandleError(isSuccess, "Couldn't initialize device");

            var bufferLength = (uint)Marshal.SizeOf(typeof(USB_DEVICE_DESCRIPTOR));
            isSuccess = WinUsbApiCalls.WinUsb_GetDescriptor(defaultInterfaceHandle, WinUsbApiCalls.DEFAULT_DESCRIPTOR_TYPE, 0, 0, out _UsbDeviceDescriptor, bufferLength, out var lengthTransferred);
            HandleError(isSuccess, "Couldn't get device descriptor");

            byte i = 0;

            //Get the first (default) interface
            var defaultInterface = GetInterface(defaultInterfaceHandle);

            _UsbInterfaces.Add(defaultInterface);

            while (true)
            {
                isSuccess = WinUsbApiCalls.WinUsb_GetAssociatedInterface(defaultInterfaceHandle, i, out var interfacePointer);
                if (!isSuccess)
                {
                    errorCode = Marshal.GetLastWin32Error();
                    if (errorCode == APICalls.ERROR_NO_MORE_ITEMS) break;

                    throw new Exception($"Could not enumerate interfaces for device {DeviceId}. Error code: { errorCode}");
                }

                var associatedInterface = GetInterface(interfacePointer);

                _UsbInterfaces.Add(associatedInterface);

                i++;
            }

            IsInitialized = true;

            RaiseConnected();

            return Task.CompletedTask;
   }

However, I did submit this sample to LibUsbDotNet and it's now the accepted Read/Write sample there (https://github.com/LibUsbDotNet/LibUsbDotNet/blob/master/src/Examples/Read.Write/ReadWrite.cs):
       public static void Main(string[] args)
        {
            using (var context = new UsbContext())
            {
                context.SetDebugLevel(LogLevel.Info);

                //Get a list of all connected devices
                var usbDeviceCollection = context.List();

                //Narrow down the device by vendor and pid
                var selectedDevice = usbDeviceCollection.FirstOrDefault(d => d.ProductId == ProductId && d.VendorId == VendorId);

                //Open the device
                selectedDevice.Open();

                //Get the first config number of the interface
                selectedDevice.ClaimInterface(selectedDevice.Configs[0].Interfaces[0].Number);

                //Open up the endpoints
                var writeEndpoint = selectedDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                var readEnpoint = selectedDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                //Create a buffer with some data in it
                var buffer = new byte[64];
                buffer[0] = 0x3f;
                buffer[1] = 0x23;
                buffer[2] = 0x23;

                //Write three bytes
                writeEndpoint.Write(buffer, 3000, out var bytesWritten);

                var readBuffer = new byte[64];

                //Read some data
                readEnpoint.Read(readBuffer, 3000, out var readBytes);
            }
        }

A: I had an issue getting my device to connect with another library because I was using upper case for alphabetic characters in the VID/PID. Have you tried using lower case ("0x005b" instead of "0x005B")?


text:
Q: Read-only file system after power outage I don't know if there is something wrong with my computer, but every time after a power outage, my file system gets corrupted. I have tried using fsck to fix this, but as soon as I start opening programs, the File System goes into read only mode again. I have found no way to fix this, and my only option is to erase my OS partition and reinstall Ubuntu all over again. Has anyone had this problem and been able to fix it? I think I can avoid this problem if I find a way for my system to automatically shut down when it's low on battery. Thoughts?
Things I have tried:

*

*fsck partion: works, but only temporarily

*mount -o remount,rw /: doesn't work. The system is write-protected

*reinstall Ubuntu: WORKS! but I don't want to have to do it every time I have a power outage.

A: Test
I have a Toshiba laptop from 2013, that I use for testing purposes.
I made a fresh installation of Ubuntu 18.04.1 LTS, made it up to date with
sudo apt update
sudo apt full-upgrade

and rebooted to have the current kernel version and everything up to date. Then I unplugged the power and let it run (most of the time playing music videos) until it started to warn about low battery. I watched it closely and at about 5% remaining power it shut down automatically and gracefully.
I plugged in the power connection again, let it charge for slightly more than one minute (so that there should be enough power for the booting process). You may need 5 minutes or more if the battery is getting tired.
Then I booted and it was successful, except that I had to turn off airplane mode for wifi. I tested a few things and they seem to work correctly.
I shutdown and booted from a live drive and checked the file system,
sudo e2fsck -f /dev/sda1

Everything looks good, there was no complaint.
Conclusion
Ubuntu 18.04.1 LTS fully up to date (today, 2019-01-26) can shutdown gracefully, when the battery is getting low in my Toshiba.
I don't think dual booting should make any difference, because the same system will be installed, although the partition number of the root partition will be different.
If Ubuntu shuts down gracefully, when you initiate it manually, the automatic shutdown should work too, unless you have modified some setting, or if the battery supervisor does not work with the computer's hardware.
I suggest that you check that the battery supervisor works with your computer's hardware.


text:
Q: How can I convert a file (pdf/doc) served at a url into json / string / base64 format without downloading on local? Let's say a pdf document is served at a url, ex - https://www.polyu.edu.hk/iaee/files/pdf-sample.pdf
I need to run a javascript that takes the url and makes a post request to a server with the pdf file data that can be converted back to file. Typical solutions for accessing files on a server location are around downloading on local first and then having the user upload it. How can we bypass the user interference ? Appreciate all inputs and workarounds like using browser cache / local storage etc.
Thanks

A: This is not possible.
JavaScript executed in a browser runs on the client machine. Thus any modification on a remote resource must be downloaded, modified and uploaded to the server.
As you already stated: using a browser cache or local storage wont help you.
You have to do this modifications on server-side e.g. with a servlet or php. You will need access to the server.


text:
Q: What is the IIS application pool size used for? Why is it important? I have had a request come through to increase the pool size in IIS which I assume to be the application pool size.
I have attempted to search for more information regarding what the pool size is, what it does, its importance as well as caveats in increasing its size.
Am unsure where to find it in IIS 7 and 7.5 as well as what the default size is.
Does changing the pool size also affect web gardens?

A: As noted in the comments, the question is ambiguous.
There is a Private Memory Limit (KB), which defines how large an application pool can grow in system RAM before it gets automatically recycled. For example, when you open Task Manager (taskmgr.exe), you'll see an instance of w3wp.exe running for each application pool. Add the Working Set column. I believe that corresponds to the Private Memory Limit setting.
There is a CPU Limit which dictates how much CPU an application pool is permitted to consume over a period of time. Its default is zero, meaning no limit.
There is a Queue Length setting which dictates how many simultaneous requests can be serviced before the server starts returning 503s. The default is 1000.
There is an Idle timeout, which defaults to 20 minutes. After 20 minutes of inactivity, the application pool stops. I always turn that off, as it takes time for the first request to process from an inactive application pool.
There is an ability to schedule a recycle at regular intervals or at one or more specific times. Perhaps an untimely recycle is interfering with a long-running operation, and the customer is having requests be canceled as a result.
Those are all of the usual suspects I can think of.


text:
Q: Angular getter on page I wanted something like this C# code:
public class MyClass
{
    public int SomeInt {get;set;}
    public string StatusDescription
    {
        if (SomeInt == 0}
        {
             return "Zero";
        }
        else
        {
            return "Not Zero";
        }
    }
}

So that on my page, I can do something like this:

<mat-card class="example-card mt-2">
    <mat-card-header>
    <mat-card-content>
        {{someClass.statusDescription}}
    </mat-card-content>
</mat-card>

My attempt at resolving this was:
export class myClass{
    someInt: number;
    get statusDescription(): string
    {
        return "Status";
    }
}

My typescript
import { Component, OnInit } from '@angular/core';
import { myClass } from '../models/myClass';

@Component({
  selector: 'app-landing',
  templateUrl: './myClass.component.html',
  styleUrls: ['./myClass.component.css']
})
export class MyClassComponent implements OnInit {

  allMyClasses: Array<myClass> = new Array<myClass>();
  constructor(private myClassService: MyClassService  )
  {
  }

  ngOnInit() {
  }

  fetchMyClasses()
  {
    this.myClassService.getMyClasses().then(
    (results) => this.allMyClasses= results
    );
  }

}

MyClassService. I'm sure this piece works, because I can see the data being pulled from here, and other properties being displayed on the page/template.
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { myClass } from '../models/myClass';

@Injectable({
  providedIn: 'root'
})
export class MyClassService {

  baseUrl: string = "https://localhost:44313/api/myClass/";
  constructor(private httpClient: HttpClient) { }

  getMyClasses()
  {
    const url = `${this.baseUrl}getMyClasses`;
    const result = this.httpClient.get<Array<myClass>>(url, {}).toPromise();
    return result;
  }

}

However, when my page renders, it does not display "Status", and no errors or warnings in the console. What am I doing wrong?

A: the problem is how you create the elements of allMyClasses. If you write, e.g.
allMyClasses:myClass[]=[new myClass(),new myClass()];

Works perfectly. I supouse you has a problem when create the list
NOTE you can use some like
   cont class=Object.assign(new myClass(),{someInt:3})

   //or, e.g.
   this.allMyClasses.push(Object.assign(new myClass(),{someInt:3}))

To create an object myClass with both "properties":, someInt and statusDescription
Update so, if you has a list
this.myClassService.getMyClasses().then(
    (results) => this.allMyClasses= results.map(x=>Object.assign(new myClass(),x))
    );

NOTE: Why is the reason to convert to promise? For me has no sense
See stackblitz

A: If you are useing VSCode i recomment using the Angular language service extension to get autocompletin in your html.
https://angular.io/guide/language-service
Always create new components with the angular cli. They will make sure that your components ts file and html file are tied in together.
e.g.
ng generate component testComponent

Your class is missing the @component annotation. The cli will auto generate this. If there is no annotation the class doesn't know that it should be a component. The files will be linked here.
Just try the cli generate to create this kind of file.
e.g.
@Component({
  selector: 'testComponent',
  templateUrl: './testComponent.component.html',
  styleUrls: ['./testComponent.component.scss']
})

https://angular.io/cli/generate
If you are calling a function in the html file do it like this:
{{this.statusDescription()}}

and in the ts like this file:
statusDescription(): string
{
    return "Status";
}

A: export class AppComponent  {
  name = 'Angular';
  private _statusDescription: string;

  get statusDescription(): string
    {
        return this._statusDescription = "Success";
    }

}

In template
{{statusDescription}}

https://stackblitz.com/edit/angular-4susrc
This is approach its not same like what asked but using this can solve issue.