text:
Q: Sorting sub-queries in SQL I've been trying to a query working in SQL 2012 which I'm almost certain I am over complicating
I have a table which stores an order number, item numbers (multiple per order), status codes (multiple per item) and a timestamp
So basically something like this
Order Item Status
1     1    1
1     1    2

2     1    1
2     1    2
2     1    3

3     1    3
3     2    1
3     2    2

Within my query (using this table as the example), I need see the following 1 entry for each line and item but only showing the highest available status... BUT not if the status is 3
So in this case, I'd want to see
Order Item Status
1     1    2
3     2    2

The issue I had is that the query itself works... but it returns the FIRST status code it finds. Not the highest one. So I end up with
Order Item Status
1     1    1
3     2    1

Here's the full expanded code snippet
with summary as (
select a.order_no as order_no, a.item_no as item_no, a.timestamp as timestamp,
max(a.status_code) as status_code, row_number() over (partition by order_no
order by item_no asc) as rn
from db.ordhist a
where a.order_no > 120400000 and a.order_no < 120800000
and a.timestamp < Dateadd(DD,-3,GETDATE() )
and a.status_code >= 133
and not exists (
select b.order_no, b.item_no
from db.ordhist b
where b.status_code in (137,170,201,999)
and b.order_no = a.order_no
and b.item_no = a.item_no)
and not exists (
select c.order_no
from db.ordhist c
where c.status_code = 6
and c.order_no = a.order_no)
group by a.order_no, a.item_no, a.timestamp)
select * from summary where rn = 1

A: I think you don't need ROW_NUMBER just use a GROUP BY with HAVING MAX([Status])<>3:
    SELECT  [Order],[Item],MAX([Status])
    FROM Table_Name
    GROUP BY [Order],[Item]
    HAVING MAX([Status])<>3

A: Ok I think I may have answered my own question.... by removing the grouping within the "summary" and doing grouping in the final results query instead
-- Produced (or higher) but not Delivery Noted --
with summary as (
select a.order_no as order_no, a.item_no as item_no, a.timestamp as timestamp, a.status_code as status_code
from db.ordhist a
where a.order_no > 120400000 and a.order_no < 120800000
and a.timestamp < Dateadd(DD,-3,GETDATE() )
and a.status_code >= 133
and not exists (
select b.order_no, b.item_no
from db.ordhist b
where b.status_code in (137,170,201,999)
and b.order_no = a.order_no
and b.item_no = a.item_no)
and not exists (
select c.order_no
from db.ordhist c
where c.status_code = 6
and c.order_no = a.order_no))
select order_no, item_no, timestamp, max(status_code) from summary
group by order_no, item_no, timestamp
order by status_code


text:
Q: Query for Programs Returns Security Exception When I try to query the Programs database by anything other than channel or program id I get the following exception:
java.lang.SecurityException: Selection not allowed for content://android.media.tv/program
    at android.os.Parcel.readException(Parcel.java:1683)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
    at android.content.ContentResolver.query(ContentResolver.java:530)
    at android.content.ContentResolver.query(ContentResolver.java:472)

Note that I can add and delete programs, so I think permissions are correctly set in the manifest file.
The following sample code tries to query by program title, but the above exception is thrown.
Uri uri = TvContract.Programs.CONTENT_URI;

Cursor cursor = null;
try {
    String mSelectionClause = TvContract.Programs.COLUMN_TITLE + " = ?";
    String[] mSelectionArgs = { "Test title" };
    cursor = resolver.query(uri, Program.PROJECTION, mSelectionClause, mSelectionArgs, null);
    if (cursor == null || cursor.getCount() == 0) {
        Log.d(TAG, "No programs found for 'Test title'");
        return programs;
    }
    Log.d(TAG, cursor.getCount() + " programs found for 'Test tilte'");
} catch (Exception e) {
    Log.w(TAG, "Unable to get programs for 'Test title'", e);
} finally {
    if (cursor != null) {
        cursor.close();
    }
}

Is it not possible to query by any column?

A: The TvProvider is not open for selections. You can add/update/delete but you cannot create custom queries. You will need to use the TvContractCompat to build your query URIs and evaluate the results.
context.getContentResolver()
    .query(TvContractCompat.buildChannelUri(channelId), null, null, null, null);

or for programs
context.getContentResolver()
    .query(TvContractCompat.buildProgramsUriForChannel(channelId), null, null, null, null);

and for a specific program
context.getContentResolver()
    .query(TvContractCompat.buildProgramUri(programId), null, null, null, null);

For your example you should query for the programs in your channels and search for the title.
try (Cursor cursor = context.getContentResolver()
                      .query(
                TvContractCompat.buildProgramsUriForChannel(channelId),
                null, null, null, null)) {
    if (cursor != null && cursor.moveToNext()) {
        Program program = Program.fromCursor(cursor);
        if( "Test Title".equals(program.getTitle()) {
            // Do stuff...
        }
    }
}

Reference:
https://developer.android.com/training/tv/discovery/recommendations-channel.html#best_practices

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular & Typescript: Replace value if it matches a given string I have an app that was written in angular and its purpose is to display metadata values of several items coming from a database. My goal is to rewrite the output of one metadatavalue, if it matches a given string (for example: If the metadatavalue matches "CC-BY-ND" it should output a link to the Creative Commons Website instead).
This is my Typescript-File ("metadata-values.component.ts"):
import { Component, Input } from '@angular/core';
import { MetadataValue } from '../../../core/shared/metadata.models';

/**
 * This component renders the configured 'values' into the ds-metadata-field-wrapper component.
 * It puts the given 'separator' between each two values.
 */
@Component({
  selector: 'ds-metadata-values',
  styleUrls: ['./metadata-values.component.scss'],
  templateUrl: './metadata-values.component.html'
})
export class MetadataValuesComponent {

  /**
   * The metadata values to display
   */
  @Input() mdValues: MetadataValue[];
  /**
   * The seperator used to split the metadata values (can contain HTML)
   */
  @Input() separator: string;

  /**
   * The label for this iteration of metadata values
   */
  @Input() label: string;

}

And this is my html file ("metadata-values.component.html"):
<ds-metadata-field-wrapper [label]="label | translate">

        {{mdValue.value}}

</ds-metadata-field-wrapper>

So basically I want to check if {{mdValue.value}} matches for example "CC-ND-BY" and replace the output with something else. Unfortunately my understanding of Typescript is very limited, so I would very much appreciate some help with my problem. :-( Thanks in advance to anyone reading this!

A: You can use indexOf on your string to see if it returns a value greater than -1. -1 being the default return of indexOf if there is no match. You can then combine this with a custom pipe, which might be overkill, or just do a basic method inside of your component like so:
translateValue(value: string) {

   //negative case.
   if(value.indexOf("whateveryouarelookingfor") == -1)
      return value;

   return "your changed value";
}

then in your HTML your {{mdValue.value}} turns into {translateValue(mdValue.value)}}
Edit: Documentation for string.indexOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Edit 2:
As mentioned by Hassan, a Pipe would be a preferred approach. The way to do it would be as follows:

*

*Create a pipe and make sure you decorate it as such

*Add this pipe in the module for which your component belongs to

*call this pipe in the html

Working stackblitz:
https://stackblitz.com/edit/angular-njqyal?file=src/app/pipe/translate.pipe.ts
So then after you make your pipe your html will look like so: {{mdValue.value | yourPipeName}}

A: You can directly check for the string match in your HTML template. For example
<ds-metadata-field-wrapper [label]="label | translate">

        {{ mdValue.value === 'CC-ND-BY' ? 'Value Matches String': mdValue.value }}

</ds-metadata-field-wrapper>

This is a very simple example considering you only want to match with a single string. I hope this can give you the guide to building more complex logic
Also, try to avoid calling a function directly in your HTML template. Performance wise it will run multiple times on every change detection i.e. in the answer given translateValue() will work but it's not the best approach.
The better approach would be to create a PIPE and use it or directly add your logic in the HTML template like I did in the example above.


text:
Q: twitter bootstrap typeahead (method 'toLowerCase' of undefined) I am trying to use twitter bootstrap to get the manufacturers from my DB.
Because twitter bootstrap typeahead does not support ajax calls I am using this fork:
https://gist.github.com/1866577
In that page there is this comment that mentions how to do exactly what I want to do. The problem is when I run my code I keep on getting:

Uncaught TypeError: Cannot call method 'toLowerCase' of undefined

I googled around and came tried changing my jquery file to both using the minified and non minified as well as the one hosted on google code and I kept getting the same error.
My code currently is as follows:
$('#manufacturer').typeahead({
    source: function(typeahead, query){
        $.ajax({
            url: window.location.origin+"/bows/get_manufacturers.json",
            type: "POST",
            data: "",
            dataType: "JSON",
            async: false,
            success: function(results){
                var manufacturers = new Array;
                $.map(results.data.manufacturers, function(data, item){
                    var group;
                    group = {
                        manufacturer_id: data.Manufacturer.id,
                        manufacturer: data.Manufacturer.manufacturer
                    };
                    manufacturers.push(group);
                });
                typeahead.process(manufacturers);
            }
        });
    },
    property: 'name',
    items:11,
    onselect: function (obj) {

    }
});

on the url field I added the

window.location.origin

to avoid any problems as already discussed on another question
Also before I was using $.each() and then decided to use $.map() as recomended Tomislav Markovski in a similar question
Anyone has any idea why I keep getting this problem?!
Thank you

A: In my case, I was getting this exact error, and it turned out that the version of Bootstrap I was using (2.0.4) did not support passing in a function to the source setting.
Upgrading to Bootstrap 2.1.1 fixed the problem.

A: UPDATED / REVISED LOOK AT THE ISSUE:  The error you mentioned "Cannot call method 'toLowerCase' of undefined" occurred to me when I used the original Typeahead extension in bootstrap that does not support AJAX. (as you have found) Are you sure that the original typeahead extension isn't loading, instead of your revised one?
I have been sucessfully using this Gist of typeahead that is a slight variation on the one you mention. Once I switched to that Gist and confirmed that the input data was good (testing that the input was a string array in an JS object, the issue went away.
Hope this helps

Original answer:
The reason the error occurs is because the value passed into the typeahead matcher function is undefined. That is just a side effect to the real issue which occurs somewhere between your input and that matcher function. I suspect the 'manufacturers' array has a problem. Test it first to verify you have a valid array.
// It appears your array constructor is missing ()
// try the following in your binding code:
var manufacturers = new Array();

Here is what I am using to bind the input to typeahead. I confirmed that it works with your modified typeahead fork.
My HTML:
<!-- Load bootstrap styles -->
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
...

<input type="text" class="typeahead" name="Category" id="Category" maxlength="100" value="" />

...
<!-- and load jQuery and bootstrap with modified typeahead AJAX code -->
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="bootstrap-modified-typeahead.js" type="text/javascript"></script>

My binding JavaScript code:
// Matches the desired text input ID in the HTML
var $TypeaheadInput = $("#Category");

// Modify this path to your JSON source URL
// this source should return a JSON string array like the following:
// string[] result = {"test", "test2", "test3", "test4"}
var JsonProviderUrl = "../CategorySearch";

// Bind the input to the typeahead extension
$TypeaheadInput.typeahead({
    source: function (typeahead, query) {
        return $.post(JsonProviderUrl, { query: query }, function (data) {
            return typeahead.process(data);
        });
    }
});

A: In my case I had null values in my source array causing this error.
Contrived example:
source : ["item 1", "item 2", null, "item 4"]

A: Typeahead expect a list of string as source
$('#manufacturer').typeahead({
    source : ["item 1", "item 2", "item 3", "item 4"]
})

In your case you want to use it with a list of objects. This way you'll have to make some changes to make it works
This should works :
$('#manufacturer').typeahead({
    source: function(typeahead, query){
        $.ajax({
            url: window.location.origin+"/bows/get_manufacturers.json",
            type: "POST",
            data: "",
            dataType: "JSON",
            async: false,
            success: function(results){
                var manufacturers = new Array;
                $.map(results.data.manufacturers, function(data){
                    var group;
                    group = {
                        manufacturer_id: data.Manufacturer.id,
                        manufacturer: data.Manufacturer.manufacturer,

                        toString: function () {
                            return JSON.stringify(this);
                        },
                        toLowerCase: function () {
                            return this.manufacturer.toLowerCase();
                        },
                        indexOf: function (string) {
                            return String.prototype.indexOf.apply(this.manufacturer, arguments);
                        },
                        replace: function (string) {
                            return String.prototype.replace.apply(this.manufacturer, arguments);
                        }
                    };
                    manufacturers.push(group);
                });
                typeahead.process(manufacturers);
            }
        });
    },
    property: 'manufacturer',
    items:11,
    onselect: function (obj) {
        var obj = JSON.parse(obj);

        // You still can use the manufacturer_id here
        console.log(obj.manufacturer_id);

        return obj.manufacturer;
    }
});

A: Your manufacturer objects don't have a "name" property, you should change
property: 'name',

to
property: 'manufacturer',

A: Have you tried using mapping variables like example below, you need to use this when you got more then one property in your object;
source: function (query, process) {
        states = [];
        map = {};

        var data = [
            {"stateCode": "CA", "stateName": "California"},
            {"stateCode": "AZ", "stateName": "Arizona"},
            {"stateCode": "NY", "stateName": "New York"},
            {"stateCode": "NV", "stateName": "Nevada"},
            {"stateCode": "OH", "stateName": "Ohio"}
        ];

        $.each(data, function (i, state) {
            map[state.stateName] = state;
            states.push(state.stateName);
        });

        process(states);
    }

A: I stumbled upon this issue a while ago. I advice you to recheck configuration where you are including typeahead libraries (via main.js, app.js or config.js).
Otherwise, you can overwrite the latest Bootstrap version to your application library.

A: Try this code:
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
    char = this.charCodeAt(i);
    hash = ((hash<<5)-hash)+char;
    hash = hash & hash; // Convert to 32bit integer
}
return hash;
};

var map_manufacter, result_manufacters;
$('#manufacturer').typeahead({
source: function(typeahead, query){
    $.ajax({
        url: window.location.origin+"/bows/get_manufacturers.json",
        type: "POST",
        data: "",
        dataType: "JSON",
        async: false,
        success: function(results){

            result_manufacter = [], map_manufacters = {};
            $.each(results.data.manufacturers, function(item, data){
                map_manufacters[data.Manufacturer.manufacturer.hashCode()] = data;
                result_manufacters.push(data.Manufacter.manufacter);
            });
            typeahead.process(result_manufacters);
        }
    });
},
property: 'name',
items:11,
onselect: function (obj) {
    var hc = obj.hashCode();
    console.log(map_manufacter[hc]);
}

});

A: I solved this problem only updating the file bootstrap3-typeahead.min.js to the file in https://github.com/bassjobsen/Bootstrap-3-Typeahead/blob/master/bootstrap3-typeahead.min.js
I think most people can solve this way.


text:
Q: Debug Log in RESTResource My problem is very similar to this . But adding necessary user(Site owner) to Debug Logs doesn't help me. I don't see any logs at all. But webservice works well.

A: Looks like the webservice / rest service is hosted as public using Sites.
I guess while calling the webservice from your client, you just need set the cookie. Something like
http.setHeader('Cookie', 'debug_logs=debug_logs,domain=.force.com')

The post Adrian linked has more details about this update. Moreover check if you can set the Traced Entity Type as your Rest Class and see if puts some log out.


text:
Q: Javascript: Sort multi dimensional Array based on first arrays sort results I have an array setup similar to this:
var ary1 = new Array("d", "a", "b", "c");
var ary2 = new Array("ee", "rr", "yy", "mm");

var mdAry = new Array(ary1, ary2);

ary1 and ary2 indexes are info related to each other in the grand scheme of things.
d ee
a rr
b yy
c mm

I can sort() ary1 and get:
a
b
c
d

but if I sorted ary2 independently I would get:
ee
mm
rr
yy

which visually breaks ary1 and ary2 connections when listed out. Can I retrieve ary1's sorted solution and apply that to ary2? I want to get this:
a rr
b yy
c mm
d ee

If not, could mdAry be sorted so that it applies mdAry[0] sorted solution to the remaining indicies?

A: If your array items are related, then store them together:
var arr = [
  {x: 'd', y: 'ee'},
  {x: 'a', y: 'rr'},
  {x: 'b', y: 'yy'},
  {x: 'c', y: 'mm'}
];

arr.sort(function(a, b) {
  if (a.x != b.x) {
      return a.x < b.x ? -1 : 1;
  }
  return 0;
});

A: One way to do this is to transform the data structure to something that can be sorted more easily, and then transform it back after
var ary1  = ["d", "a", "b", "c"],
    ary2  = ["ee", "rr", "mm", "yy"]
    mdAry = [ary1, ary2];

// convert to form [[d, ee], [a, rr], ..]
var tmp = mdAry[0].map(function (e, i) {
    return [e, mdAry[1][i]];
});
// sort this
tmp.sort(function (a, b) {return a[0] > b[0];});
// revert to [[a, b, ..], [rr, mm, ..]]
tmp.forEach(function (e, i) {
    mdAry[0][i] = e[0];
    mdAry[1][i] = e[1];
});
// output
mdAry;
// [["a", "b", "c", "d"], ["rr", "mm", "yy", "ee"]]

A: Just to add yet another method in there, you could get a sort "result" from the first array and apply that to any other related list:
function getSorter(model) {
    var clone = model.slice(0).sort();
    var sortResult = model.map(function(item) { return clone.indexOf(item); });

    return function(anyOtherArray) {
        result = [];
        sortResult.forEach(function(idx, i) {
            result[idx] = anyOtherArray[i];
        });
        return result;
    }
}

Then,
var arr = ["d", "a", "b", "c"];
var arr2 = ["ee", "rr", "yy", "mm"];

var preparedSorter = getSorter(arr);
preparedSorter(arr2);
//=> ["rr", "yy", "mm", "ee"];

Or,
multidimensional = [arr, arr2];
multidimensional.map(getSorter(arr));
// => [["a", "b", "c", "d"], ["rr", "yy", "mm", "ee"]]

A: In your example the result should be (if I understand correctly)
a rr
b mm
c yy
d ee

So this one should to the job:
Array.prototype.sortRelated = function(related) {
    var clone = this.slice(0),
        sortedRelated = [];
    clone.sort();

    for(var i = 0; i < this.length; i ++) {
        sortedRelated[clone.indexOf(this[i])] = related[i];
    }

    return sortedRelated;
}

var ary1 = new Array("d", "a", "b", "c");
var ary2 = new Array("ee", "rr", "mm", "yy");

var sorted = ary1.sortRelated(ary2);

Working demo here: http://jsfiddle.net/cwgN8/

A: You could "merge" them into a single object with two properties, sort by the first one, and then separate back in the end (see demo here):
function sortBoth(ary1, ary2) {
    var merged = [];
    for (var i=0; i < ary1.length; i++) merged.push({'ary1': ary1[i], 'ary2': ary2[i]});
    merged.sort(function(o1, o2) { return ((o1.ary1 < o2.ary1) ? -1 : ((o1.ary1 == o2.ary1) ? 0 : 1)); });
    for (var i=0; i < merged.length; i++) { ary1[i] = merged[i].ary1; ary2[i] = merged[i].ary2; }
}

var ary1 = new Array("d", "a", "b", "c");
var ary2 = new Array("ee", "rr", "mm", "yy");

console.log(ary1);
console.log(ary2);

sortBoth(ary1, ary2);

console.log(ary1);
console.log(ary2);

Output:
[ "d",  "a",  "b",  "c"]
["ee", "rr", "mm", "yy"]
[ "a",  "b",  "c",  "d"]
["rr", "mm", "yy", "ee"]


text:
Q: WithUrl() not found in Core 3 client My .NET SignalR client code not working any more in Core 3 (WPF):
string hubAddress = "https://localhost:44329/Hub";
HubConnection hub = new HubConnectionBuilder().WithUrl(hubAddress).Build(); // WithUrl not found

MS document said it is there
Anyone know how to fix this?

A: Found a solution:  make sure project referencing Microsoft.AspNetCore.SignalR.Client, but not Microsoft.AspNetCore.SignalR.Client.Core.

A: Remove the dependency Microsoft.AspNetCore.SignalR.Client.Core from your app and then add
Using Package Manager Console
Install-Package Microsoft.AspNetCore.SignalR.Client -Version 6.0.0

Using .Net CLI
dotnet add package Microsoft.AspNetCore.SignalR.Client --version 6.0.0

It will fix your issue


text:
Q: JSF 2 facelets  in template and page I have the following template (masterLayout.xhtml):
<!DOCTYPE html>

    <f:view contentType="text/html">
        <ui:insert name="metadata"/>
        <h:head>
            <title><ui:insert name="windowTitle"/> | MySite</title>
        </h:head>

        <h:body>

                    <ui:insert name="header">
                        <ui:include src="/WEB-INF/templates/header.xhtml"/>
                    </ui:insert>

                    <ui:insert name="content"/>

                    <ui:insert name="footer">
                        <ui:include src="/WEB-INF/templates/footer.xhtml"/>
                    </ui:insert>

        </h:body>
    </f:view>

and page that uses it (search.xhtml):

    <h:head>
        <title></title>
    </h:head>
    <h:body>
        <ui:composition template="/WEB-INF/templates/masterLayout.xhtml">
            <ui:define name="metadata">
                <f:metadata>
                    <f:viewParam name="address" value="#{searchBean.address}"/>
                    <f:event type="preRenderView" listener="#{userSessionBean.preRenderViewCookieLogin(e)}"/>
                    <f:event type="preRenderView" listener="#{searchBean.preRenderView(e)}"/>
                </f:metadata>
            </ui:define>
            <ui:define name="windowTitle">#{searchBean.address}</ui:define>

            <ui:define name="content">

            </ui:define>
        </ui:composition>
    </h:body>

The problem is that I want to place the call to userSessionBean.preRenderViewCookieLogin(e) in the template because there are many other pages. This method checks that the user is logged in (according to session state) and, if not, checks that a cookie is available which can be used to log the user in and, if so (and if valid), logs the user in automatically. The system works in the code above, but when I try to push this into the template, my view parameters are no longer being set.
Here's the modified version of the above, with userSessionBean.preRenderViewCookieLogin(e) pushed up to the template.
masterLayout.xhtml:
<!DOCTYPE html>

    <f:view contentType="text/html">
        <f:metadata>
            <f:event type="preRenderView" listener="#{userSessionBean.preRenderViewCookieLogin(e)}"/>
            <ui:insert name="metadata"/>
        </f:metadata>
        <h:head>
            <title><ui:insert name="windowTitle"/> | MySite</title>
        </h:head>

        <h:body>

                    <ui:insert name="header">
                        <ui:include src="/WEB-INF/templates/header.xhtml"/>
                    </ui:insert>

                    <ui:insert name="content"/>

                    <ui:insert name="footer">
                        <ui:include src="/WEB-INF/templates/footer.xhtml"/>
                    </ui:insert>

        </h:body>
    </f:view>

search.xhtml

    <h:head>
        <title></title>
    </h:head>
    <h:body>
        <ui:composition template="/WEB-INF/templates/masterLayout.xhtml">
            <ui:define name="metadata">
                <f:viewParam name="address" value="#{searchBean.address}"/>
                <f:event type="preRenderView" listener="#{searchBean.preRenderView(e)}"/>
            </ui:define>
            <ui:define name="windowTitle">#{searchBean.address}</ui:define>

            <ui:define name="content">

            </ui:define>
        </ui:composition>
    </h:body>

Notice that I've moved the <f:metadata/> tag to the template. That alone is the problem as removing userSessionBean.preRenderViewCookieLogin(e) makes no difference. I also tried a variation on the code that worked, which was to just move userSessionBean.preRenderViewCookieLogin(e) into the template which means it can't be inside the <f:metadata/> tag. In this case, that method executed after all the view parameters had been set and searchBean.preRenderView(e) called. I want userSessionBean.preRenderViewCookieLogin(e) to be called before any page's preRenderView(e) is called, not after. And just for fun I tried putting an <f:metadata/> around userSessionBean.preRenderViewCookieLogin(e), which called this method, but didn't set the view parameters.
So, I would like to know:

*

*Why is this happening and is there a way to fix it?

*Is there a better way to ensure the same method is called for each page before anything else?

Edit:
I just tried something else - a phase event:
<f:view contentType="text/html" beforePhase="#{userSessionBean.beforePhase(e)}">
This is in masterLayout.xhtml. It is not being called at all; not for any phase.
Edit:
Removed the e (damn you NetBeans!):
<f:view contentType="text/html" beforePhase="#{userSessionBean.beforePhase}">
This is only called before the render response phase, which of course means it's called after the preRenderView event is raised.

A:
Why is this happening and is there a way to fix it?

From the <f:metadata> tag documentation (emphasis of 2nd paragraph is mine):

Declare the metadata facet for this view. This must be a child of the <f:view>. This tag must reside within the top level XHTML file for the given viewId, or in a template client, but not in a template. The implementation must insure that the direct child of the facet is a UIPanel, even if there is only one child of the facet. The implementation must set the id of the UIPanel to be the value of the UIViewRoot.METADATA_FACET_NAME symbolic constant.

So, it really has to go in the top view, not in the template.

Is there a better way to ensure the same method is called for each page before anything else?

In your particular case, store the logged-in user as a property of a session scoped managed bean instead of a cookie and use a filter on the appropriate URL pattern to check it. Session scoped managed beans are in the filter available as HttpSession attributes. Homegrown cookies are unnecessary as you're basically reinventing the HttpSession here. Unless when you want a "remember me" facility, but this should not be solved this way. Do it in a filter as well.
See also:

*

*Prevent accessing restricted page without login in Jsf2

A: I got this working using a PhaseListener instead.
public class CookieLoginPhaseListener implements PhaseListener
{
    @Override
    public void beforePhase(PhaseEvent event)
    {
    }

    @Override
    public void afterPhase(PhaseEvent event)
    {
        UserSessionBean userSessionBean = Util.lookupCdiBean("userSessionBean");
        userSessionBean.handleAuthCookie();
    }

    @Override
    public PhaseId getPhaseId()
    {
        return PhaseId.RESTORE_VIEW;
    }
}

and the little bit of bean lookup magic is here:
public static <T> T lookupCdiBean(String name)
{
    return (T) FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{" + name + "}", Object.class);
}

Thanks to @BalusC for this: JSF - get managed bean by name. Since I'm using CDI, I can't use the more declarative @ManagedProperty option. Not a big deal though.


text:
Q: Javascript / Flask - No 'Access-Control-Allow-Origin' header is present on the requested resource I have a FlaskAPI back-end and a Vue front-end and I am trying to send responses between the two. I am having an issue with the implementation of FlaskCors. This module should handle 'OPTIONS' as well from what I can tell, however I am having issues still. Any help would be appreciated. The documentation does not say to utilize the '@cross-origin' decorator if I choose to allow everything.
Javascript error:

Access to XMLHttpRequest at 'http://localhost:5000/login' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.

Flask Runner
#! /usr/bin/python3.6
from caffeine import create_app
import os

app = create_app()

# app.secret_key = os.environ.get("SECRET_KEY")

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)

init.py
import os
from pathlib import Path

from flask_api import FlaskAPI
from flask_cors import CORS

from caffeine.config import Config

def create_app():
    """Instantiates and initialize the Flask application"""
    app = FlaskAPI(__name__)
    app.config.from_object(Config)
    CORS(app)

    from caffeine.routes.bp_auth import auth

    app.register_blueprint(auth)

    return app

Flask Config:
class Config:
    """Base configuration."""

    API_VERSION = "1.0.0"
    SECRET_KEY = os.environ.get("SECRET_KEY")
    CORS_HEADERS = "Access-Control-Allow-Origin"

Flask Auth Blueprint:
@auth.route("/login", methods=["GET", "POST", "OPTIONS"])
def login():
    """
    present the 'login-page' for entering LDAP credentials to be validated and added to the database

    if user is already authenticated, they will be routed to the home route (routes.py)

    :return: user login-in UI view
    """

    if request.method == "POST":
        user_sso = request.data["sso"].strip()

        access_token = encode_access_token(user_sso)

        response = jsonify(
            status="success",
            message="successfully logged in",
            access_token=access_token,
            token_type="bearer",
            expires_in=get_token_expire_time(),
        )
        response.status_code = HTTPStatus.CREATED
        response.headers["Cache-Control"] = "no-store"
        response.headers["Pragma"] = "no-cache"

        return response

A: i've had a similar problem with react, this is how i could solve it on my app:
class config:
CORS_ALLOW_CREDENTIALS = True
init.py
...
from flask_cors import CORS

cors = CORS()

def create_app():
    ...
    cors.init_app(app=app, supports_credentials=True)
    ...


text:
Q: Export/Save jLabel contents to new folder I have a program that perform two functions: Upload image, Export image.
after uploading an image it will shown in a jLabel,

*

*my question : is there any way to save this image and export it to a new folder on desktop or any place the user choose?

*for example, if I uploaded an image and its displayed on jLabel, when I press the Export button the program should open a dialog window asks me to choose a name for a folder and save the image in it.
Thanks in advance!

A: It sure is possible!
Take a look a JFileChooser, ImageIcon, and ImageIO and specifically search around for tutorials on using ImageIO


text:
Q: PyQgis Exporting Print Layout: "ERROR 6: The PNG driver does not support update access to existing datasets." I am trying to export a .tif loaded into a pre-configured print layout template and further exported as .png
def openLayer(project, fp, basename, vector=True):
  layer = QgsVectorLayer(fp, basename) if vector else QgsRasterLayer(fp, basename)
  if not layer.isValid():
    print("Layer failed to load!")

  project.addMapLayer(layer)
  return layer

def openTemplate(layout, templatePath):
  template = open(templatePath, 'rt')
  content = template.read()
  template.close()
  doc = QDomDocument()
  doc.setContent(content)
  context = QgsReadWriteContext()
  if not layout.loadFromTemplate(doc, context):
    print('unable to load template: {}'.format(templatePath))

def export(layout, dest, filename):
  dest = os.path.join(dest, filename + '.png') #FIXME: set filetype in config
  export = QgsLayoutExporter(layout)
  export.exportToImage(dest, QgsLayoutExporter.ImageExportSettings())

# initialize
QGS = QgsApplication([], False)
QGS.initQgis()

# create project & layout
project = QgsProject()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

# load layers
baseLayer = openLayer(project, r'C:\Users\X\Desktop\atlas\ar_base.tif', 'ar_base', vector=False)

# open template
openTemplate(layout, r'C:\Users\X\Desktop\atlas\test.qpt')

# export
print('exporting . . .')
export(layout, r'C:\Users\X\Desktop\atlas', 'test')

The snippet successfully creates a .png with the image inside. However I get the following error:
ERROR 6: The PNG driver does not support update access to existing datasets.
Would anyone know why that is? I wasn't able to find a concrete answer by searching unfortunately.

EDIT:
seems related to the PNG GDAL driver. However, there is no updating within this process but simply creation.
I can suppress the error / warning via:
from osgeo import gdal
gdal.PushErrorHandler('CPLQuietErrorHandler')

But I rather not have to.


text:
Q: Ajax + jQuery - getting successful response? Trying to practice pulling data via an API with jQuery. I watched some YouTube tutorial and I'm basically just trying to get a successful response... but I can't for the life of me get it to work..
Apart from YouTube, I'm subscribed to Codeschool and they cover ajax and json, but they don't have a real life example unfortunately... or at least not yet.
The API I'm using is My API Films - http://www.myapifilms.com/imdb.do
jsfiddle and code are below.
I guess it will be better if you get your own tokens? Many many thanks in advance.
https://jsfiddle.net/oddtbaq6/
var url = 'http://www.myapifilms.com/imdb/idIMDB?title=batman&' + token + '&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0';

$.ajax(url, {
    success: function(data) {
    console.log(data);
  },
  error: function() {
    console.log('error');
  },
  dataType: 'json',
  type: 'GET'
});

console errors:
XMLHttpRequest cannot load.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.

A: When making an AJAX request from a browser, the browser will only allow the request to be made if the target API is CORS enabled. This is done for security reasons so that if a website has a private API, that API cannot be accessed in the browser via an AJAX request from a domain other than its own. For example, mywebsite.com cannot make an AJAX request to yourapi.com unless yourapi.com designates its routes as being accessible from other domains.
I suggest finding a popular, public API that will certainly be CORS enabled. You can also run your own server to serve both your client-side code and your own api.

A: You have CORS issues:
However, you can use the https://crossorigin.me/ service.
Then, you should request: «https://crossorigin.me/http://www.myapifilms.com/imdb/idIMDB?title=batman&' + token + '&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0».
var url = "https://crossorigin.me/http://www.myapifilms.com/imdb/idIMDB?title=batman&' + token + '&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0";

A: Please, try to change like this.
var url = 'http://www.myapifilms.com/imdb/idIMDB?title=batman&' + token + '&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0';

$.ajax({
    url: 'url',
    success: function(data) {
            console.log(data);
         },
    error: function() {
        console.log('error');
    },
    dataType: 'json',
    type: 'GET'
});


text:
Q: How do I change canvas height or parent in tkinter outside of a funtion? so I'm very new to programming and especially with python, and I still don't know how to work with object oriented programming so I haven't been working with that.
I wanted to create a couple of scrollable frames in tkinter, and I didn't want to write the same code for every frame again and again, and since I don't work with object oriented programming yet I created this helper function:
def scrolled_frame(frame):

    canvas = Canvas(frame, height=550, width=root.winfo_screenwidth() - 120)
    canvas.pack(side=LEFT, fill=BOTH, expand=1)
    scrollbar = ttk.Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
    scrollbar.pack(side=RIGHT, fill=Y)
    canvas.configure(yscrollcommand=scrollbar.set)
    canvas.bind("<Configure>", lambda e: canvas.config(scrollregion=canvas.bbox(ALL)))
    second_frame = tk.Frame(canvas)
    canvas.create_window((0, 0), window=second_frame)
    return second_frame

Because I want to add another frame beneath the canvas that could be opened and closed, I want to be able to play with canvas height outside of the function. Clearly if I'm declaring canvas inside this function that I wrote, that would be impossible! So I was wondering if there's a way to declare the canvas outside the function yet set it's frame in the function.. or also if there's another solution I'd be glad to hear!
Thanks in advance!


text:
Q: Can I combine subcollection data of firestore? I have diary collection in firestore.
And in diary collection, I have likes sub-collection.
Sometimes I need data all likes regardless of diary.
In that case, Can I combine all likes sub-collection data ?
If it is not possible, so should I create one more collection of likes?


text:
Q: Как присвоить постоянное значение для новых записей в триггере? В БД нужно после добавления новой записи заменять значение в колонке на 0.
Родил следующий триггер при помощи гугла:
create or replace trigger AutoDisabled
  after insert on SCHEMA."Reason" for each row
begin
  :new. "AutoEnabled" := 0;
end;

При выполнении триггер намертво повесил Toad.
Что я сделал не так?

A:
Что я сделал не так?

*

*в коде триггера допустили синтаксические ошибки

*проигнорировали сообщения компилятора об ошибках

*не обратились за помощью к документации.

При выполнении вставки должна была появится следующая ошибка :

SQL Error: ORA-04098: trigger 'ME.AUTODISABLED' is invalid and failed re-validation

Если бы были учтены упомянутые выше пункты, получилось бы следующее:
create or replace trigger AutoDisabled
    before insert on me."Reason" for each row
begin
    :new."AutoEnabled" := 0;
end;
/
Trigger AUTODISABLED compiled

insert into "Reason" values ('Reason name 1', null)
/

1 row inserted.


text:
Q: Problema de diseño con Menu Fijo/Sticky Estoy desarrollando una plantilla básica que incluye un menu fijo (sticky).
Logré que el logo de la izquierda y los iconos de la derecha sean fijos, pero aún así, falta un fondo a ese menu para que no se diferencie con el contenido de la web del body.
Imagen de como está ahora:

Y este sería el problema que se presenta cuando se navega con ese menu:

Si logran apreciar, no hay fondo en el menu.
Acabo de subir los ficheros ya que son muchos para mostrarlos acá
https://mega.nz/#!Fp5kTQhR!Bmvts-ghpsfQLnt7zvhuE6bAXeA78IAQP677_5xrayE
Pero aún así este sería un trozo de código del menú:

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                      Toggle navigation

                    </button>

Mi Perfil

Blog

Contacto

Intenté añadir un simple background en el css pero al parecer tengo un problema con los divs.

A: Debes agregarle un color de fondo al DIV del menu (NAV)
En tu css agrega:
#tf-menu {
background-color:#ffffff;
}

A:
La barra de navegación también se puede fijar en la parte superior o inferior de la página.

Una barra de navegación fija permanece visible en una posición fija (superior o inferior) independiente del desplazamiento de la página.
La clase .fixed-top hace que la barra de navegación esté fija en la parte superior:

  ...

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  Logo

      Link

      Link

Top Fixed Navbar

A fixed navigation bar stays visible in a fixed position (top or bottom) independent of the page scroll.

Scroll this page to see the effect

Ejemplo de navbar top Bootstrap


text:
Q: Where is the admin bar instantiated? There are so many resources on how to enable, disable, change and fix the admin bar, but per a question from a student, we just want to follow the path to how it's made.
What we know:
1. The trail starts with footer.php -> wp_footer();
2. The trail ends with wp_includes/adminbar.php
What's the trail in the middle?

A: Here is the backtrace of the adminbar rendering in the home page of the backend for WordPress 4.9.2
array (
  'file' => 'wp-admin/index.php',
  'line' => 100,
  'function' => 'include',
)
array (
  'file' => 'wp-admin/admin-header.php',
  'line' => 219,
  'function' => 'do_action',
)
array (
  'file' => 'wp-includes/plugin.php',
  'line' => 457,
  'function' => 'do_action',
  'class' => 'WP_Hook',
  'type' => '->',
)
array (
  'file' => 'wp-includes/class-wp-hook.php',
  'line' => 310,
  'function' => 'apply_filters',
  'class' => 'WP_Hook',
  'type' => '->',
)
array (
  'file' => 'wp-includes/class-wp-hook.php',
  'line' => 286,
  'function' => 'wp_admin_bar_render',
)
array (
  'file' => 'wp-includes/admin-bar.php',
  'line' => 92,
  'function' => 'render',
  'class' => 'WP_Admin_Bar',
  'type' => '->',
)
array (
  'file' => 'wp-includes/class-wp-admin-bar.php',
  'line' => 263,
  'function' => '_render',
  'class' => 'WP_Admin_Bar',
  'type' => '->',
)
array (
  'file' => 'wp-includes/class-wp-admin-bar.php',
  'line' => 413,
)

and here the path on the home page
array (
  'file' => 'index.php',
  'line' => 17,
  'function' => 'require',
)
array (
  'file' => 'wp-blog-header.php',
  'line' => 19,
  'function' => 'require_once',
)
array (
  'file' => 'wp-includes/template-loader.php',
  'line' => 74,
  'function' => 'include',
)
array (
  'file' => 'wp-content/themes/storefront/page.php',
  'line' => 38,
  'function' => 'get_footer',
)
array (
  'file' => 'wp-includes/general-template.php',
  'line' => 76,
  'function' => 'locate_template',
)
array (
  'file' => 'wp-includes/template.php',
  'line' => 647,
  'function' => 'load_template',
)
array (
  'file' => 'wp-includes/template.php',
  'line' => 688,
  'function' => 'require_once',
)
array (
  'file' => 'wp-content/themes/storefront/footer.php',
  'line' => 36,
  'function' => 'wp_footer',
)
array (
  'file' => 'wp-includes/general-template.php',
  'line' => 2630,
  'function' => 'do_action',
)
array (
  'file' => 'wp-includes/plugin.php',
  'line' => 457,
  'function' => 'do_action',
  'class' => 'WP_Hook',
  'type' => '->',
)
array (
  'file' => 'wp-includes/class-wp-hook.php',
  'line' => 310,
  'function' => 'apply_filters',
  'class' => 'WP_Hook',
  'type' => '->',
)
array (
  'file' => 'wp-includes/class-wp-hook.php',
  'line' => 286,
  'function' => 'wp_admin_bar_render',
)


text:
Q: Headless Umbraco CMS with ASP .NET Core we have an ASP .NET Core website and would like to use Umbraco. It is my understanding there is no .Net Core version of Umbraco, therefore we would need to use a headless integration. To do this, I will need to create web api's in my project, however I am not able to use Umbraco.Web.WebApi, because there is no ASP .NET Core library, so I am assuming I need to custom create my own using the standard ASP .NET Web Api. If all these assumptions are correct, I have no idea how to begin. I was curious if there are any sample .NET Core projects that show how to create the Web Api? If these assumptions are not correct, could someone please help me better understand. Thanks!!

A: You can use the Umbraco.Web.WebApi.UmbracoApiController on your Umbraco project controllers, these would expose the information you need to run your Core app using a REST interface.
Then, from your Core application, you need to make REST calls to your previously created Umbraco controllers. It seems like this SO post should get you on the way to making those calls.

A: You are correct, Umbraco 8 requires 4.7 .net Framework rather than .net core.
If you want to self-host you can extend Umbraco 8 with either GraphQL or Head Rest Packages however these are not recently updated.
Alternatively, Umbraco offers Heart Core which is cloud only headless CMS which would work. This has a reset API and soon a Graph QL.


text:
Q: Android MediaPlayer setDataSource iOS alternative I have android implementation which sets media player data source range between 10000 bytes and 40000000 bytes:
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + "path to video file");
mMediaPlayer.setDataSource(fis.getFD(),1000,40000000);

Is there any alternative to do the same in iOS?

A: I don't think you can set the range based on bytes in iOS. But you can specify the video's playback range based on time. An example is given in this link.

A: You have to calculate it manually by the combination of the two:
// 1 Get AVAsset file size
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
// 2 now from the estimated data rate
Get Estimated data rate
so now you can have the CMTime and you can pass it accordingly.
Hope this helps.


text:
Q: Attempting to check if any of event checkboxes are checked When the name text field is changed I want to check if it contains text, the terms are accepted and 1 or more events checkbox is checked. If this is the case I want the submit button to become enabled.
I was told that this  document.querySelector('[name=event[]]:checked') !== null is the way I should check if an event checkbox is checked, however, it is the only part of the code I can't get to work.

function checkStuff(){
 if (document.getElementsByName("termsChkbx")[0].checked && document.getElementsByName("name")[0].value.length != 0 && document.querySelector('[name=event[]]:checked') !== null) {
  document.getElementsByName("submit")[0].disabled = false;
}
  else{
    document.getElementsByName("submit")[0].disabled = true;
  }
}

document.getElementsByName("termsChkbx")[0].addEventListener('change', (event) => {
checkStuff();
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">

Select Events

      Event number 1
      10.50
      <input type='checkbox' name='event[]' value='1' data-price='10.50'>

      Event number 2
      5.00
      <input type='checkbox' name='event[]' value='2' data-price='5.00'>

      <input type="radio" name="delivery" value="ticket" data-price="10">

Total Price

      Total Price <input type="text" name="total" size="12">

Name<input type="text" name="name">

Terms & conditions<input type="checkbox" name="termsChkbx">

<input type="submit" name="submit" value="Book" disabled>

</form>

A: Your selector is not right. You need to add quote around the value of your attribute selector :
document.querySelector('[name="event[]"]:checked')

function checkStuff(){
 if (document.getElementsByName("termsChkbx")[0].checked && document.getElementsByName("name")[0].value.length != 0 && document.querySelector('[name="event[]"]:checked') !== null) {
  document.getElementsByName("submit")[0].disabled = false;
}
  else{
    document.getElementsByName("submit")[0].disabled = true;
  }
}

document.getElementsByName("termsChkbx")[0].addEventListener('change', (event) => {
checkStuff();
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">

Select Events

      Event number 1
      10.50
      <input type='checkbox' name='event[]' value='1' data-price='10.50'>

      Event number 2
      5.00
      <input type='checkbox' name='event[]' value='2' data-price='5.00'>

      <input type="radio" name="delivery" value="ticket" data-price="10">

Total Price

      Total Price <input type="text" name="total" size="12">

Name<input type="text" name="name">

Terms & conditions<input type="checkbox" name="termsChkbx">

<input type="submit" name="submit" value="Book" disabled>

</form>

A: You should try removing the [] from the name attribute of your checkboxes. That might be messing up your logic.
<input type='checkbox' name='event' value='2' data-price='5.00'>

You'll also need to modify your javascript
document.querySelector('[name=event]:checked')

https://codepen.io/orunnals/pen/XWJVqVv

A: You can use some to see if any one of input with name='event[]' is checked and input with name termsChkbx are checked.

function checkStuff(){
    const submit = document.querySelector('input[type="submit"]');
    const isChecked = [...document.querySelectorAll("[name='event[]'")].some(e => e.checked) && document.querySelector('[name="termsChkbx"').checked;
    submit.disabled = !isChecked;
};

document.querySelectorAll('input[type="checkbox"]')
   .forEach(checkbox => {
        checkbox.addEventListener('change', checkStuff);
   });
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">

Select Events

            Event number 1
            10.50
            <input type='checkbox' name='event[]' value='1' data-price='10.50'>

            Event number 2
            5.00
            <input type='checkbox' name='event[]' value='2' data-price='5.00'>

            <input type="radio" name="delivery" value="ticket" data-price="10">

Total Price

            Total Price <input type="text" name="total" size="12">

Name<input type="text" name="name">

Terms & conditions<input type="checkbox" name="termsChkbx">

<input type="submit" name="submit" value="Book" disabled>

      </form>

A: The js would look like this
var checkbox2 = document.getElementByName('termsChkbx'); //Get the checkbox status

    function checkStuff() {

        if ($(checkbox2).prop('checked')) {
        //Do Stuff
        }

        else {
        //Do Stuff
        }

    }


text:
Q: nextjs console.log doesn't work inside function return function I'm playing around with nextjs
and I've trouble to debug a function like
this:
export const authInitialProps = isProtectedRoute => {
  console.log("mylog");// this works
  return ({ req, res }) => {
    console.log("inner my log", req); // this doesn't work
  };
};

Using in a page
ProfilePage.getInitialProps = async () => {
  const auth = authInitialProps(true);
  if (!typeof auth === "function") {
    const user = await getUserProfile();
    return { user };
  }
  return { user: null };
};

I never see "inner my log" both in chrome console
and in my console terminal.
What's the problem please?

A: Try this It may work:
ProfilePage.getInitialProps = async () => {
  const auth = await authInitialProps(true); // await added
  if (!typeof auth === "function") {
    const user = await getUserProfile();
    return { user };
  }
  return { user: null };
};

I think it should be async to not pass over it!


text:
Q: Xamarin error on visual studio I install xamarin on my visual studio and when i want to create a blank app project it gives error :Object refrence not set to an instance of an object.
this is out put:
enter image description here

A: Looks like you didn't install the (right) Android SDKs.
Go into Tools > Options and find the 'Xamarin' page. Then go into 'Android Settings' and check if the SDK path is found.

If these aren't filled correctly you should install them. Easiest is to download the installer from Xamarin or reinstall from Visual Studio (through add/remove applications and edit Visual Studio installation).
You can install and manage seperate SDKs by using the Android SDK manager. You can find this under Tools > Android > Android SDK manager.

In the next screen you can install the SDKs you want to use with the according emulator images, etc.


text:
Q: Dynamically change JLabel icons based on x,y of mouse click I am using NETBEANS and have several JLabels that need to display a specific icon/image based on a decision/boolean. I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one. Rather I would prefer to use the x,y as the name of the JLabel and then set icon based on the x,y. I have no problems getting the x.y but cannot seem to figure out how to do something like this (xy.setIcon(new ImageIcon(Hit)); here is my code.
/**
 * Mathematical coordinates of player1Fleet.
 * Used to realign ships from Ship Class
 * for use on game board.
 */
public void mouseClicked(MouseEvent e) {
    Launch1();
}
public void FleetP1() {
    for (Ship s : player1Fleet) {
        int size = s.getSize();

        for (int i = 0; i < size; i++) {
            player1Ships.add((((s.getXCoordinate(i) + 1) * 45) + 90) + "" + (((s.getYCoordinate(i) + 1) * 45) + 180));

        }
    }
    // Verification of Math
    System.out.println(player1Ships);
}

/**
 * Determine Hit or Miss based on location of Cross-hairs
 * for player 1/West on game board.
 * @return
 */
//public boolean setStrike1(){
public boolean Launch1() {
    w93.setIcon(null);
    player1Ships.clear();
    FleetP1();
    boolean strike1 = false;
    boolean Launch = false;
    for (int i = 0; i < this.player1Ships.size(); i++) {
        if (this.player1Ships.get(i).equals(LblCrossHairs.getX() + "" + LblCrossHairs.getY())) {
            strike1 = true;
            //break;
        }
        if (strike1) {
            strike1 = true;
            (LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit));
            //Launch = theAttack.Strike1(strike1);
            //w93.setIcon(new ImageIcon(Hit));
            URL url = this.getClass().getResource("MissleHit.au");
            AudioClip ac = Applet.newAudioClip(url);
            ac.play();
            System.out.println("HIT");
            break;
        } else {
            strike1 = false;
            (LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit));
            //w93.setIcon(new ImageIcon(Miss));
            URL url = this.getClass().getResource("MissileMiss.au");
            AudioClip ac = Applet.newAudioClip(url);
            ac.play();
            System.out.println("MISS");
        }
    }
    TxtClick.setText(LblCrossHairs.getX() + "" + LblCrossHairs.getY() + ".setIcon");
    return strike1;
}

Thank you in advance for all your help. This has been driving me crazy for the last two days

A:
I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one.

You don't have to create a separate listener. You can share the same listener with every JLabel. The basic code is:
public void mouseClicked(MouseEvent e)
{
    JLabel label = (JLabel)e.getSource();
    label.setIcon(...);
}


text:
Q: Cordova Plugin to ask for Ratings I am looking for a cordova plugin that asks for ratings similar to askingpoint.com. Basically I need a plugin that can send a popup to the user to rate the app after a specific task or amount of days using the app. Of course this needs to be for Phonegap/Cordova

A: you can check these link out...
https://github.com/pushandplay/cordova-plugin-apprate (this one is easy to set up)
http://www.joshuawinn.com/adding-rate-button-to-cordova-based-mobile-app-android-ios-etc/ (haven't used this but heard good reviews abt it)
Hope it helps.!


text: Q: Trying to create a database in PSQL from the command line I have been trying to create a simple test database from my terminal by running the command 'createdb test'. I installed PostgreSQL using brew on my Mac OS. I have attached an image of the error message I get. I also tried adjusting the pg_hba.conf file using nano from my terminal but that didn't work.


text:
Q: pip -r not working as expected in virtualenv I have a really strange issue with the behavior of pip in a virtualenv.
I have set
export PIP_REQUIRE_VIRTUALENV=true
export PIP_DOWNLOAD_CACHE=$HOME/.pip/cache
export VIRTUALENV_DISTRIBUTE=true

Now, when I'm in my virtualenv and want to install my dependencies:
pip install -r requirements/_base.txt

(for testing purposes, requirements/_base.txt only contains:)
Django==1.5

Anyway, when I try to install it, I only get:
Downloading/unpacking Django==1.5 (from -r requirements/_base.txt (line 1))
Running setup.py egg_info for package Django

warning: no previously-included files matching '__pycache__' found under directory '*'
warning: no previously-included files matching '*.py[co]' found under directory '*'

And after that, Django is not installed.
Here comes the strange part: When I install Django manually with
pip install Django==1.5

it's working perfectly (though the same two warnings appear):
Downloading/unpacking Django==1.5
Running setup.py egg_info for package Django

warning: no previously-included files matching '__pycache__' found under directory '*'
warning: no previously-included files matching '*.py[co]' found under directory '*'
Installing collected packages: Django
Running setup.py install for Django
changing mode of build/scripts-2.7/django-admin.py from 644 to 755

warning: no previously-included files matching '__pycache__' found under directory '*'
warning: no previously-included files matching '*.py[co]' found under directory '*'
changing mode of /usr/local/share/python/django-admin.py to 755
Successfully installed Django
Cleaning up...

A: I faced a similar problem and realized that removing the version requirement solved the problem. Don't know why though...

A: I figured out why this was happening to me, which may also solve the problem for others who see this page. For me, the problem was that I had a requirement that can not install automatically via pip. The pip freeze exported the package name and version but, for whatever reason, pip cannot install that package directly in a requirements install. I have to instead install it manually from a zip file.
The problem you might be experiencing, then, is that you have a requirement which cannot be installed by pip's requirements installer. Check your output log for red text, errors, that sort of thing.
I figured this out using this post:
pip fails to install packages from requirements.txt


text:
Q: WebGL How to pass big numbers to shaders I am making app by using javascript and webgl. I need to pass big numbers (for example 1647843999744) to shader but when I get this value with this code gl.getUniform(this.shaderProgram, this.maxTimeLoc) , I see different value. 1647843999744 is changing to 1647844041000.
This is my code
    createShaderProgram: function () {
        const { gl } = this
        var VertexShaderCode = `
                precision lowp float;
                attribute vec4 vertexPos;
                uniform mat4 modelViewMatrix;
                uniform mat4 projectionMatrix;
                uniform vec3 transPos;
                uniform float maxPointSize;
                uniform float minPointSize;
                uniform float maxTime;
                uniform float minTime;
                varying float scale;
                void main(void) {
                   scale = (vertexPos.w - minTime) / (maxTime - minTime);
                   gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPos.xyz - transPos.xyz, 1.0);
                   gl_PointSize = minPointSize + ((maxPointSize - minPointSize)*scale);
                }
    `

        var vertexShader = gl.createShader(gl.VERTEX_SHADER)
        gl.shaderSource(vertexShader, VertexShaderCode)
        gl.compileShader(vertexShader)

        var FragmentShaderCode = `
                    precision lowp float;
                    varying float scale;
                    uniform vec3 startColor;
                    uniform vec3 endColor;
                    uniform bool applyOpacity;
                void main() {
                  float r = 0.0;
                  vec2 cxy = 2.0 * gl_PointCoord - 1.0;
                  r = dot(cxy, cxy);
                  if(r > 1.0 ){ discard;}
                  vec3 factor = (endColor - startColor) * r;
                  if(applyOpacity==true){
                     gl_FragColor = vec4(startColor + factor, scale * (1.0-r));
                  }else{
                     gl_FragColor = vec4(startColor + factor, 1.0 - r);
                  }
                }`

        var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
        gl.shaderSource(fragmentShader, FragmentShaderCode)
        gl.compileShader(fragmentShader)

        this.shaderProgram = gl.createProgram()
        gl.attachShader(this.shaderProgram, vertexShader)
        gl.attachShader(this.shaderProgram, fragmentShader)
        gl.linkProgram(this.shaderProgram)
    }

Any ideas?What should I do?


text:
Q: HTML5 localStorage + Twitter oAuth I have a jQuery Mobile app that uses Twitter oAuth to handle login and registration. However iPhone Mobile apps that get added to the home screen doesn't handle sessions. I have been told I need to use localStorage. Here is my current code that I need help translating to localStorage rather than sessions. Any help would be much appreciated.
Main page:
<?php
require("lib/twitteroauth.php");
session_start();

// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('consumer key','secret');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('login.php');

// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
    header ('Location: '.$url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.');
}
?>

After Twitter handles the login it redirects to login.php:
<?php
require("lib/twitteroauth.php");
session_start();

if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){

// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth("consumer key", "secret",$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
}
?>

Thanks!

A: This should help understand what you need to complete the task of saving to LocalStorage.
http://sixrevisions.com/web-development/html5-iphone-app/
nb: see section near end of the article on Offline Data


text:
Q: Retrieving column name based on user input in MYSQL using php Currently i am doing a PHP GET and getting values after clicking the submit button.
I got the values out from the submit button but I dont know how to reference them to the values in column.
For example, after clicking the submit button, I get the value 1.
Inside my database i have 3 columns
Col 1     Col 2      Col 3
 2   3  1

How do i get the COLUMN name by just having the value itself? Thank you so much!

A: Ugly/silly, but would do what you want:
Query:
SELECT * FROM yourtable WHERE 1 in (col1, col2, col3, ... ,colN)

and then manually pick out the value in client code:
$row = mysql_fetch_assoc($result);
$matches = array_search(1, $row);
var_dump($matches);

You can't get away from listing all of the columns in the query, because there's no WHERE x IN (*)-type construct.

A: I would do it like this.
Get all table columns
then loop throug results and run select for each column
$columnVsValue = array();

foreach($columns as $column) {
  $q = "SELECT id FROM table where {$column} = {$value}";
  if(TRUE) { // you have to check that query return value
    $columnVsValue[] = $column;
  }
}

I did it quick probably there is more efficient way to do it


text:
Q: TSQL pulling records from two tables that are not in parity I have two tables, one contains a list of employees, the other contains a list of PO's.
The PO Table looks like:
PoID PO# Name             City     State
1    55  Jasons Company   Miami    FL
2    66  Mikes Company    NewYork  NY
3    77  Sallys Company   Dallas   TX

My Employees Table looks like:
EmployeeID  Name    Phone         Email    PoID
1           John    123-123-1233  j@j.com  1
2           Alex    234-234-2344  a@a.com  1
3           Cindy   345-345-3455  c@c.com  2
4           Jessica 356-356-3566  j@j.com  3

Now if my SQL Select statement is this:
SELECT * FROM PO p
LEFT JOIN Employees e
ON p.PoID = e.PoID

It will return all records in my PO table and perhaps just the top entry of any employee associated with that record. I need the Names/Emails of all records associated to be pulled as well.
I'm not sure how I can accomplish this as I do not want duplicate PO entries but rather just a comma delimited list of any possible names/emails associated with that PO to pull up in two additional columns on my PO.
Hope it makes sense, if anyone has come across this your insight is appreciated.

A: You can try this query
SELECT p.*,
 STUFF((SELECT DISTINCT ',' + Name
          FROM @Employees e1
          WHERE e1.PoID = p.PoID
          FOR XML PATH (''))
          , 1, 1, '')  AS Names
,STUFF((SELECT DISTINCT ',' + Phone
          FROM @Employees e1
          WHERE e1.PoID = p.PoID
          FOR XML PATH (''))
          , 1, 1, '')  AS Phones
,STUFF((SELECT DISTINCT ',' + Email
          FROM @Employees e1
          WHERE e1.PoID = p.PoID
          FOR XML PATH (''))
          , 1, 1, '')  AS Emails
 FROM @PO p

Result

Below you can see the entire script with test data
declare @po table(PoID int, PO int, Name varchar(100),City varchar(100),State varchar(100))

insert into @po
select 1,55,'Jasons Company','Miami','FL' union
select 2,66,'Mikes Company','NewYork','NY' union
select 3,77,'Sallys Company','Dallas','TX'

declare @Employees table(EmployeeID int, Name varchar(100),Phone varchar(100),Email varchar(100), PoID int)

insert into @Employees
select 1,'John','123-123-1233','j@j.com',1  union
select 2,'Alex','234-234-2344','a@a.com',1 union
select 3,'Cindy','345-345-3455','c@c.com',2 union
select 4,'Jessica','356-356-3566','j@j.com',3

SELECT p.*,
 STUFF((SELECT DISTINCT ',' + Name
          FROM @Employees e1
          WHERE e1.PoID = p.PoID
          FOR XML PATH (''))
          , 1, 1, '')  AS Names
,STUFF((SELECT DISTINCT ',' + Phone
          FROM @Employees e1
          WHERE e1.PoID = p.PoID
          FOR XML PATH (''))
          , 1, 1, '')  AS Phones
,STUFF((SELECT DISTINCT ',' + Email
          FROM @Employees e1
          WHERE e1.PoID = p.PoID
          FOR XML PATH (''))
          , 1, 1, '')  AS Emails
 FROM @PO p

A: You can use this.
DECLARE @PO TABLE (PoID INT, PO INT,  Name VARCHAR(20), City VARCHAR(20), State vARCHAR(10))
INSERT INTO @PO
VALUES
(1, 55, 'Jasons Company','Miami','FL'),
(2, 66, 'Mikes Company','NewYork','NY'),
(3, 77, 'Sallys Company','Dallas','TX')

DECLARE @Employees  TABLE (EmployeeID INT, Name VARCHAR(20), Phone VARCHAR(20), Email VARCHAR(20), PoID INT)
INSERT INTO @Employees
VALUES
(1,'John','123-123-1233','j@j.com',1 ),
(2,'Alex','234-234-2344','a@a.com',1),
(3,'Cindy','345-345-3455','c@c.com',2),
(4,'Jessica','356-356-3566','j@j.com',3)

SELECT
    *,
    STUFF ( (SELECT
            ', '  + Name + '/' + Email
        FROM
            @Employees e WHERE e.PoID = p.PoID FOR XML PATH('') ) ,1,1,'') [names/emails]
FROM
    @PO p

Result
PoID        PO          Name                 City                 State      names/emails
----------- ----------- -------------------- -------------------- ---------- -------------------
1           55          Jasons Company       Miami                FL          John/j@j.com, Alex/a@a.com
2           66          Mikes Company        NewYork              NY          Cindy/c@c.com
3           77          Sallys Company       Dallas               TX          Jessica/j@j.com


text:
Q: Parse complex JSON in Typescript The response of a request delivers a JSON. The structure of the JSON looks like this:
{
"32": {
    "docKey": "32",
    "outletId": 32,
    "mdngOutlet": {
        "outletBasic": {
            "outletId": 32,
        }
    }
},
"33": {
    "docKey": "32",
    "outletId": 32,
    "mdngOutlet": {
        "outletBasic": {
            "outletId": 32,
        }
    }
},
"34": {
    "docKey": "32",
    "outletId": 32,
    "mdngOutlet": {
        "outletBasic": {
            "outletId": 32,
        }
    }
},
"35": {
    "docKey": "32",
    "outletId": 32,
    "mdngOutlet": {
        "outletBasic": {
            "outletId": 32,
        }
    }
},
}

What does the interface look like? 32, 33, 34, ... seem to act like map. How can you use a map in an interface?

A: Typescript interface can have dynamic keys.
interface YourJSON{
    [key: string]: yourObjectInterface
}


text:
Q: Prevent a control from databinding to an ObjectDataSource? I have a page which expects a numeric query string value. For example:
Details.aspx?rgn=1234

On this page is an <asp:repeater> which is databound to an <asp:objectdatasource>. The datasource looks something like this:
<asp:ObjectDataSource ID="ObjectRegion" runat="server" SelectMethod="GetRegions" TypeName="Region">
  <SelectParameters>
    <asp:QueryStringParameter Name="RegionID" QueryStringField="rgn" Type="Int32" DefaultValue='0' />
  </SelectParameters>
</asp:ObjectDataSource>

Since this is a public page, sometimes I get passed a non-numeric value by hackers / search engines / curious folks. I validate this in my Page_Load. Something like this:
protected void Page_Load(object sender, EventArgs e)
{
    int RegionID;
    string strRegion = Request.QueryString["rgn"];
    if(string.IsNullOrEmpty(strRegion) || !int.TryParse(strRegion, out RegionID))
    {
        // setup permanent redirect
        return;
    }
}

The problem is that my repeater still does its databinding anyway which causes a [FormatException: Input string was not in a correct format.]... which is something I want to prevent. Any ideas of a simple way to get around this?

A: I answered my own question. I forgot to add a Response.End() on the permanent redirect:
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location",URL);
Response.End();


text:
Q: Cross Domain login system for sites on different Servers I already implemented single sign on (SSO)  for sub-domain on same and different server.
Using the following technique:
session_name('example');
session_set_cookie_params(0, '/', '.example.com');
session_start();

d1.example.com on SERVER1
d2.example.com on SERVER1
d3.example.com on SERVER2

and this successfully works.
To create session for sub-domain d3.example.com on SERVER2 i use a curl to invoke a page on that server
But now i added another domain www.different.com to SERVER2, all data, users, services, code are shared from example.com, but its not a subdomain.
I tries same login technique of cURL for this new domain(www.different.com), but failed to login to www.different.com. although user is shown logged-in on all other sites.
Because www.different.com is not a subdomain of example.com, so cookie(i.e. session_set_cookie_params(0, '/', '.example.com'); ) is not written for this site.
I want to know if there any solution that need minimum changes, because there are 18 subdomains working on above scenario. and changing all these is very tedious.


text:
Q: How to make IDLE window more readable? Font too small for me to see I can't seem to figure out how to zoom in or anything, and the font is so small. Thank you for your help. I'm using a mac if that helps

A: On the top menu, choose Options, then Configure IDLE.  The Fonts/Tabs tab will be displayed.  There is a Size button.  Click on it and select a bigger size than the default of 10.  At present, this only only affects the font in Shell, editor, and output windows, but that is the main issue for me.
EDIT: correct Options menu entry as suggested by Nathan Wailes.  IDLE Preferences was once the title of the resulting dialog, but it is now Settings.

A: For Mac Python 3.9, Go to Idle -> Preferences -> Fonts/Tabs Option.
Screenshot for more clear


text:
Q: How to make an embedded question from "What time is it?" If the original question is "What time is it?" and I want to communicate it to another person, are these Embedded Questions OK?

*

*I don't know what time is it.

or

*

*I didn't know what time was it. (if communicated later)

A: The easy way to find the word order in an embedded question is to make an in situ question with the embedded section. To make an in situ question, we just take a normal sentence and put the appropriate question word in the place of the missing information:

*

*His name is what?

*He is who?

*Who killed JR?

*You met my elephant where?

*It is what time?

To make the embedded clause, move the wh word to the front of the clause but don't change anything else. If the wh word is already at the front, still don't change anything:

*

*... what his name is.

*... who he is.

*... who killed JR.

*... where you met my elephant.

*... what time it is.

You can then embed this in the main sentence. Let's use I don't know for the beginning of the sentence:

*

*I don't know what his name is.

*I don't know who he is.

*I don't know who killed JR.

*I don't know where you met my elephant.

*I don't know what time it is.

So, for the Original Poster's example the first example needs to be I don't know what time it is. For the second example we can test it like this:

*

*It was what time

*... what time it was.

*I didn't know what time it was.

This shows that the Original Poster needs to change round was and it to make their sentence good.
Hope this is helpful!


text:
Q: Shortcut to toggle Bluetooth in Montery via blueutil shell script executed with AppleScript in BetterTouchTool I have set the Mission Control key in BetterTouchTool to execute an AppleScript and it worked fine before the update from Mojave to Montery which I just did
do shell script "../bluetoggle.sh"

content of file is
#!/bin/sh

blueutil -p toggle

but can't execute in BetterTouchTool.. it says

Executing file from Terminal works flawless.
Executing another script (do shell script "../karaprof.sh") in BetterTouchTool with following content to switch profile in Karabiner also works perfectly
#!/bin/sh

pro0="e"
pro1="g"

cli='/Library/Application Support/org.pqrs/Karabiner-Elements/bin/karabiner_cli'

name=$("$cli" --show-current-profile-name)
if [ "$name" = $pro0 ]; then
"$cli" --select-profile $pro1
else
"$cli" --select-profile $pro0
fi

So my guess is I need to set permission for BetterTouchTool to execute scripts in Terminal, but how? I can't figure

A: set path to blueutil
/usr/local/Cellar/blueutil/2.9.0/bin/blueutil

and it worked like a charm


text:
Q: Motor Control board -replace capacitor with higher voltage? I hope that someone may be able to help me with a problem i have-
My good lady wife dusted down her trusty Kenwood mixer last night to get started on the Christmas cake (apparently it must be done this weekend or doom will ensue)
On attempting to use it she found that when switched on the motor would start then stop then slowly start etc etc- generally misbehave.
Here is a short video of the misbehaving motor:
https://youtu.be/7Mmma936F_w
I stripped the beast and checked the brushes- all ok and so took further advise from a "kenwood expert" who says my speed control is likely goosed (a common problem it seems).
He recommended replacing the triac, a couple of 4.7k resistors, a 220uF capacitor and a 150nF resistor.
Although i can't see any obvious signs of distress on the board such as blown / leaking cap's or charred resistors i am not capable of testing the triac with the limited equipment i have so thought it best to go ahead and replace the components suggested by "the Kenwood man"
The control board is actuated by a rotary dial - the spindle passes through the board and the speed control (Potentiometer?) we have a direct mains voltage input, a motor output and a thermistor input (thermistor is attached to the motor to prevent overheat)
Upon turning the dial the motor speed should increase progressively depending on dial position-  The machine also has a function whereby you can turn the dial in the opposite direction for a "pulse" of full power- this full power is applied until you release the dial and it returns to 0 (stop) via some sort of spring action in the potentiometer?

I only have a Maplin in my area and can't seem to find a like for like match on the capacitor which should be a 150nF 275v x2
The only available 150nF capacitor at Maplin is a Wima Polypropylene Metal Foil 1250V 0.15uF Capacitor which is obviously 4.5 x the voltage of the one i want to replace, other than that the closest match i can come up with at Maplin is a 0.1uF 275V X2 RFI Metallised Polypropylene Capacitor.
Can anyone tell me if either of these two capacitors are likely to be acceptable?
I thank everyone in advance for their time, i'm sure you all get fed up with people like me popping up out of nowhere asking for help but it really is appreciated!
Regards,
Rob

A: The precise value of an RFI suppression capacitor like that is not terribly critical, so using a 100nF X2 cap instead of a 150nF one should get the circuit up and running for now at least.  You can order the 150nF/275V X2 cap from most mail-order suppliers though -- I'd try Farnell, given where you're at.

A: IME, a higher-voltage capacitor would be a suitable replacement. Except in some cases of high-capacitance electrolytics, using a higher-voltage capacitor carries no significant risks or disadvantages.
Note that typically special kinds of capacitors are used with circuits connected directly to the power mains. These are "X capacitors" and "Y capacitors".  But using a much higher voltage capacitor with a (presumably) double-insulated kitchen appliance is probably safe.

A: I suspect the wiper on the big black VR1 pot for speed control is intermittent, which sort of matches your description.

slowly start etc etc- generally misbehave.

Beside it is an internal VR2 trimpot . Perhaps contact cleaner or WD40... on the VR1. Nothing looks like it has overheated.

Reminds me of a Piher brand pot around 1K I once knew around that vintage.

Plastic caps are pretty reliable.
Can you describe the malfunction more clearly?
e.g. ( Hysteresis ? dead spots? late surge start at 30%? then smooth then  erratic 75 to 100%?
My Mother usually started Xmas Cake 3 mos before. others got so many they were aged 1 yr +3 mos ;)
If all erratic responses come via the speed control, then a new  Pot or WD40 may work.  New Piher pots are round.  http://www.piher.net/sensors/index.php?page=shop.product_details&flypage=flypage.tpl&product_id=24&category_id=1&option=com_virtuemart&Itemid=31


text:
Q: what happens when a plane polarized light is incident on a half wave plate? what happens when a plane polarized light is incident on a half wave plate?
i know what happens in the case of a quarter wave plate but there is no information available about the half wave plate. Please help

A: Half wave plates have two principal axes. If the light is linearly polarized and the polarization direction coincide with one of the axes of the waveplate, the polarization remains the same. When the polarization direction of the incident light does not coincide with one of the principal axes, the half wave plate will rotate the plane of polarization with twice the angle between the polarization of the incident light and the axes.
For example, if the angle between the polarization of the incident light and the principal axes of the half wave plate is $45^\circ$, the polarization plane will be rotated with $90^\circ$.

A: A Half wave plate introduces $\pi$ phase shift between $x$ and $y$ components (there is a $\lambda/2$ shift in phase). Hence, we get a rotation of $2\theta$ if incident at an angle of $\theta$


text:
Q: Perl equivalent of a sample JavaScript codes I have this code:
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData
  })

I'd like to convert that into Perl, what I have so far is:
my $req = HTTP::Request->new( 'POST', 'https://graph.facebook.com/v2.6/me/messages');
$req->header( 'Content-Type' => 'application/json' );
$req->content( $messageData );

I not sure how I can incorporate the following line into my Perl code:
qs: { access_token: PAGE_ACCESS_TOKEN },

It specifies a query parameter to add to the URL.
I tried to search the net but most example either sends the json content or the query string but not both.  I need something that can send both if my interpretation to the JavaScript code is correct.
Thanks in advance to anyone who will guide me.

A: You can use the URI module (possibly supplemented by the URI::QueryParam module) to build (and manipulate) a URL.
use HTTP::Request::Common qw( POST );
use JSON::XS              qw( encode_json );
use URI                   qw( );

my $message_data = encode_json(...);

my $url = URI->new('https://graph.facebook.com/v2.6/me/messages');
$url->query_form( access_token => PAGE_ACCESS_TOKEN );

my $req = POST($url,
   Content_Type => 'application/json',
   Content      => $message_data,
);


text:
Q: Listar todos os meses em um intevalo, ou na query ou na programação? Estou fazendo um gráfico que lista uma certa quantidade por mês, mas pode ter mès que não tem nada, com isso não me retorna nenhum valor e não lista no gráfico.
Não sei se devo fazer a alteração na query ou na programação, será que alguém consegue me ajudar?
A minha query esta assim:
SELECT DATE_FORMAT(dt_validade, '%y-%m') as anoMes, count(*) as qtde
FROM tabela
WHERE dt_validade > '{$today}'
GROUP BY anoMes
ORDER BY anoMes

o retorno dela é mais ou menos isso

anoMes  | qtde
14-08   | 2
14-09   | 5
14-12   | 10
14-12   | 10
14-12   | 10
15-01   | 1
15-03   | 1

e com isso, no php eu rodo um loop no resultado, jogo os dados para um array que mando um json_encode para os dados para o gráfico, mas com isso só irá me mostrar no gráfico dados dos meses 08, 09 e 12, mas preciso que mostre também dos meses 10 e 11 com valores zerados.
E resumindo, o que fiz na programação foi isso:
$cols = array(
    array(
        'Período',
        'Quantidade'
    )
);
$rows = array();

$query = "A query passada";
$result = $query->result();
foreach ($result as $r) {
    array_push($rows, array(
        $r->mesAno,
        (int) $r->qtde
    ));
}

$dados = array_merge($cols, $rows);

return json_encode($dados);

E como sugestão que me foi dada, o resultado esperado é esse:
anoMes  | qtde
14-08   | 2
14-09   | 5
14-10   | 0
14-11   | 0
14-12   | 10
15-01   | 1
15-03   | 1

Segue link com o build no SQLFIDDLE, assim imagino que posso ficar um pouco mais claro

A: Não ficou a coisa mais linda do mundo, mas funcionou:
$rows = array();

$query = "SELECT DATE_FORMAT(dt_validade, '%m-%y') as anoMes, count(*) as qtde
          FROM tabela
          WHERE dt_validade > now()
          GROUP BY anoMes
          ORDER BY dt_validade";

$result = $query->result();
foreach ($result as $r) {
    $rows[$r->mesAno] = (int) $r->qtde;
}

reset($rows);
list($mes, $ano) = explode('-', key($rows));
$current = strtotime(($ano+2000).'-'.$mes.'-01');

end($rows);
list($mes, $ano) = explode('-', key($rows));
$last = strtotime(($ano+2000).'-'.$mes.'-01');

$dates = array();
while( $current <= $last ) {
    $dates[date('m-y', $current)] = 0;
    $current = strtotime('+1 month', $current);
}

$rows = array_merge($dates, $rows);
$dados = array( array('Período', 'Quantidade'));
foreach($rows as $key => $value) $dados[] = array($key, $value);

return json_encode($dados);

A: Meus conhecimentos em PHP são muito limitados, mas eu posso tentar ajudar com uma solução do lado do banco.
Estabeleça o período
SELECT @mindate = MIN(dt_validade), @maxdate = MAX(dt_validade) FROM tabela

Resultado parcial:
|                    @mindate |                     @maxdate |
|-----------------------------|------------------------------|
| July, 30 2014 00:00:00+0000 | March, 15 2015 00:00:00+0000 |

Obtenha a lista de meses entre os dois períodos: Armazene em tabela temporária
CREATE TEMPORARY TABLE
IF NOT EXISTS
ListaAnoMes AS
SELECT Date_format(m1, '%y-%m') AS anoMes
FROM   (SELECT ( @mindate - INTERVAL Dayofmonth(@mindate)-1 day ) +
               INTERVAL m month AS
                      m1
        FROM   (SELECT @rownum := @rownum + 1 AS m
                FROM   (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) t1,
                       (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) t2,
                       (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) t3,
                       (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) t4,
                       (SELECT @rownum :=- 1) t0) d1) d2
WHERE  m1 <= @maxdate
ORDER  BY m1;

Resultado parcial:
SELECT * FROM LISTAANOMES

| ANOMES |
|--------|
|  07-14 |
|  08-14 |
|  09-14 |
|  10-14 |
|  11-14 |
|  12-14 |
|  01-15 |
|  02-15 |
|  03-15 |

Cruze as duas tabelas
SELECT         B.AnoMes,
               Count(a.id) as qtde
FROM           ListaAnoMes as B
LEFT JOIN      tabela as A
           ON  DATE_FORMAT(A.dt_validade, '%m-%y') = B.anoMes
GROUP BY       B.AnoMes

Resultado:
| ANOMES | QTDE |
|--------|------|
|  01-15 |    1 |
|  02-15 |    0 |
|  03-15 |    1 |
|  07-14 |    1 |
|  08-14 |    2 |
|  09-14 |    5 |
|  10-14 |    0 |
|  11-14 |    0 |
|  12-14 |   10 |

A: Você quer um intervalo de data ?
SELECT DATE_FORMAT(dt_validade, '%m-%y') as mesAno, count(*) as qtde
FROM tabela
WHERE dt_validade > '{$today}' OR dt_validade = NULL OR dt_validade = ''
GROUP BY mesAno

Não sei se está o default do campo null ou string vazia, dependendo não precisa dos 2 or, sṍ um


text:
Q: Of what use is the vars() function? I have came across the function vars() in python i know it returns __dict__ attribute of the object passed to the function But can you give me a real world usage example  like where we can use it in real project

A: Let me take an example:
sometimes you may need check a class object's attribute is None or others, you can use the vars()
class Test(object):
    def __init__(self):
        self.a = None
        self.b = None
        self.c = None

    def init_abc(self, init_dict):
        """init class param"""
        self.a = init_dict.get('a')
        self.b = init_dict.get('b')
        self.c = init_dict.get('c')

    def __repr__(self):
        return 'a=%s,b=%s, c=%s' % (self.a, self.b, self.c)

test = Test()
init_abc_dict = {'a':1, 'c':2}
test.init_abc(init_abc_dict)
print 'Test:%s' % test
if None in vars(test).values():
    print 'some attr is None'


text:
Q: ECDHE Security with Bouncy Castle I am quite new and unexperienced in the field of Elliptic Curve cryptography. After some research I have determined unlike traditional DHE, ECDHE parameters should not be generated but rather chosen from a list of pre-defined curves (examples include 'P-521', 'prime192v3').
Whilst creating an network based security-sensitive application is it better (or even logical) to choose different curves randomly at runtime vs using a single hard-coded curve?
Also, is there such a concept of a stronger and  weaker curves amongst all the curves to choose from?
So far, this is my code to initiating a ECDH exchange:
//For readability purposes exception checking code not shown, all code is properly exception-handled
SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG", "SUN");

X9ECParameters curve = ECNamedCurveTable.getByName("prime192v3");

ECDomainParameters domain = new ECDomainParameters(curve.getCurve(), curve.getG(), curve.getN(), curve.getH(), curve.getSeed());
ECKeyGenerationParameters ecgen = new ECKeyGenerationParameters(domain, rnd);

ECKeyPairGenerator kpgen = new ECKeyPairGenerator();

kpgen.init(ecgen);

AsymmetricCipherKeyPair kp = kpgen.generateKeyPair();

Is there anything wrong with this code so far?

A: With ECC cryptography, it takes a very long time to create domain parameters. It is also pretty hard to check the security of domain parameters, check for instance the SafeCurves research by Daniel J Bernstein and Tanja lange. Generating your own curve can be done, but probably not in real time. Furthermore, the security may be less than the ones pre-defined, and you may run into compatibility issues later on.
The size of the curve is obviously important, although anything 256 bit of over should provide enough security. It is still possible - although not that likely - that the NIST curves are generated using a scheme that could weaken security. If you are worried about that, choose a curve from the site above (e.g. the BrainpoolP384r1 curve), or one of the more "academic" curves. F(p) curves should probably be preferred over other curves.
Although this is not a code review site, there does not seem to be anything particularly wrong with the code you provided.


text:
Q: How do I configure traefik properly for docker services on subdomains? The example from the traefik quickstart guide for using the whoami image on the whoami subdomain works, but I can't get jellyfin working in a similar setup, and I can't figure out what's different:
kevin@pihost:~/personal$ curl -H Host:jellyfin.kevinm416.com http://127.0.0.1
Bad Gateway
kevin@pihost:~/personal$ curl -H Host:whoami.kevinm416.com http://127.0.0.1
Hostname: f7820e1787fe
IP: 127.0.0.1
...

This is my docker-compose file, which has all the traefik config:
version: "3"

volumes:
  jellyfin-config:
  jellyfin-cache:

services:
  reverse-proxy:
    image: traefik:v2.2
    # Enables the web UI and tells Traefik to listen to docker
    command:
      - "--api.insecure=true"
      - "--providers.docker"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
    ports:
      - "80:80"
      - "443:443"
      # The Web UI (enabled by --api.insecure=true)
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  whoami:
    image: containous/whoami
    labels:
      - "traefik.http.routers.whoami.rule=Host(`whoami.kevinm416.com`)"

  jellyfin:
    image: jellyfin/jellyfin
    network_mode: "host"
    environment:
      TZ: 'America/Los_Angeles'
    ports:
      - "8096:8096"
    volumes:
      - jellyfin-config:/config
      - jellyfin-cache:/cache
      - /home/kevin/microcenter:/microcenter:ro
    labels:
      - "traefik.http.routers.jellyfin.rule=Host(`jellyfin.kevinm416.com`)"
      - "traefik.http.services.jellyfin.loadbalancer.server.port=8096"
    restart: always

A: I guess there could be two problems:

*

*you haven't specified entrypoints for your containers, e.g. for whoami it could be (maybe you want new one for jellyfin with port 8096?):

- "traefik.http.routers.whoami.entrypoints=web"

*network_mode: "host" in jellyfin -- traefik should be in the same network as container (or try to use traefik.docker.network setting), so I would suggest just remove that line.


text:
Q: Is there a way to append user input text to a file untill an exit character without appending the exit character in JAVA? Hello I am trying to append user input to a file untill the user enters an exit character. I have reached to a certain point but the problem i have is that the exit character also gets appended in the text file.
Below is some code concerning the issue.
Thanks in advance.
public class Main {

public static void main(String[] args) throws IOException {

    BufferedWriter writer = null;
    BufferedReader reader = null;

    try {
        writer = new BufferedWriter(new FileWriter("C:\\Users\\gg\\newfile.txt",true));
        Scanner input = new Scanner(System.in);
        System.out.println("Enter text to enter file: ");
        //String text = input.nextLine();
        String text = "";
        while(!text.equals("/")){
            text = input.nextLine();
            writer.write(text);
            writer.newLine();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    writer.close();
}

}

A: You can wrap the calls to writer.write(); and writer.newLine() in an if clause that checks whether text is equal to the exit character to avoid it being appended to the file.
By the way, string comparisons where you compare a fixed string with a variable of type String should be done the other way around. Call equals on the fixed string and pass the variable as an argument of equals(). This is because the variable could be null, and then it would trigger a NullPointerException.


text:
Q: Yii MANY_MANY additionall join condition Relation:
'users' => array(self::MANY_MANY, 'Users', 'comments_views(comment_id, user_id)', 'together' => true),

SQL:
LEFT OUTER JOIN "comments_views" "users_users"
ON (
       "t"."id"="users_users"."comment_id"
)
LEFT OUTER JOIN "users" "users"
ON (
       "users"."id"="users_users"."user_id"
)

How to modify relation to get this sql:
LEFT OUTER JOIN "comments_views" "users_users"
ON (
       "t"."id"="users_users"."comment_id"
   AND "users_users"."user_id" = <param>
)
LEFT OUTER JOIN "users" "users"
ON (
       "users"."id"="users_users"."user_id"
)

A: You should use on not condition.
'users' => array(
              self::MANY_MANY,
              'Users',
              'comments_views(comment_id, user_id)',
              'together' => true
           ),

becomes
     'users' => array(
              self::MANY_MANY,
              'Users',
              'comments_views(comment_id, user_id)',
              'together' => true,
              'on'=>'users_users.user_id=:user_id',
              'params'=>array(':user_id' => $user_id),
           ),

Ideally, users_users should be replaced with the name of the relation.


text:
Q: Go Lang, Postgres: cannot get oid after Scan I have 2 columns if table accounts:
oid and balance
By the next code I try to extract oid then balance:
// variable `id` comes from an another part

sqlstr := `SELECT * ` +
    `FROM accounts ` +
    `WHERE oid=` + id + `;`

q, err := db.Query(sqlstr)

if err != nil {
    fmt.Println("Error: GetAccount \n", err)
    return Account{}, err
}
defer q.Close()

var _id string
var bal float64

q.Next()
q.Scan(&_id)
fmt.Println("_id ", _id)

q.Next()
q.Scan(&bal)
fmt.Println("bal ", bal)

After the first q.Next() I expected to extract oid and after the second to extract balance.
But every time after the first q.Next() and after the second I only get balance.
I tried to change sqlstr to the next:
sqlstr := `SELECT oid, balance ` +
    `FROM accounts ` +
    `WHERE oid=` + id + `;`

But I still cannot extract oid.

A: Try this q.Scan(&_id, &bal), func (*Row) Scan has this signature:
func (r *Row) Scan(dest ...interface{}) error

It expects the the pointers to the values where it will store the queried data.
If you are only querying for a single row, there is func (*DB) QueryRow(). Then your code will simplify to
row := db.QueryRow(sqlstr)
err := row.Scan(&_id, &bal)
// err will be sql.ErrNoRows if no rows have been selected