text:
Q: NestJS Exception filter messes up error array if it comes from ValidationPipe So I use the ValidationPipe to validate my DTOs in NestJS, like this:
// auth.dto.ts
export class AuthDto {
  @IsEmail()
  @IsNotEmpty()
  email: string;
}

Without the Exception filter the error message works as intended. I leave the email field empty and I receive an array of error messages:
// Response - Message array, but no wrapper
{
  "statusCode": 400,
  "message": [
    "email should not be empty",
    "email must be an email"
  ],
  "error": "Bad Request"
}

Perfect. Now I want to implement a wrapper for the error messages, so I create a new filter and add it to to bootstrap:
// main.ts
async function bootstrap() {
  // ...
  app.useGlobalFilters(new GlobalExceptionFilter());
}
bootstrap();

// global-exception.filter.ts
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import { IncomingMessage } from 'http';

export const getStatusCode = <T>(exception: T): number => {
  return exception instanceof HttpException
    ? exception.getStatus()
    : HttpStatus.INTERNAL_SERVER_ERROR;
};

export const getErrorMessage = <T>(exception: T): string => {
  return exception instanceof HttpException
    ? exception.message
    : String(exception);
};

@Catch()
export class GlobalExceptionFilter<T> implements ExceptionFilter {
  catch(exception: T, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<IncomingMessage>();
    const statusCode = getStatusCode<T>(exception);
    const message = getErrorMessage<T>(exception);

    response.status(statusCode).json({
      error: {
        timestamp: new Date().toISOString(),
        path: request.url,
        statusCode,
        message,
      },
    });
  }
}

It works great for most of my errors:
// Response - Good format (wrapped), single message expected
{
  "error": {
    "timestamp": "2022-05-11T19:54:59.093Z",
    "path": "/auth/signup",
    "statusCode": 400,
    "message": "Email already in use"
  }
}

But when I get a ValidationError from the ValidationPipe it should give me an array or messages like before, but it gives this message instead:
// Response - Wrapper: check, single message instead of array
{
  "error": {
    "timestamp": "2022-05-11T19:59:17.282Z",
    "path": "/auth/signup",
    "statusCode": 400,
    "message": "Bad Request Exception" // it should be "message": ["not empty", "must be email"]
  }
}

The exception object in my exception filter has a response field which contains the message array:
// HttpException object inside the filter class
{
  response: {
    statusCode: 400,
    message: [ 'email should not be empty', 'email must be an email' ],
    error: 'Bad Request'
  },
  status: 400
}

But exception.response.message doesn't work, because the field is private and TypeScript throws an error:Property 'response' is private and only accessible within class 'HttpException'.
Does any of you know how could I reach the message array, so I could format my error response properly?
EDIT: Sorry for the long post!

A: As @tobias-s commented, there's a workaround, which solved the problem:

Try exception["response"]["message"]. This bypasses the private restriction

A: As you are using @Catch decorator, you could get a HttpException or not, so we need to evaluate it.
Let's create an interface to "parse" Nest.js built-in HttpException class response:
export interface HttpExceptionResponse {
    statusCode: number;
    message: any;
    error: string;
}

Now we can process it:
export const getErrorMessage = <T>(exception: T): any => {

  if(exception instanceof HttpException) {

    const errorResponse = exception.getResponse();
    const errorMessage = (errorResponse as HttpExceptionResponse).message || exception.message;

    return errorMessage;
  } else {
    return String(exception);
  }
};

exception.getResponse() can be a string or an object, that's because we handle it as message: any of course.


text:
Q: NGINX rewrite rules for multisite I have a WordPress 4.6 network running on an Ubuntu 16.04 server with NGINX.
I have one main site and then I migrated a single site installation to a subsite under that main site. I made all the DB changes, URL changes, copied over all the themes and plugins, and copied all the uploads to wp-content/uploads/sites/2 with 2 being the site ID.
When I go to view the site everything looks fine except the images do not display. when I click on the image, the path indicates that its looking for the image in the wp-content/uploads folder instead of the wp-content/uploads/sites/2 folder.  Would this be an issue with the rewrite rules? If so, how would I go about fixing it? Any help would be greatly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stock Turn : Inventory TurnOver I am trying to Calculate Stock Turn = (COGS for last 12 months from Current date)/Average Inventory Cost for last 12 months).So my 1st step is to Calculate COGS for last 12 months(Cost of Good Sold). I am using the following Query:

SUM( ClosingPeriod([Date].[Calendar].[Month], [Date].[Calendar].[All
  Periods]).Lag(12):ClosingPeriod([Date].[Calendar].[Month],
  [Date].[Calendar].[All Periods]), [Measures].[Cogs Amount])

But the Calculated Member is giving me Null results.
Please help.!!
Cheers
Rushir

A: You are using [ALL Periods]. You should not use that member because it is the root.
The Lag(12) of [All Periods] doesn't exist.
Try using an specific member, something like this:
SUM({ClosingPeriod([Date].[Calendar].[Month], [Date].[Calendar].[2011].[11]).Lag(12):ClosingPeriod([Date].[Calendar].[Month], [Date].[Calendar].[2011].[11])}, [Measures].[Cogs Amount])

Or something like this:
SUM({[Date].[Calendar].CurrentMember.Lag(12):[Date].[Calendar].CurrentMember}, [Measures].[Cogs Amount])


text:
Q: Connection to server timed out in PhoneGap window.location.assign() Using PhoneGap on android I get the following error:

Application Error: The connection to the server timed out. (serverUrl)

while navigating with window.location.assign(serverUrl).  Is there any way to catch this exception inside JavaScript code?

A: Add below line of code in your MainActivity.java file:
super.getIntent().putExtra("loadUrlTimeoutValue", 80000);


text:
Q: Haskell remove parenthesis for a tuple I'm a beginner in Haskell, and this is a question for an assignment.
I'm pretty much done the problem, but I can't figure out how to remove the parenthesis that is surrounding a tuple that I calculated.
get_balance_partition :: Int -> [([Int], [Int])] -> (Int, ([Int], [Int]))
get_balance_partition min (x:xs)
    | null xs && difference_partitions x == min = (min, x)
    | null xs = (min, ([], []))
    | difference_partitions x == min = (min, x)
    | otherwise = get_balance_partition min xs

This is a helper function for working code, and I use it like this :
get_balance_partition 2 (two_partitions [7, 4, 3, 6, 10])

output : (2,([7,4,3],[6,10]))

I want to get rid of the parenthesis surrounding the pair of partitions so that the result,
 (2,([7,4,3],[6,10]))

looks like
 (2,[7,4,3],[6,10])

How can I get rid of the parenthesis when the pair of partitions is stored in x?

A: There are no standard functions that work on triples, you have to write them yourself.
munge :: (a,(b,c)) -> (a,b,c)
munge (x,(y,z)) = (x,y,z)

munge (get_balance_partition 2 (two_partitions [7, 4, 3, 6, 10]))

Or anonymously as a lambda
(\(x,(y,z)) -> (x,y,z)) (get_balance_partition 2 (two_partitions [7, 4, 3, 6, 10]))

Another way is to modify your definition to match on the tuple in the list directly:
get_balance_partition :: Int -> [([Int], [Int])] -> (Int, ([Int], [Int]))
get_balance_partition min ((x,y):xs)
   ...

And use (x,y) instead of x everywhere, then you can return e.g. (min, x, y) in the first case, and similarly in other cases.


text:
Q: Graph API 2.3 Event location If I query an api request for the location of an event I get:
{
  "error": {
    "message": "(#12) location field is deprecated for versions v2.3 and higher",
    "type": "OAuthException",
    "code": 12
  }
}

I'm making a party calender based on facebook events. without the location the app is useless.. Is there any way around?

A: You should use place as specified here https://developers.facebook.com/docs/graph-api/reference/v2.3/event :
https://graph.facebook.com/v2.3/{event-id}/?fields=place


text:
Q: How to print documents to pdf I like to print PDFs of my documents. I've been using PDFCreator. Is this a good choice, are there any better solutions?

A: I use pdf995. Shareware, but the license isn't too expensive and it works really nicely. Also has the ability to split and merge pdfs, add watermarks and more.

A: I use doPDF and it is very successful. And free...
doPDF installs itself as a virtual PDF printer driver so after a successful installation will appear in your Printers and Faxes list. To convert to PDF, you just have to print the document to doPDF.

A: OpenOffice is another option.

A: CutePDF Writer is working well for us (way less flaky than the slightly old version of Acrobat we are running at work, anyway)
EDIT: There is also information in the CutePDF FAQ about using parameters to change the print quality/file size settings which we have found useful for larger documents.

A: Another option (the one I used to use until all the other programs listed here came out) is to install a printer driver for a Postscript printer, connected to the FILE: port.
When you print to that printer, you'll get a postscript (.ps) file.  You can then open that using Ghostscript and Ghostview and convert them to PDF from there.

A: I prefer PDFCreator  over the other tools. Much more flexibility than the others but probably is an overkill for simple purposes.

A: If "free" is not a requirement I would suggest Adobe Acrobat. It still is the most professional tool for creating PDFs.

A: I've used Bullzip pdf printer for a year or so and have been very happy with it.
It installs as just another printer, so is available to any application.
It's reliable, does watermarks, pdf merging, no ads, simple to use and good quality output.

A: Google Docs download as PDF option is the best option if you want to convert your documents to PDF on the fly without installing anything...

A: Using the built-in Export to PDF option in OpenOffice.org has one VERY major advantage over anything that simulates a printer: it creates clickable table of contents, cross-references, indexes and explicit internet links. Of course, most PDF viewers will recognise some URLs and email addresses. But when linking some text to some URL, most PDF printers do not make that into a clickable link. That's simply because the print processor does not "tell" the PDF printer about this.
As a side note: on a Mac, PDF is very much integrated. Still, when using OpenOffice.org on a Mac, one should also explicitly use Export to PDF -- using the Save to PDF option from a Mac's print dialog does not create clickable links. However, some other Mac programs do in fact somehow send such information to the Mac's print processor, through the print dialog. For example, when saving to PDF using the print dialog in Pages, Safari or OmniWeb (the latter being non-Apple software), all links are in fact clickable. (On a Mac, when one does NOT want clickable links when saving a web site as PDF, one should in fact use Firefox instead.)
By the way: getting a clickable table of contents is a very good reason to learn how to use styles and headers. One should never have to create a table of contents manually!

A: If it's Office 2007 applications that you're printing from, there's an add-in to provide a Save as PDF option:
Office 2007 Save as PDF Add-in

A: I used primo pdf since a while, and it works great

A: I use pdfFactory from Fineprint Software.

A: Quite frankly, I use google docs and download my file as PDF from there :P

A: *

*At work Neevia docuPrinter LT (not free)

*At home Bullzip (free) I like the autosave with configurable filenames.

A: We are using FreePDF (formely known as "FreePDF XP") and it's working like a charm.

A: Amyuni PDF Converter (Commercial) Usual Disclaimer applies


text:
Q: Deciding whether a number is rational (2 examples) 1) Prove that number irrational $\sqrt{7-\sqrt{2}}$
I created a polynomial $x=\sqrt{7-\sqrt{2}}$ so
$P(x)=x^4-14x^2+47$ and since $47$ is prime we check $P(x)$ for $ {1,-1,47,-47}$ and since all of them are $P(x)\neq0$ it means our number is irrational.
Is my prof OK ?
2) Decide if the number $\sqrt{\sqrt{5}+3}+\sqrt{\sqrt{5}-2}$ is rational or irrational. I don't know how to tackle this one. I'd be grateful for hints

A: You don't need all that! If $\sqrt{7-\sqrt 2} = \dfrac{p}{q}$ is rational, then $\sqrt 2 = 7 - \dfrac{p^2}{q^2}$is rational. Which it isn't.

A: For 2).
If $p=\sqrt{\sqrt 5+3}+\sqrt{\sqrt 5-2}$ is a rational number, then
$$\begin{align}p-\sqrt{\sqrt5+3}=\sqrt{\sqrt5-2}&\Rightarrow p^2-2p\sqrt{\sqrt5+3}+\sqrt5+3=\sqrt5-2\\&\Rightarrow 2p\sqrt{\sqrt5+3}=p^2+5\\&\Rightarrow 4p^2(\sqrt 5+3)=(p^2+5)^2\\&\Rightarrow \sqrt5=\frac{(p^2+5)^2}{4p^2}-3\end{align}$$
implies that $\sqrt 5$ is a rational number. This is a contradiction.


text:
Q: T-SQL: Dynamic Where clause in normal SQL statement I looking for a way to dynamicly add a filter to my statment without using dynamic SQL.
I want to select all computers from a table, but when I pass a computer id to the sp, I want to get only this computer.
Actually I try this on
DECLARE @ComputerFilter AS INT
DECLARE @ComputerID AS INT

SELECT Computername
FROM   Computer
WHERE  (ComputerID = @ComputerID) OR (@ComputerFilter IS NULL))

But this is 100 times slow then this statment and tooks as long as SELECT * FROM Computer
SELECT Computername
FROM   Computer
WHERE  ComputerID = @ComputerID

Is there a way to speed this statment up or is there any other way to solve this problem with one select und without dynamic sql?

A: The easiest way would be to use IF statement.
IF @ComputerID IS NULL BEGIN
  SELECT Computername
  FROM   Computer
END
ELSE BEGIN
  SELECT Computername
  FROM   Computer
  WHERE  ComputerID = @ComputerID
END

A: DECLARE @ComputerID AS INT
SET @ComputerID  = null -- fro all null or just id for one

SELECT Computername
FROM   Computer
WHERE  ComputerID = ISNULL( @ComputerID, ComputerID  )

When you dont need

A: SQL Server is often bad at optimising queries with an OR in the WHERE clause. Sometimes a UNION or UNION ALL is better. In your case, perform the @ComputerFilter IS NULL check first in in IF statement, and just do a SELECT without a WHERE if true...

A: Do you have indexing on the table?  That should help performance.

A: There is no "one size fits all" query approach for this, there are subtle performance implications in how you do this. If you would like to go beyond just making the query return the proper answer, no matter how slow it is, look at this article on Dynamic Search Conditions in T-SQLby Erland Sommarskog


text:
Q: Covering finite groups by kernels Let $G$ be a finite group. When does there exist a finite group $H$ such that every $h\in H$ is in the kernel of some epimorphism $H\to G$?
This is well-known to be true for $G$ abelian, for example $H=G\times G$ works. I would like very much to know such an $H$ for non-abelian $G$, e.g. for symmetric groups $G$.
Note that this is related to question "Normal Covering of a Finite Group"; there, it is discussed when $H$ is a union of proper normal subgroups (but not necessarily all with quotient $G$).

A: If $G$ is nonabelian simple, then $H$ cannot exist.
Lemma : Let $\cal X$ be a collection of normal subgroups of a group $H$ such that $\bigcap \cal X = 1$, and assume that $H/X$ is nonabelian simple for all $X \in \cal X$. Then $H$ is isomorphic to a direct product of nonabelian simple groups.
Proof: Let $M \triangleleft H$ be minimal such that $H/M$ is isomorphic to a direct product of nonabelian simple groups. To complete the proof, we show $M = 1$. Otherwise, there exists $X \in \cal X$ such that $M \cap X < M$, and we write $D = M \cap X$. Now
$M \not\subseteq X$, so $MX > X$, and since $H/X$ is simple, it follows that $MX = G$. Then $H/D \cong M/D \times X/D$, and this is a direct product of nonabelian simple groups since $M/D \cong H/X$ is nonabelian simple and $X/D \cong H/M$ is a direct product of nonabelian simples. This contradicts the minimality of $M$.QED
Theorem: A finite group $H$ cannot be covered by a collection $\cal X$ of normal subgroups such that $H/X$ is nonabelian simple for all $X \in \cal X$.
Proof: Assume $H$ actually can be so covered, and let $D = \bigcap \cal X$. Then $D \triangleleft H$ and $H/D$ is covered by the normal subgroups $X/D$, and each of these has a nonabelian simple quotient. We can thus replace $H$ by $H/D$, so we can assume $D = 1$. The lemma then applies, and $H$ is a direct product of a collection $\cal Y$ of nonabelian simple subgroups. Then every normal subgroup of $H$ is a product of some subset of $\cal Y$, and proper normal subgroups are products of proper subsets of $\cal Y$. Now choose one nonidentity element of each member of $\cal Y$ and let $h$ be the product of the chosen elements. Then $h$ lies in no proper normal subgroup of $H$, and this is a contradiction.


text:
Q: Non-Alpha Sort of ASP.NET DataGrid I need to perform a customized sort of a .NET DataGrid. The UserRole column returns a set of three string values from SQL via a stored procedure: No Access, View, and Update.
<asp:DataGrid ID="UserList" runat="server" AllowPaging="True" AutoGenerateColumns="False" AllowSorting="True" OnDataBinding="UserList_DataBinding">
    <Columns>
        <asp:BoundColumn DataField="FirstName" HeaderText="First Name"></asp:BoundColumn>
        <asp:BoundColumn DataField="LastName" HeaderText="Last Name" SortExpression="LastName ASC, LastName"></asp:BoundColumn>
        <asp:BoundColumn DataField="EmailAddress" HeaderText="Email Address"></asp:BoundColumn>
        <asp:BoundColumn DataField="UserRole" HeaderText="User Role" SortExpression="UserRole DESC, UserRole"></asp:BoundColumn>
    </Columns>
</asp:DataGrid>

I need to be able to sort to display the "Update" value in the UserRole column at the top of the table. As it current sorts in descending order via the SortExpression property, "View" comes before "Update".
Where the above code is legacy code I'm not in a position to be able to full rewrite the code but is there another way to achieve this kind of custom non-alpha sorting?

A: You should sort your data before binding it to the grid. Depending on how you access the underlying data you could use some sort of OrderBy clause and order DESC. If you simply want "Update" to be first, that will be a little harder.


text:
Q: Creating a Combination chart(line and bar) for same json data using c3js I want to create a combination chart (line and bar) for same json data so that the line touches the all the bars since datapoints are same.
Here is the code
var graphdata=[
{ 'indicator': 'X', 'total': 100 },
            { 'indicator': 'Y', 'total': 200 },
            { 'indicator': 'Z', 'total': 300 }
];
var g1=[
{ 'indicator': 'X', 'total': 150 },
            { 'indicator': 'Y', 'total': 220 },
            { 'indicator': 'Z', 'total': 330 }
];
setTimeout(function () {
    chart.load({
          data: {
        type: 'line',
        json: g1,
        keys: {
            x: 'indicator',
            value: ['total']
        },

    },
    axis: {
            x: {
                type: 'category'
            }
    },
    });
}, 1000);
var chart = c3.generate({
    data: {
        type: 'bar',
        json: graphdata,
        keys: {
            x: 'indicator',
            value: ['total']
        },

    },
    axis: {
            x: {
                type: 'category'
            }
    },
    bar: {
        width: {
            ratio: 0.5
        }
    }
});

The output of this is only bar chart,the line chart is not loading.

A: try this code
var data = [
{ 'date': '2015-01-01', 'Dept': null, 'SMV': 3},
{ 'date': '2015-01-02', 'Dept': 1, 'SMV': 4}
];

Example You separated all the date, the Dept and the SMV data into separate arrays. The way to go here is the following: The data should contain one array of several arrays. The first argument is defined as the key of the dataset. An example dataset looks then like this:
var data = [
['date', '2015-01-01', 2015-01-02'],
['Dept', null, 1],
['SMV', 3, 4]
];

A: Try the simple code below, you can use a simple JSON file as shown below.
var graphdata={data1:[100,200,300],data2:[150,220,330]};
var chart = c3.generate({
    data: {
        types: {data1:'spline',
            data2:'bar'
        },
        json: graphdata,
    },
    bar: {
        width: {
            ratio: 0.5
        }
    }
});

For more details you can try http://c3js.org/samples/chart_combination.html .


text:
Q: App crashes when run more than once on GMSMAPVIEW I have an app that finds places near the user's location, however, the app crashes the second time it runs with the exception:
fatal error: unexpectedly found nil while unwrapping an Optional value.
On line:
 self.googleMapView.animate(toLocation: coordinates)
I checked and the googleMapView is nil but I don't understand how it is nil or how it ran the first time. It only starts crashing on subsequent tries if I delete and reinstall the app it works fine on the first try but after that it keeps crashing even if I restart the app. Full code below
import UIKit
import GoogleMaps
import GooglePlacePicker
import MapKit

 class MapViewController: UIViewController, CLLocationManagerDelegate {
var currentLongitude: CLLocationDegrees = 0
var currentLatitude: CLLocationDegrees = 0
var locationManager: CLLocationManager!
var placePicker: GMSPlacePickerViewController!
var googleMapView: GMSMapView!

@IBOutlet weak var mapViewContainer: MKMapView!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.googleMapView = GMSMapView(frame: self.mapViewContainer.frame)
    self.googleMapView.animate(toZoom: 18.0)
    self.view.addSubview(googleMapView)
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.locationManager = CLLocationManager()
    self.locationManager.delegate = self
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location:CLLocation = locations.last {
        self.currentLatitude = location.coordinate.latitude
        self.currentLongitude = location.coordinate.longitude
    }
    else {
        print("Location Error")
    }

    let coordinates = CLLocationCoordinate2DMake(self.currentLatitude, self.currentLongitude)
    let marker = GMSMarker(position: coordinates)
    marker.title = "I am here"
    marker.map = self.googleMapView
    self.googleMapView.animate(toLocation: coordinates)
}

private func locationManager(manager: CLLocationManager,
                     didFailWithError error: Error){
    print("An error occurred while tracking location changes : \(error.localizedDescription)")
}

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

}

A: Crash is pretty self-explanatory:
You are setting your location's delegate in the viewDidLoad but creating the map in the viewDidAppear.
If the location was known by iOS, you will receive the message before viewDidAppear call so in the line : self.googleMapView.animate(toLocation: coordinates), your map is still nil
You can either define your map as optional : var googleMapView: GMSMapView?, or you can wait for your map to be defined to create your location Manager.


text:
Q: Recommended rare items to upgrade in Kanai's Cube I am looking for The Furnace, the Wand of Woh the Orb of Infinite Depth and In-geom.
I heard the best way to get these items is to upgrade rare items in Kanai's cube.
But which rare items should I buy at the blacksmith that have the highest probability to turn into the items I am looking for?
Is there a list with more legendary items and their recommended rare counterpart?

A: When you use "Hope of Cain" recipe to upgrade a rare item to a legendary, the game creates a random item of type and level that the rare item was. Hence, to get The Furnace, you need to be upgrading a Rare Two-handed Mace (you can either find one, or craft a Sovereign Persuader at the Blacksmith).
When the game chooses which legendary to drop, it uses weights that determine how rare or common each legendary is. For example, here are all the Legendary two-handed maces and their weights:

*

*Arthef's Spark of Life - 100

*Crushbane - 100

*Schaefer's Hammer - 100

*Skywarden - 100 - does not drop for Wizard

*Sledge of Athskeleng - 100

*The Furnace - 25

*Wrath of the Bone King - 50
Hence, every time you roll for a legendary 2H Mace as a Wizard, you have 25/475 = 5.26% chance to get The Furnace, 50/475 = 10.53% chance to get a Wrath of the Bone King, and 100/475 = 21.05% chance to get each of four other maces.
You can check here for a table of all weights and drop chances for 2.4.2. In further versions, searching for "diablo 3 legendary drop rates " should get you there.


text:
Q: Use string to access variable in javascript If I have:
name.sub = function() {
    var sub = {};
    var placeholder = "test"
    var test = function() {
        return 42;
    };

    // Desired code would be here

    return sub;
};

I want to use a placeholder to access the variable so that I get 42.
Something like
window["name"]["sub"][placeholder] is seemingly looking for name.sub.test.
The only answers I found were if it was a global variable.
Using eval would work, but I've heard it should be avoided where possible.
placeholder = "test";
console.log(eval(placeholder + '()'))
// Would return 42

My actual end goal is to have an associative array where:
console.log(array[placeholder]);
// Would return 42

Any help would be appreciated.

This is what I ended up using for anyone interested:
name.sub= function() {
    var sub = {};
    var placeholder = "test"
    var test = function() {
        return 42;

    var newObj = {};
    newObj["test"] = function() {test()}

    console.log(newObj[placeholder]())
    // Should return 42
    };

A: You can't access variables inside a function from outside said function.
Instead, you could do this:
name.sub = function(placeholder) {
  var functions = {
    "test": function() {
      return 42;
    },
  };
  return functions[placeholder]();
};

name.sub("test"); // 42

I'm not sure if that's what you're looking for but hopefully it is. Explain more?

A: You can't access local variables inside a function the same way you can access properties of window in global scope.
kangax wrote an interesting article about Understanding delete [in JavaScript], which includes an explanation of what Activation objects are - which I think is what you're looking for.
I suggest you read the entire article, but long story short:
Inside functions, declared variables (and functions) are added as properties to the activation object of the current scope, as they get added to window in the global scope.
But unlike window:

Note that Activation object is an internal mechanism and is never really accessible by program code.

Conclusion: What you're asking is not (currently) possible.
Your options are limited to:

*

*Using an intermediate object:
name.sub = function() {
    var sub = {};
    var placeholder = "test";
    var array = {};
    array.test = function() {
        return 42;
    };
    console.log(array[placeholder]());
    return sub;
};

*Using eval, exactly like you suggested:
name.sub = function() {
    var sub = {};
    var placeholder = "test";
    var test = function() {
        return 42;
    };
    console.log(eval(placeholder + '()'));
    return sub;
};

*Using window, by removing var from test's declaration:
name.sub = function() {
    var sub = {};
    var placeholder = "test";
    test = function() {
        return 42;
    };
    console.log(window[placeholder]());
    return sub;
};

I suggest the first option for the sake of performance over eval, for compatibility over window (might collide with other code), and simply because of personal taste and what I consider good practice.

A: By what i understand of your question,
its seem like you are looking for a key/value pair to a JavaScript object literal,
window.name is reserved btw: https://developer.mozilla.org/en-US/docs/Web/API/Window/name
var sub = {
    'test': function() {
        return 42;
    },
    'test2': 42;
}

sub['test']();
sub['test2'];

add by
Using dot notation:
sub.test3 = "value3";

Using square bracket notation:
sub["test4"] = "value4";

Maybe im thinking to simple , but seems like this is what you are looking for


text:
Q: Edges reflecting weight in Cytoscape I just started looking into Cytoscape
I was looking at the example here. My goal is to have a weighted directed graph (pretty much like a dendrogram, except weighted). I need to have the edges reflect the weight (either in terms of length, or color but some sort of visual denotion). However, from the example, irrespective of what the edge weight is, I see no change in the graph. Does anyone know how I can achieve that?
Alternately, if there are other JS libraries that can help me visualize a weighted graph, I'd appreciate pointers on that as well.

A: Simply set your edge style appropriately in your stylesheet, with a mapper.

A: mappers are used to allow a per-element style encoding.
http://js.cytoscape.org/#style/mappers
what is unfortunately missing from the documentation is a more detailed explanation of what kind of values it can map as well as an example of how/where to apply such a mapper:
style: [
{
  selector: 'node',
  style: {
    'content': 'data(name)',
    'font-family': 'helvetica',
    'font-size': 14,
    'text-outline-width': 3,
    'text-outline-color': '#999',
    'text-valign': 'center',
    'color': '#fff',
    'width': 'mapData(weight, 30, 80, 20, 50)',
    'height': 'mapData(height, 0, 200, 10, 45)',
    'border-color': '#fff'
  }
}]

supported values for interpolation (the last two input parameters) are:
colors (as described in the docs), and numbers (as seen in the example above).


text:
Q: pyodbc not working when runing unicorn/fastapi I have a fastAPI program that needs to use pyodbc to connect to SQL server. Please refer to the code
from fastapi import FastAPI, Request, Body
from pydantic import BaseModel
import json
import pyodbc
from datetime import date, datetime

app = FastAPI()
############## Setup SQL connection
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=192.168.1.x;'
                      'Database=test;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()

def check_exists_device(DevEUI):
    cursor.execute(f"SELECT * FROM iotDevice WHERE devuid='{DevEUI}'")
    queryResult = cursor.fetchall()
    if len(queryResult) >0:
        print("Exist device")
    else:
        print("Not Exist device")

When I run the program, it works well, the function check_exists_device works. But when I start the uvicorn on the terminal this command:
uvicorn webService:app --host 0.0.0.0 --port 7878 --reload

it shows the error
     File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 315, in _bootstrap
    self.run()
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\site-packages\uvicorn\_subprocess.py", line 76, in subprocess_started
    target(sockets=sockets)
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\site-packages\uvicorn\server.py", line 60, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\site-packages\uvicorn\server.py", line 67, in serve
    config.load()
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\site-packages\uvicorn\config.py", line 479, in load
    self.loaded_app = import_from_string(self.app)
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\site-packages\uvicorn\importer.py", line 24, in import_from_string
    raise exc from None
    module = importlib.import_module(module_str)
  File "C:\Users\martin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\martin\PycharmProjects\pythonKafka\.\webService.py", line 4, in <module>
    import pyodbc
ModuleNotFoundError: No module named 'pyodbc'

Please help, I install and import pyodbc module already and when I run the program it works well, just when I start program by uvicorn, the error shows.


text:
Q: LINQ to XML to parse multiple Uri's to a single hyperlinkbutton I had a problem with passing a parsed string to a button click event. It was solved in this thread here, but now there's another small problem but it's with LINQ TO XML. I'm making a page which will show all of the apps that I make and will be updated with XML which I'll host on my server. On that page I'm parsing the icon, the title, the price and the marketplace Uri of the apps. I'm binding the Uri and the title of the apps to a single hyperlinkbutton but the problem is that every hyperlinkbutton on the list takes me to the same marketplace page. How can I fix it so every hyperlinkbutton navigates to a different page?
Here's the code:
  public partial class MorePage : PhoneApplicationPage
{
    private string appLink;

    public MorePage()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        WebClient client = new WebClient();
        Uri uritoXML = new Uri("http://www.allanhaapalainen.com/AppsXML/MorePageXML.xml", UriKind.RelativeOrAbsolute);
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.DownloadStringAsync(uritoXML);

        base.OnNavigatedTo(e);
    }

 public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        XDocument moreApps = XDocument.Parse(e.Result);

        morePageAppList.ItemsSource = from Apps in moreApps.Descendants("App")
                                       select new MoreApps
                                       {
                                           MoreImage = Apps.Element("link").Value,
                                           Price = Apps.Element("price").Value,
                                           Title = Apps.Element("title").Value
                                       };

        var attribute = (from Apps in moreApps.Descendants("App")
                         select new MoreApps
                         {
                             AppAttribute = (string)Apps.Attribute("id").Value
                         }).FirstOrDefault();

        string appAttr = attribute.AppAttribute;

        var link = (from Apps in moreApps.Descendants("App")
                    where Apps.Attribute("id").Value == appAttr
                    select new MoreApps
                    {
                        AppUri = (string)Apps.Element("marketplace").Value
                    }).FirstOrDefault();

        appLink = link.AppUri;
    }

    private void App_Name_Click(object sender, RoutedEventArgs e)
    {
        ShowMarket(appLink);
    }

    private void ShowMarket(string id)
    {
        MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
        marketplaceDetailTask.ContentIdentifier = id;
        marketplaceDetailTask.Show();
    }

}

AND THE XAML:
<ListBox Height="500" Width="Auto" Name="morePageAppList" Margin="0,0,0,0" ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                        <StackPanel Orientation="Horizontal" Height="173">
                            <Image Source="{Binding MoreImage}" Height="Auto" Width="Auto" />
                                <StackPanel Orientation="Vertical">
                                     <HyperlinkButton Name="appName" Content="{Binding Title}" Margin="15,60,0,0"  Click="App_Name_Click" />
                                     <TextBlock Name="price" Text="{Binding Price}" Margin="28,0,0,0" Foreground="#FFBD0000" />
                                </StackPanel>
                        </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

A: Like I mentioned in your previous post, you can use the tag parameter. Update your DataTemplate
<DataTemplate>
                        <StackPanel Orientation="Horizontal" Height="173">
                            <Image Source="{Binding MoreImage}" Height="Auto" Width="Auto" />
                                <StackPanel Orientation="Vertical">
                                     <HyperlinkButton Name="appName" Content="{Binding Title}" Tag="{Binding}" Margin="15,60,0,0"  Click="App_Name_Click" />
                                     <TextBlock Name="price" Text="{Binding Price}" Margin="28,0,0,0" Foreground="#FFBD0000" />
                                </StackPanel>
                        </StackPanel>
                </DataTemplate>

then in your event
private void App_Name_Click(object sender, RoutedEventArgs e)
    {
        var button = (HyperLinkButton)sender;
        var selectedApp = (MoreApps)button.Tag;

        ShowMarket(selectedApp.AppUri);
    }


text:
Q: How to preserve the comments when parsing yaml stream in C#? I am using YamlDotNet for reading and writing yamls. The content of the yaml file is first loaded into YamlStream and the document is processed and modified. After the document is processed, the content is written back to the file. During this process, comments are not preserved and its crucial in my project to preserve the comments. E.g.,
Yaml file:
            users:
            - id: someid
              # comment that needs to be preserved
              emailAddress: something@some.com
              phone:

and the code is
        var input = new StringReader(Document);
        var yaml = new YamlStream();
        yaml.Load(input);

        var document =
            (YamlMappingNode)yaml.Documents[0].RootNode;

        /* document is updated here */

        var serializer = new SerializerBuilder().Build();
        var updatedYaml = serializer.Serialize(document);

        Console.WriteLine(updatedYaml);

and the expected output is
            users:
            - id: someid
              # comment that needs to be preserved
              emailAddress: something@some.com
              phone:

But the comments are not preserved in the actual output. I have looked at this thread about comment preservation, but it talks about emitting the comments with data member attributes. But in my scenario, I am not using any class to deserialize/serialize the yaml. I just want to maintain the existing comments in an yaml when reading and writing it back. Is it possible to do this using YamlDotNet?


text:
Q: Way to externalize underscore templates I'm starting with marionette.js and was searching for ways to use external templates instead of script ones. I have read Derick's post about how it is a bad idea to load templates in async way. I have also checked BBCloneMail to see how templates are loaded there. It turned out that those are included into the index.html page when the web application loads. I wonder if this is a good idea for some big applications that might have 30+ templates and 10+ screens (sub-applications). Am I mistaken?
I was thinking that, instead of loading all templates at once I would load them when I load some specific sub-application. Is it a good way or is there a better way of dealing with external underscore templates?
If it may help in providing the answer, I've planned to use module system provided by marionette, not RequireJS.
Thank you in advance.
Best Regards.

A: @Roman
We load templates from external files using requireJS!text.  That is how we make templates modularized.
You can take a look at the example in here.

A: I know i'm late, but i have solved the topic by using JST Templates. A gulp process creates the JST object on runtime. I override marionette templates:
// use jst templates by overriding marionette render
Marionette.Renderer.render = function(template, data) {
    // allow No template
    if (template === undefined) {
        return '';
    }
    if (!window.JST[template]) {
        throw 'Template "' + template + '" not found!';
    }
    // underscore create a template
    return _.template(JST[template](data));
};

Check this usage on my skeleton example for this:
https://github.com/LucaMele/skeleton-marionette-require-gulp

A: Since you have 10+ subapps with 30+ templates, assuming 3 templates per subapplication average, it would be a really bad idea to load them by 3, unless the templates itself are very heavy. Also, today internet is quite fast everywhere I would not afraid creating a bit more heavier pages.
However, having 30+ templates in a single html file makes mess. In this case I would recommend using Jammit or something similar. It lets you have separate html file for every template in development and builds it into a single file for production.

A: I ran into the same issue.  I found an example online, I modified it to make it work for what I was doing it for (they were pulling html files and I wanted to pull ASP.net pages) but I can't find the example online again to give that person the credit.  However, here is my modified code.
The first is the template loader:
if (!window.JackTemplateLoader) {

function JackTemplateLoader(params) {
    if (typeof params === 'undefined') params = {};
    var TEMPLATE_DIR = params.dir || '';

    var file_cache = {};

    function get_filename(name) {
        if (name.indexOf('-') > -1) name = name.substring(0, name.indexOf('-'));
        return TEMPLATE_DIR + name;
    }

    this.get_template = function (name) {
        var template;
        var file = get_filename(name);
        var file_content;
        var result;
        if (!(file_content = file_cache[name])) {
            $.ajax({
                url: file,
                async: false,
                success: function (data) {
                    file_content = data;
                    file_cache[name] = file_content;
                }
            });
        }
        return file_content;
    }

    this.clear_cache = function () {
        template_cache = {};
    };

  }
 }

Then inside my Marionette App, I created an addInitilizer that over writes Marionettes template loader.
    app.addInitializer(function (options) {
    app.JackTemplateLoader = new JackTemplateLoader({ dir: "/api/ApplicationScreens/", ext: '' });
    Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (name) {
        if (name == undefined) {
            return "";
        } else {
            var template = app.JackTemplateLoader.get_template(name);
            return template;
        }
    };

The best part is the template loader will cache my templates so they are only loaded once.  I am working on making a change to this code to send a flag that will indicate whether or not I want to cache the template.


text:
Q: how to set this table in IEEE paper
\begin{table}[h]

 \begin{center}

   \caption{ Comparison of Maximum Accuracy of Different Methods on BCI comp III dataset IIIa
}\label{tab:2}

   \begin{tabular}{c c c c c c}
     \hline
     % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
     $Feature Extraction^a$ & $Classifier^b$ & & Accuracy(\%)  &  &  \\
     \hline
      &  & K3  & K6  & L1  & $mean^c$ \\
     AAR & MDA[9] & 66.6 & 38.5 & 49.5 & 51.5 \\
     CAR+CSP & NN[10] & 81.7 & 76.7 & 73.3 & 77.2 \\
     Barlow method & SVM[11] & 63.3 & 45.0 & 60.0 & 56.1 \\
       WPD & ME[12] & 90.4 & 66.0 & 79.6 & 78.7\\
      WPD+CSP & SVM+NN[13] & 83.1 & 84.4 & 85.6 & 84.4 \\
     PLV  & SVM+Quicksort[14] & 86.0 & 82.0 & 77.0 & 81.7 \\
     Sparse PCA+Sparse CSP & SVM[15] & 85.1 & 81.6 & 80.1 & 82.3 \\
     STFT+CSP & SVM[16] & 71.3 & 88.1 & 71.2 & 76.9\\
     \hline
      4 band CSP (our method)& SVM & 93.3 & 77.5 & 85.8 & 85.5\\

     \hline

   \end{tabular}

 \end{center}
\end{table}

A: Your table has a number of serious issues. The fact that it is wider than \columnwidth is just the most serious one.

*

*To make the table fit inside the text block, it suffices to (a) set the parameter \tabcolsep to 0pt and (b) switch from a tabular to a tabular* environment. Armed with the @{\extracolsep{\fill}} directive, the tabular* environment will reduce the intercolumn whitespace as much as is needed to make the table fit.
If the table were any wider, one would also have to introduce line breaks in some of the cells in the two text columns. However, that doesn't seem to be necessary here.

*The table's layout is -- pardon my bluntness -- quite unattractive. I suggest you (a) load the booktabs package, (b) use its line-drawing macros instead of \hline, and (c) provide more deliberate structure to the header material. For instance, to center the string "Accuracy (\%)" above the four data columns, encase it in a multicolumn{4}{c}{...} directive.

*It looks like you're trying to create some in-table footnote markers. Whatever else you do, don't abuse TeX's math mode in this way. I suggest you (a) load the threeparttable package, (b) use \tnote directives to place the footnote markers, and (c) use a tablenotes environment after \end{tabular* to place the corresponding footnote material.

*In one of the header cells, replace the odd-looking fi with fi.

\documentclass{IEEEtran}
\usepackage{booktabs,ragged2e}

\usepackage[flushleft]{threeparttable}
\renewcommand\TPTtagStyle{\textit}

\begin{document}

\begin{table}[h]
\begin{threeparttable}
\caption{Comparison of Maximum Accuracy of Different
        Methods on BCI comp III dataset IIIa}
\label{tab:2}
\setlength\tabcolsep{0pt} % make LaTeX figure out intercolumn spacing

\begin{tabular*}{\columnwidth}{@{\extracolsep{\fill}} ll cccc}
\toprule
     Feature Extraction\tnote{a} & Classifier\tnote{b} &
     \multicolumn{4}{c}{Accuracy (\%)} \\
\cmidrule{3-6}
     & & K3 & K6 & L1 & mean\tnote{c} \\
\midrule
     AAR & MDA [9] & 66.6 & 38.5 & 49.5 & 51.5 \\
     CAR+CSP & NN [10] & 81.7 & 76.7 & 73.3 & 77.2 \\
     Barlow method & SVM [11] & 63.3 & 45.0 & 60.0 & 56.1 \\
     WPD & ME [12] & 90.4 & 66.0 & 79.6 & 78.7\\
\addlinespace
     WPD+CSP & SVM+NN [13] & 83.1 & 84.4 & 85.6 & 84.4 \\
     PLV  & SVM+Quicksort [14] & 86.0 & 82.0 & 77.0 & 81.7 \\
     Sparse PCA+Sparse CSP & SVM [15] & 85.1 & 81.6 & 80.1 & 82.3 \\
     STFT+CSP & SVM [16] & 71.3 & 88.1 & 71.2 & 76.9\\
\addlinespace
      4 band CSP (our method)& SVM & 93.3 & 77.5 & 85.8 & 85.5\\
\bottomrule
\end{tabular*}

\smallskip
\scriptsize
\begin{tablenotes}
\RaggedRight
\item[a] AAR: Adaptive Autoregressive;
         CAR: Common Average Reference;
         CSP: Common Spatial Pattern;
         WPD: Wavelet Packet Decomposition;
         \dots
\item[b] \dots
\item[c] \dots
\end{tablenotes}
\end{threeparttable}
\end{table}
\end{document}


text:
Q: How are if conditions read? In this exemple, if the first conditions is matched, are the other one tested by the compilator ?
a = 10
if (a % 2 == 0 || a / 2 == 5 || a == 10)
   echo 'hello world'

A: In logical or conditions are checked from left to right.
If the left condition is true then remaining right conditions are not checked by the compiler.
bool condition_1 = true;
bool condition_2 = false;
if(condition_1 || condition_2) in this case condition_2 is not checked by compiler.


text:
Q: How to add extra custom content type to Contacts based ListInstance I am trying to build a custom ListInstance for deployment in Visual Studio. It should be based on the Contacts template so it can be opened in/linked to Outlook, but I also want to add two other custom content types to the ListInstance. How do I do that?
It is possible to create what I want through the web interface, but I would like to do it in Visual Studio.

A: Have you tried exporting the site where you have created the lists as a WSP and imported the project in Visual Studio?
List instances in SP2010 use the CustomSchema attribute in Elements schema. Exporting the list should give you the Schema.xml for the list instance


text:
Q: Remove the uploaded image onclick text Once user click on Mask image, we are allowing user to upload custom image.... Along with image, we are displaying text "Remove Image"....
Issue :
Onclick on that text, i want to delete the uploaded image like in this codepen1.... but right now only text is removing when i used below code :

var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
  "layers" : [
    {
      "x" : 0,
      "height" : 612,
      "layers" : [
        {
          "x" : 0,
          "y" : 0,
          "name" : "L2a"
        },
        {
          "x" : 160,
          "layers" : [
            {
              "x" : 0,
              "src" : "ax0HVTs.png",
              "y" : 0,
              "name" : "L2b-1"
            },
            {

              "x" : 0,
              "y" : 0,
              "name" : "L2b-2"
            }
          ],
          "y" : 291,
          "name" : "user_image_1"
        },
        {
          "x" : 25,
          "layers" : [
            {
              "x" : 0,
              "src" : "hEM2kEP.png",
              "y" : 0,
              "name" : "L2C-1"
            },
            {
              "x" : 0,
              "y" : 0,
              "name" : "L2C-2"
            }
          ],
          "y" :22,
          "name" : "L2"
        }
      ],
      "y" : 0,
      "width" : 612,
      "name" : "L1"
    }
  ]
};

$(document).ready(function() {

    // below code will upload image onclick mask image

   $('.container').click(function(e) {

        var res = e.target;
        target = res.id;
        console.log(target);
        if (e.target.getContext)
  {
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
        }
    });

 // Below code will fetch mask images from json file

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
     name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
      name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
       name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

     function json(data)

        {
            var width = 0;
            var height = 0;

            let arr = getAllSrc(data.layers);

            let layer1 = data.layers;
            width = layer1[0].width;
            height = layer1[0].height;
            let counter = 0;
            let table = [];

            for (let {
                    src,
                    x,
                    y,
     name
                } of arr) {
                $(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
                if(name.indexOf('mask_') !== -1){
                    var imageUrl1 = imageUrl;
                }else{
                    var imageUrl1 = '';
                }
                var mask = $(".container").mask({
       imageUrl: imageUrl1,
                    maskImageUrl: 'https://i.imgur.com/' + src,
                    onMaskImageCreate: function(img) {

                        img.css({
                            "position": "absolute",
                            "left": x + "px",
                            "top": y + "px"
                        });

                    },
                    id: counter
                });
                table.push(mask);
                fileup.onchange = function() {

                    let mask2 = table[target];
                    mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                    document.getElementById('fileup').value = "";

     // Below code to Remove image

                $("" +
                    "" +
                    "
Remove image" +
                    "").insertAfter("#fileup");

                $(".remove").click(function() {
                    $(this).parent(".pip").remove();
                });

                // Remove image code ended here....
                };
                counter++;
    // get the text

            }
        }
json(jsonData);
}); // end of document ready

// jq plugin

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
        }, options);

        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div;

        container.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }

        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };

        container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }

        container.onDragStart = function(evt) {
            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;

                $(canvas).attr("active", "true");
                container.selected(evt);
                prevX = evt.clientX;
                prevY = evt.clientY;
                var img = new Image();
                evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
                evt.originalEvent.dataTransfer.setData('text/plain', 'anything');

            }
        };

        container.getImagePosition = function() {
            return {
                x: settings.x,
                y: settings.y,
                scale: settings.scale
            };
        };

        container.onDragOver = function(evt) {

            if (evt.target.getContext) {
                var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
                if (pixel[3] === 255) {
                    if (draggable && $(canvas).attr("active") === "true") {
                        var x = settings.x + evt.clientX - prevX;
                        var y = settings.y + evt.clientY - prevY;
                        if (x == settings.x && y == settings.y)
                            return; // position has not changed
                        settings.x += evt.clientX - prevX;
                        settings.y += evt.clientY - prevY;
                        prevX = evt.clientX;
                        prevY = evt.clientY;
                        clearTimeout(timeout);
                        timeout = setTimeout(function() {
                            container.updateStyle();
                            renderInnerImage();
                        }, 20);
                    }
                } else {
                    evt.stopPropagation();
                    return false;
                }
            }
        };

        container.updateStyle = function() {
            return new Promise((resolve, reject) => {
                context.beginPath();
                context.globalCompositeOperation = "source-over";
                image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = settings.maskImageUrl;
                image.onload = function()
                {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    div.css({
                        "width": image.width,
                        "height": image.height
                    });
                    resolve();
                };
            });
        };

        function renderInnerImage() {
            img = new Image();
            img.setAttribute('crossOrigin', 'anonymous');
            img.src = settings.imageUrl;
            img.onload = function() {
                settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
                settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
                context.globalCompositeOperation = 'source-atop';
                context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                initImage = false;
            };
        }

        // change the draggable image
        container.loadImage = function(imageUrl) {
             console.log("load");
            //if (img)
               // img.remove();
            // reset the code.
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;
            container.updateStyle().then(renderInnerImage);
        };

        // change the masked Image
         container.loadMaskImage = function(imageUrl, from) {
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImageUrl = imageUrl;
            div = $("
", {
                "class": "masked-img"
            }).append(canvas);

            // div.find("canvas").on('touchstart mousedown', function(event)
            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);
            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
            container.loadImage(settings.imageUrl);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        return container;
    };
}(jQuery));
.temp {}

.container {
 background: gold;
  position: relative;

}

.container img {
   position:absolute;
   top:0;
   bottom:250px;
   left:0;
   right:0;
   margin:auto;
   z-index:999;
}

.masked-img {
 overflow: hidden;
 position: relative;
}

.txtContainer{ position:absolute;  text-align:center; color:#FFF}

.pip {
  display: inline-block;
  margin: 10px 10px 0 0;
}
.remove {
  display: block;
  background: #444;
  border: 1px solid black;
  color: white;
  text-align: center;
  cursor: pointer;
}
.remove:hover {
  background: white;
  color: black;
}

<input id="fileup" name="fileup" type="file" style="display:none" >

Please let me know if you need any other information....

A: So to start with you should tackle 2 different problems:
1) Some how have a reference to your image in the button.
Buttons are not very smart and you will need to add some magic. As if you follow your code, when you load an image basically you are uploading a canvas with a new draw, so it is not easy to identify what to delete. One problem of this approach is that is difficult for you to find the image to delete. But you could, once the image is loaded, return the information about this image in the canvas and then adding it to an array.
As far as I can see there would be only one image per canvas, or at least it will draw over the last one, so the easiest solution is to clean the whole canvas. First, we return the id of the canvas that contains the image:
// change the draggable image
    container.loadImage = function(imageUrl) {
         console.log("load");
        //if (img)
           // img.remove();
        // reset the code.
        settings.y = startY;
        settings.x = startX;
        prevX = prevY = 0;
        settings.imageUrl = imageUrl;
        initImage = true;
        container.updateStyle().then(renderInnerImage);

        // Add this
        return settings.id;
    };

Then you can save it in this line: const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
Second step in this challenge is to basically add this as the id of the button (this is not the recommended way though, but is the one that will make you modify your code the less):
$("
Remove image").insertAfter("#fileup");

Now your button has a reference to the image that you uploaded.
2) Actually delete it.
This problem is easier though, you just need to clear the image in the canvas:
$("canvas#" + id).getContext('2d').clearReact(...)
And this is all, I would suggest you refactor and clean a bit your code. And you could add some improvements like.
IF you want to upload more than one image to a canvas then this method is not the best one to delete a unique image, but your code also does not allow you to do it correctly right now. If you want to keep several images I suggest you check this answer, so basically you need to keep track of every image as a new layer.
Handling the click event with a closure instead of saving the id to the button (this makes the ID not being unique but rather exist in both, the button and the canvas).
Making the load image process a bit more intuitive, even, for example, use the counter instead of the time stamp.
Disclaimer: This solution does not improve your code base, it just offers you a possible solution to the problem you are having and the proposed solution just touch as little number of lines as possible. I suggest few things at the end, but with time and more experience with jQuery / JavaScript, you will tackle this problem in a better way.


text:
Q: What happens when you add another method as property to a function in Javascript? I agree that Functions are objects in JS. When using a Function as a constructor we can add properties to the object create by adding these properties to the prototype property on the function. This is what I tried:
var Mammal = function(name) {
    this.name = name;
};

var Cat = function(name) {
    this.saying = 'meow';
};

Cat.prototype = new Mammal();

Cat.prototype.display = function() {
    console.log('I display Cats');
};

//This is what I find hard to digest
Cat.display = function() {
    console.log('I display cats but at the top level');
};

What I find hard to grasp is the commented portion. I was just trying to picture what goes where and this particular part I don't understand. I mean if I had to write a function and do something like this while defining the function what would be the syntax like?
If I try something like the following:
function demo() {
    this.saying = function() {
        console.log('I display cats but at the top level');
    };
};

The variable this here refers to the DOMWindow. How do I achieve the above thing within a function definition.
I am a total newbie to JS. I apologize for any ignorance on my part.

A: The question is not absolutely clear...
But, consider the following code:
function Test(title) { // object constructor (class)
    this.title = title;
}

Test.prototype.getTitle = function () { return this.title }; // shared (inherited) getter method
Test.version = 1; // static property (no need to instantiate an object)

var obj = new Test('hello, world!'); // an instance of the 'Test' class
console.log(obj.constructor.version); // reference to a static property of the class

When function is called along with the new keyword it is a constructor and this points to the object being constructed (new Test('hello, world!')).
When function is called as an object method (e.g., obj.getTitle()), this points to that object.
When function is called normally (Test('hello, world!')), this points to the global object (Window).
Does this help? :)

A: Those are analogous to static methods in class based objects. That is, the method can only be accessed from the constructor, not from the instance itself.
A good example of this ìs jQuery.get() You can't do
$('.someclass').get(myUrl);

You have to use
$.get(myUrl);

However, if you do need to access the static method from an instance, you have two options
var cat = new Cat('catName');
cat.constructor.display();
Cat.display();

http://jsfiddle.net/c39bW/
Not that your constructor property for Cat is broken, when you setup inheritance, you should fix the Cat.prototype.constructor to point back to Cat, see my jsFiddle above. Also, you're not calling the base constructor (Mammal) from Cat's constructor. For a tutorial on the minimal requirements for inheritance, see http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
A good example as to when static properties are useful is when an object needs to keep track of how many times it has been instantiated, you can't do that at an instance level;
function Tracker() {
   this.constructor.count++;
}

Tracker.count = 0;

Tracker.getCount = function() {
     return Tracker.count;
}

A: For clarity, I've changed your Cat class to Animal.
Anything added to Animal's prototype will be applied to any new instances of Animal.  When called, the keyword this will refer to the instance.
var cat = new Animal();
cat.display(); // calls Animal.prototype.display(), 'this' points to 'cat'

Anything attached directly to Animal will not be, and can only be accessed directly:
Animal.display(); // 'this' points to 'Animal'


text:
Q: Troubles with slow speeds in opencl I am trying to use opencl for the first time, the goal is to calculate the argmin of each row in an array. Since the operation on each row is independent of the others, I thought this would be easy to put on the graphics card.
I seem to get worse performance using this code than when i just run the code on the cpu with an outer forloop, any help would be appreciated.
Here is the code:
#pragma OPENCL EXTENSION cl_khr_fp64 : enable

int argmin(global double *array, int end)
{
  double minimum = array[0];
  int index;
  for (int j = 0; j < end; j++)
  {
    if (array[j] < minimum)
    {
      minimum = array[j];
      index = j;
    }
  }
  return index;
}

kernel void execute(global double *dist, global long *res, global double *min_dist)
{
  int row_size = 0;
  int i = get_global_id(0);

  int row_index = i * row_size;
  res[i] = argmin(&dist[row_index], row_size);
  min_dist[i] = dist[res[i] + row_index];

}

A: The commenters make some valid points, but I'll try to be a little more constructive and organised:

*

*Your data appears to consist of double precision floating point values. Depending on your GPU, this can be bad news in itself. Consumer grade GPUs typically are not optimised for working with doubles, often only achieving 1/32 or 1/16 the throughput compared to single-precision float operations. Many pro-grade GPUs (Quadro, Tesla, FirePro, some Radeon Pro cards) are fine with them though, achieving 1/2 or 1/4 throughput versus float. As you're only performing a trivial arithmetic operation (comparison), and there's a good chance your runtime is dominated by memory access, it could be fine on consumer hardware too.

*I assume your row_size is not actually 0, it would help to know what the true (typical) value is, and whether it's fixed, variable by row, or variable per run but the same for each row. In any case, unless row_size is very small, the fact that you are running a serial for loop over it could be holding your code back.

*How big is your work size? In other words, how many rows in your array (give a typical range if it varies)? If it is very small, you will see little benefit from GPU parallelism: GPUs have a large number of processors and can schedule a few threads per processor. So your work items will need to number hundreds or better thousands to achieve decent hardware utilisation.

*You are reading a very large array from (presumably) system memory and not performing any intensive operations on it. This means your bottleneck will typically be on the memory access side - for discrete GPUs, system memory access needs to go through PCIe, so the speed of that link will place an upper bound on your performance. Additionally, your memory access pattern far from ideal for GPUs - you typically want work items to read adjacent memory cells at the same time as the memory unit typically fetches 64 bytes or more at once.

Improvement suggestions:

*

*Profiling. If at all possible, use your GPU vendor's profiling tools to determine your true bottlenecks. Otherwise we're just guessing.

*For (4) - if at all possible, try not to move large amounts of data around too much. If you can generate your input arrays on the GPU, do so, so they never leave VRAM.

*For (4) - Optimise your memory accesses. AMD, NVidia and Intel all have OpenCL GPU optimisation guides which explain how to do this. Essentially, re-structure your data layout, or your kernel such that adjacent work items read adjacent pieces of memory. You ideally want work item 0 to read array item 0, work item 1 to read array item 1, etc. You may need to use local memory to coordinate between work items. Another option is to read vector-sized chunks of data per work item. (e.g. each work-item reads a double8 at a time) Watch for alignment in this case though.

*For (2) & (3) - Unless row_size is very small (and fixed), try to split your loop across multiple work items and coordinate using local memory (reduction algorithms) and atomic operations in global memory.

*For (1): If you've optimised everything else and profiling is telling you that comparing doubles on consumer hardware is too slow, either check if you can generate the data as floats without loss of accuracy (this will also halve your memory bandwidth woes), or check if you can otherwise do better somehow, for example by treating the double as a long and manually unpacking and comparing the exponent and mantissa using integer operations.


text:
Q: where to store photos, in database or in api I'm currently working on creating a website for my college. I want to include a galary section on the page.
so through admin page, authorities can upload photos of special college events. Now my question is where to store those images. I have two options 1)storing in the Database using gridfs 2) storing in the api. I have done a lot of research on this topic but everyone saying it depends on the situation. What do you think the best option for this situation. I'm still new to server side programming, so please help me. I'm using nodejs with ejs and mongodb


text:
Q: Catching String returned from REST in angular. I have already implemented it but I want to know if it's done the right way In Angular Service.ts:
changePriority(ticket : TicketDetails) {
    return this.http.put("api/serviceEngineer/updatePriority", ticket, {responseType : 'text'})
  }

I declared the Http Client in the following way using a constructor:

constructor(private http: HttpClient) { }

In this way Iam catching the string returned from REST in angular but I got to know from a friend that it is not the right way to do so and I want to know why exactly. He was saying it would always be active unlike an Observable. Any help would be extremely appreciable. Thank you!!!


text:
Q: What is the best way to embed Mailerlite forms in Nuxt JS I want to embed Mailerlite forms on my Nuxt Js website.
Need the whole form to show up. (All fields)
Mailerlite gives 3 options: Javascript, HTML(with script) and Popup.


text:
Q: Accessing a model Field in admin.ModelAdmin in Django hi I want to access the value of a field in Django admin Form
model.py
from __future__ import absolute_import, division
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class MySqlQuery(models.Model):
  name = models.CharField(max_length=100)
  query = models.TextField(max_length=1000)

    class Meta:
      verbose_name = 'SQL Query'
      verbose_name_plural = 'SQL Queries'
    def __str__(self):
      return self.name

admin.py
 class MySqlQueryAdmin(admin.ModelAdmin):

  list_display = ('query', 'name', 'action')

  def get_urls(self):
      urls = super(MySqlQueryAdmin, self).get_urls()
      my_urls = patterns('', url(r"^execute/$",
                       self.admin_site.admin_view(self.execute_query)))
      return my_urls + urls

  def execute_query(self, request):
      cursor = connection.cursor()
      try:
        #------------------------------------------
        #need to access query field from the models
        #------------------------------------------
        cursor.execute(self.form.query)
      except:
        logger.error('query was not right')
      finally:
        cursor.close()

      return HttpResponseRedirect(request.META['HTTP_REFERER'])

  def action(self, form):
      return "execute"

  action.allow_tags = True

 admin.site.register(MySqlQuery, MySqlQueryAdmin)

I have created a models.py, which have field query, i want to execute query from the Django admin. For which i need to access the field in django admin form.

A: This isn't different from any other Django view. The instance of MySqlQueryAdmin doesn't refer to any instance of MySqlQuery: it's an admin for the whole model class, not any particular instance of it. That means there's no way of getting "the" value of a query instance without passing an identifier and getting the object from the database using that identifier.
class MySqlQueryAdmin(admin.ModelAdmin):

  list_display = ('query', 'name', 'action')

  def get_urls(self):
      urls = super(MySqlQueryAdmin, self).get_urls()
      my_urls = patterns('', url(r"^execute/(?P<id>\d+)/$",
                       self.admin_site.admin_view(self.execute_query), name="execute"))
      return my_urls + urls

  def execute_query(self, request, id):
       query = MySqlQuery.objects.get(id=id)
       ...

  def action(self, obj):
      return "execute" % reverse(admin:execute, kwargs={'id': obj.id})
  action.allow_tags = True

Of course, I wouldn't recommend doing anything like this at all, since you seem to be executing arbitrary user-supplied SQL against your database, but I guess you already know the risks of that.


text:
Q: Switching 3.3V 150mA efficiently I have a load (from 20 LEDs with 20 resistors) that I want to switch on/off as a single block, using a GPIO pin from a micro-controller.
I have measured the current to be 145mA at 3.3V Vcc.

simulate this circuit – Schematic created using CircuitLab
I have tried switching this load using two methods:
Attempt A: N-channel mosfet

simulate this circuit
When I switch the load on with a 2N7002 N-channel mosfet, I see that only 86mA makes it through the switch.
I also tried the 2N7000 N-channel mosfet, and I see 90mA for that.
Attempt B: Darlington Array

simulate this circuit
I tried switching it through the ULN2003 darlington array, using just 1 of 7 channels, I see a measly 64mA makes it through. (Coincidentally, this part seems to be sold-out everywhere, so I cannot use it anyway.)
Am I wrong to expect more current when switched? Did I use the mosfets or darlingtons incorrectly?

A: Technically, you either expect devices to work better given the circumstances, or use them wrong. They are not zero ohm switches.
Case A: 2N7000 needs more than 3.3V at gate to turn on with low enough drain-source resistance to allow for more current. So too low gate voltage prevents the FET from turning fully on and there is a voltage drop over the FET, it has Vds larger than zero. This might get better by just recalculating a smaller resistor. Even at gate voltage of 4.5V, and 75mA drain current, the Vds voltage drop could be up to 0.4V.
Case B: ULN2003 channel is a Darlington transistor and these have Vce voltage drop of around 1V, so by calculating that into account you need to make the resistance smaller.

A: The ULN2003A is about 30 years old. It amazes me that folks do not look up newer/equivalent parts.
The best FET equivalent is the TPL7407, but this is in short supply.
However there is a FET based pin equivalent that is readily available, the ULN2003V12. The device uses an N-channel FET instead of the Darlington arrangement in the ULN2003A.

There will still be an on-state V(low) limitation:

The ULN2003V12 is just 7 N-chan FETs, so they can be paralleled to bring the V(low) down. They also work just fine on 3.3V systems


text:
Q: Add user to group in signal post_save I want to add a user to a group after the user object is saved. Each user has a user type corresponding to the group the user belongs to. For example, if the user_type is 2, then the user belongs to Group_3, and so on.
This is my code:
class User(AbstractBaseUser, PermissionsMixin):
    """ Custom user model """
    USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student'))
    email = models.EmailField(
        _("Email Address"),
        max_length=255,
        unique=True,
        help_text="Ex: example@example.com",
    )
    eec = models.ForeignKey(
        EEC, on_delete=models.CASCADE, null=True, related_name='eec',blank=True)
    is_staff = models.BooleanField(_("Staff status"), default=False)
    is_active = models.BooleanField(_("Active"), default=True)
    date_joined = models.DateTimeField(_("Date Joined"), auto_now_add=True)
    last_updated = models.DateTimeField(_("Last Updated"), auto_now=True)
    user_type = models.IntegerField(default=1, choices=USER_TYPE)
    lastName = models.CharField(default='', max_length=250)
    firstName = models.CharField(default='', max_length=250)
    objects = UserManager()
    USERNAME_FIELD = "email"

    def __str__(self):
        return self.email

class Teacher(models.Model):
    admin = models.OneToOneField(User, on_delete=models.CASCADE)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.user_type == 1:
            Admin.objects.create(admin=instance)
        if instance.user_type == 2:
            try:

                Teacher.objects.create(admin=instance)
                g1 = Group.objects.get(name='teacher')
                instance.groups.add(g1)

            except:
                print("Exception")
        if instance.user_type == 3:
            Student.objects.create(admin=instance)

Basically, when I save the user model with a user type of 2, the group does not get updated


text:
Q: Difference between Tensorflow convolution and numpy convolution import numpy as np
import tensorflow as tf

X_node    = tf.placeholder('float',[1,10,1])
filter_tf = tf.Variable( tf.truncated_normal([3,1,1],stddev=0.1) )

Xconv_tf_tensor = tf.nn.conv1d(X_node, filter_tf,1,'SAME')

X = np.random.normal(0,1,[1,10,1])
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    feed_dict = {X_node: X}
    filter_np = filter_tf.eval()
    Xconv_tf = sess.run(Xconv_tf_tensor,feed_dict)
    Xconv_np = np.convolve(X[0,:,0],filter_np[:,0,0],'SAME')

I am trying to see the results of convolutions from Tensorflow to check if it is behaving as I intended.
When I run the numpy convolution and compare it to the Tensorflow convolution, the answer is different.
The above code is how I ran the test.
I was hoping the Xconv_tf and Xconv_np would be equal.
My final goal is the run 2D convolution on a matrix with a 1 dimensional filter that runs 1d-convolution on each row with the same filter. In order to make this work (which will be basically a loop of 1d convolution over the rows) I need to figure out why my np.convolve and tf.conv1d give me different answers.

A: The order of filter is reversed. TensorFlow convolution is actually correlation. Numpy gets notation from math, TF gets notation from machine learning papers and somewhere the order got reversed.
This prints True
filter_np2=filter_np[::-1,0,0]
np.allclose(np.convolve(X[0,:,0],filter_np2,'SAME'),  Xconv_tf.flatten())    np.convolve(X[0,:,0],filter_np2,'SAME')

A: The problem that you see is because TF does not really calculate the convolution. If you will take a look at the explanation of what convolution actually does (check for Visual explanations of convolution), you will see that the second function is flipped:

*

*Express each function in terms of a dummy variable

*Reflect one of the functions (this is the flip)

*..... Some other stuff which I will not copy here.

TF does everything except of that flip. So all you need to do is to flip the kernel either in TF or in numpy. Flipping for 1d case is just kernel in a reverse order, for 2d you will need to flip both axis (rotate the kernel 2 times).
import tensorflow as tf
import numpy as np

I = [1, 0, 2, 3, 0, 1, 1]
K = [2, 1, 3]

i = tf.constant(I, dtype=tf.float32, name='i')
k = tf.constant(K, dtype=tf.float32, name='k')

data   = tf.reshape(i, [1, int(i.shape[0]), 1], name='data')
kernel = tf.reshape(k, [int(k.shape[0]), 1, 1], name='kernel')

res = tf.squeeze(tf.nn.conv1d(data, kernel, 1, 'VALID'))
with tf.Session() as sess:
    print sess.run(res)
    print np.convolve(I, K[::-1], 'VALID')


text:
Q: GitAhead disable HTTPS Login Window Each 4 minutes GitAhead opens a small window for asking HTTPS Login/Password.
How I can say : Please do not disturb me !

A: You can turn off automatic fetch from Tools -> Options... -> General -> Automatic Actions -> Fetch every xx minutes.


text:
Q: Open executable file from graphics button without closing parent window I've created a game "dice poker" using Zelle's graphing package, and have a button on the main screen which opens a text file.  The text file opens when the button is clicked, but the main window closes.  How can I keep the parent window open?
The button class is below:
from graphics import *
from tkinter import Button as tkButton

class Button():

    """A button is a labeled rectangle in a window.
    It is activated or deactivated with the activate()
    and deactivate() methods. The clicked(p) method
    returns true if the button is active and p is inside it."""

    def __init__(self, win, center, width, height, label):
        """ Creates a rectangular button, eg:
        qb = Button(myWin, centerPoint, width, height, 'Quit') """

        w,h = width/2.0, height/2.0
        x,y = center.getX(), center.getY()
        self.xmax, self.xmin = x+w, x-w
        self.ymax, self.ymin = y+h, y-h
        p1 = Point(self.xmin, self.ymin)
        p2 = Point(self.xmax, self.ymax)
        self.rect = Rectangle(p1,p2)
        self.rect.setFill('lightgray')
        self.rect.draw(win)
        self.label = Text(center, label)
        self.label.draw(win)
        self.deactivate()

    def clicked(self, p):
        "Returns true if button active and p is inside"
        return (self.active and
                self.xmin <= p.getX() <= self.xmax and
                self.ymin <= p.getY() <= self.ymax)

    def getLabel(self):
        "Returns the label string of this button."
        return self.label.getText()

    def activate(self):
        "Sets this button to 'active'."
        self.label.setFill('black')
        self.rect.setWidth(2)
        self.active = True

    def deactivate(self):
        "Sets this button to 'inactive'."
        self.label.setFill('darkgrey')
        self.rect.setWidth(1)
        self.active = False

How can I include a command argument that can open an executable in a fashion similar to this tkinter implementation:
import Tkinter as tk

def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

Where the command can be subprocess.run(['open', '-t', 'poker_help.txt']) and still keep the original window open?

A: I have to make some assumptions since you didn't include top level code (e.g. you're on a Mac):
Zelle graphics, unlike tkinter and turtle, which is also built on tkinter, doesn't have an explicit win.mainloop() call to turn control over to the Tk event handler to idle awaiting events to happen.  Instead, you have to patch one together yourself, otherwise once you get the mouse click that fires off your button, the program falls through the end of the file and the main window closes:
import subprocess
from graphics import *
from button import Button

win = GraphWin()

help_button = Button(win, Point(150, 150), 50, 50, "Help")
help_button.activate()

quit_button = Button(win, Point(50, 50), 50, 50, "Quit")
quit_button.activate()

while True:
    point = win.getMouse()

    if help_button.clicked(point):
        subprocess.call(['open', '-t', 'poker_help.txt'])
    elif quit_button.clicked(point):
        win.close()

Where from button import Button brings in your button code above.  Another thing to check is your window is actually closing, and not simply being obscured by the new window opened atop it.


text:
Q: R.string error cannot be resolved or is not a field I'm getting the error "cannot be resolved or is not a field" on this line of code.
int textString = R.string.start;

The strings.xml file is located in the res > layout directory so it's not in another package.
Why is this error occurring even after I clean and/or rebuild the project?
import com.example.lab08_2hw.R;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView av; //UI reference
    int textString = R.string.start;
    int backgroundColor = Color.DKGRAY;
    final Handler mHandler = new Handler();
    // Create runnable for posting results to the UI thread
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            av.setText(textString);
            av.setBackgroundColor(backgroundColor);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        av = (TextView) findViewById(R.id.computation_status);
        Button actionButton = (Button) findViewById(R.id.action1);
        actionButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                doWork();
            }
        });
    }
    //example of a computationally intensive action with UI updates
    private void doWork() {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                textString=R.id.start;
                backgroundColor = Color.DKGRAY;
                mHandler.post(mUpdateResults);
                computation(1);
                textString=R.id.first;

                backgroundColor = Color.BLUE;
                mHandler.post(mUpdateResults);
                computation(2);
                textString=R.id.second;
                backgroundColor = Color.GREEN;
                mHandler.post(mUpdateResults);
            }
        });
        thread.start();
    }

    final static int SIZE=1000; //large enough to take some time
    double tmp;
    private void computation(int val) {
    for(int ii=0; ii<SIZE; ii++)
        for(int jj=0; jj<SIZE; jj++)
            tmp=val*Math.log(ii+1)/Math.log1p(jj+1);
        }
    }

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HandlerUpdateUi!</string>
<string name="app_name">HandlerUpdateUi</string>
<string name="action">Press to Start</string>
<string name="start">Starting...</string>
<string name="first">First Done</string>
<string name="second">Second Done</string>
</resources>

A: try this code
 getResources().getString(R.string.start);

A: There are lots of flaws in your code. The ones that could be relevant for your problem are below:
First change your strings.xml location to res/values.  res > layout directory should be used for your layouts.
Second change int textstring to String textstring.
And third call this line String textString = R.string.start; inside onCreate() method.The place you are initiliazing it right now is wrong.

A: Put your string.xml file to values folder.
then use the following code to get string from string.xml file
getResources().getString(R.string.start);


text:
Q: Can't Execute Any Command After Switch Set in PHP let's say I have a switch set
switch(telco) {
    CASE "TELKOMSEL":
        require($_SERVER['DOCUMENT_ROOT'].'/libs/functions/InjectMT_Telkomsel.php');
        InjectMe($service, $reply, $mt_type, $service, $mtsid);
        break;
    CASE "INDOSAT":
        require($_SERVER['DOCUMENT_ROOT'].'/libs/functions/InjectMT_Indosat.php');
        InjectMe($service, $reply, $mt_type, $service, $mtsid);
        break;
    default:
        print "undefined carrier";
}

Somehow other PHP function after this switch is not executed. Is this switch behaviour or something I forget?

A: Yes, the function inside the case fail to insert to DB. Already fixed it and now it works. Thanks for the clue @FirstOne


text:
Q: Mocking a dependent property with Moq If I have a class that has a dependency that is resolved via property injection, is it possible to Mock the behavior of that property using Moq?
e.g.
    public class SomeClass
     {
        //empty constructor
        public SomeClass() {}

        //dependency
        public IUsefuleService Service {get;set;}

        public bool IsThisPossible(Object someObject)
        {
           //do some stuff

           //I want to mock Service and the result of GetSomethingGood
           var result = Service.GetSomethingGood(someObject);
        }

     }

So, SomeClass is under test and I am trying to figure out if I can mock the behavior of IUsefulService with Moq so when I test IsThisPossible and the line using the service is hit, the mock is used...

A: I may be misunderstanding and oversimplifying the question, but I think code below should work. Since you have the Service property as a public property, you can just mock IUsefulService, new up SomeClass, and then set the Service property on SomeClass to your mock.
using System;
using NUnit.Framework;
using Moq;

namespace MyStuff
{
    [TestFixture]
    public class SomeClassTester
    {
        [Test]
        public void TestIsThisPossible()
        {
            var mockUsefulService = new Mock<IUsefulService>();
            mockUsefulService.Setup(a => a.GetSomethingGood(It.IsAny<object>()))
                .Returns((object input) => string.Format("Mocked something good: {0}", input));

            var someClass = new SomeClass {Service = mockUsefulService.Object};
            Assert.AreEqual("Mocked something good: GOOD!", someClass.IsThisPossible("GOOD!"));
        }
    }

    public interface IUsefulService
    {
        string GetSomethingGood(object theObject);
    }

    public class SomeClass
    {
        //empty constructor
        public SomeClass() { }

        //dependency
        public IUsefulService Service { get; set; }

        public string IsThisPossible(Object someObject)
        {
            //do some stuff

            //I want to mock Service and the result of GetSomethingGood
            var result = Service.GetSomethingGood(someObject);
            return result;
        }
    }
}

Hope that helps. If I'm missing something let me know and I'll see what I can do.


text:
Q: Javascript fetch is calling backend twice I have backend app written in java ee and jersey. When I posting data to my rest endpoint, using JavaScript Fetch API I see that the filter is fired twice. Once it haven't authorization header, second it have. When I try open my site from web browser then this filter is called only once. Why this happened. Maybe it's because of CORS?
below my logs from single post both printed from the same filter.
 http://localhost:8080/BlogRest/controller/endpoint/|#]
  Key=host, value=localhost:8080|#]
  Key=origin, value=http://localhost:3000|#]
  Key=access-control-request-method, value=POST|#]
  Key=content-length, value=0|#]
  Key=access-control-request-headers, value=authorization,content-type|#]
  Key=connection, value=keep-alive|#]
  Key=accept, value=*/*|#]
  Key=user-agent, value=user agent data|#]
  Key=referer, value=http://localhost:3000/|#]
  Key=accept-language, value=pl-pl|#]
  Key=accept-encoding, value=gzip, deflate|#]

second call
  http://localhost:8080/BlogRest/controller/endpoint/|#]
  Key=host, value=localhost:8080|#]
  Key=origin, value=http://localhost:3000|#]
  Key=content-type, value=application/json|#]
  Key=accept-language, value=pl-pl|#]
  Key=accept-encoding, value=gzip, deflate|#]
  Key=connection, value=keep-alive|#]
  Key=accept, value=*/*|#]
  Key=user-agent, value=user agent data|#]
  Key=authorization, value=Bearer token|#]
  Key=referer, value=http://localhost:3000/origin|#]
  Key=content-length, value=15|#]

A: There are two requests because of CORS. One request method is OPTIONS, and when it is preformed then starts expected POST request. OPTIONS request doesn't call the endpoint, it just get te server configuration. So I filtered in my Java filter request by method using HttpServletRequest getMethod().
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest requ = (HttpServletRequest) request;

        if (requ.getMethod().toLowerCase().equals(HttpMethod.OPTIONS)) {
            chain.doFilter(request, response);
            return;
        }

        //do something on not options method.

        chain.doFilter(request, response);

    }


text:
Q: Managed Package Patch: Is new label creation allowed It's mentioned that addition of new artifacts is not allowed in the scope of patch changes for managed package. The question here is - does label creation considered to be an addition of new artifact? I'm not sure, because from metadata perspective it's just the same file being edited.

A: The creation of new anythings in a patch is prohibited, including a label. Just because they all happen to reside in the same metadata file, does not mean they are all considered one unit. If that were true, you could add new fields to an existing object, and it wouldn't violate the "new artifact" rule, which is equally untrue. To determine if something would be allowed, simply ask yourself this question: "Do the number of elements that would appear in the package manifest change?" If so, it's not allowed.

A: You might find the following two resources useful here:

*

*"Understanding Packages" which explains package components (the things that @sfdcfox is discussing) which cannot be added or deleted in a patch, and describes what is upgradeable and what is not in the context of Managed and Unmanaged packages.

*ISVForce guide, specifically the section on "Components available in Managed Packages", which covers what is and what is not upgradeable in a patch release.


text:
Q: Tool to Identifying Global Variables in VB.NET Is there an automated tool for VB.Net that will identify all global variables in a project?
Short of that, is there any scripts that can be used that will facilitate a manual review of global variables?
There seems to be tools for C/C++, but not for VB.Net:

Tools to find global/static variables in C codebase
Is there a tool to list global variables used and output by a C function?

EDIT:
My current approach uses the following VS REGEX searches:
For finding global variables:
~(Private:b+)Shared:b+:i:b+As:b+

For finding global properties:
~(Private:b+)Shared:b+(~(ReadOnly:b+):i:b+)@Property:b+:i([(][)]|[]):b+As:b+

A: fxCop might help, but you might need to write a plugin for that particular function.
Also, ndepend (Using the CQL "code query langauge") I'm pretty sure will give you a report or globals (and a whole lot more).

A: What are you calling a "global variable"?  a variable defined as Shared (private or otherwise) isn't 'global' at all.
Really, the only 'global' variables left in vb.net are declared as public in a module