text:
Q: ReactJS: fetch give error cannot read properties I'm trying to make an api call ( a get ) to download a document.
My problem is that when I make this api call I receive error:

TypeError: Cannot read properties of undefined (reading 'payload')

const printPin = event => {
    event.preventDefault()
    //....
    props.printedPin(scePersonaEntity.perCod, activateAlert)
}

my reducer:
export const printedPin= (id, callback) => {
  const requestUrl = `${apiUrl}/${id}/printpin`
  fetch(requestUrl)
    .then((response) => {
      response
        .blob()
        .then(blob => {
          console.log("blob ", blob)
          if (blob.type === 'application/problem+json') {
            callback();
          }
          else {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'pin.pdf';
            a.click();
          }
        })
        .catch(err => console.log(err))
    })
}

In your opinion how can I fix this error? Thank you.

A: I think your .then chaining is incorrect.
Could you try this once?
 export const printedPin = (id, callback) => {
  const requestUrl = `${apiUrl}/${id}/printpin`
  fetch(requestUrl)
    .then((response) => response.blob()).then(blob => {
      console.log("blob ", blob)
      if (blob.type === 'application/problem+json') {
        callback();
      }
      else {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'pin.pdf';
        a.click();
      }
    })
    .catch(err => console.log(err))

}

Your first then  will return response.blob() and next then will handle the response of the previous one.


text:
Q: Find ranking to maximize average correlation to multiple known rankings I have n measured rankings for k objects, which I want to combine such that the combined ranking maximizes the average correlation with the measured rankings.
As correlation measures I need solutions for spearman's rank correlation and for Kendall-Taus.
The intention here is to find the upper limit on the average correlation for the given data to compare to the performance of various models & predictors.
I have searched through this webpage, wikipedia and some forums, but found only references to heuristic methods like averaging or taking medians etc. and many posts describing that you might come to different conclusions if you weigh the different rankings differently.
While this is all true, it does not solve my problem. So to emphasize the points how my question differs:
1) There is no weighting or different interpretation for the different rankings (think: I asked n people to rank these objects, all opinions are equally important)
2) The metric for what is the best ranking is clear: Maximize spearman rank correlation/ Kendall-taus. I am not searching for just any method which sensibly averages rankings.
I would be grateful for any hints to literature on how to do this!
P.S: I guess for spearman simply averaging the ranks should do the trick, but it would still be great to have a source confirming this (or tell me if it should be the median instead for example)

A: You are correct that simply averaging the ranks for each of the $k$ objects will provide you the overall rank that maximises the Spearman $\rho$ correlation with each of the individual ranks. This is equivalent to the Borda count method. The reference for this is Kendall & Gibbons (1990, pg. 125).
Finding the ranking that maximises Kendall's $\tau$ is a little more complicated. The Kemeny-Young method can determine the overall rank that minimises the Kendall's $\tau_D$ rank distance between itself and each of the individual ranks. Because Kendall's $\tau$ is a normalisation of the $\tau_D$ distance between two ranks,
$$\tau=1-2 \binom k2 ^{-1} \tau_D$$
The Kemeny-Young method yields the overall rank with the highest Kendall's $\tau$ correlation. Note this is problem is NP-hard though, so if you're working with large $k$, computation may be challenging.
For ways to calculate the average $\rho$ and $\tau$ between a criterion (e.g. overall) ranking and a group of ranks, see Lyerly (1952) and Hays (1960) respectively.

References
Hays, W. L. (1960). A note on average tau as a measure of concordance. Journal of the American Statistical Association, 55(290), 331-341.
Kendall, M. G. and J. D. Gibbons. 1990. Rank Correlation Methods. 5th ed. London: Griffin.
Lyerly, S. B. (1952). The average Spearman rank correlation coefficient. Psychometrika, 17(4), 421-428.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show menus to one admin username So I've got this code which does the reverse of what I want it to do.
add_action('admin_menu', 'remove_admin_menu_links');
function remove_admin_menu_links(){
    $user = wp_get_current_user();
    //if( $user && isset($user->user_email) && 'user@email.com' == $user->user_email ) {
    if( !$user && isset($user->user_login) && 'USERNAMEHERE'  == $user->user_login ) {
        remove_menu_page('tools.php');
        remove_menu_page('tools.php');
        remove_menu_page('themes.php');
        remove_menu_page('options-general.php');
        remove_menu_page('plugins.php');
    remove_menu_page('users.php');
    remove_menu_page('edit-comments.php');
    remove_menu_page('page.php');
    remove_menu_page('upload.php');
    remove_menu_page( 'edit.php?post_type=page' );
    remove_menu_page( 'edit.php?post_type=videos' );
    remove_menu_page( 'edit.php' );

    }
}

remove_theme_support( 'user-admin-menu' );

So the above code hides admin menu's if the username is "USERNAMEHERE",   however id like it to do the complete opposite, so id like all menu's to be hidden to all admins apart from a certain username.
I thought adding ! inside the if statement might have done it but it doesnt seem to work ?

A:     function hide_menu() {
    global $current_user;
    $current_user = wp_get_current_user();
    $user_name = $current_user->user_login;

        //check condition for the user means show menu for this user
        if(is_admin() &&  $user_name != 'USERNAME') {

        //your code here
   }
}
add_action('admin_head', 'hide_menu');


text:
Q: Passing Variable From Javascript to HTML Form Im trying to make a simple ideal weight counter, i thought the logic is correct but there must be a fault in the codes, can someone show me where is it..? Thank you..

  Height (Cm)
  <input type=text id="height">

  <button onClick="Count()">Submit</button>

  Ideal Weight (Kg)
  <input type=text id="ideal">

A: I think there are two issues:
var hei = document.getElementById('height').**v**alue;
and
document.get**E**lementById('ideal').value = ideal;


text:
Q: In Magento 1.6, changes to login.phtml don't reflect I customized the file app\design\frontend\base\default\template\checkout\onepage\login.phtml to hide the login fields in onepage checkout. It works well in 1.5 version.
When I do the same modifications in 1.6 version, nothing changes in the frontend. I observed that in 1.6 version, onepage.phtml is not using onepage\login.phtml unlike in 1.5. I did the basic checks of file location mistake(base\default and default\default) and cache refresh.
I am having trouble figuring out which login.phtml is being picked up in onepage.phtml in the line getChildHTML('login') [to display the login fields in checkout step 1].
Thanks in advance.

A: a) Do Not ever edit anything in Base, man!
b) Configuration -> Developer, Switch to Website or store or store view scope, turn on Template path hints, Look into your Frontend, you'll See The path!

A: Your problem may be related to the following Thread http://www.magentocommerce.com/boards/viewthread/243571/ about Persistent Shopping Cart.
I encoutered a similar issue because of the template override name:

*

*before 1.6, my template override was: frontend/default//template/customer/form/login.phtml

*
1.6: frontend/default//template/persistent/customer/form/login.phtml
  Elsewhere you can find the default template path from 1.6 : frontend/base/default/template/persistent/customer/form/login.phtml

For more information about Persistent Shopping Cart, please refer to http://www.magentocommerce.com/blog/comments/persistent-shopping-cart-customer-segmentation-just-getting-better/


text:
Q: Using GPS with DOZE in Android 8 I have an app which runs a background service to monitor GPS location and compare it to a list of locations. When it finds a match, it sends a broadcast to trigger a foreground activity which then displays information about the location. The GPS tracking uses the GPS capability in Google Play Services, and needs to get an update about every 20 seconds.
Most of the time, the user is unaware of the app and can do other stuff. The foreground UI will probably not be triggered more often then every 2 minutes, and it could be as long as 20 minutes or more. The rest of the time, it is important that the app can continue to get GPS locations without interrupting whatever else the user is doing.
I am trying to understand the impact of the new Doze and Standby features in Android 8. It looks to me from reading the latest docs that it will no longer work, and the background service will not get its updates (or will only get a few every hour, which is useless). Can anyone tell me if this is right?
They appear to say that I should use a foreground service, but elsewhere they say that foreground services should only be used where some user interaction is needed. Seems like catch 22. Is a foreground service ok for something like this?
The docs also refer to whitelisting, but I'm not clear what this really does. Can I whitelist my app to make it continue to work?
Can anyone help a confused amateur developer?
Chris S

A: I now understand it a little better. I have not found any way do this using a background service. I tried asking for REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission in the manifest, but it still didn't work - the GPS tracking stops after a few minutes. To do what I want, I have had to convert the tracking to a foreground service - that works OK.


text:
Q: Running into problems with omniauth with multiple providers. Should I use an omniauth.rb file? I want to implement omniauth-instagram and omniauth-facebook into my Rails project and keep running into problems and also keep getting confused by all the resources that are out there.
I want to focus on this resource:
https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
The resource above mentions:
Remember that config.omniauth adds omniauth provider middleware to your application. This means you should not add this provider middleware again in config/initializers/omniauth.rb as they'll clash with each other and result in always-failing authentication.
I want to clarify what this means in relation to the config/initializers/omniauth.rb mentioned in other documentation.
My actual question:
Should I have an omniauth.rb file or does the devise.rb configuration (as posted below) work in place of it?
devise.rb
  require "omniauth-instagram"
  OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE if Rails.env.development?
  config.omniauth :instagram, 'client_id', 'secret_key'

Any points in the right direction would be great!

A: I use devise+omniauth to enable users to login through facebook. The setup is in config/initializers/devise.rb. I don't have omniauth.rb.
devise.rb looks like this.(only omniauth part)
 Devise.setup do |config|

   # ==> OmniAuth
   # Add a new OmniAuth provider. Check the wiki for more information on setting
   # up on your models and hooks.
   # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'

   config.omniauth :facebook, 'APP_ID', 'APP_SECRET'

 end

Also, your devise.rb is too short. You can generate devise.rb template and using this command.
rails generate devise:install


text:
Q: Should I sign an APK that will be distributed just by side-loading I'll distribute and APK by email and/or web link.

*

*Should I sign it (Generate Signed APK) ?

*What are the advantages of having it signed if I won't deploy it on Play Store?

*Why there are erros that just show when building a Signed APK?

A: From developer.android.com

Android requires that all apps be digitally signed with a certificate
  before they can be installed. Android uses this certificate to
  identify the author of an app, and the certificate does not need to be
  signed by a certificate authority. Android apps often use self-signed
  certificates. The app developer holds the certificate's private key.

Even in debug mode your app is signed with a debug key. If you want to give the apk file to your friends you should definitely sign it or else they won't be able to install the package (it will give a parser error).
On your second question, there are not any real advantages unless you actually deploy to the play store (when you would push an update for example, the update will install without any problems because it is signed with the same key).
On part 3, which errors are you receiving?


text:
Q: Why iOS devices running BLE GATT Service in peripheral mode are not discovered in Windows (and Windows RT) 8 & 8.1 I have used the Heart Rate Monitor sample application C# and modified it to look for my custom profile that the iPhone is advertising. I double checked if the iPhone Peripheral is working using a Mac configured as central and android device also as central. The android device is not connecting to it because of an issue in andoid api but it can see the service.
I paired successfully the two devices (iOS and Windows, iOS and WindowsRT) and they are connected. I also restarted the Bluetooth on the both devices and reconnected them multiple times before debugging.
The windows 8 Heart Rate Monitor sample and the windows 8.1 Heart Rate Monitor sample doesn't discover the iPhone device service with the given uuid. I also tried to leave the UUID to the default one and mimic the Heart rate peripheral using iOS but with same outcome.
I even tried to connect to every BLENUM device that findAllAsync() discovers and none of them provide  the configured custom service.
Multiple solution proposals are welcome, the support for Windows BLE is next to nothing.

A: After working on BLE for a while i found out this:
Keep the advertised data shorter than 26bytes (36 including the name), otherwise it will not show in the findAllAsync() result.


text:
Q: ASP.NET with OpenIdAuthentication: redirect to url if not authorized I am attempting to write an ASP.NET application that uses a hybrid authentication scheme.
A user can either have his username and password hash stored in the UserStore, or he can authenticate via Azure Active Directory.
I have created the login form pictured. It has the standard UserName and Password inputs, but also has a "Login via Active Directory" button.

This works well.
Now for the problem: The application's home page has the [Authorize] attribute.
public class DefaultController : Controller
{
    [Authorize]
    public ViewResult Index()
    {
    // Implementation
    }
}

If the user is not logged in, I want it to redirect to the page Account/Login, allowing the user to choose the authentication method.
Once I added IAppBuilder.UseOpenIdConnectAuthentication to the pipeline setup, it no longer redirects to that page. Instead, it goes straight to the Microsoft Login page.
How do I configure it so that OpenID authentication is part of the system, but allow me to specify how to perform redirections when the user is not authenticated?
Here's the code where I set up the pipeline:
appBuilder.SetDefaultSignInAsAuthticationType(CookieAuthenticationDefaults.AuthenticationType_;
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationType.ApplicationCookie,
     LoginPath = new Microsoft.Owin.PathString("/Account/Login"),
     Provider = new Security.CookieAuthenticationProvider()
};
appBuilder.UseCookieAuthentication(cookieAuthenticationOptions);
// Now the OpenId authentication
var notificationHandlers = new OpenIdConnectAuthenticationNotificationHandlers
{
   AuthorizationCodeReceived = async(context) => {
       var jwtSecurityToken = context.JwtSecurityToken;
       // I've written a static method to convert the claims
       // to a user
       var user = await GetOrCreateUser(context.OwinContext, jwtSecurityToken.Claims);
       var signInManager = context.OwinContext.Get<SignInManager>();
       await signInManager.SignInAsync(user, true, false);
   }
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);

When you click "Active Directory Signin", it posts to "Account/SignInWithOpenId"
public ActionResult SignInWithOpenId()
{
    // Send an OpenID Connect sign-in request.
    if (!Request.IsAuthenticated)
    {
        var authenticationProperties = new AuthenticationProperties
        {
            RedirectUri = "/"
        };
        HttpContext.GetOwinContext().Authentication.Challenge
        (
            authenticationProperties,
            OpenIdConnectAuthenticationDefaults.AuthenticationType
        );
        return new EmptyResult();
    }
    else
    {
        return RedirectToAction("Index", "Default");
    }
}

A: The call to IAppBuilder.UseOpenIdConnectAuthentication(...) puts an Owin middleware component in the pipeline. When ASP.NET MVC returns an HttpResponse of 401 (Unauthorized), the Owin Middleware component detects this and changes it to an Http Redirect (code 302), and the redirection path is to the Open Id provider.
But there's a way to get around this: before the middleware component performs the redirect, it invokes the callback RedirectToIdentityProvider. From here, you can override this redirection.
Here is my code that overrides the redirection unless it is from the request  path Account/SignInWithOpenId.
var notificationHandlers = new OpenIdConnectAuthenticationNotifications
{
    AuthorizationCodeReceived = async(context) => {
       // Sign in the user here
    },
    RedirectToIdentityProvider = (context) => {
        if(context.OwinContext.Request.Path.Value != "/Account/SignInWithOpenId")
        {
             context.OwinContext.Response.Redirect("/Account/Login");
             context.HandleResponse();
        }
        return Task.FromResult(0);
    }
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);

A: Please try to move the UseOpenIdConnectAuthentication before UseCookieAuthentication , then it will redirect user to "login" page .
// Now the OpenId authentication
var notificationHandlers = new OpenIdConnectAuthenticationNotificationHandlers
{
  // Handler methods here
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);

appBuilder.SetDefaultSignInAsAuthticationType(CookieAuthenticationDefaults.AuthenticationType_;
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationType.ApplicationCookie,
     LoginPath = new Microsoft.Owin.PathString("/Account/Login"),
     Provider = new Security.CookieAuthenticationProvider()
};
appBuilder.UseCookieAuthentication(cookieAuthenticationOptions);

Please let me know whether it helps.
Update :
Or you could  using a custom Authorize Attribute to override the default behavior, for example :
    public class CustomAuthorizeAttribute: AuthorizeAttribute
    {
        public CustomAuthorizeAttribute(): base()
        {
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {

            }
            else
            {
                filterContext.HttpContext.Response.Redirect("Account/login");
            }
        }
    }

Then just change your usage to :
[CustomAuthorize]
public ActionResult Index()
{
    return View();
}

A: If you set the OIDC's Authentication Mode to Passive it should only respond to explicit Open ID Connect requests (e.g. posting to Account/SignInWithOpenId):
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     // ...
     AuthenticationMode = AuthenticationMode.Passive
}

Source: "Explicit use of Challenge and SignOut" section of The OWIN OpenID Connect Middleware


text:
Q: Eclipse Neon 2.0 Append automatically comments Smalle question.
Is there a way to append automatically generate comments/trigger notification/popup window at the end of new code.
Example:
int i = 0; //my comment

Whenever I start writing "int i = 0;", "//my comment" is appended automatically.
Or if u have any suggestion regarding something like this.
Kind regards,
Gregory

A: There are code templates
Goto Window -> Preferences -> Java -> Code Style -> Code Templates
Under Code there are different options, maybe yours is Method Body
Click on Edit, remove the comment and Save


text:
Q: Use websocket in java web application My web application was developed by JDK 1.6. Now i want to use websock, but jdk 6 does not support this. Please introduce me to use which library to do websocket for jdk6 and how to configure in web.xml. I tried using Jetty version 9 but i still can not implement

A: Hope this helps. It has both implementation of websocket at server side and client side.
https://github.com/TooTallNate/Java-WebSocket


text:
Q: Is there an easy way of using the QVariant class with hexadecimal strings? This code sample works as I would expect:
v = QVariant("123456");
qDebug() << v; // QVariant(QString, "123456")
v.convert(QVariant::Int);
qDebug() << v; // QVariant(int, 123456)
v.convert(QVariant::String);
qDebug() << v; // QVariant(QString, "123456")

Where as this doesn't:
v = QVariant("0xBEEF");
qDebug() << v; // QVariant(QString, "0xBEEF")
v.convert(QVariant::Int);
qDebug() << v; // QVariant(int, 0)
v.convert(QVariant::String);
qDebug() << v; // QVariant(QString, "")

Is there any simple way to make the QVariant class work with hexadecimal strings so the second example would work something like this:
v = QVariant("0xBEEF");
qDebug() << v; // QVariant(QString, "0xBEEF")
v.convert(QVariant::Int);
qDebug() << v; // QVariant(int, 48879)
v.convert(QVariant::String);
qDebug() << v; // QVariant(QString, "48879")

A: When converting a qvariant to a numeric value you need to specify the base. Also make sure the value will fit in the int/long/longlong or then the conversion will fail for that reason instead.
QVariant v = QVariant("0xDEADBEAF");
bool test;
qDebug() << v.toString().toLongLong(&test,16);
qDebug() << test;

will produce the correct output
3735928495
true

while
QVariant v = QVariant("0xDEADBEAF");
bool test;
qDebug() << v.toString().toInt(&test,16);
qDebug() << test;

will output
0
false

A: After the points made by this answer about numerical overflow, I did some investigation and it seems the QVariant's conversion routines are flawed. The easiest way way to convert a QVariant safely is by using QString's conversions instead. This also seems like the easiest way to use QVariant with hexadecimal strings. I've summarised my findings below. The comments would be the resulting output of making a call to qDebug() << v; at that point in the code.
Scenario 1: Number stored as a hexadecimal string
v = QVariant("0xBEEF"); // 'QVariant(QString, "0xBEEF") '
v = v.toString().toInt(0, 16); // 'QVariant(int, 48879) '

v = QVariant("0xDEADBEEF"); // 'QVariant(QString, "0xDEADBEEF") '
v = v.toString().toInt(0, 16); // 'QVariant(int, 0) '

The easiest and safest way of converting a string-which-represents-a-decimal-number into a number type is by using QString's toInt(bool * ok = 0, int base = 10) method.
Scenario 2: Number stored as a decimal string
v = QVariant("123456"); // 'QVariant(QString, "123456") '
v.convert(QVariant::Int); // 'QVariant(int, 123456) '

QVariant's convert(Type t) method works as one would expect in this scenario.
v = QVariant("2147483649"); // 'QVariant(QString, "2147483649") '
v.convert(QVariant::Int); // 'QVariant(int, -2147483647) '

v = QVariant("9223372036854775807"); // 'QVariant(QString, "9223372036854775807") '
v.convert(QVariant::Int); // 'QVariant(int, -1) '

However using the same method when the string contains a number that is too large for the data type causes a silent overflow, instead of doing something more useful like returning false and setting the QVariant to 0.
v = QVariant("2147483649"); // 'QVariant(QString, "2147483649") '
v = v.toString().toInt(); // 'QVariant(int, 0) '

v = QVariant("9223372036854775807"); // 'QVariant(QString, "9223372036854775807") '
v = v.toString().toInt(); // 'QVariant(int, 0) '

By using the same method as in Scenario 1, one can prevent this from happening and also use the optional *bool parameter of toInt() to be alerted of failures.


text:
Q: SessionAuthenticationModule Cookie Handler not creating HttpOnly secure cookie I am using System.IdentityModel to authenticate users in an ASP.NET MVC4 web application using forms auth with a claims principal. (code based on this article: http://brockallen.com/2013/01/26/replacing-forms-authentication-with-wifs-session-authentication-module-sam-to-enable-claims-aware-identity/)
My ClaimsBasedAuthenticationService class issues the SAM cookie from the SessionSecurityToken, and all has been well...except that I just now noticed that it is not creating the session cookies as HTTPOnly or requiring them to require SSL.  When I debug the code, I can see those properties on the CookieHandler object are set correctly in the debugger, but the final session cookie that is created simply doesn't have the HTTPOnly and Secure flags marked.
I have the web.config lines to set these to true explicitly as such:
<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true" />
  <authentication mode="Forms">
     <forms ... requireSSL="true" />
  </authentication>
 ...
</system.web>
<system.identityModel.services>
  <federationConfiguration>
    <cookieHandler requireSsl="true" hideFromScript="true" />
  </federationConfiguration>
</system.identityModel.services>

Can someone tell me if there's something else I am missing in order for my FedAuth cookies to be hidden from script (HTTPOnly) and require SSL?

A: I am using the same implementation and do not see your issue using Fiddler2.  However maybe the issue is related to your debugging tool?  In IE10 debugging tools the secure and http only flags are only displayed when the cookies are first received.  If you check using Chrome debugging tools you should see the flags displayed correctly on all requests.

A: Did you get this working?  I've been using basically the same code and it's all fine.
I can't see that the following suggestions have anything to do with anything, but the only things I can suggest, are to set the cookie lifetime

<cookieHandler hideFromScript="true" requireSsl="true" persistentSessionLifetime="30" />

<forms loginUrl="/Whereever" timeout="30" requireSSL="true" />

and

<system.webServer>
  <modules>
    <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
  </modules>
</system.webServer>


text:
Q: Python tkinter PhotoImage not working well? Why do my Tkinter images not appear?
i wrote this code
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog

root = Tk()

def ouvrir():
    global image
    root.filename = filedialog.askopenfilename(initialdir="\Khaoula\Desktop\open_cv_book", title="Select a file",filetypes=(("jpg files", "*.jpg"), ("all files", "*.*")))
    image = ImageTk.PhotoImage(Image.open(root.filename))

button = Button(root, text="Open File", command=ouvrir)
button.pack()

root.mainloop()

No errors
But the picture didn't show up
Could you help please ?

A: As per the code you have given above :
You are just creating an instance of that image.
If you want the window to show up the image then you should call it up on Labels/Button/Canvas.
Hope it will help!


text:
Q: Is a simple property delegation possible? In the code below, all Test() objects depend on a single Aux() helper. The helper has a property prop. What I want sounds simple: to export that property (and only that property) through the Test class API.
Indeed it is very simple to write it explicitly:
class Aux:
    def __init__(self):
        self._prop = 0

    @property
    def prop(self):
        print("read:", self._prop)
        return self._prop

    @prop.setter
    def prop(self, val):
        print("write:", val)
        self._prop = val

    # other Aux methods here

class Test:
    _aux = Aux()

    @property
    def prop(self):
        return self._aux.prop

    @prop.setter
    def prop(self, val):
        self._aux.prop = val

    # other Test methods here

# try it out:
t = Test()
print(t.prop) # read: 0
t.prop = 123  # write: 123
print(t.prop)

However I thought for a moment I could use a direct reference somehow. This is wrong:
class Test:
    prop = Aux.prop     # WRONG! (references `_prop` attr in this class, not in the helper)
    prop = Aux().prop   # WRONG! (equals to simple prop = 0)

but maybe:
class Test:
    prop = property(...)   # BUT HOW?

But after a while I could not find a simple prop=... solution. Now I'm curious. Does it exist?

There is a similar question python @property setter delegation but it does not help me. I don't want to delegate everything.


text:
Q: Insert Menu Option into ApplicationIcon Menu Windows applications have an icon in the top left of the titlebar, to the left of the application name? If you click it, it has options like Restore, Minimize, Maximize.. etc.
In many programs they have additional menu options there (beyond the default one's provided by Windows).  How can I implement this in C# Winforms?

A: Tutorials for "Customizing the System Menu in a Windows Forms Application":
http://www.codeproject.com/KB/dotnet/CustomWinFormSysMenu.aspx
http://www.codeguru.com/csharp/csharp/cs_misc/userinterface/article.php/c9327
Snippet:
Import user32.dll to access the functions required to alter the system menu.
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool InsertMenu (IntPtr hMenu,
    Int32 wPosition, Int32 wFlags, Int32 wIDNewItem,
    string lpNewItem);

Get the current system menu, and add items to it:
IntPtr sysMenuHandle = GetSystemMenu(this.Handle, false);
//It would be better to find the position at run time of the 'Close' item, but...

InsertMenu(sysMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
InsertMenu(sysMenuHandle, 6, MF_BYPOSITION , IDM_CUSTOMITEM1, "Item 1");
InsertMenu(sysMenuHandle, 7, MF_BYPOSITION , IDM_CUSTOMITEM2, "Item 2");

public const Int32 WM_SYSCOMMAND = 0x112;
public const Int32 MF_SEPARATOR = 0x800;
public const Int32 MF_BYPOSITION = 0x400;
public const Int32 MF_STRING = 0x0;
public const Int32 IDM_CUSTOMITEM1  = 1000;
public const Int32 IDM_CUSTOMITEM2 = 1001;

Capture the selection of the new custom items in order to assign methods to them:
protected override void WndProc(ref Message m)
{
    if(m.Msg == WM_SYSCOMMAND)
    {
        switch(m.WParam.ToInt32())
        {
            case IDM_CUSTOMITEM1 :
                MessageBox.Show("Clicked 'Item 1'");
                return;
            case IDM_CUSTOMITEM1 :
                MessageBox.Show("Clicked 'item 2'");
                return;
            default:
                break;
        }
    }
    base.WndProc(ref m);
}


text:
Q: Listview setonitemclicklistener I've looked up similar post regarding this question but they didn't solve my issue, so here it is.
I'm trying to set a setOnItemClickListener, for when I click on any item of my list I will open a dialog with the info (retrieve from the list) on the clicked list and more info. But i'm struggling to implement the setOnItemClickListener part.
I'm getting and error in line:  myList.setOnItemClickListener(new OnItemClickListener()){
package com.example.proyectoprueba;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;;

public class PlantillaChina extends ActionBarActivity{

     // DB Class to perform DB related operations
    DBController controller = new DBController(this);
    // Progress Dialog Object
    ProgressDialog prgDialog;
    HashMap<String, String> queryValues;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lista);
        Intent myIntent = getIntent();

        String value = myIntent.getStringExtra("key");
        TextView titulo=(TextView)findViewById(R.id.titulo);

     // Get Platos records from SQLite DB

        ArrayList<HashMap<String, String>> platoList = controller.getAllEntremeses();
        if (value.equals("entremeses")){
            platoList = controller.getAllEntremeses();
            titulo.setText(value);
        }else if(value.equals("arroces y pasta")){
                platoList = controller.getAllArrocesyPasta();
                titulo.setText(value);
            }else if(value.equals("mar")){
                    platoList = controller.getAllMar();
                    titulo.setText(value);
                 }else if(value.equals("carnes")){
                            platoList = controller.getAllCarnes();
                            titulo.setText(value);
                 }
        // If Platos exists in SQLite DB
        if (platoList.size() != 0) {
            // Set the Plato Array list in ListView
            ListAdapter adapter = new SimpleAdapter(PlantillaChina.this, platoList, R.layout.itemlista, new String[] {
                            "platoId", "platoNombre", "platoDescripcion", "platoPrecio" }, new int[] {R.id.codigo, R.id.nombre, R.id.descripcion, R.id.precio });
            ListView myList = (ListView) findViewById(R.id.listaplatos);
            myList.setAdapter(adapter);
            myList.setOnItemClickListener(new OnItemClickListener()){

        }
    }

Thank you for your time

A:  It think you want something like this.

 myList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int
                               position, long id)
        {
            // You have the position available here as well as the clicked view.
        }

    });

A: You need to actual define the OntItemClickListener to do something.
First, the code you have doesn't make much sense. You want something like this:
myList.setOnItemClickListener(new OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
    {
        // Your code here
    }
});

Basically you are creating your own OnItemClickListener class, and overriding the OnItemClick method. This callback will get called whenever an item in your list is clicked. You can do whatever processing you would like inside that function.


text:
Q: Subscribe to an array of HTTP observables I have an array of Observable contained in activatedRoute.data.example and i want to subscribe to the latest value emitted.
private data$ = forkJoin(
  this.activatedRoute.data.pipe(
    map(({ examples }) => examples)
  )
);

ngOnInit(): void {
  this.data$.subscribe((v) => console.log(v));
}

Every example here is an http request:
this.http.get<Example>(`${this.baseUrl}`, { params: query })

But I never see neither the log nor the API call to the backend in the network browser's tab.

A: map is an option, clearer way to do it with switchMap with from rxjs operators (you can also look for concatMap and mergeMap). So in the implementation, you can basically do:
  this.activatedRoute.data.pipe(
    map(({ examples }) => from(examples)),
    concatMap((examples) => examples)
  ).subscribe(...);

If that was not helpful, I'm attaching a Stackblitz link .

A: map of rxjs is not same as 'map' of Array.
Rough example of show it should actually work:
private data$: Observable;

ngOnInit(): void {

  let getExample = (query) => this.http.get < Example > (`${this.baseUrl}`, {
    params: query
  });

  this.activatedRoute.data.subscribe(({ examples}) => { // if example is array

    let obsArray: Observable[] = Object.entries(examples).map(([key, value] => getExample({
        [key]: value
      }));

      data$ = forkJoin(obsArray);
      data$.subscribe(); // if needed
    });

}

A: I solved returning directly the forkJoin() of the Observables from the resolver, and than subscribing to that Observable throuhg a ReplaySubject


text:
Q: Swift - How to get notified after removeFromSuperview() has been called? I have two view controllers. The firstVC is being loaded when the app launches, then if a certain button was tapped then secondVC is being called using this code:
    let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "tagsStory") as! TagsVC
    self.addChildViewController(popOverVC)
    popOverVC.view.frame = self.view.frame
    self.view.addSubview(popOverVC.view)
    popOverVC.didMove(toParentViewController: self)

In the secondV when a certain button is tapped the secondVC gets removed and firstVC gets back to the user via this code:
self.view.removeFromSuperview()

My question is, how do I get notified when the secondVC has been removed inside the firstVC?
I tried to use, viewDidAppear, viewWillAppear, willMove... but nothing worked yet.

A: If you simply want to make a function call, simply use notification. In your parent view controller, register notification to receive function calls.
NotificationCenter.default.addObserver(self, selector: #selector(listnerFunction), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

func listnerFunction() {
    tableView.reloadData()
}

Done forget to remove this listener when the view controller is destroyed
deinit {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "notificationName"), object: nil)
}

Then in your child view controller, when you are about to remove it from parent, call the registered notification funtion in this way
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: nil)

A: In the secondVC when a certain button is tapped the secondVC gets removed and firstVC gets back to the user that is already notified you, You can make the delegate for this or fire the notification if the case is one to many.

A: This is covered in the UIViewController documentation.
Your firstVc is a container view controller, so it has certain responsibilities:

Your container view controller must associate a child view controller with itself before adding the child's root view to the view hierarchy. This allows iOS to properly route events to child view controllers and the views those controllers manage. Likewise, after it removes a child's root view from its view hierarchy, it should disconnect that child view controller from itself. To make or break these associations, your container calls specific methods defined by the base class. These methods are not intended to be called by clients of your container class; they are to be used only by your container's implementation to provide the expected containment behavior.

You are doing the right thing when you add the second view controller by calling didMove(toParentViewControler:) before you add the subview but you also need to call removeFromParentViewController() after you remove the subview.
If you do this then the viewDid/WillDisappear methods will be called.


text:
Q: Facebook like button iframe code not showing I have just started to create a new website, which is currently not on the internet. My very first website so everything is new to me. I'm trying to implement the Facebook like button. I have inputted the code but nothing is being displayed. I am using TextWrangler to create the website and using MacBook Air. Not sure if this information will help. Perhaps it's not working because of the meta properties? I didn't quite understand what information I needed to input there.
Here is my code:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>[]</title>
<meta property="og:title" content="The []" />
<meta property="og:type" content="website" />
<meta property="og:url" content="file:///Users/[]/Documents/Sites/IBS.html" />
<meta property="og:image" content="http://[].jpeg" />
<meta property="og:site_name" content="The []" />
<meta property="fb:admins" content="218100060" />

hello

If you can help I would greatly appreciate it.
Thank you.

A: The problem is that the code you provided is double escaped.
Which means that they are "&amp"s everywhere in the iFrame URL (src) code you provided:
//www.facebook.com/plugins/like.phphref=file%3A%2F%2F%2FUsers%2Fshikhaverma%2FDocuments%2FSites%2FIBS.html&
send=false&layout=standard&width=450&show_faces=true&font=arial&
colorscheme=light&action=like&height=80

Try pasting the url in your web browser, and it won't work, because it's so mal-formed.
Besides, Facebook like button can't use a local url to like, (in this case you used file:///Users/shikhaverma/Documents/Sites/IBS.html. ).
It has to be using an online, functioning URL. So for now, just enter any random URL of an online website untill you get your site hosted online.
I un-escaped the url, and it's still mal-formed. It should be "like.php?href=file" instead of "like.phphref=file". Why don't you just go back to Facebook and re-generate the code.
Also, is there a problem with your code editor? Why is everything getting double-escaped?
Edit: By the way, you can always utilize the unescape() JavaScript command to unescape text. More here on Mozilla dev.


text:
Q: Performing mathematical operations on attribute value I am attempting to perform mathematical operations with JavaScript on values obtained from an attribute. The attribute is created via a PHP loop. I will give an example of one of the html tags containing the attributes, but keep in mind that there are many of these tags which contain unique attribute values.
The HTML:

The JavaScript(jQuery):
    $("a[href^='secondary_imgs.php']").click(function(){
        var pageWidth = $(window).width();
        var maxshadowWidth = (Math.floor(pageWidth * 0.91808874)) - 2;
        var mWidth = $(this).attr("mwidth");
        var maxSecondaryWidth = mWidth + 60;
        alert (maxSecondaryWidth);
        if(maxSecondaryWidth <= maxshadowWidth) {
            var shadowWidth = maxSecondaryWidth;
        } else {
            var shadowWidth = maxshadowWidth;
        }
        var shadowboxrel = 'shadowbox;width=' + shadowWidth;
        $(this).attr('rel', shadowboxrel);

The operation doesn't seem to be working, and I have a feeling it has to do with my lack of experience using mathematical operations in javascript. In this case, I think something is wrong with my method of using the attribute value, in the mathematical operation.
For example, the above width attribute is defined as 593. I define the maxSecondaryWidth as mWidth + 60. I fired an alert to see what value I was getting. It should have been shown as 653, yet the value that is 'alerted' is 59360. Obviously I don't understand how to add, as the + is concatenating the two values, as opposed to adding them together. Could it have to do with needing to transform the attribute value from a string into an integer?

A: You have to convert to a number using parseInt(), otherwise + will do string concatenation:
var mWidth = parseInt($(this).attr("mwidth"), 10);

If the attribute can also be a float, use parseFloat() instead of parseInt().

A: Do this to make sure mwidth is a number:
var mWidth = parseInt($(this).attr("mwidth"), 10);

Otherwise, + will perform a string concatenation. Alternatively, if you need mwidth to be a floating point number, do this:
var mWidth = parseFloat($(this).attr("mwidth"));

A: You can do a couple things:
parseInt(mWidth, 10); // int
parseFloat(mWidth); // float
Number(mWidth); // number

otherwise javascript will believe it's a string.
Some less common conversions:
mWidth | 0; // int (javascript bitwise operations are 32-bit signed intergers)
+mWidth; // force Number

A: i think that you must do something safer (as it is always better);
You should check if it is a number or not:
DOM:

JS:
$("a[mwidth]").each(function(){
    var $attr = $(this).attr('mwidth');
    if(!isNaN($attr)){
        sum += (parseInt($attr));
    }
});

If you remove the condition the results will be NaN
Take a look at : http://jsfiddle.net/zVwYB/


text:
Q: Visually determine pole from Bode plot
Currently I'm taking a basic electronics course and this was a part of homework. The Bode plot represents the frequency response of an amplifier and from this plot we had to determine the dominant pole. I got the answer right (7 MHz) but I guess there was some tolerance in the answers.
How can I visually determine the pole within 1 MHz from a Bode plot like this?
Where is the pole when there isn't a sharp angle at the wanted frequency?


text:
Q: Reusing call back functions in Lightning I have two Apex methods "c.getStudentGrades" and "c.getStudentAverage". They both reference the same table and use the same ID but the returned results are different. I'm trying to cut down on some repetitive code in my helper function and I'm wondering if it's possible to re-use a callback function for the two different Apex controller calls.
One idea I had was to pass the actionType in as a variable to my helper. I've tested it out and it works but I'm just wondering if it's good practice?
Controller.js
handleStudent: function(component, event, helper){
    var selected = event.getParam("student");
    helper.getStudent(component, selected.Id, 'c.getStudent', 0);
    helper.getStudent(component, selected.Id, 'c.getStudentAvg', 1);
}

Helper.js
getStudent : function(component, id, actionType, index){
    var action = component.get(actionType);

    action.setParams({
       "id": id
    });
    action.setCallback(this, function(response){
       var state = response.getState():
       if (component.isValid() && state === "SUCCESS") {
          var student = response.getReturnValue();
          component.set("v.student", student);
          this.testFunction(student, index);
      }
   }
});

A: This is a little open-ended, but I would advise against passing in an array or list of parameters that rely on a specific order. It's not intuitive to use and you have to establish an arbitrary association between index 0 and 1 and 2, etc. when a map or a custom object can do the same thing while also having a more static, descriptive structure.
In your case, I wouldn't worry about repeating code - especially since you're just trying to consolidate two methods. Code is read more often than it's written, so coming up with a clever method that does two things is not going to be as maintainable than two methods that do two different things well. It's not clear what possible values are allowed to be passed to getStudent but currently actionType is limited to c.getStudent and c.getStudentAvg and testIndex to 0 and 1. So there are multiple runtime errors that can create and the only indications for acceptable values of actionType are written into your controller. But what if you need to add another action? How is another developer going to feel about extending this code?
If you're looking to gain efficiencies, then I would look towards why you make two subsequent calls to the Salesforce server in sequence every time you need information about a student. If grades and GPA are always needed together, then refactor your Apex code to return all of the information together rather than doing refactoring in your component (you can use a wrapper class for this). You could easily return one response that includes both grades and GPA in one call - then you could also cache that because the greatest bottlenecks in any web project (generally speaking) are time spent sending data over the network and time spent accessing data from a database.
EDIT: I would not recommend just returning a map to get both results back, but instead use a wrapper class (formally known as the adapter pattern - called such because you "adapt" the response to a format the caller is expecting. You'll find a lot of examples and documentation if you search for either). An example for your use case:
// change `Object` to your respective Objects
public class StudentWrapper {
    @AuraEnabled
    public List<Object> gradesByQuarter { get; set; }
    @AuraEnabled
    public Map<Id, Object> gradePointAverage { get; set; }
}

// assigning values, adjust to your codebase

StudentWrapper gradeInfo = new StudentWrapper();
gradeInfo.gradesByQuarter = getStudent(studentId);
gradeInfo.gradePointAverage = getStudentAvg(studentId);

action.setCallback(this, function(response){
    var state = response.getState():
    if (component.isValid() && state === "SUCCESS") {
        /**
        *  The returned object structure:
        *
        *   {
        *       gradesByQuarter: [ ... ],
        *       gradePointAverage: { ... }
        *   }
        *
        */

        var gradeInfo = response.getReturnValue();
        component.set('v.gradesByQuarter', gradeInfo.gradesByQuarter);
        component.set('v.gradePointAverage', gradeInfo.gradePointAverage);

        // ex. accessing specific value
        console.log(gradeInfo.gradePointAverage['someKey']);
    }
}

In terms of Apex maps returned to JavaScript, they're synonymous with plain old JavaScript objects and you'd access them the same way.

A: In Apex you can fetch the data from both the methods and add it to a wrapper.
public class TestWrapper{
    @AuraEnabled public FirstWrapper firstWrapper {get; set;}
    @AuraEnabled public SecondWrapper secondWrapper {get; set;}
}

With one call from UI populate both data in the wrapper and pass that to UI.
Also you can remove component.isValid() as salesforce internally handles that.


text:
Q: Wordpress Media Page lists only pictures of current user and administrator It is possible, I list images of the current user and administrator, below is the code I am using.
It currently works normally for just the current user to list their images, but I wish the admin images could also be listed.
In other words, listing the images of the current user and the administrator, is it possible?
// Page media list only store images
add_filter( 'posts_where', 'attachments_wpquery_where' );
function attachments_wpquery_where( $where ) {
    global $current_user;

    if ( is_user_logged_in() && !current_user_can( 'administrator' ) ) {
        // we spreken over een ingelogde user
        if( isset( $_POST['action'] ) ){
            // library query
            if( $_POST['action'] == 'query-attachments' ) {
                $where .= ' AND post_author='.$current_user->data->ID;
            }
        }
    }

    return $where;
}

A: I managed using this code, the conditional makes all the difference.
// Page media list only store images
add_action( 'pre_get_posts','users_own_attachments' );

function users_own_attachments( $wp_query_obj ) {
    global $current_user, $pagenow;

    if ( current_user_can( 'administrator' ) )
        return;

    if ( !is_a( $current_user, 'WP_User' ) )
        return;

    if ( ( 'edit.php' != $pagenow ) && ( 'upload.php' != $pagenow ) && ( ( 'admin-ajax.php' != $pagenow ) || ( $_REQUEST['action'] != 'query-attachments' ) ) )
        return;

    $author__in = array( $current_user->id, 1 );
    $wp_query_obj->set('author__in', $author__in );

    return;
}


text:
Q: Stringer equivalent for json marshal I can implement Stringer to specify how fmt.Print() will write my custom type as a string. Is there an equivalent for json marshal?
I want to store unique values in go and represent it as a slice in json. Using a slice in go isn't optimal for this. This O(n) insert seems unnecessary - a binary tree or map would be faster, specially since I'm keeping the list sorted at all times.

A: Yes, json.Marshaler and json.Unmarshaler.
Implementing MarshalJSON and UnmarshalJSON will give you what you want.


text:
Q: Spring Boot Referential integrity constraint violation At the beginning, I know there are lots of posts about this here on stackoverflow, I've tried every solution I found.
I'm creating a OneToMany relationship between my "ARTICLE" and "USER" tables - one USER to many ARTICLEs. The entities' codes are below (I'm also using Lombok, hence @Getter and @Setter annotations).
ARTICLE:
@Entity
@Table(name = "ARTICLE")
@Getter
@Setter
public class Article extends BaseEntity {

    private String title;
    private String name;
    private String iconName;

    @ManyToOne
    @JoinColumn(name = "AUTHOR_ID")
    private UserItem author;

    private Long editorId;

    @Lob
    private String article;

}

USER:
@Entity
@Table(name = "USER")
@Getter
@Setter
@EqualsAndHashCode(callSuper = false, of = { "username", "company" })
public class UserItem extends BaseEntity {

    private String username;
    private String name;
    private String lastName;
    private String phone;
    private String password;
    private String company;
    private String reasonsForAccess;
    private Integer failLogins = 0;

    private boolean enabled = true;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean passwordNonExpired;
    private boolean credentialsNonExpired;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "USER_TO_ROLE",
            joinColumns = @JoinColumn(
                    name = "USER_ID"),
            inverseJoinColumns = @JoinColumn(
                    name = "ROLE_ID"))
    private Set<RoleItem> roles;

    @ManyToMany(cascade = { CascadeType.PERSIST }, fetch = FetchType.LAZY)
    @JoinTable(
            name = "USER_ANSWER",
            joinColumns = { @JoinColumn(name = "USER_ID") },
            inverseJoinColumns = { @JoinColumn(name = "QUESTION_ANSWER_ID") }
    )
    Set<QuestionAnswerItem> answers = new HashSet<>();

    @OneToMany(mappedBy = "author")
    private Set<Article> articles;
}

My program initializes database by using data.sql file. I've put INSERT statements for the above tables in below fragment:
INSERT INTO PUBLIC.ARTICLE(ID, VERSION, ARTICLE, AUTHOR_ID, ICON_NAME, NAME, TITLE, EDITOR_ID) VALUES
(4, 0, 'clobclobyolo', 1, 'book', 'Introduction to 1, Consumer Place', 'one', null),
(5, 0, 'clobclobyolo', 1, 'mail', 'Email Solution (Digital Marketing Center)', 'one', null),
(6, 0, 'clobclobyolo', 1, 'glob', 'Global Registration System (GRS)', 'one', null),
(7, 0, 'clobclobyolo', 1, 'ticket', 'Ticketing Tool to drive CRM work (Service Now)', 'one', null),
(8, 0, 'clobclobyolo', 1, 'pie-chart', '1.Consumer Place Reporting', 'one', null),
(9, 0, 'clobclobyolo', 1, 'sms', 'SMS Solution', 'one', null),
(10, 0, 'clobclobyolo', 1, 'list', 'Driving trial through Brand Propensity Model', 'one', null),
(11, 0, 'clobclobyolo', 1, 'line-chart', 'Data Integration Capabilities', 'one', null),
(12, 0, 'clobclobyolo', 1, 'application', 'What is DMP, CRM and DMP better together', 'one', null),
(13, 0, 'clobclobyolo', 1, 'bar-chart', 'Data Source performance Tracking', 'one', null),
(14, 0, 'clobclobyolo', 1, 'facebook', 'Facebook Leads Campaigns', 'one', null),
(15, 0, 'clobclobyolo', 1, 'cloud-glob', 'Learn more about Data Enrichments', 'one', null);

INSERT INTO PUBLIC.USER(ID, VERSION, CREDENTIALS_NON_EXPIRED, ACCOUNT_NON_EXPIRED, ACCOUNT_NON_LOCKED, COMPANY, ENABLED, FAIL_LOGINS, LAST_NAME, NAME, PASSWORD, PASSWORD_NON_EXPIRED, PHONE, REASONS_FOR_ACCESS, USERNAME) VALUES
(1, 7, TRUE, TRUE, TRUE, 'lingaro', TRUE, 0, 'admin', 'admin', '$2a$11$TiefIbi6p15IAlGZsTIxquCNDrRCCjmzt9lTN0/D.toRFDVG3ECYO', TRUE, NULL, 'good', 'admin@mail.com'),
(2, 0, TRUE, TRUE, TRUE, 'lingaro', TRUE, 0, 'user', 'user', '$2a$10$GS4IiuO9ygrHOr2e.lFx4euYACa6ZENz52KmGx8l.WCEqH03.HPsO', TRUE, NULL, 'good', 'user@mail.com'),
(33, 4, TRUE, TRUE, TRUE, 'lingaroaaaaaaaa', TRUE, 0, 'admin', 'admin', '$2a$10$AJMuV2lAeg1XQoPIYQklju9t6aWyVrPMreXVOCaRgJhoxsp831Yhe', TRUE, NULL, 'good good', 'admin1'),
(97, 0, TRUE, TRUE, TRUE, 'PG', TRUE, 0, 'hu_ta', 'hu_ta', '$2a$10$3opTpBQkdbvt8AA1aEOaM.YyCHh98ODxsPBlQ6IrX23o9HxUDyALq', TRUE, NULL, 'Ping Federation', 'hu_ta'),
(161, 0, TRUE, TRUE, TRUE, 'PG', TRUE, 0, 'tatar.ht', 'tatar.ht', '$2a$10$iDfgmuKJI1YHRK4DKsm4mOZ/CdnE.5GoWYijEzdsdU/SnulJCHRYS', TRUE, NULL, 'Ping Federation', 'tatar.ht');

After starting tests, I've got exception "Failed to load ApplicationContext", which is thrown because of "Referential integrity constraint violation". I've pasted only a fragment of the stacktrace because it's almost everything the same, just different INSERTs:
java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)

...

Referential integrity constraint violation: "FKGWRTDBQVT9UCNTP82ND3YIUEC: PUBLIC.ARTICLE FOREIGN KEY(AUTHOR_ID) REFERENCES PUBLIC.USER(ID) (1)"; SQL statement:
INSERT INTO PUBLIC.ARTICLE(ID, VERSION, ARTICLE, AUTHOR_ID, ICON_NAME, NAME, TITLE, EDITOR_ID) VALUES (4, 0, 'clobclobyolo', 1, 'book', 'Introduction to 1, Consumer Place', 'one', null), (5, 0, 'clobclobyolo', 1, 'mail', 'Email Solution (Digital Marketing Center)', 'one', null), (6, 0, 'clobclobyolo', 1, 'glob', 'Global Registration System (GRS)', 'one', null), (7, 0, 'clobclobyolo', 1, 'ticket', 'Ticketing Tool to drive CRM work (Service Now)', 'one', null), (8, 0, 'clobclobyolo', 1, 'pie-chart', '1.Consumer Place Reporting', 'one', null), (9, 0, 'clobclobyolo', 1, 'sms', 'SMS Solution', 'one', null), (10, 0, 'clobclobyolo', 1, 'list', 'Driving trial through Brand Propensity Model', 'one', null), (11, 0, 'clobclobyolo', 1, 'line-chart', 'Data Integration Capabilities', 'one', null), (12, 0, 'clobclobyolo', 1, 'application', 'What is DMP, CRM and DMP better together', 'one', null), (13, 0, 'clobclobyolo', 1, 'bar-chart', 'Data Source performance Tracking', 'one', null), (14, 0, 'clobclobyolo', 1, 'facebook', 'Facebook Leads Campaigns', 'one', null), (15, 0, 'clobclobyolo', 1, 'cloud-glob', 'Learn more about Data Enrichments', 'one', null) [23506-197]

What can be wrong with this code? I've spent about 5 hours so far and I'm giving up, rewrote the relation thousand times with every possible solution I've found over the internet.
If it's relevant, you can spot the Long editorId - it's because I'm rewriting the code to include object with mapping instead of Long fields.
EDIT: I'm not the original author of the app so I didn't know about another .sql file until now - this one creates the above tables, maybe answer is here. I'm not sure though, because e.g. in ARTICLE table there is now "EDITOR_ID" column, I think the whole file could be deleted. As far as I know Hibernate creates the DB on the run by itself and it was working before I changed Long authorId to UserItem author.
CREATE TABLE ARTICLE(
    ID BIGINT PRIMARY KEY NOT NULL,
    VERSION BIGINT NOT NULL,
    ARTICLE CLOB NOT NULL,
    AUTHOR_ID BIGINT NOT NULL,
    ICON_NAME VARCHAR(255) NOT NULL,
    NAME VARCHAR(255) NOT NULL,
    TITLE VARCHAR(255) NOT NULL,
    EDITOR_ID BIGINT
);

CREATE TABLE USER(
    ID BIGINT PRIMARY KEY NOT NULL,
    VERSION BIGINT NOT NULL,
    CREDENTIALS_NON_EXPIRED BOOLEAN NOT NULL,
    ACCOUNT_NON_EXPIRED BOOLEAN NOT NULL,
    ACCOUNT_NON_LOCKED BOOLEAN NOT NULL,
    COMPANY VARCHAR(255) NOT NULL,
    ENABLED BOOLEAN NOT NULL,
    FAIL_LOGINS INTEGER NOT NULL,
    LAST_NAME VARCHAR(255) NOT NULL,
    NAME VARCHAR(255) NOT NULL,
    PASSWORD VARCHAR(255) NOT NULL,
    PASSWORD_NON_EXPIRED BOOLEAN NOT NULL,
    PHONE VARCHAR(255),
    REASONS_FOR_ACCESS VARCHAR(255) NOT NULL,
    USERNAME VARCHAR(255) NOT NULL
);

Also, the database I'm using is H2 if it makes any difference.


text:
Q: Dependencies Between Workflows on Github Actions not working I have two workflows and i do from this manual - https://docs.github.com/en/github-ae@latest/actions/using-workflows/workflow-syntax-for-github-actions#onworkflow_runbranchesbranches-ignore  but dependent workflow not starting..
name: Tests

on:
  push:
    branches:
      - '**'        # matches every branch
      - '!main'   # excludes master

jobs:
  setup-tests-job:
    runs-on: ubuntu-latest

and dependent workflow
name: Build

on:
  workflow_run:
    workflows:
      - 'Tests'
    branches:
      - '**'
    types:
      - completed

jobs:
   setup-tests-job:
     runs-on: ubuntu-latest

Maybe i do smthg wrong?


text:
Q: Change the size of ggplot2 plot in Sweave without making the text/numbers disproportionately large I found this question about changing the size of a ggplot2 plot in Sweave. I added the Sweaveopts{width=3, height=3} and it does shrink the size of the plot, but it doesn't scale down the text. So in the end, all of the numbers on the axes overlap.
Is there a way to scale the entire ggplot2 plot in Sweave so that I don't have to manually scale every component in the original ggplot2 call? It seems like something I should be able to do, but I can't find it in the ggplot2 book or on the website. Thanks!
FWIW, here's my call in Sweave:
\SweaveOpts{width=3, height=3}
\begin{figure}
\begin{center}
<<fig=TRUE>>=
print(plot.m)
@
\end{center}
\caption{stuff}
\label{fig:stuff}
\end{figure}

And the call that generates the ggplot2 plot:
plot.m <- ggplot(temp, aes(date, spread)) + geom_bar(stat="identity") + scale_x_date(major="years", minor="months")

A: It's basically a Sweave FAQ. Google and you will find a gazillion hits.
One approach is to just write the file to pdf (no scaling) and to then scale on the \includegraphics command.  I just looked at a vignette I finished a couple of days ago where I wanted something approximately as wide as the page and I did:
\begin{figure}[t!]
  \centering
<<someLabel,fig=TRUE,width=8>>=
## some R code omitted
print(dotplot(foo ~ bar | someFactor, group=someThing,
              data=someDF, layout=c(1,3),
              xlab="some X label", ylab="",
              key=simpleKey(text=c("A","B"), space="top")))
@
  \caption{Some caption.}
  \label{fig:someLabel}
\end{figure}

some basically just one width dimension at the Sweave options level.  I found that small values do not work well -- so try something bigger as eg 6 or 7 inches.


text:
Q: Gerar pdf com Javascript ou AngularJS Alguém conhece uma forma de gerar pdf de uma página via javascript sem o uso de biblioteca ou no maximo com uso do angular JS ?

A: Conheço dois, um deles converte Markdown para PDF, o outro usa um esquema de sintaxe parecido com o FPDF.
https://github.com/MrRio/jsPDF
https://github.com/devongovett/pdfkit
https://github.com/alanshaw/markdown-pdf
Fiz alguns testes com o jsPDF e pdfkit, são bem parecidos no uso e funcionam à contento, mas ainda não testei com geração de muitas páginas.


text:
Q: Collecting time stamp data in Android app I'm trying to collect time stamps through a questionnaire app. Every time the user answers a question I collect the time stamp and send it to the server.  That part is working fine through the app.  The issue is the questions are on a viewpager w/ 5 fragments.  I want to record the time stamp of when the last fragment is destroyed.  The way I'm doing that is by using a static method that calls my background task with the necessary parameters I want to pass.
I tried using onDestroy() in the fragment but that doesn't seem to work.  Any ideas?
@Override
    public void onDestroy() {
    super.onDestroy();
    Magic.stampThis(getContext(), FINAL_EXIT, user_id);
}


text:
Q: JavaScript set scrollHeight In JavaScript what's the right way to set the scrollHeight of one element to that of another element? Direct assignment has no effect.
Thanks, Greg

A: It's not possible directly. The scrollHeight is a read only property that contain the total height of element content in pixels.
If have element A and you want to have element B with the same scrollHeight as element A, make it so that element B has a single child DIV element (move all previous element B content as child nodes of the DIV) that is set to:
width : 100%;
overflow : hidden;

and using javascript set the height of DIV to scrollHeight of element A (in pixels):
document.getElementById('B').childNodes.item(0).style.height = document.getElementById('A').scrollHeight + 'px';


text:
Q: Cannot find class when refrencing from another project I have looked at the following which I thought would work but it did not.

Could not find class XXX referenced from method XXX.
Hello world, libgdx crashes on phone
Android Libgx Frogger game crashing: Could not find class 'com.rengelbert.froggergdx.FroggerGame'

My main diffrence between all the other questions is that I did not create the android project when I created the desktop project which I create with the Gdx-setup.jar. I decided to make an android project quite a bit after I created the desktop version.
I am getting the error:
08-23 05:30:09.341: E/dalvikvm(27497): Could not find class 'com.cvgstudios.pokemonchrome.ChromeGame', referenced from method com.cvgstudios.pokemonchrome.RunAndroidChrome.onCreate
08-23 05:30:09.341: W/dalvikvm(27497): VFY: unable to resolve new-instance 1027 (Lcom/cvgstudios/pokemonchrome/ChromeGame;) in Lcom/cvgstudios/pokemonchrome/RunAndroidChrome;
08-23 05:30:09.341: D/dalvikvm(27497): VFY: replacing opcode 0x22 at 0x0014
08-23 05:30:09.341: D/dalvikvm(27497): DexOpt: unable to opt direct call 0x2a07 at 0x16 in Lcom/cvgstudios/pokemonchrome/RunAndroidChrome;.onCreate
08-23 05:30:09.341: D/dalvikvm(27497): Trying to load lib /data/app-lib/com.cvgstudios.pokemonchrome-1/libgdx.so 0x41a79df0
08-23 05:30:09.349: D/dalvikvm(27497): Added shared lib /data/app-lib/com.cvgstudios.pokemonchrome-1/libgdx.so 0x41a79df0
08-23 05:30:09.349: D/dalvikvm(27497): No JNI_OnLoad found in /data/app-lib/com.cvgstudios.pokemonchrome-1/libgdx.so 0x41a79df0, skipping init
08-23 05:30:09.357: D/AndroidRuntime(27497): Shutting down VM
08-23 05:30:09.357: W/dalvikvm(27497): threadid=1: thread exiting with uncaught exception (group=0x41809700)
08-23 05:30:09.364: E/AndroidRuntime(27497): FATAL EXCEPTION: main
08-23 05:30:09.364: E/AndroidRuntime(27497): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cvgstudios.pokemonchrome/com.cvgstudios.pokemonchrome.RunAndroidChrome}: java.lang.NullPointerException
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.ActivityThread.access$600(ActivityThread.java:153)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1269)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.os.Looper.loop(Looper.java:137)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.ActivityThread.main(ActivityThread.java:5289)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at java.lang.reflect.Method.invokeNative(Native Method)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at java.lang.reflect.Method.invoke(Method.java:525)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at dalvik.system.NativeStart.main(Native Method)
08-23 05:30:09.364: E/AndroidRuntime(27497): Caused by: java.lang.NullPointerException
08-23 05:30:09.364: E/AndroidRuntime(27497):    at com.cvgstudios.pokemonchrome.RunAndroidChrome.onCreate(RunAndroidChrome.java:17)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.Activity.performCreate(Activity.java:5133)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-23 05:30:09.364: E/AndroidRuntime(27497):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2293)
08-23 05:30:09.364: E/AndroidRuntime(27497):    ... 11 more

As you can see the error is that

Could not find class 'com.cvgstudios.pokemonchrome.ChromeGame',
  referenced from method
  com.cvgstudios.pokemonchrome.RunAndroidChrome.onCreate

While looking around to find the answer to my dilema a possible solution was to make sure it was exporting the main project properly. I fixed that:

However the problem still persists.
I've checked everything all of the order and export boxes, in desktop, main and android project's buildpaths.
This is my class
import android.os.Bundle;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;

public class RunAndroidChrome extends AndroidApplication {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
        cfg.useGL20 = true;

        Gdx.app.log(ChromeGame.LOG,
                "Attempting to make Android Chrome Work");
        initialize(new com.cvgstudios.pokemonchrome.ChromeGame(), cfg);
    }
}

A:
There is an import missing in your Class RunAndroidChrome

import com.cvgstudios.pokemonchrome.ChromeGame;

Usually the IDE automatically import the depended Class.
If that is not a class defined by you, then the you must have forgot to Add Build Path..
Look here for how to add Build Path.

One another possibility is that you might have tested that in a wrong
  machine.

Also in cfg.useGL20 = true; we tell Android to use OpenGL ES 2. This means we will be able to test it only on a device as the emulator does not support OpenGL ES 2. In case there is a problem with it, switch this to false.
Check this Link for more information


text:
Q: Is there a possible way to optimize this union all sql? SELECT SUM(`amount`) AS total_amount,
       count(*) AS charge_count
FROM `chargetable`
WHERE appid='123'
  AND status='1'
UNION ALL
SELECT SUM(`amount`) AS total_amount,
       count(*) AS charge_count
FROM `chargetable`
WHERE appid='123'
  AND status='1'
  AND ch_created_time >='2015-07-28 00:00:00'
  AND ch_created_time <'2015-07-28 01:00:00'
UNION ALL
SELECT SUM(`amount`) AS total_amount,
       count(*) AS charge_count
FROM `chargetable`
WHERE appid='123'
  AND status='1'
  AND ch_created_time >='2015-07-28 01:00:00'
  AND ch_created_time <'2015-07-28 02:00:00'

Maybe there's a MySQL function can do the time auto split 1 hour, I couldn't find it.


text:
Q: How to 'name' images in Rails? So in html you can have the code  which makes editing in .css easier.
What is the equivalent of this when working with a .html.erb file?
e.g where do I define the class in this <%= image_tag "image.jpg" %>?

A: You can still use the native HTML in a .html.erb file, exactly as you've shown.  This definitely works in the ERB template:

This will often render slightly faster than using a dynamic approach, and has the benefit of being exactly what you intend.
If you choose the dynamic tag option, you can refer to the ActionView::Helpers::AssetTagHelper reference.  To get the Rails (ActionView) equivalent to what you've shown, you can use this syntax:
<%= image_tag 'image.jpg', class: 'myimage' %>

Note that the portion with the class: 'myimage' is providing the class attribute as a hash value, and this is simply shortcut syntax for { class: 'myimage' }.
You can also provide an ID to distinguish this image from other images of the same class by providing the id option, like so:
<%= image_tag 'image.jpg', class: 'myimage', id: 'image-1' %>

This will generate the following HTML:

From that point, you can style the image-1 image independently of other myimage images, should you need to do so.

A: you can use this syntax;
<%= image_tag('foo.jpg', class: 'myimage') %>

it will work for you!

A: I think comma will help, so:
 <%= image_tag 'foo.jpg', class: 'bar' %>


text:
Q: Set 2 color for an icon font I'm using IcoMoon font icons. I would like to display a star icon 80% blue and 20% white like the image below. How would I achieve that?

A: Here is what I usually use when i want to do a rating bar. enter link description here

You just place two icons on top of each other and limit the width of the colored ones.


text:
Q: What is a self-dual category? $\newcommand{\C}{\mathcal{C}}\newcommand{\D}{\mathcal{D}}\newcommand{\op}{\mathrm{op}}$I would like to define the notion of a self-dual category, which should mean a category isomorphic to its opposite in a natural way, and the notion a self-dual functor between such categories. For a category $\C$, I denote by $\C^\op$ its opposite category; for a functor $F \colon \C \to \D$ its opposite functor is $F^\op \colon \C^\op \to \D^\op$; for a natural transformation $\eta \colon F \Rightarrow G$ I denote $\eta^\op \colon G^\op \Rightarrow F^\op$ its opposite natural transformation.
Definition. A self-dual category is a category $\C$, a functor $i_\C \colon \C \to \C^\op$, and a natural isomorphism $$\epsilon_\C \colon i_\C^\op \circ i_\C \Rightarrow \mathrm{id}_\C.$$
I think this is the "correct" definition. (Not quite, see below.) An example would be for $\C$ the category of finite dimensional vector spaces over a field $k$, and $i_\C = \mathrm{Hom}(-,k)$. We would now like to talk about functors being self-dual, which should mean that they commute with taking duals.
Definition. A self-dual functor $\C \to \D$ is a functor $F \colon \C \to \D$ and a natural isomorphism
$$ \eta \colon i_\D \circ F  \Rightarrow  F^\op \circ i_\C $$
satisfying the following coherence condition: The diagram of natural isomorphisms
$$\begin{matrix} F \circ i_\C^{\op} & \stackrel{\eta^{\op}}{\Rightarrow} & i_\D^{\op} \circ F^{\op} \\\\ \epsilon_D \Uparrow ~  ~ ~ & &  ~ ~ ~ \Downarrow \epsilon_C^{\op} \\\\ i_\D^{\op} \circ i_\D \circ F \circ i_\C^{\op} & \stackrel{\eta}{\Rightarrow} & i_\D^{\op} \circ F^{\op} \circ i_\C \circ i_\C^{\op} \end{matrix}$$
commutes.
This whole definition is quite a mouthful and it feels like someone ought to have defined this carefully somewhere. Googling for self-dual or autodual categories produces several hits where people use this term for categories isomorphic to their opposite, but I haven't seen anyone discuss categories which have such an isomorphism in a coherent way. Does anyone know whether there is such a reference? Maybe this is a special case of a more general construction?

A: The question has essentially been answered in the comments, I am recording this here so that the question does not get bumped back to the top. Theo Buehler and Buschi Sergio both gave nice references, and it seems that this notion is well known in K-theory under the name "category with duality". Martin's remarks were also helpful.

A: Grothendieck defined the notion of "autodualité" in SGA 1 VI 11 d) "Exemples divers" in his formalism of fibred categories.


text:
Q: Laravel migration without losing the real data Is there a possible way to run artisan command to refresh a database without any lost any data?
In my past working, laravel with propel can make the database but doesn't lose any real data with propel:migration:diff.
Anyway with laravel default artisan migrate can it do it the same way?

A: By definition, refreshing the database (php artisan migrate:refresh) means you are removing all of the data.
The idea is that you're rolling back and re-running all of your migrations which would likely mean that your schema has changed a bit if not significantly and therefore the current data in your database might not match the new schema (and if it did then why would you be refreshing).
A better approach is to add to your migrations to alter columns and tables as you move through your development. In fact, this is one of the main advantages of having this type of "version control" for your DB.


text:
Q: iPhone:Color of TabBar image? I have added an image(Orange color) to TabBar, but when I run application image shown gray !
How can I slove this problem ?
thanks

A: The color is fixed to blue. You could either try to write your own custom tab bar interface, or hack together something to place custom icons over the tab bar in a subclassed UITabBarController, like this:
-(void)setActiveCustomOverlay
{
    if ( self.activeOverlay )
    {
            [self.activeOverlay removeFromSuperview];
    }

    NSString *imagename = [NSString stringWithFormat:@"tab_%d.png",
                                                        [self selectedIndex]];
    UIImage *img = [UIImage imageNamed:imagename];
    self.activeOverlay = [[[UIImageView alloc] initWithImage:img] autorelease];
    self.activeOverlay.frame = CGRectMake(2.0f+64.0f*[self selectedIndex],3.0f,60.0f,44.0f);

    [tabbar addSubview:activeOverlay];
    [tabbar bringSubviewToFront:activeOverlay];
}

And also do this:

*

*add a UIView property (nonatomic, retain) called activeOverlay

*add a tabbar property and hook it to the tab bar in IB

*call setActiveCustomOverlay whenever the tab changes.

This is an ugly hack, but the easiest fix to implement in existing projects. Apple will not reject it either.
For iPad you need to tweak the numbers, and use wider tab bar images.

A: The tab bar image color cannot be changed, it should be always be in the default color. Do read the Human interface guidelines of ios for more details.


text:
Q: Effects of a Resistor With this question I would like to clarify an understanding of resistors.
I have built these two schematics and performed a test.
Lighting the particular LED I use in this experiment directly with 1.5V produces no light at all, and lighting it directly with 3V lights it well.

I conclude the LED does not light with 1.5V for that is not enough voltage to open the diode's 'gate' at all,  yet the LED in "Schematic 2" is very dimly lit.
Measuring voltage between point A and B in "Schematic 1" reads 1.5V. Some may say by Kirchhoff's laws that is the voltage dropped by the resistor.
If the resistors actually 'drop' voltage this way, why does the LED light?
Is it safe to conclude the resistors only reduce current to the LED in this fashion and do not effect voltage to the LED?
Is 3V provided to the LED in "Schematic 2"?
I have created another one of these experiments.
Now, with a 10K and a 1M resistor, this LED (the green portion of an RGB) remains lit.
This LED still will not light on a single 1.5V AA.

I think using the classic needle voltmeter is giving an invalid reading.
Using an oscilloscope on difference mode at 1V a division,
I measure 2V on the LED (between B and C) no matter what resistors I use.
Measuring the resistors (between A and B, C and D) the sum of their voltage is about 1V, in the case of the photo, the 1M drops most of the 1V.
On the other schematic with the 1K's, both dropped about 0.5V
Do resistors drop a constant voltage upon completing a circuit and then only drop current from then on as resistance is increased?
The only voltage drop here to me seems directly caused by the diode.

A: Your question is far from clear to me. Your first schematic doesn't even show an LED. I will try to explain how everything works without any mysticism.
Resistors have two terminals, and they enforce a rule between those two terminals.
The rule is called "Ohm's law." Mathematically, the rule is V = I * R.
V is the voltage across the resistor.
I is the current flowing through the resistor.
R is the characteristic value of the resistor, normally measured in units called "Ohm's." Your resistors are 1k, so V = I * 1000.
Diodes are more complicated, so I am going to give you a simplified model. Assuming voltage polarity on the diode is correct (forward bias) the rule enforced by the diode is approximately V = K. (K is a constant). However, if the circuit is not capable of supplying that voltage across the diode, then it will enforce a different rule: I = 0. The constant, K, depends on the type of diode.
For an LED, any time I > 0, it may be emitting light. Red LED's are especially sensitive, and will emit light when even a tiny current is flowing.
A voltage supply also enforces the rule V = constant, normally by supplying current from its + terminal.
You put all these rules together, and hopefully everything will make sense. What circuits do is find the one unique solution to all the various rules. Sometimes the solution conditions cause the diode current (and light) to be zero. One way to check is to remove the diode from the circuit, then solve it. If V where the diode is supposed to go is > K for that diode, then the diode is in forward bias, and you need to put it back in and solve for the circuit assuming the voltage at that node is K.
Hope this makes some sense.

A: Resistors do drop voltage - but the voltage across a resistor is determined by the current through it - as calculated by Ohm's Law.  Also, by Ohm's Law, the current through a resistor is determined by the voltage across it.
In your circuit 1, with two 1K resistors across a 3 volt battery, you have 3 volts across a 2000 ohm resistance so the current in the circuit will be I = E/R = 3/2000 = .0015 Amp, or 1.5 mA.
In circuit 2, you still have 2K resistance in the circuit, but the LED will (for a typical red LED) drop about 1.8 volts.  (This voltage drop will increase slightly with increasing current.)  In this circuit, the total voltage across the two resistors will be the battery voltage, 3 volts, minus the LED voltage, 1.8 volts, or about 1.2 volts.  The current through the circuit will then be 1.2/2000 = .0005 Amp, or 0.5 mA, which will barely light the LED.
If you connect the LED directly to your 3 volt battery, without a resistor, the LED will try to draw enough current to reduce the battery voltage to the LED voltage, and will probably die in the attempt.  Batteries do have an internal resistance that varies with the state of charge or age of the battery - if the battery's internal resistance is high enough, the LED may survive for a while.


text:
Q: Difficulty parsing text file from FTP download t2=url("ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE1nnn/GSE1000/matrix/", open = "", blocking = TRUE, encoding = getOption("encoding"))
t2
t2=t2[-2]
isOpen(t2)
t2= readLines(t2, n = 4200)
t2[4010]
summary(t2)

With the above code I am able to get the ftp file, but I am unable to do any further plotting?
I am able to see the data.
But, I am unable to arrange it in table.
Can anybody help

A: The code below will read the data with no problems:
dta <- read.csv("ftp://ftp.ncbi.nih.gov/genbank/genomes/Bacteria/Escherichia_coli_K_12_substr__MG1655_uid225/U00096.ptt",
header = TRUE, skip = 2, sep = "\t")

I'm guessing that you are after a data frame:
> head(dta)
    Location Strand Length     PID Gene Synonym Code COG                                                Product
1   190..255      +     21 1786182 thrL   b0001    -   -                              thr operon leader peptide
2  337..2799      +    820 1786183 thrA   b0002    -   -  Bifunctional aspartokinase/homoserine dehydrogenase 1
3 2801..3733      +    310 1786184 thrB   b0003    -   -                                      homoserine kinase
4 3734..5020      +    428 1786185 thrC   b0004    -   -                                   L-threonine synthase
5 5234..5530      +     98 1786186 yaaX   b0005    -   -            DUF2502 family putative periplasmic protein
6 5683..6459      -    258 1786187 yaaA   b0006    -   - peroxide resistance protein, lowers intracellular iron

In order to simplify the import I skipped the first two lines:
Escherichia coli str. K-12 substr. MG1655, complete genome. - 1..4641652
4140 proteins
Location    Strand  Length  PID Gene    Synonym Code    COG Product
190..255    +   21  1786182 thrL    b0001   -   -   thr operon leader peptide

In case you want to read the whole file, I would suggest that you that have a look at this post. You can consider reading the whole thing and accessing the first two lines separately and then importing the rest to a data frame.

A: Testing my comment:
read.delim( text=c("4350031..4351662\t-\t543\t1790567\tdcuS\tb4125\t-\t-\tsensory histidine kinase in two-component regulatory system with DcuR, regulator of anaerobic fumarate respiration"   ,
"4351843..4352073\t+\t76\t1790568\tyjdI\tb4126\t-\t-\tputative 4Fe-4S mono-cluster protein" ), header=FALSE)
#---------
                V1 V2  V3      V4   V5    V6 V7 V8
1 4350031..4351662  - 543 1790567 dcuS b4125  -  -
2 4351843..4352073  +  76 1790568 yjdI b4126  -  -
                                                                                V9
1 sensory histidine kinase in two-component regulatory system with DcuR, regulator of anaerobic fumarate respiration
2                                                                               putative 4Fe-4S mono-cluster protein

I suspect that the first line is actually a header since that seems to be the pattern in the README files I looked at in that FTP site, so you probably would remove the header=FALSE. These are only lines [3883- 3884].


text:
Q: how to use variable in jstree data? this is my code
var treedata = ['{ "id" : "ajson1", "parent" : "#", "text" : "Customer" }',
   '{ "id" : "ajson2", "parent" : "ajson1", "text" : "Order number" }',
   '{ "id" : "ajson3", "parent" : "ajson1", "text" : "Date" }',
   '{ "id" : "ajson4", "parent" : "#", "text" : "Company Name" }',
   '{ "id" : "ajson5", "parent" : "#", "text" : "Contact Name" }',
   '{ "id" : "ajson6", "parent" : "#", "text" : "Name1" }',
   '{ "id" : "ajson7", "parent" : "#", "text" : "Product number1" }'];

$('#data').jstree({
        'core' : {
            'data' : treedata
        }
    });

but when i run it it do nothing but we i use this

$('#data').jstree({
        'core' : {
            'data' : {
                   ['{ "id" : "ajson1", "parent" : "#", "text" : "Customer" }',
   '{ "id" : "ajson2", "parent" : "ajson1", "text" : "Order number" }',
   '{ "id" : "ajson3", "parent" : "ajson1", "text" : "Date" }',
   '{ "id" : "ajson4", "parent" : "#", "text" : "Company Name" }',
   '{ "id" : "ajson5", "parent" : "#", "text" : "Contact Name" }',
   '{ "id" : "ajson6", "parent" : "#", "text" : "Name1" }',
   '{ "id" : "ajson7", "parent" : "#", "text" : "Product number1" }'];

}
        }
    });

it work
so how can i use variable in data ??
i wanted to run first code but it is not working

A: Do you mean that you want to use a variable for a property value?
If you just want to use the variable:
let n = 42;

const obj = {
  'id': n
}

If you want to place the variable within a string, any of the following works:
let name = 'Bob';

const obj = {
  'description1': `User, ${name}, is cool`,
  'description2': 'User, ' + name + ', is cool',
  'description3': 'User, '.concat(name, ', is cool')
};


text:
Q: Display the result of a function as variable in a browser using document.getElementbyId.innerHTML in JavaScript I am a newbie to JavaScript < 1 Week old
I wrote a very short HTML/JavaScript and got it to display on console.
Basically, I want to display the result of a function used as a variable inside the
 tag of the HTML.
I got the script to display in the console.
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>

How do I get the result of the function as a variable i.e var kilo (pounds)... to display in the p tag with id Kilograms?

A: Try this
var p = document.getElementById('Kilograms');
p.innerHtml = 'any text';
// OR
p.innerHtml = kilog(440);

A: Script shold be after BODY code, or you should add document ready event listener. So, try this solution:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>

Example in JSBin: https://jsbin.com/pacovasuve/edit?html,output

A: You can try this in your js code.
document.getElementById("Kilograms").innerHTML="write whatever you want here";


text:
Q: Preload polyfills before executing main code I'm trying to load some polyfills only if the user needs them but I can't get the scripts to download and be executed in order causing errors.
Dependencies have the asynchronous attribute and the main code has the defer attribute although is located at the end of the body tag so much of the parsing is already done.
Is there any simple way of doing this without using a preloader?
<html>
  <head>
  </head>
  <body>
    <script>
      // Google Analytics
    </script>
    <script>
      var firstScript = document.getElementsByTagName('script')[0];

      if (!self.fetch) {
        var fetchScript = document.createElement('script');
        fetchScript.src = '/js/fetch.min.js';
        fetchScript.async = 1;
        firstScript.parentNode.insertBefore(fetchScript , firstScript);
      }

      if (!self.URLSearchParams) {
        var urlspScript = document.createElement('script');
        urlspScript.src = '/js/url-search-params.min.js';
        urlspScript.async = 1;
        firstScript.parentNode.insertBefore(urlspScript , firstScript);
      }
    </script>
    <script defer src="/js/main.min.js"></script>
  </body>
</html>


text:
Q: EventEmitter and ag-grid-angular How to use the `emit` method in` ag-grid-angular` How to use the emit method inag-grid-angular. In ag-grid-angular I have buttons that should hide alternately and when clicking on another line.
When I click on another line the button does not change.
I try using the method emit, but I can't see it in my another component ButtComponent where I have buttons. I do not know if that's a good idea.
gridComponent.component.html:
   <ag-grid-angular
        (rowSelected)="onRowSelected($event)"
        [rowSelection]="rowSelection"
        (selectionChanged)="onSelectionChanged($event)"
        [suppressChangeDetection]='true'
        #agGrid
        style="width: 100%; height: 100%;"
        id="uprawnieniaGrid"
        class="ag-theme-balham"
        [columnDefs]="columnDefs"
        [rowData]="rowData"
        [frameworkComponents]="frameworkComponents"
         (gridReady)="onGridReady($event)">
    </ag-grid-angular>

gridComponent.component.ts:
export class GridComponent implements OnInit {

      @Output() eventEmitter: EventEmitter<string> = new EventEmitter<string>();
      rowData:any;
      frameworkComponents: any;
      gridApi?: GridApi;
      columnApi?: ColumnApi;
      columnDefs:any;

      constructor( private dataService: DataService ) {

        this.frameworkComponents = {
          buttons: ButtComponent,
          col5RenderComponent: Col3RenderComponent,
        };

        this.columnDefs = [{
          headerName: '',
          headerCheckboxSelection: true,
          checkboxSelection: true,
        }, {
          headerName: 'col 1',
          field: 'col1'
        }, {
          headerName: 'col 2',
          field: 'col2'
        }, {
          headerName: 'col 3 ',
          field: 'col3',
          editable: true,
          cellRenderer: 'col3RenderComponent'
        }, {
          headerName: "Edition",
          field: "value",
          cellRenderer: "buttons",
          colId: "edition"
        }
        ];

      }

       ngOnInit() {
        this.dataService.dataList().subscribe(dataList => {
          if (dataList.data) {
              this.rowData = dataList.data;
          }
        });
       }

      onGridReady(params: any) {
        this.gridApi = params.api;
        this.columnApi = params.columnApi;
        params.api.sizeColumnsToFit();
      }

      onSelectionChanged(event: any) {
        var rowCount = event.api.getSelectedNodes().length;
        console.log("selection changed, " + rowCount + " rows selected");
      }

      onRowSelected(event: any) {
        console.log("row " + event.node.data.id + " selected = " + event.node.selected);
       if (event.node.selected == false){
        this.eventEmitter.emit('Register click');
        console.log('EMIT');

       }
      }
    }

ButtComponent.component.html:
I have buttons here, but the eventEmitterTemp method is not called.

buttComponent.component.ts:
export class ButtComponent implements ICellRendererAngularComp  {

      params: any;
      isShowButton = {
        val1: true,
        val2: false
      };

      agInit(params: any): void {
        this.params = params;
      }

      constructor(private dataService: DataService) {}

      refresh(params: any): boolean {

        this.isShowButton.val1 = false;
        this.isShowButton.val2 = true;
        console.log('refresh');
        return true;
      }

      onClick1($event: any) {
        this.isShowButton.val1 = false;
        this.isShowButton.val2 = true;

        const startParams = {
          rowIndex: this.params.data.id - 1,
          colKey: 'col4'
        };
        this.params.api.startEditingCell(startParams);
      }

      onClick2($event: any) {

        this.isShowButton.val1 = true;
        this.isShowButton.val2 = false;

        this.dataService.dataSet().subscribe(dataList => {
            if (dataList.data) {
                this.rowData = dataList.data;
            }
        });
      }

        eventEmitterTemp($event: any){

        this.isShowButton.val1 = false;
        this.isShowButton.val2 = true;
            console.log('-----EMIT GET 1');
        }

    }

How to run the eventEmitterTemp method from the GridComponent component from the onRowSelected method when the condition is met:
if (event.node.selected == false)
Thank you very much for your help.

A: First of all, it would be really helpful if you posted a full running example, on say, StackBlitz.
However, I think that your issue is your attempt to bind to 'eventEmitter', i.e. your code:

As far as I know, given the code that you've shown, that should produce a compiler error.
I'm not really sure what you meant it to do...
If you want the code in the eventEmitterTemp method to be executed when the button is clicked, why not just either add that code to one of the click handler methods (onClick1 or onClick2, or both, depending on what you want to do)?
It seems to me that you have an additional design problem here.
Your 'ButtComponent' is a cell renderer, but you have it calling services, and apparently trying to interact with the grid (changing grid rows, etc.)
Interaction with the grid should be done in it's parent component, and the renderer should be kept really simple - just present the buttons, enable and disable them as necessary, and notify the parent component when a button is clicked.
The non-obvious part of that is how to notify the parent component when a button is clicked, and I'm guessing that that's why you are trying to do all of that stuff in the renderer.
The trick to doing that is to specify 'cellRendererParams' in your column definition.
The value for 'cellRendererParams' can be anything you want (see https://www.ag-grid.com/javascript-grid-cell-rendering-components/#complementing-cell-renderer-params).
In your case, you can pass in a call-back method. The renderer can get the call-back method in it's agInit() method, and call it whenever one of the buttons is clicked.


text:
Q: SpringBoot unit test inject properties on object annotated with @InjectMocks I have a class which handles jwt creation:
public class JwtTokenHandler {
    @Value("${jwtSecret}")
    private String jwtSecret;

    @Value("${jwtExpirationInMs}")
    private int jwtExpirationInMs;

    public String generateToken(String subject) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }
}

And it takes jwtSecret and jwtExpirationInMs from properties file which lies in resources folder.
In my unit test i just want to test that this class works as expected and generates JWT token, the problem i face is that these two properties don't get injected when i run the test even though i have another properties file in test/resources folder.
I found that there is solution using ReflectionTestUtils.setField but it's more like a workaround.
My unit test looks like this:
@RunWith(SpringRunner.class)
public class JwtTokenProviderTest {

    @InjectMocks
    private JwtTokenProvider jwtTokenProvider;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGenerateToken() {
        String result = jwtTokenProvider.generateToken("Test");
        assertThat(result).isNotBlank();
    }

A: Instead of @InjectMocks, I suggest look into Spring Boot's @MockedBean annotation. Faking beans is much easier with it.