text:
Q: Less repetitive way to add class to DOM element with Angular JS I am building an AngularJS application using materializecss for the UI.
Now, in the examples of materializecss, they add the focused class to all its forms elements in order to get certain behavior.
In order to achieve this, the immediate solution is to add the ng-class to the parent container asking for a variable which will be setting by using the ng-blur and ng-focus attributes in the input element.
This code ilustrates the above solution:

    <input type="text" name="myfield" data-ng-model="vm.myfield"
        data-ng-focus="vm.focused = true" data-ng-blur="vm.focused = false"/>

Is there any way to make this process less repetitive for all the components of my forms?

A: You may try to make a component / directive which encapsulates this behavior, similar to this: AngularJS custom text input component. And then you use directive / component like this:
<my-input model="vm.myField" name="myField"></my-input>

You have simplicity of ng-class solution, but code is still DRY.

A: I built a directive:
(function () {
     'use strict';

    function focused() {

        return {
            restrict: 'A',
            link:
            function (scope, element, attrs) {
                var clazz = attrs['focused'] || "focused";

                var parent = angular.element(element.parent());
                element.on("focus",function () {
                    if (!parent.hasClass(clazz)) {
                        parent.addClass(clazz)
                    }
                    scope.$apply();
                });
                element.on("blur",function () {
                    if (parent.hasClass(clazz)) {
                        parent.removeClass(clazz)
                    }
                    scope.$apply();
                });
            }
        }
    }

    angular.module('app')
        .directive('focused', [focused]);
 }());

Now, I can reduce my code to this:

    <input type="text" name="myfield" data-ng-model="vm.myfield"
        data-ng-focused/>


text:
Q: tinymce inline editor binding for loaded content I'm trying to make an e-mail template builder and I'm using tinyMCE 4.3.2.
I need a simple solution about binding editor to a div.
Steps :
1) I load an HTML block by using jquery.load
2) I look in this loaded HTML block and I give it a unique id (like id-234234324)
3) Then I bind the tinyMCE "inline" editor to this div.
It works correctly.
But when my loaded HTML block contains a "TABLE", TinyMCE not binding to resize actions for table cell.
Codes:
1) I'm dragging an item to template area
function draggingEnds(ui, templatePath, editorType) {

$(ui.helper).load(templatePath, '', function (body) {
    var rand = parseInt(Math.random() * 1000000000).toString();
    var newId = 'id-' + rand;
    $(body).insertAfter($(ui.helper)).find("div").attr("id", newId);
    $(ui.helper).remove();
    $("#template > *").bind("mouseover");
    bindSortable();
    if (editorType != "none") { bindEditor(newId, editorType); };
});};

2) Then I'm binding inline tinyMCE editor by using bindEditor() function
function bindEditor(id) {

tinymce.init({
    selector: '#' + id,
    language: 'tr',
    inline: true,
    plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table contextmenu paste',
    toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image'
});}

3) Loaded HTML

     Taşı
     Kopyala
     Sil

As you can see, tinyMCE not set "resizing actions" for cells:

redpajama_set_name: RedPajamaStackExchange


text:
Q: In the code igniter 3, how is the unique code applied in online nominal payments? I'm a beginner in programming. please allow me to ask. So I'm making a top up form with Codeigniter 3. I want to give a unique code for each nominal top up. For example, a member will top up 100,000, then what must be transferred is 100,123 (example). how to generate 3 numbers behind it?
Thanks for reading and willing to help

A: please let me help to answer the question. I think, you just add another php function, for random numbers as needed.
My Example code like this:
<?php
// get top up value from form
$value_top_up = 100000;
// add random number
$value_top_up += rand(100,999);
// example result = 100729

echo $value_top_up;
?>


text:
Q: Animation with css I want to move my left object till the red box and then hide it, then I want to show the right object just near the red box and then that object will also be move from red box to the right side of the page.
How to do this?
For explanation - click here
Image Link

A: Just challenged myself. You can use absolute positioning in a relative positioned container, and animate the absolute position of each other with a delay at the second object.

.all_container {
  position: relative;
  width: 100%;
  height: 50px;
}

.man_prev {
  position: absolute;
  left: 0;
  top: 10px;
  width: 40px;
  height: 40px;
  background: blue;
  z-index: 1;
  animation-name: man_prev;
  animation-duration: 3s;
  animation-delay: 0s;
  animation-fill-mode: forwards;
  animation-iteration-count: infinite;
}

.red_box {
  position: absolute;
  left: 50%;
  transform: translateX(-50%); /* to center it */
  top: 0;
  width: 60px;
  height: 60px;
  background: red;
  z-index: 2;
}

.man_next {
  position: absolute;
  left: 50%;
  transform: translateX(-50%); /* to center it */
  top: 10px;
  width: 40px;
  height: 40px;
  background: green;
  z-index: 1;
  animation-name: man_next;
  animation-duration: 3s;
  animation-delay: 2.3s;
  animation-fill-mode: forwards;
  animation-iteration-count: infinite;
}

@keyframes man_prev {
    from {left: 0;}
    to {left: 50%; transform: translateX(-50%);}
}

@keyframes man_next {
    from {left: 50%; transform: translateX(-50%);}
    to {left: 100%; transform: translateX(-100%);}
}

A: Try transition property with transition delays like this
For more information read this

.a {
    left :0;
    transition: left 2s linear 0s, opacity 0s linear 2s;
}
.b {
    left :50%;
}
.c {
    left: 50%;
    transition: opacity 0s linear 2s, left 2s linear 2s;
    opacity: 0;

}
.a.animate {
    left :50%;
    opacity: 0;
}
.c.animate {

  left: 96%;
  opacity: 1;

}

<button id="abc" style="margin-top: 50px;">
    Activate
</button>


text:
Q: Best way for draggable objects collision detection with complex objects I'm having a difficult time figuring out having objects with multiple bounds for a drag-able object. HitTest isn't working because when dragging fast, the object will overlap before HitTest fires. I was wondering if there was a more efficient way for figuring out this interaction.
I'm going to try to store each rectangle x,y,width,height, and then loop through those, to figure out if the object has touched and stop the player from being draggable in that direction.

A: Because you are trying to detect collisions happening at high speeds, you need to use some form of swept-polygon collision detection. Sampling collision at only one time between the previous and the last frame will always have a chance of failing.
Check out this brief explanation of Swept Collision detection:
http://howlingmoonsoftware.com/wordpress/?p=300
Or just do a search for "swept collision detection"
If you are doing this in a game, you might also find using a library like Box2D would be a worthy solution to the problem. In Box2D parlance what you want is continuous collision detection.
http://www.box2d.org/manual.html


text:
Q: How can I group items in a ruby array based on characteristics of each element? I have a letter array created by splitting any given word. I have a constant array of all five vowels, and I use that to classify each letter in the letter array as either a consonant or a vowel.
VOWELS = ["a","e","i","o","u"]

letters = "compared".split("")
   # => ["c", "o", "m", "p", "a", "r", "e", "d"]

word_structure = letters.map { |letter| VOWELS.include?(letter) ? "v" : "c" }
   # => ["c", "v", "c", "c", "v", "c", "v", "c"]

I want to somehow achieve two things:

*

*Group adjacent letters in the "letters" array that have the same "word_structure".

*Take those groups and return each possible VCV combination as another array. V represents a grouping of all adjacent vowels, and C represents a grouping of all adjacent consonants.

.
 groups = ["c", "o", "mp", "a", "r", "e", "d"]

 vcv_groups = ["-co", "ompa", "are", "ed-"]

In this example, the first VCV group begins with a "-" because there is no first grouping of vowels. The next two groupings fit the pattern fully, and the last has another "-" because there was no final vowel to complete the pattern.
I've experimented with Enumerable#chunk, Enumerable#partition and Enumerable#slice_before, but they're all just confusing to me. If somebody understands a simple way to achieve this, I would really appreciate the help.

A: You can do that with a regex (followed by a messy bit to insert hyphens as required):
VOWELS = 'aeiou'

R = /
    (?=                # begin positive look-ahead
      (                # begin capture group 1
        (?:            # begin a non-capture group
          [#{VOWELS}]+ # match one or more vowels
          |            # or
          \A           # match the beginning of the string
        )              # end non-capture group
        [^#{VOWELS}]+  # match one or more consonants
        (?:            # begin a non-capture group
          [#{VOWELS}]+ # match one or more vowels
          |            # or
          \z           # match end of string
        )              # end non-capture group
      )                # end capture group 1
    )                  # end positive lookahead
    /x                 # extended mode

 def extract(str)
   arr = str.scan(R).flatten
   arr[0].insert(0, '-') unless VOWELS.include?(arr[0][0])
   arr[-1] << '-' unless VOWELS.include?(arr[-1][-1])
   arr
 end

 extract 'compare'    #=> ["-co", "ompa", "are"]
 extract 'compared'   #=> ["-co", "ompa", "are", "ed-"]
 extract 'avacados'   #=> ["ava", "aca", "ado", "os-"]
 extract 'zzz'        #=> ["-zzz-"]
 extract 'compaaared' #=> ["-co", "ompaaa", "aaare", "aare", "are", "ed-"]

A: "compare"
.split(/([aeiou]+)/).unshift("-").each_cons(3)
.each_slice(2).map{|(v1, c, v2), _| v2 ||= "-"; [v1, c, v2].join}


text:
Q: Access not granted or expired GMAIL API and Oauth2 / How to set email signatures using GMAIL API with a GSuite domain i'm currently setting up an automatic signature system for every user of a google organisation but I haven't succeed to do so. I followed this guide but I have the following error : Service_.getAccessToken @ Service.gs:454. The problem is that: I don't have access to the file Service.gs and when I googled my error, no answers, either on google's github or stack overflow's website suits me well.
Here is the code (from the guide, I of course changed the auth values):
var accountsToIgnore = [
  'ignore-me@example.com',
  'noreply@example.com'
];

var auth = {
  "private_key": "-----BEGIN PRIVATE KEY-----\nABCDE\n-----END PRIVATE KEY-----\n",
  "client_email": "name@project-id-XXX.iam.gserviceaccount.com",
  "client_id": "INSERT_CLIENT_ID_HERE"
};

function go() {
  var pageToken;
  var page;

  do {
    page = AdminDirectory.Users.list({
      domain: 'example.com',
      orderBy: 'familyName',
      maxResults: 250,
      pageToken: pageToken,
      projection: 'full',
      // query: "email=your.email@example.com"
    });
    if (page.users) {
      page.users.forEach( function (user){
        if (accountsToIgnore.indexOf(user.primaryEmail) == -1) {

        var service = getOAuthService(user.primaryEmail);
        // Pull in the signatire template file contents into this variable
        var signatureTemplate = HtmlService.createHtmlOutputFromFile("signature").getContent();

          // Set up a userData variable, with some blank defaults as backups
          var userData = {
            email: user.primaryEmail,
            firstName: user.name.givenName,
            lastName: user.name.familyName,
            jobTitle: "",
            showJobTitle: true,
            workingHours: "",
            directPhone: ""
          };
          if (typeof user.customSchemas !== 'undefined') { // Email sig settings are set
            if (typeof user.customSchemas.Email_signature !== 'undefined') {

              if (typeof user.customSchemas.Email_signature.Show_job_title_in_signature !== 'undefined' && user.customSchemas.Email_signature.Show_job_title_in_signature == false) {
                userData.showJobTitle = false;
              }

              if (typeof user.customSchemas.Email_signature.Working_Hours_Description !== 'undefined' && user.customSchemas.Email_signature.Working_Hours_Description != "") {
                userData.workingHours = "

"+user.customSchemas.Email_signature.Working_Hours_Description+"
";
              }

            }
          }

          if (user.hasOwnProperty('organizations') && user.organizations[0].hasOwnProperty('title') && typeof user.organizations[0].title !== "undefined" && userData.showJobTitle == true) {
            userData.jobTitle = user.organizations[0].title+"
";
          }

          if (user.hasOwnProperty('phones') && Array.isArray(user.phones) && user.phones.length >0) {
            for (var p = 0; p < user.phones.length; p++) {
              if (user.phones[p].customType == "Google Voice") {
              // Depending on where in the world you are, you may need to adjust this formatting for your own needs... This replaces the +44 UK country code with a local "0" and adds a space after the local area code for formatting.
               userData.directPhone = "
D: " + user.phones[p].value.replace('+44', '0').replace('1158', '1158 ');
              }
            }
          }

          // Replace the placeholders as seen in the signature.html file with the actual data from the userData variable set up earlier.
          var userSig = signatureTemplate
          .replace(/(\r\n|\n|\r)/gm, "")
          .replace(/{email}/g, userData.email)
          .replace(/{firstName}/g, userData.firstName)
          .replace(/{lastName}/g, userData.lastName)
          .replace(/{jobTitle}/g, userData.jobTitle)
          .replace(/{workingHours}/g, userData.workingHours)
          .replace(/{directNumber}/g, userData.directPhone);

          var sigAPIUrl = Utilities.formatString('https://www.googleapis.com/gmail/v1/users/%s/settings/sendAs/%s',userData.email, userData.email);

          var response = UrlFetchApp.fetch(sigAPIUrl, {
            method: "PUT",
            muteHttpExceptions: true,
            contentType: "application/json",
            headers: {
              Authorization: 'Bearer ' + service.getAccessToken()
            },
            payload: JSON.stringify({
              'signature': userSig
            })
          });

          if (response.getResponseCode() !== 200) {
            Logger.log('There was an error: ' + response.getContentText());
          } else {
            Logger.log("Signature updated for "+user.primaryEmail);
          }
        }
      });

    } else {
      Logger.log('No users found.');
    }
    pageToken = page.nextPageToken;
  } while (pageToken);
}

function getOAuthService(userId) {
  return OAuth2.createService("Signature Setter "+userId)
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')
  .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') // Added thanks to research
  .setClientId(auth.client_id) // same
  .setCallbackFunction('authCallback') // same
  .setPrivateKey(auth.private_key)
  .setIssuer(auth.client_email)
  .setPropertyStore(PropertiesService.getScriptProperties())
  .setSubject(userId)
  .setParam('access_type', 'offline')
  .setScope('https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/gmail.settings.sharing');
}

The problem comes from the GMAIL API (100% errors on the google's API page) or from Google's OAuth2.
Here is some pages I found that are related to my problem:

*

*github Issue

*Stack Overflow
Full error code from apps.google: Error: Access not granted or expired. Service_.getAccessToken @ Service.gs:454
The credentials API (the warning sign mean that it has been created automatically):
https://prnt.sc/yy8kg5
The files and services I have on google's apps script editor: https://prnt.sc/yy9dyw
Thanks for the help.

A: Thanks to the answers above and some personal research, I managed to set up an automatic signature with Google Console and Gmail API.
This is a step by step guide on how to set up the system.
DISCLAIMER: I'm not a professionnal and I may do mistakes (so feel free to correct me if i'm wrong :) ), but I still want to make this "guide"... maybe it can help someone, who knows ?
1. GOOGLE APPS SCRIPTS
The steps are for the "New" Editor.

*

*Go to this link (google apps scripts) and create a new script.

*Go to Settings > Check "Show appsscript.json manifest file in editor"

*Editor > edit appsscript.json and add the oauthScopes:

{
...
"oauthScopes": [
      "https://www.googleapis.com/auth/gmail.settings.basic",
      "https://www.googleapis.com/auth/gmail.settings.sharing",
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/admin.directory.user",
      "https://www.googleapis.com/auth/script.external_request"
    ]
...
}

*In Editor tab: add the OAuth2 Library

*add the Gmail and AdminDirectory Services

*Copy this code (based on this page) and add your OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY and OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL (you'll get it in the next part)

*Create an new file HTML file named signature.html

*In Settings tab under "GCP Projet": add your projet Number (you'll get it in the next part)

2. GCP Project

*

*Go to this link and create a project

*On the project Info card, you can see the "Project Number" copy it, and paste it in the Google script settings tab.

*Go to "APIs & Services" > Credentials > create a "Service Accounts" (you don't need roles)

*Edit that Service Account you just created and check "Enable G Suite domain-wide delegation" under "Service account status" and create a new json key (this will make you dowload a file, save it in a safe place, sharing this will result in a security leak in your G Suite domain (don't forget to add the OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY and OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL in the script).

3. Google Admin (G Suite's Organization page)

*

*Go to Security > API Controls > "Manage Domain-wide delegation"

*Add new and add this scopes:

- https://www.googleapis.com/auth/gmail.settings.basic
- https://www.googleapis.com/auth/gmail.settings.sharing
- https://www.googleapis.com/auth/userinfo.email
- https://www.googleapis.com/auth/admin.directory.user
- https://www.googleapis.com/auth/script.external_request

4. Conclusion
It's now the part where you test the stuff, don't forget to create your signature via the signature.html file; look at the code.gs file to create something with user's info, it's pretty explicit.
If you have any problems, feel free to post a comment, i'll do my best to answer you.


text:
Q: generar pdf con Django Estoy utilizando una librería llamada weasyPrint para generar un PDF con una plantilla HTML y un CSS.
Mi problema es que no carga {% load static %} y no puedo cargar las imagenes que llevan ese pdf. Tampoco carga {% load bootstrap %} y {% extends %}.
Cuando genero el template y lo paso como plantilla HTML y no como PDF carga todas las propiedades que he dicho antes y consigo verlo bien.
Mi template
{% extends "frontend/base_frontend.html" %}
{% load static %}
{% block content %}

        <div class="separacion" style="background: rgba(5,171,168,1);background: -moz-linear-gradient(left, rgba(5,171,168,1) 0%, rgba(156,229,222,1) 26%, rgba(217,238,219,1) 42%, rgba(251,203,183,1) 59%, rgba(249,168,155,1) 75%, rgba(237,100,109,1) 100%);background: -webkit-gradient(left top, right top, color-stop(0%, rgba(5,171,168,1)), color-stop(26%, rgba(156,229,222,1)), color-stop(42%, rgba(217,238,219,1)), color-stop(59%, rgba(251,203,183,1)), color-stop(75%, rgba(249,168,155,1)), color-stop(100%, rgba(237,100,109,1)));background: -webkit-linear-gradient(left, rgba(5,171,168,1) 0%, rgba(156,229,222,1) 26%, rgba(217,238,219,1) 42%, rgba(251,203,183,1) 59%, rgba(249,168,155,1) 75%, rgba(237,100,109,1) 100%);background: -o-linear-gradient(left, rgba(5,171,168,1) 0%, rgba(156,229,222,1) 26%, rgba(217,238,219,1) 42%, rgba(251,203,183,1) 59%, rgba(249,168,155,1) 75%, rgba(237,100,109,1) 100%);background: -ms-linear-gradient(left, rgba(5,171,168,1) 0%, rgba(156,229,222,1) 26%, rgba(217,238,219,1) 42%, rgba(251,203,183,1) 59%, rgba(249,168,155,1) 75%, rgba(237,100,109,1) 100%);background: linear-gradient(to right, rgba(5,171,168,1) 0%, rgba(156,229,222,1) 26%, rgba(217,238,219,1) 42%, rgba(251,203,183,1) 59%, rgba(249,168,155,1) 75%, rgba(237,100,109,1) 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#05aba8', endColorstr='#ed646d', GradientType=1 );height: 4px;width: 100%;position: absolute;right: 0;">

COMPROBANTE DE COMPRA

CÓDIGO DE PEDIDO

{{pedido.id}}

CÓDIGO DE TRANSACCIÓN

{{pedido.id_transaccion}}

FECHA DE CREACIÓN

{{pedido.f_ped}}

PRECIO PRODUCTO

$ {{pedido.cp_total}}

NOMBRE COMPRADOR

{{pedido.cp_nombre_completo}}

E-MAIL COMPRADOR

{{pedido.perfil.usuario.email}}

{% endblock %}

Mi Función
def descargar_comprobante_compra(request, pedido):
    pedido = Pedido.objects.get(id=pedido)
    html_template = get_template('intranet/pdf/comprobante-compra.html')
    rendered_html = html_template.render().encode(encoding="UTF-8")
    pdf_file = HTML(string=rendered_html).write_pdf()
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'filename="comprobante.pdf"'
    return response


text:
Q: Dispose DbContext in MVC Controller, which way "better"? In MVC 5, the scaffolding codes will have something like:
    public class MyController : Controller
{
    private MyContext db = new MyContext();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

otherwise, I need to have
using (var db = new MyContext())
{...}

in each action.
The codes look good, so I don't need to use using in each action. However, is this subject to preference of programmers, or such style has some advantage over using in each action that needs to use the dbcontext?

A: Both solution are good - both solution will dispose db context. But in my opinion the second option will be better - you create db context just where you have to.
But what if another class (some service class) also uses db context. It is good practice to have one db context for the whole web request. In that case you should pass previous created db context to all classes that use db context to prevent creating new db context in all clases. So I will consider usage of IoC containers. IoC container will resolve your dependencies and also will mange object lifetime. Bellow
I listed a few IoC containers:

*

*Castle Windsor

*Spring Framework

*StructureMap

A: For simple scenarios calling Dispose (or using Using) is not necessary at all :)
"The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed."
From here:
http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/

A: In terms of best practices, you should absolutely use the template scaffolded stuff and not mess with the using(){} pattern unless you have some really good overriding reason. Both solutions produce the same result, but both are not good solutions. The reason why the template has a single DbContext is to make it easier to test - heres an example:
public class SomeController : Controller
{
    private ApplicationDbContext db;

    public AccountController()
    {
        db = new ApplicationDbContext();
    }

    public AccountController(ApplicationDbContext context)
    {
        db = context;
    }
}

The first constructor with no arguments is that which is used in production and automatically creates a new db context based on the app config file. The second allows you to inject a mocked db context when you are doing unit testing.
At the end of the day, this question and my answer isn't really about disposing db contexts - it's about why the code template designers chose to take the approach they did and why it will help you. You should read more on unit testing.

A: A Using statement calls the Dispose() method at the end of the Using block automatically. The Using statement calls the Dispose() method even if there was an error in the code.


text:
Q: What is the relationship between the structure/composition of the medium and the speed of light in this medium? We kwon that the speed of light (C=Co/n) depends on the properties of the medium in which it propagates (n, index of refraction).
As n is characteristics of the environment in which light propagates, in other words we could say from spectroscopy that it is a function of the Physicochemical properties of substance. We could include here, the chemical composition, as well as the spatial distribution of these atoms or elements, and other thermodynamic parameters such as temperature, pressure , …., etc.
Would it be possible to attribute a structure and composition to the vacuum knowing that n for the vacuum equals 1?
Would it be possible to proceed in reverse?

A: The speed of light is related to two properties, the permittivity $\varepsilon$ and the permeability $\mu$, by the equation:
$$ v = \frac{c}{n} = \frac{1}{\sqrt{\varepsilon \mu}} $$
In a dielectric material like glass the permittivity and permeability can in principle be calculated from the electronic structure of the material, though in practice the calculation may be too hard to do with any great accuracy. In this sense the speed of light is indeed related to the properties of the dielectric as you suggest.
However we cannot start with the speed of light and use it to tell us very much about the properties of the dielectric. The speed of light is just one number, and the electronic properties of the dielectric will in general be fiendishly complicated.
The permittivity and permeability of a dielectric are basically due to the electrons present in that dielectric and the quantum states those electrons occupy. But if we remove all the electrons (and the nuclei they orbit), so we are left with a vacuum, the permittivity and permeability do not disappeaer. Instead they become the vacuum permittivity $\varepsilon_0$ and the vacuum permeability $\mu_0$, and the speed of light is then just:
$$ c = \frac{1}{\sqrt{\varepsilon_0 \mu_0}} $$
and your question is whether the values of $\varepsilon_0$ and $\mu_0$ tell us anything about the structure of the vacuum.
But we run into the same problem as when we were considering the properties of a dielectric. The electromagnetic vacuum is described by quantum electrodynamics, and in principle we can use quantum electrodynamics to calculate the vacuum permittivity and permeability. So in this sense the speed of light in vacuum is related to the structure of the vacuum.
The problem is that, as before, the QED vacuum is very complicated and the speed of light is just one number. So while we can calculate the speed of light if we know the properties of the QED vacuum,  we can't go the other way i.e. start with the speed of light and calculate the properties of the vacuum from it.


text:
Q: How can I use a singleton design pattern for establishing and closing connection of JDBC? Here is my problem: I know it's not considered as a good pracitse, however I've been told by teacher to use singleton for JDBC connection.
Argument for why was that database connection is very expensive operation so I shouldn't connect to database every time I need to do operation with my database.
But how can I close the connection if my code looks like this? What are the options? I was looking for a solution of my problem but I couldn't find one.
Thank you very much!
I really appreaciate all your time and effort.
public class DbConnect {

    public static Connection con;
    public static Statement st;
    public static ResultSet rs;

    public DbConnect() throws SQLException{

       con = getDbConnection();
       st = con.createStatement();
       rs = null;
    }

    public static Connection getDbConnection(){
          try{
            Class.forName(("com.mysql.cj.jdbc.Driver"));

            con = DriverManager.getConnection( ....
                  ....
}

public static void closeConnection() throws SQLException{
    con.close();
    st.close();
    rs.close();
}

// Example of how I use it:
public void removeCustomer(String value) throws SQLException{

        String query="DELETE FROM customer WHERE idCustomer="+value;
        pst=DbConnect.con.prepareStatement(query); // THIS
        try {
            pst.executeUpdate();
        } catch (SQLException ex) {
                Logger.getLogger(CustomerRemover.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            pst.close();
        }

}

A: Your teacher should look up connection pools :)
He is correct, that opening a connection to a database with authentication and all that stuff is quite expensive. But this issue is solved with connection pools. That way, the database driver takes care of keeping a connection open.
So you can simply open / close a connection as open as you want: Opening a connection will check if there is already an connection open inside the connection pool and closing a connection will just put a connection back to the connection pool.
The important thing is, that a connection can time out. So if you simply try to keep one connection open all the time, then you might get an exception when trying to use the connection. (Some drivers can reopen connections automatically but afaik most don't.)
So my suggestion is really: When you need connection, then open it, use it and close it afterwards. And make sure to use connection pooling.
But if you really want to us a singleton, then use it correctly. A Singleton class normally has a private constructor and a static method to get the instance. The instance is a static variable which is either set inside the static constructor (So it is defined like static private MyClass instance = new MyClass(); ) or the getInstance checks if the instance is null and creates a first instance if required (using synchronized in case multiple threads try to call getInstance at the same time!)

A: Your teacher is incorrect. Remember you have two things that use resources. Your application and your database. So,
1. Always use Try With Resources convention so that you resources are properly closed. I witnessed a large software company use a thread pool to make JDBC connections. The database was not reachable for about two minutes but the application kept trying to make connections creating a new thread each time. This was assentially a memory leak and brought the whole system down. Use try with resources.
2. Having one persistent connection is less expensive for the front end application, but it is exponentially more expensive for the database. The common knowledge basic thing to do is to connect, select, and close as fast as possible.


text:
Q: How to convert json string to methodinfo parameter? I am trying to convert a json string to a MethodInfo parameter type. I have the followings:
Type type = typeof(MyClass);
MethodInfo mi = type.GetMethod(myMethod);
ParameterInfo [] parameteres=mi.GetParameters();
var jsonString="{\"LastName\":\"Test\"}"

Using these codes I have the input type of mymethod and it is a class containing a property named LastName (the class name is Class1).
Now how to convert jsonString to Class1.
Hint: We get the type Class1 in run time.

A: So, ParameterInfo calss has it own property ParameterType.
You should get this parameter and some lib to working with Json like this
https://www.nuget.org/packages/Newtonsoft.Json/
Then code will be like
Type type = typeof(MyClass);
MethodInfo mi = type.GetMethod(myMethod);
ParameterInfo [] parameteres=mi.GetParameters();
ParameterInfo myParameter = parameteres.FirstOrDefault();

var jsonString="{\"LastName\":\"Test\"}"
var myObjParameter = JsonConvert.DeserializeObject(jsonString, myParameter.ParameterType );

//Then create an objevt of main class.
ConstructorInfo constr = type .GetConstructor(Type.EmptyTypes);
object classInstance = constr.Invoke(new object[]{});

//And call method for this object
mi .Invoke(classInstance , new object[]{ myObjParameter });

A: Let's say your class looks like this
        public class MyClass
        {
            public string LastName { get; set; }
            private void myMethod(string LastName)
            {
                //do sutff
            }
        }

you can simply deserialize string like this(you can use Json.NET)
   var jsonString = "{\"LastName\":\"Test\"}";
   var lastName = JsonConvert.DeserializeObject<MyClass>(jsonString);

now you can use lastName as you wish dynamically or statically


text:
Q: Android Studio keeps reverting my changes I need help with my Android Project. More specifically, I want to know why Android Studio keeps reverting my changes for some reason.
I first got an error in my XML file saying, "Apostrophe is not preceeded \"
So I fixed the error and cleaned my project - but the change was undone, and the same error popped up.
I even tried deleting the entire string resource to avoid it, but all changes were reverted, and the message popped up again.
Does anyone know what kind of ghost is pranking me right now?

A: Search for all ' and " in your string.xml (and others if any) to be sure that they are all escaped as \' and \" resp.
For example string Can't do that must be escaped Can\'t do that

A: Try This in Android Studio Build Clean Project


text:
Q: Find PDF page count without reading the whole file My problem is the following:
There are some huge PDF files (>500MB) and I want to find their page count, using JAVA. If I use itext or pdfbox, I have to wait until it reads the whole file and most of the times this fails, because of the large size of the file or it just takes a lot of time.
So, I would like to know if there is any quick and efficient way to find the page count of a PDF file.

A: Possible duplicate? Page count of Pdf with Java
and from that's post, Mark Storer's answer:

The itext API underwent a little overhaul. Now (in version 5.4.x) the
  correct way to use it is to pass through java.io.RandomAccessFile:

int efficientPDFPageCount(File file) {
     RandomAccessFile raf = new RandomAccessFile(file, "r");
     RandomAccessFileOrArray pdfFile = new RandomAccessFileOrArray(
          new RandomAccessSourceFactory().createSource(raf));
     PdfReader reader = new PdfReader(pdfFile, new byte[0]);
     int pages = reader.getNumberOfPages();
     reader.close();
     return pages;
}


text:
Q: Show that $H$ is normal subgroup of $G$. Let $H\leq G$. Show that $H$ is normal iff $xHx^{-1}=H\space \forall x\in G$.
My textbook defines normal subgroup of $G$ as kernel of some homomorphism which has $G$ as domain.
I showed that if $H$ is normal, than $xHx^{-1}=H$ holds.
Suppose $f$ is some homomorphism from $G$ with $H$ in the kernel. Consider $h\in H$. Then $f(xhx^{-1})=f(x)f(h)f(x^{-1})=f(x)f(x)^{-1}=e'$. So $xhx^{-1}$ lies in the kernel and $xHx^{-1}=H$.
Can you give me idea how to show that if $xHx^{-1}=H$ then $H$ is a kernel of some homomorphism from $G$?

A: Thanks for comments. Based on them I'll try to answer on my own question. $xHx^{-1}=H \implies xH=Hx$. So we can consider a quotient group $G/H$. Now consider a homomorphism $f:G\to G/H$, where $f(x)=xH$. The kernel is $\{x\in G: f(x)=eH=H\}$.
I have to show that this set is equivalent to $H$. Since $H$ is a group then $xH$ for $x\in H$ is a subset of $H$. If $x\in G$ but $x\notin H$ then $xh\notin H$ just because $xe\notin H$. So $H=\{x\in G: f(x)=eH=H\}$ which means that $H$ is a kernel or normal subgroup of $G$.
Is there something wrong?


text:
Q: Backup PGSQL in a container using Golang docker SDK On host machine I have docker-compose stack that have a service called
transactions-db
its a PostgreSQL container
I want to create a backup service using Golang to be able to create .sql to be used for restores later on
docker-compose.yml for backup service
version: "3.8"

services:
  backup-service:
    build:
      context: .
      dockerfile: Dockerfile
    image: backup-service
    container_name: backup-service
    volumes:
      - .:/app
      - /var/run/docker.sock:/var/run/docker.sock

main.go
package main

import (
    "context"
    "fmt"
    "os"
)

func main () {
    result, err := ExecuteCommandOnContainer(context.Background(), ConnectToDocker(), "transactions-db")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(result.ExitCode)
}

docker.go
package main

import (
    "context"
    "fmt"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client"
)

func ConnectToDocker() *client.Client {
    cli, err := client.NewClientWithOpts()
    if err != nil {
        fmt .Println(err)
    }
    return cli
}
func ExecuteCommandOnContainer(ctx context.Context, cli *client.Client, containerID string) (types.ContainerExecInspect, error) {
    command := []string{"pg_dumpall", "-c", "-U", "user", "|", "gzip", ">", "backup/tr.sql"}
    execConfig := types.ExecConfig{
        Tty:          true,
        AttachStdin:  true,
        AttachStderr: true,
        AttachStdout: true,
        Cmd:          command,
    }
    create, err := cli.ContainerExecCreate(ctx, containerID, execConfig)
    if err != nil {
        fmt .Println(err)
    }

    inspect, err := cli.ContainerExecInspect(ctx, create.ID)
    if err != nil {
        fmt .Println(err)
    }
    return inspect, nil
}

basically nothing happens when I run this code. I only get the following:
backup-service  | 0
backup-service exited with code 0
I tried to normally run: go run .
I've also tried using my docker-compose up
same result
note: I've tested listing container it works but when trying to execute a command nothing


text:
Q: Maven archetypes not appearing in m2eclipse Nexus indexer I'm setting up a new workstation for Java development in Eclipse. On my previous machine, I don't recall having to do anything special to see the standard collection of archetypes under 'New > Other > Maven project > select archetype' with Nexus Indexer selected. On this machine, the list of archetypes is empty. I can create archetype-based projects from the command line, so it's not a show-stopper, but I just don't understand why the archetypes are missing (and it makes me wonder what else is broken that I haven't noticed yet).
Eclipse 3.5.1, Sun JDK 1.6.0_17, m2Eclipse 0.9.8.200905041414

A: Ian, make sure you update to 0.9.9 (the update-dev).   Open the Maven Repositories view in Eclipse (this is a new view only available in a recent build of m2eclipse).   From here you will be able to right click on a particular remote repository and force a redownload.
Once you do that, open up the console view and select "Maven Console", you should see m2eclipse printing out log messages detailing the index download. If it succeeded or failed.
Good luck.

A: Works fine here with the following configuration: Eclipse 3.5.1 20090920-1017, Sun JDK 6u16, m2eclipse 0.9.8.200905041414.
alt text http://img13.imageshack.us/img13/126/screenshotnewmavenproje.png
Are you sure m2eclipse has finished downloading nexus-maven-repository-index.gz from the maven central repository? Does this file looks "good"?
BTW, the index is stored in the plugin's metadata location which is <workspace root>/.metadata/.plugins/org.maven.ide.eclipse/nexus. As workaround, you could maybe try to copy the index from the machine where everything works to this destination on the "buggy" machine. But this shouldn't be necessary, things should just work.


text:
Q: Javascript dataURL POST to PHP not working I'm trying to post dataURL over to php but with no succsess.
My .js file is as follow.
var dataURL = signaturePad.toDataURL();
alert(dataURL);
$.ajax({
    type: "POST",
    url: "test.php",
    data: {
    imgBase64: dataURL
    }
    }).done(function(o) {
      console.log('saved');
      alert(o);
    });

alert(dataURL) output is as follow;
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....

test.php
<?php
if($_POST['imgBase64']) {
$img = $_POST['imgBase64'];
}
else{
$img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....";
}
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$timestamp = date('YmdHis');
$fileName = ''.$timestamp.'.png';
echo"$fileData";
file_put_contents($fileName, $fileData);
?>

In my php file I have entered the value of my alert for testing purposes. Now my php page is working 100% due to the test and passing no value from my .js function. but with the correct value it's not even posting to my php page, only when I remove all not standard characters from the dataURL then it post but obvious with corrupt data.
To avoid further confusion the following code works 100%, the .js and the php. where var dataURL = signaturePad.toDataURL(); is passed to the function
function postData(data) {
    alert(data);
    var desired = data.replace(/[^\w\s]/gi, '');
    $.ajax({
        type: "POST",
        url: "test.php",
        data: {
        imgBase64: desired
        }
    }).done(function(o) {
       console.log('saved');
       alert(o);
    });
}

So the problem is the .js will not post with the given dataUrl due to special characters, but I cant remove them.. I even tried var desired = encodeURIComponent(data); witch I can at least decode on the php page but this also does not want to post.

A: data: {
    imgBase64: data
    //send key is imgBase64 and data value is undefined in given scope
    //replace data with dataURL
}

And in php file change this $_POST['image'] to $_POST['imgBase64']

A: Thanks for the replies..
I ended up creating a blob first and posting the blob.
function dataURLToBlob(dataURL) {
  var parts = dataURL.split(';base64,');
  var contentType = parts[0].split(":")[1];
  var raw = window.atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  return new Blob([uInt8Array], { type: contentType });

    $.post("test2.php",
    {
      name: uInt8Array
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });

}


text:
Q: Package does not exist on build but importing without errors? My project was building fine until I added Kryo dependency to my project. I can use both Netty and Kryo without syntax errors in my IDE but it won't build. All I did was adding Kryo to my common module and started implementing Kryo in my code, when I wanted to run Gradle it returned a big list of errors about none existent Netty and Kryo packages.
My gradle is very simple, client and server module both depend on common which atm has 2 custom classes and implement Kryo and Netty.
project(":common") {
    apply plugin:'java'
    dependencies {
        // https://mvnrepository.com/artifact/io.netty/netty-all
        implementation group: 'io.netty', name: 'netty-all', version: '4.1.33.Final'
        // https://mvnrepository.com/artifact/com.esotericsoftware.kryo/kryo
        implementation group: 'com.esotericsoftware.kryo', name: 'kryo', version: '2.24.0'
    }
}

project(":server") {
    apply plugin:'java'
    dependencies {
        implementation project(":common")
        // https://mvnrepository.com/artifact/org.mongodb.morphia/morphia
        compile group: 'org.mongodb.morphia', name: 'morphia', version: '1.3.2'
    }
}

project(":client") {
    apply plugin:'java'
    dependencies {
        implementation project(":common")
    }
}

In client and server (both just java applications atm) I am using Kryo and Netty without syntax errors but when I run or build I get the following list for each class that imports Netty or Kryo.
error: package io.netty.channel does not exist
error: package io.netty.channel does not exist
error: package io.netty.channel does not exist
error: package io.netty.channel.group does not exist
error: cannot find symbol class ChannelInboundHandlerAdapter
error: cannot find symbol class ChannelGroup
error: cannot find symbol class ChannelHandlerContext
error: cannot find symbol class ChannelGroup
error: cannot find symbol class ChannelHandlerContext
error: cannot find symbol class ChannelHandlerContext
error: method does not override or implement a method from a supertype
error: method does not override or implement a method from a supertype

I tried the most obvious invalidate cache / restart, cleaning, rebuilding without success. Apart from that I tried fiddling with the plugin, setting it to java-library and back. The only thing I did differently then usual is that I tried to exclude Kryo for the other 2 modules but I gave up on that after a few attempts for the time being and erased those exclude lines. It's probably just something I overlooked but I can't put my finger on it.


text:
Q: Angular momentum conservation in a rocket-sun-moon system Let us describe a rocket traveling from earth to the moon and back. I want to show that the rocket's angular momentum is conserved to be able to conclude that the rocket's motion is restricted to a two-dimensional plane. Let us assume that the earth is in the origin and the moon is located at $\boldsymbol{r}_\mathrm{M} = d\boldsymbol{e}_1$, where $d$ is the distance between earth and moon.
Let $\Phi(\boldsymbol{r}) = -\gamma\left(\frac{m_\mathrm{E}}{|\boldsymbol{r}|}+\frac{m_\mathrm{M}}{|\boldsymbol{r}-\boldsymbol{r}_\mathrm{M}|}\right)$ be the gravitational potential. The gravitational force reads
\begin{equation}
\boldsymbol{F}(\boldsymbol{r}) = -\gamma m_\mathrm{R}\left(\frac{m_\mathrm{E}}{|\boldsymbol{r}|^3}\boldsymbol{r}+\frac{m_\mathrm{M}}{|\boldsymbol{r}-\boldsymbol{r}_\mathrm{M}|^3}(\boldsymbol{r}-\boldsymbol{r}_\mathrm{M})\right).
\end{equation}
The angular momentum with respect to the origin is however not conserved as
\begin{equation}
\dot{\boldsymbol{L}} = \boldsymbol{r}\times\boldsymbol{F} = \frac{\gamma m_\mathrm{R} m_\mathrm{M}}{|\boldsymbol{r}-\boldsymbol{r}_\mathrm{M}|^3}\,\boldsymbol{r}\times\boldsymbol{r}_\mathrm{M}.
\end{equation}
I also thought about choosing another coordinate system (e.g. center of mass) but this did not work. Any ideas how to show this? Thank you in advance!

A: Conservation laws often come from symmetries of the Hamiltonian. In this case, in order to conserve angular momentum you would need a rotationally symmetric Hamiltonian. But a system of two point masses is not rotationally symmetric and therefore, as you have discovered, the angular momentum of the rocket is not conserved.
If the initial position and velocity of the rocket, the Moon and the Earth lie on the same plane, you can expect that the motion will be restricted to such plane. Otherwise, the trajectory will be tridimensional.

The intuitive proof of this statement is that the force always lies in the plane formed by $\vec{r}_M$ and $\vec{r}(t)$, therefore the rocket won't feel any force orthogonal to the plane. If the velocity lies on this plane too, the rocket won't leave the plane and the orbit is planar.
A somewhat more rigorous proof:
An orbit is said planar if it is fully contained in a plane.  This statement can be written as
$$\exists \vec{w} : (\vec{r}(t)-\vec{r}_0)\cdot\vec{w} = 0 \tag 1$$
where $\vec{r}_0$ is the initial position (at $t=0$) and $\vec{w}$ is the vector normal to the plane of the orbit. Differentiating the equation one obtains:
$$\dot{\vec{r}}(t) \cdot \vec{w} = 0  \tag 2$$
$$\ddot{\vec{r}}(t) \cdot \vec{w} = 0 \tag 3$$
This means that both velocity and acceleration must lie on the same plane for the whole motion.
Let's consider the plane formed by the vectors $\vec{F}(\vec{r}_0)$ and $\vec{r}_M$, and let $\vec{w} = \vec{F}(\vec{r}_0) \times \vec{r}_M$. It is easy to see that for every point $\vec{r}$ on the plane, equations $(1)$ and $(3)$ hold.
If we want a planar orbit, it is necessary at this point to choose the initial velocity such that $\vec{v}_0 \cdot \vec{w} = 0$, and you can see that after a small time
$$\vec{v}(\delta t) \cdot \vec{w} = (\vec{v}_0 + \dot{\vec{v}}\delta t) \cdot \vec{w} = \vec{v}_0 \cdot \vec{w} + (\vec{F}(\vec{r}_0) \cdot \vec{w}) \delta t/m = 0$$
In other words, as long as the rocket is on the plane, its velocity will keep lying on it.

A: The angular momentum is conserved if the force points always to the system COM, that means: it is radial, so that $\mathbf r \times \mathbf F = 0$.
It is not the case for the Earth-Moon system. For example: any object nearby the Moon will not fall to the system COM, or an astronaut could not walk in the Moon surface.

A: The angular momentum of the system; earth, moon, and rocket, can be conserved. The the angular momentum of the rocket cannot.  The rocket will be subject to two forces. At least one of these will produce a torque about any chosen reference point.


text:
Q: How to read values from one of custom Queries in MS Access VBA? I have a MS ACCESS query called Query11 that sums up amounts.
Let's say it's got SUM_WEEKLY and SUM_MONTHLY as a field in Query11
In VBA, how could I get each value?
I have tried to get them with the codes below and it did not work.
Dim dbMyDB As Database
Dim rsMyRS As Recordset

Set dbMyDB = CurrentDb
Set rsMyRS = dbMyDB.OpenRecordset("Query11")

MsgBox rsMyRS("SUM_WEEKLY")
MsgBox rsMyRS("SUM_MONTHLY")

A: Your code should work, and you don't tell the error, but try to be a bit more explicit:
Dim dbMyDB As DAO.Database
Dim rsMyRS As DAO.Recordset

Set dbMyDB = CurrentDb
Set rsMyRS = dbMyDB.OpenRecordset("Query11")

' Check that a record exists.
MsgBox CStr(rsMyRS.RecordCount)

MsgBox rsMyRS("SUM_WEEKLY").Value
MsgBox rsMyRS("SUM_MONTHLY").Value

A: Dim db As DAO.Database
Dim rs As DAO.Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("Query11")

' Check a record exists
If rs.RecordCount > 0 Then
 MsgBox "SUM_WEEKLY = " & rs!SUM_WEEKLY
 MsgBox "SUM_MONTHLY = " & rs!SUM_MONTHLY
Else
 MsgBox "Recordset has no records"
End If


text:
Q: Swift iOS: Unable to Upload Image to AWS S3 So, I've created an S3 bucket with the following policy:
{
    "Version": "2012-10-17",
    "Id": "Policy123",
    "Statement": [
        {
            "Sid": "Stmt123",
            "Effect": "Allow",
            "Principal": {
                "AWS": "User_ARN"
            },
            "Action": "s3:ListBucket",
            "Resource": "Buckent_ARN"
        },
        {
            "Sid": "Stmt1569218242333",
            "Effect": "Allow",
            "Principal": {
                "AWS": "User_ARN"
            },
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "Buckent_ARN/*"
        }
    ]
}

I've also created a Cognito Identity Pool & an IAM user. Now, I'm trying to upload an image to my bucket from my app and am getting:
The operation couldn't be completed. (com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.)
In my AppDelegate I'm setting up with the following:
 let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.usWest2,
           identityPoolId:"us-west-2:XXXXX")

        let configuration = AWSServiceConfiguration(region:.usWest2, credentialsProvider:credentialsProvider)

        AWSServiceManager.default().defaultServiceConfiguration = configuration

and trying to upload my image like this:
if let imageToUpload =  self.myImage {
    let awsTransferUtilitytransferUtility = AWSS3TransferUtility.default()
    let s3BucketName = "my-bucket"

    let pngImage = imageToUpload.pngData()
    let filename = "someImage.png"
    let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
    do {
        try pngImage?.write(to: fileURL)

        awsTransferUtilitytransferUtility.uploadData(pngImage!, bucket: s3BucketName, key: filename, contentType: "img/png", expression: nil) { (uploadTask, error) in
            if error != nil {
                print("error is: \(error!.localizedDescription)")
            } else {
                print("Task Result: \(uploadTask)")
            }
        }

    } catch {
        print("File not saved!")
    }
}

I'm pretty sure this is a permissions issue, because I created a public bucket and was able to upload the image without a problem.  I'm new to AWS and the permissions are very confusing to me.  I created an IAM role, which I've assigned to the bucket policy and I've setup a Cognito Identity Pool.  But, what's the link between Cognito & IAM?  Do I need to provide IAM credentials in my code to upload?  I've done my setup with the following article:  https://medium.com/@haydnjmorris/uploading-photos-to-aws-s3-getting-started-with-cognito-and-iam-c96ba5b5496d
Any help would be greatly appreciated!


text:
Q: How to invoke client side form validation in MVC 5 without a Submit button How to force MVC-5 client side engine to validate the form with out using submit button?
I have one button and one check box in the form, I want to get validate the form when I click on the button or press the check box. The type of button is not submit.

A: var form = document.forms[0];
$(form).validate();
if(!$(form).valid()){
          alert("Error's in the module");
          return;
}


text:
Q: php echo database row results into a card I am trying to echo my database results into a bootstrap 4 card, each row result will be in its own bootstrap card.
I have been able to show the results in a table
Echo to table - THIS WORKS

  <?php echo "
";

// table header
echo "
Company Name	Date Requested	Request By	Graphic Type	Double Sided	Design Info	Purpose	Approved	Approval Date
";

// output data of each row
while($row=mysqli_fetch_assoc($designresult)) {

    echo "
".$row["companyName"]."	".$row["dateReq"]."	".$row["yourName"]."	".$row["graphicType"]."	".$row["doubleS"]."	".$row["info"]."	".$row["purpose"]."	".$row["approved"]."	".$row["appDate"]."
";
}

// table footer

echo "
";

?>

My attempt at echoing into cards
<?php
// output data of each row
while($row=mysqli_fetch_assoc($designresult)) {

echo "

 div class="card-header">

Track Design

 Company Name ".$row["companyName"].";

";

}
?>

A: In the first solution you are escaping " in using ' quotes.
In the second one, you are using " in your HTML code. As you echo that and your echo starts with " aswell, you are ending the echo.
echo "<div class=" <-- Ending the echo, not starting the class name

You have to change it to this:
echo "
"

You can also close the PHP tag:
<?php
// output data of each row
while($row=mysqli_fetch_assoc($designresult)) {

?>

Track Design

 Company Name <?php echo $row["companyName"]; ?>

<?php

}
?>


text:
Q: Error:An error occurred configuring project ':app'. > The SDK directory does not exist i am importing one project. i am running this on linux. but when i build my project it gives me this error.
**Error:A problem occurred configuring project ':app'.

The SDK directory '/home/custom/Documents/Zebra_RFID_Mobile-1.0.2.17/C:\Users\DHXW76\AppData\Local\Android\Sdk' does not exist.**
  Below is my local.properties file

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Mon Sep 11 14:54:05 IST 2017
ndk.dir=/home/custom/Android/Sdk/ndk-bundle
sdk.dir=/home/custom/Android/Sdk

I am wondering that how is this error showing c:\users.... path, although i am trying it to run this on linux.
I have also checked my sdk location, it is perfect. can anybody help me solve this issue?

A: I had this problem. I'm using Linux.
Project stucture windows
How I corrected the error:

*

*Need to check SDK Manager. Is the SDK similar to your project?SDK Manager
2.Checking Gradle.Gradle Folder Gradle
The version number in the Project Structure /project and in the /opt/android-studio/gradle/gradle-4.6/ folder should be the same. If the problem persists, update the Gradle.
2.1 We go to the site: https://gradle.org/install/#with-a-package-manager and download the binary version. Download the archive we throw in the folder /opt/android-studio/gradle/gradle-4.6/ and write down its version number in Project Structure /project.
3.Restart the studio.
If the program code shows an incorrect version of Gradle, then an error will appear that is difficult to fix. Try to check all the code or create a new project.
Check Gradle easily by creating a new project. I like this method.


text:
Q: How exactly do I make money with AdMob? I have AdMob ads in my app, and there are things that still are not clear to me. I have searched a long time on the internet, and many people say different things.
I know I make money when people click on my ads . But do I make money by impressions as well, or only clicks. Many guys says if there is no clicks, there is no money. Say I have 1 000 000 impressions daily, but no clicks. I then make zero money?
Also some people are saying if you have a lot of impressions, you don´t make much money if people click on your ads. Lets say App Nr.1 has got 1 000 000 impression daily and 100 clicks daily, and App Nr.2. has got only 10 000 impressions daily but the same number of clicks. Which app makes more money on their clicks?
Do my fill rate have anything to say on what I make on impressions? It says: Additionally, the number of impressions may be lower if your app preloads ads. For example, if an app sends an ad request when it opens, but only shows that ad to users if certain criteria are met, such as reaching a specified level. If a user doesn't meet the criteria, the ad will not be shown and will report no impressions for that request.  My app preloads most of its ads, for example when my interstitial that is being shown when a user has made a turn in my TurnBased game is being closed by the user, I load a new interstitial right away. I do it so the ad is "available" when another turn is being made, which Admob Guide Lines advised me to do. Will this "hurt" my revenue in any way?

A: This has been answers many times.
Generally you are only paid for the clicks on ads.
If you generate a really large number of impressions then you might also get paid something for your impressions.
Fill rate is just the percentage of time that an ad was available to you when you requested it. There may not always be an ad available to your user, because of current ad market, their location, time of day, type of device they are using. It is a good idea to use mediation to ensure that if one ad network has no ad that another is asked. This can ensure a 100% fill rate. Which means you are showing ads 100% of the time that you could.
Gaming the system is not a good idea. Google run all kinds of analysis over your requests, impressions, clicks. When (not if) you are caught you will have your account banned.


text:
Q: How to erase lines with nothing in second column in bash? This is a sample output of curl -s ifconfig.me/all | column -t:
ip_addr:      193.136.19.55
remote_host:  gwec.di.uminho.pt
user_agent:   curl/7.22.0        (x86_64-pc-linux-gnu)  libcurl/7.22.0  OpenSSL/1.0.1  zlib/1.2.3.4  libidn/1.23  librtmp/2.3
port:         37429
lang:
connection:
keep_alive:
encoding:
mime:         */*
charset:
via:
forwarded:

I like to parse this in such a way that the user_agent field doesn't get tabs, and erase all fields with no results.
ip_addr:      193.136.19.55
remote_host:  gwec.di.uminho.pt
user_agent:   curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
port:         37429
mime:         */*

A: With awk you can use awk '$2', that will check whether the 2nd field exists or not. If it does exist, the line will be printed.
In your case,
curl -s ifconfig.me/all | column -t | awk '$2'

Example
$ awk '$2' your_result
ip_addr:      193.136.19.55
remote_host:  gwec.di.uminho.pt
user_agent:   curl/7.22.0        (x86_64-pc-linux-gnu)  libcurl/7.22.0  OpenSSL/1.0.1  zlib/1.2.3.4  libidn/1.23  librtmp/2.3
port:         37429
mime:         */*

I like to parse this in such a way that the user_agent field doesn't
  get tabs, and erase all fields with no results.

Use the input field separator (FS=tab) and output field separator (OFS=space) like this:
$ awk 'BEGIN{FS="\t";OFS=" "} $2 {printf "%s\t",$1; for (i=2; i<=NF; i++) printf $i ; printf "\n"}' your_result
ip_addr:        193.136.19.55
remote_host:    gwec.di.uminho.pt
user_agent:     curl/7.22.0(x86_64-pc-linux-gnu)libcurl/7.22.0OpenSSL/1.0.1zlib/1.2.3.4libidn/1.23librtmp/2.3
port:   37429
mime:   */*

A: awk 'BEGIN{OFS=" "}NF>1{t=$1;$1="";printf "%-13s%s\n",t,$0}'

Output with the sample input:
ip_addr:      193.136.19.55
remote_host:  gwec.di.uminho.pt
user_agent:   curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
port:         37429
mime:         */*


text:
Q: What does this expression calculate Suppose X and Y are two positive integers and Y is a power of two. Then what does this expression calculate?
(X+Y-1) & ~(Y-1)
I found this expression appearing in certain c/c++ implementation of Memory Pool (X represents the object size in bytes and Y represents the alignment in bytes, the expression returns the block size in bytes fit for use in the Memory Pool).

A: &~(Y-1) where Y is a power of 2, zeroes the last n bits, where Y = 2n: Y-1 produces n  1-bits, inverting that via ~ gives you a mask with n zeroes at the end, anding via bit-level & zeroes the bits where the mask is zero.
Effectively that produces a number that is some multiple of Y's power of 2.
It can maximally have the effect of subtracting Y-1 from the number, so add that first, giving (X+Y-1) & ~(Y-1). This is a number that's not less than X, and is a multiple of Y.

A: It gives you the next Y-aligned address of current address X.
Say, your current address X is 0x10000, and your alignment is 0x100, it will give you 0x10000. But if your current address X is 0x10001, you will get "next" aligned address of 0x10100.
This is useful in the scenario that you want your new object always to be aligned to blocks in memory, but not leaving any block unused. So you want to know what is the next available block-aligned address.

A: Why don't you just try some input and observe what happens?
#include <iostream>

unsigned compute(unsigned x, unsigned y)
{
    return (x + y - 1) & ~(y - 1);
}

int main()
{
    std::cout << "(x + y - 1) & ~(y - 1)" << std::endl;
    for (unsigned x = 0; x < 9; ++x)
    {
        std::cout << "x=" << x << ", y=2 -> " << compute(x, 2) << std::endl;
    }

    std::cout << "----" << std::endl;

    std::cout << "(x + y - 1) & ~(y - 1)" << std::endl;
    for (unsigned x = 0; x < 9; ++x)
    {
        std::cout << "(x=" << x << ", y=2) -> " << compute(x, 2) << std::endl;
    }

    return 0;
}

Live Example
Output:
First set uses x in [0, 8] and y is constant 2. Second set uses x in [0, 8] and y is constant 4.
(x + y - 1) & ~(y - 1)
x=0, y=2 -> 0
x=1, y=2 -> 2
x=2, y=2 -> 2
x=3, y=2 -> 4
x=4, y=2 -> 4
x=5, y=2 -> 6
x=6, y=2 -> 6
x=7, y=2 -> 8
x=8, y=2 -> 8
----
(x + y - 1) & ~(y - 1)
(x=0, y=2) -> 0
(x=1, y=2) -> 2
(x=2, y=2) -> 2
(x=3, y=2) -> 4
(x=4, y=2) -> 4
(x=5, y=2) -> 6
(x=6, y=2) -> 6
(x=7, y=2) -> 8
(x=8, y=2) -> 8

It's easy to see the output (i.e., result right of ->) is always a multiple of y such that the output is greater than or equal to x.

A: Let's break it down, piece by piece.
(X+Y-1) & ~(Y-1)

Let's suppose that X = 11 and Y = 16 in accordance with your rules and that the integers are 8 bits.
(11+16-1) & ~(16-1)

Do the Addition and Subtraction
(26) & ~(15)

Translate this into binary
(0001 1010) & ~(0000 1111)

~ means not or to invert the zeros and ones
(0001 1010) & (1111 0000)

& means only to take the bits that are both ones
0001 0000

convert back to decimal
16

other examples
X = 78, Y = 32 results in 96
X = 25, Y = 64 results in 64
X = 47, Y = 16 results in 48

So, it would seem to me that the purpose of this is to find lowest multiple of Y that is equal to or greater than X. This could be used for finding the start/end address of a block of memory, or it could be used for positioning items on the screen, or any number of other possible answers as well. But without context and possibly even a full code example. There's no guarantee.

A: First I assume that X and Y are unsigned integers.
Let's have a look at the right part:

*

*If Y is a power of 2, it is represented in binary by one bit to 1 and all the others to 0.  Example 8 will be binary  00..01000.

*If you substract 1 the highest bit will be 0 and all the bits to its right will become 1.  Example 8-1= 7 and in binary 00..00111

*If you ~ negate this number you will make sure that all highest bit (including the original one will turn to 1 and the lovest to 0.  Example:  ~7 will be 11..11000

*Now if you do a binary AND (&) with any number, you will set to 0 all the lower bits, in our example, the 3 lower bits.  THe resulting number is hence a multiple of Y.

Let's look at the left side:

*

*We've already analysed Y-1.  In our example we had 7, that is 00..00111

*If you add this to any number, you make sure that the result is greater than or equal to Y.  Example with 5: 5+7=12 so 00..01100 and example with 10:  10+7=17  so 00..10001

*If you then perform the AND, you'll erase the lower bits. so in our example with 5, we come to 00..01000 = 8 and in our example with 10 we get 00..10000 16.

Conclusion, it's the smallest multiple of Y wich is greater or equal to X.

A: It seems provides a specified alignment of a value for example of a memory address (for example when you want to get the next aligned address).
For example if you want that a memory address would be aligned at the paragraph bound you can write
( address + 16 - 1 ) & ~( 16 - 1 )

or
( address + 15 ) & ~15

or
( address + 15 ) & ~0xf

In this case all bits before 16 will be zeroed.
This part of expression
( address + alignment - )

is used for rounding.
and this part of expression
~( alignment - 1 )

is used to build a mask thet zeroes low bits.

A: (X+Y-1) & ~(Y-1)
x = 7 = 0b0111
y = 4 = 0b0100

x+y-1 = 0b1010
y-1 = 3 = 0b0011
~(y-1) = 0b1100

(x+y-1) & ~(y-1) = 0b1000 = 8

--
x = 12 = 0b1100
y = 2 = 0b0010
x+y-1 = 13 = 0b1101

y-1 = 1 = 0b0001
~(y-1) = 0b1110

(x+y-1) & ~(y-1) = 0b1100 = 12

(x+y-1) & ~(y-1) is the smallest multiple of y greater than or equal to x


text:
Q: There is a way to update view without use Two way bind There is a way to update a value in object and my view (HTML) display the new value without use two way bind with Angular 1.5.3?

A: If I understand you correctly you need a one-way bind from your controller to your view. If so, you can just use ng-bind
E.g.
{{ctrl.myName}} or
If you want a one-time bind, this was introduced in angular 1.3:
E.g.:
{{::ctrl.myName}} binds myName once, future changes to it won't be picked up


text:
Q: Retrieve value from webservice called from javascript? Is it possible to retrieve value or date from calling a webmethode from javascript, here is a sample code:
//This method is in a webservice.asmx file.
[WebMethod]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{

    return Cities.GetAllCitiesByCountry(CountryID: countryID);
}

<script language="javascript" type="text/javascript">

function fillCities() {
    var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>');
    var selectedIndex = dropDownList.selectedIndex;
    var value = dropDownList[selectedIndex].value;

   WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, "");

}

   function onSuccess(result){
      alert(result[0].(PropertyName));
      }

The variable x doesn't retrieve anything and I guess that it produce an error. I have tried to define an array but still it didn't work. Any idea ?
Edit:
The above code have been altered and is now an answer to my question along with the answer below which used JQuery.

A: Use Json response with Jquery, Its realy cool and easy.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class CitiService : WebService
{
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<tbl_City> GetAllCitiesByCountry(int countryID)
    {
     List<tbl_City> cities = GetCities(countryID);
     JavaScriptSerializer js = new JavaScriptSerializer();
        var jsonObj = js.Serialize(cities);
        Context.Response.Clear();
        Context.Response.Write(jsonObj);
        Context.Response.End();
     }
 }

on ASp.net page
<script language="javascript" type="text/javascript">
 $.ajax({
        url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>',
        dataType: "json",
        data: "{countryID:'100'}",
        success: function (result) {
            alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid
        }
      });

A: you can do this easily with JQuery and ASP.NET webmethods Encosia

A: You need to register your web service with ScriptManager and then call it from the client side. Take a look on this tutorial:
Client-Side Web Service Calls with AJAX Extensions
Also you can use web service with jQuery but in this case you need to switch to JSON: Calling ASMX from jQuery


text:
Q: How to make Eclipse load all properties from Ant properties file? I am using Eclipse 3.2.0 on Red Hat Enterprise Linux Server release 5.2 Beta (Tikanga) and am trying to create a project using an Ant build file and properties file.  When I load the build file the only properties that are loaded are the ${build.dir}, ${bin.dir}, and ${dist.dir}.  All the other properties in the properties file do not load.  Can anyone help me determine why the rest of the properties would not be loading?  Please see the code below.
build.properties:
bin.dir=bin
build.dir=build
dist.dir=dist
src.dir=src
doc.dir=doc
config.dir=config
common.lib.dir=lib
reports.dir=reports

build.xml:
tools.lib.dir=tools/lib
tools.etc.dir=tools/etc
findbugs.home.dir=tools/findbugs
findbugs.lib.dir=tools/findbugs/lib

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="build" name="FalconLogParser">
    <property file="build.properties" />

    <path id="compile.classpath">
        <fileset dir="${common.lib.dir}">
            <include name="*.jar" />
        </fileset>
    </path>

    <path id="run.classpath">
        <pathelement location="${build.dir}" />
        <path refid="compile.classpath" />
    </path>

    <path id="dist.classpath">
        <fileset dir="${dist.dir}">
            <include name="*.jar" />
        </fileset>
        <path refid="compile.classpath" />
    </path>

    <path id="tools.classpath">
        <fileset dir="${tools.lib.dir}">
            <include name="*.jar" />
        </fileset>
    </path>

    <path id="findbugs.classpath">
        <fileset dir="${findbugs.lib.dir}">
            <include name="*.jar" />
        </fileset>
    </path>

    <!-- Create directories to place classes and JARs -->
    <target name="init" description="Create directories to place classes and JARs">
        <tstamp />
        <mkdir dir="${build.dir}" />
        <mkdir dir="${build.dir}/3rdparty" />
        <mkdir dir="${build.dir}/com" />
        <mkdir dir="${bin.dir}" />
        <mkdir dir="${bin.dir}/3rdparty" />
        <mkdir dir="${dist.dir}" />
        <mkdir dir="${dist.dir}/bin" />
        <mkdir dir="${dist.dir}/bin/3rdparty" />
        <mkdir dir="${dist.dir}/cfg" />
        <mkdir dir="${dist.dir}/config" />
        <mkdir dir="${dist.dir}/logs" />
        <mkdir dir="${dist.dir}/output" />
        <mkdir dir="${dist.dir}/scripts" />
    </target>

    <!-- Remove all build artifacts -->
    <target name="clean_build" description="Remove all build artifacts">
        <delete dir="${build.dir}" />
        <delete dir="${bin.dir}" />
        <delete dir="${dist.dir}" />
    </target>

    <!-- Remove all reports -->
    <target name="clean_reports" description="Remove all reports">
        <delete dir="${reports.dir}" />
        <mkdir dir="${reports.dir}"/>
    </target>

    <!-- Remove all build artifacts -->
    <target name="clean_docs" description="Remove all documention">
        <delete dir="${doc.dir}" />
        <mkdir dir="${doc.dir}"/>
    </target>

    <!-- Compile source code -->
    <target name="build" depends="init" description="Compile Java files">
        <copy todir="${build.dir}/3rdparty" >
            <fileset dir="${common.lib.dir}"/>
        </copy>
        <javac destdir="${build.dir}">
            <src path="${src.dir}" />
            <include name="**/*.java" />
            <exclude name="**/*Test.java" />
            <!-- So that Eclipse automatically copies changed files to build directory -->
            <classpath refid="compile.classpath" />
        </javac>
    </target>

    <!-- Run unit tests -->
    <target name="test" depends="build" description="Run unit tests">
        <junit description="AllTests" fork="yes">
            <batchtest todir=".">
                <fileset dir="${src.dir}">
                    <include name="**/*Test.java" />
                </fileset>
            </batchtest>
            <formatter type="xml" usefile="yes" />
            <formatter type="plain" usefile="yes" />
            <classpath>
                <path refid="run.classpath" />
            </classpath>
        </junit>
    </target>

    <!-- Make distribution jar files -->
    <target name="jar" depends="build" description="Make distribution jar files">
        <jar destfile="${bin.dir}/falconLogParser.jar" basedir="${build.dir}/com" />
        <copy todir="${bin.dir}/3rdparty">
        <fileset dir="${build.dir}/3rdparty" />
    </copy>
    </target>

    <!-- Make distribution files -->
    <target name="dist" depends="jar" description="Make distribution files">
        <copy todir="${dist.dir}/bin">
            <fileset dir="${bin.dir}" />
        </copy>
        <copy todir="${dist.dir}/config">
            <fileset dir="${config.dir}" />
        </copy>
    </target>

    <!-- Make Java documentation for API -->
    <target name="doc" depends="build">
        <delete dir="${doc.dir}" />
        <mkdir dir="${doc.dir}" />
        <javadoc doctitle="Falcon Log Parser" classpathref="run.classpath" destdir="${doc.dir}" private="true">
            <fileset dir="${src.dir}">
                <include name="**/*.java" />
                <exclude name="**/*Test.java" />
            </fileset>
            <link href="${java.apidoc.url}" />
        </javadoc>
    </target>

    <target name="run" depends="build">
    </target>

    <!--  Static code checking -->
    <target name="checkcode" description="Static source code code checking" depends="build">

        <fileset dir="${src.dir}" id="tocheck">
            <include name="**/*.java" />
            <exclude name="**/*Test.java" />
        </fileset>

        <mkdir dir="${reports.dir}" />

        <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask" classpathref="tools.classpath" />
        <pmd rulesetfiles="basic,design,coupling,strings" targetjdk="1.6">
            <formatter type="xml" toFile="${reports.dir}/pmd_report.xml" />
            <fileset refid="tocheck" />
        </pmd>
        <xslt in="${reports.dir}/pmd_report.xml" style="${tools.etc.dir}/wz-pmd-report.xslt" out="${reports.dir}/pmd_report.html" />
        <echo message="${reports.dir}/pmd_report.xml and ${reports.dir}/pmd_report.html written out" />

        <taskdef resource="checkstyletask.properties" classpathref="tools.classpath" />
        <checkstyle config="${tools.etc.dir}/sun_checks.xml" failOnViolation="false">
            <formatter type="xml" tofile="${reports.dir}/checkstyle_report.xml" />
            <fileset refid="tocheck" />
        </checkstyle>
        <echo message="${reports.dir}/checkstyle_report.xml written out" />
        <xslt
            in="${reports.dir}/checkstyle_report.xml"
            out="${reports.dir}/checkstyle_report.html"
            style="${tools.etc.dir}/checkstyle-noframes-sorted.xsl"
        />

        <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask" classpathref="findbugs.classpath" />
        <findbugs home="${findbugs.home.dir}" output="xml" outputFile="${reports.dir}/findbugs_report.xml">
            <auxClasspath refid="compile.classpath" />
            <sourcePath path="${src.dir}" />
            <class location="${build.dir}/com" />
        </findbugs>
        <echo message="${reports.dir}/findbugs_report.xml written out" />
        <xslt
            in="${reports.dir}/findbugs_report.xml"
            out="${reports.dir}/findbugs_report.html"
            style="${findbugs.home.dir}/src/xsl/default.xsl"
        />

    </target>

</project>

A: Simple answer is that that file is not the file you pasted here. The easiest way to find out what is wrong, to paste the following somewhere to see loaded file:
<property name="whatswrong" location="build.properties"/>
<echo>The absulute path of property file is ${whatswrong}/>

This is based on the fact, that location attribute always will give back absolute path.
ps: use maven, since your build script is just like a lifecycle


text:
Q: VBA "&" functionality on a range of cells I know this may be a basic question, but being new with VBA, I am having trouble getting the syntax to work. I've searched alot of sites, but could only get it to work within part of the range, but not both. So if I wanted to merge cells Q, R, S, T on row 1, I could easily write:
Range("Q1:T1").Merge

However, As I am working within a loop, I'd like to have row numbers that alter. How could I fix the syntax on this? Y being the row count.
Range("Q"&y":T"&y).Merge

A:  Range("Q" & y & ":T" & y).Merge

You missed a '&' between the first y and the quote.

A: There are several options, including:
Range("Q" & y & ":T" & y).Merge

or
Range("Q" & y, "T" & y).Merge

or
Range("Q" & y).Resize(, 4).Merge

A: Here is another way of writing it that I like but you never see examples of it:
Rows(y).Columns("Q:T").Merge


text:
Q: Почему так считает? Коллеги, почему компилятор выдаёт цифру 3 в консоль? Первый раз такое встречаю..
public class Main
{
    public static void main(String[] args) {
        System.out.println(2|1);
    }
}

A: Это битовое логическое или 0b10 | 0b01 = 0b11

A: | это оператор побитового сравнение "ИЛИ"
Записав 2|1 мы на самом деле сравниваем эти числа в двоичной системе.
Вот небольшая таблица десятичные - двоичные
1 - 01
2 - 10
3 - 11
4 - 100
5 - 101

А теперь как идёт само сравнение
10
--
01

==
11

Берётся столбик и если встречается 1 - то результат будет 1... В итоге результат равен 11 ( что в десятичной системе исчесления 3)


text:
Q: Cambiar el sonido de una notificación desde una url Muy buenas noches Amigos
me gustaria cambiar el sonido de una notificacion, he visto que la colocan en la carpeta raw/ y la llaman desde ahi. Pero a mi me gustaria llamar el sonido de mi notificacion desde una url. pero no encuentro la forma. yo estoy haciendo esto:
    private void createNotificacion(){
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);
    builder.setSmallIcon(R.drawable.logonegro);
    builder.setContentTitle(titulo);
    builder.setContentText("Mensaje Hariza");
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText(detalle));
    builder.setColor(R.color.colorAccent);
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setLights(Color.RED,1000,1000);
    builder.setVibrate(new long[]{1000,1000,1000,1000});
    //builder.setDefaults(Notification.DEFAULT_SOUND);
    builder.setContentInfo("EatBox Domicilio Zonal");
    builder.setSound(Uri.parse("https://hariza.com/Sonido/sound_app/baila_conmigo_.mp3"));
    //builder.setContentIntent(clicknoti());
    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
    Random random = new Random();
    int idNotify = random.nextInt(80000);
    notificationManagerCompat.notify(idNotify,builder.build());
}

A: Cargar un audio desde una url se puede realizar, convirtiendo la url a una Uri que es lo que estas realizando:
Uri myUri = Uri.parse("https://--------------.mp3");
builder.setSound(myUri);

No debes tener ningun problema pero debes contemplar estos puntos.
1 La url del .mp3 debe existir.
2 Debes definir dentro de tu AndroidManifest.xml el permiso:
<uses-permission android:name="android.permission.INTERNET"/>

*Asegura que el dispositivo tenga activado el sonido para reproducir en el caso de notificaciones.


text:
Q: Probability of 4 balls in the same jar I put 10 balls numbered 1 through 10 in a black box. Next to it, I placed two jars, labeled "A" for the first jar and label "B" for the second jar.
I want to distribute the balls in the jars as follows:
1- I take a ball randomly from the box and place it in the "A" jar.
2- I take a ball randomly from the box and put it in the "B" jar.
3- I take a ball randomly from the box and place it in the "A" jar.
...
I will perform these steps until all the balls are distributed in the jars as shown.
Question: What are the chances of balls 1,2,3 and 4 being in the same jar?

A: Looks like each jar gets $5$ balls.  You want to know the probability that four desired balls end up in jar A or jar B.
Let's look at the probability ($p_\text{A}$) they end up in jar A.  We'll multiply by $2$ at the end.
There are $\pmatrix{10 \\5}$ ways of selecting $5$ balls and putting them in jar A.  How many have $\{1,2,3,4\}$?  Well, there are six other balls, so:
$$p_\text{A} = \frac{6}{\pmatrix{10 \\5}}=\frac{6\cdot5!\cdot5!}{10!}=\frac{ 5 \cdot 4 \cdot 3 \cdot 2}{10\cdot 9 \cdot 8 \cdot 7 }=\frac{1}{42}$$.
The probability that all four balls $\{1,2,3,4\}$ end up in the same jar is thus:
$$p=2p_\text{A} = \frac{1}{21}.$$


text:
Q: Flash movie has issues with parallax technique I have created a site using the parallax technique. I have used a transparent flash movie with animation on the front parallax layer and when the mouse curson is on top of  the movie the screen seems to tremble in contrast to the rest of the site in which the move seems much more smoother. I am not sure if is has anything to do with the size of the movie. It has a width of 1450px and a height of 825px.
Thanks in advance


text:
Q: getting out parameter from mysql stored procedure in java I am having problem retrieving OUT parameter from mysql stored procedure in java.
CALL proc_after_topic_add('newtest',@result);
SELECT @result;

this query gives me desired out parameter but how would i retrieve it in java.I tried using CallableStatement but i get
java.sql.SQLException: Callable statments not supported.

error.Please guys help me.
I have tried following
String sql = "CALL proc_after_topic_add(?,?);";
            CallableStatement cstmt = conn.prepareCall(sql);
            cstmt.setString(1, topicname);
            cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
            ResultSet rs = cstmt.executeQuery();
            if (rs.next()) {
                if (rs.getInt(1) == 1) {
                    res = 0;
                } else {
                    res = -1;
                }
            }

I havent posted stored procedure code because there is nothing wrong with it.
PS:I a using mysql 5.5.21 and yes i should probably mention i am using mysql connector 3.0.15

Okay this is solved.For anyone who encounters the same problem,just download latest version of mysql connector.

A: Error in this line
 cstmt.registerOutParameter(2, java.sql.Types.INTEGER);

change like this
 String sql = "CALL proc_after_topic_add(?,?);";
 cstmt.registerOutParameter(2, java.sql.Types.INTEGER);

A: Create a schema test and create a table employee in schema with 2 columns.
id and employeename and insert some data.

Use this Stored Procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_count_name1` $$
CREATE PROCEDURE  `test`.`get_count_name1`(IN the_name VARCHAR(64),OUT
the_count INT)

BEGIN
SELECT COUNT(*) INTO the_count from employee where employeename=the_name;
END$$
DELIMITER ;

Use this example.
    username and password are root and root for me. change as per your
    requirement. Here i am counting the occurence of employeename="deepak"
import java.sql.*;
public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/test";

   //  Database credentials
   static final String USER = "root";
   static final String PASS = "root";

   public static void main(String[] args) {
   Connection conn = null;
   CallableStatement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      String sql = "{call get_count_name1 (?, ?)}";
      stmt = conn.prepareCall(sql);

      //Bind IN parameter first, then bind OUT parameter
      String name = "Deepak";
      stmt.setString(1, name); // This would set ID as 102
      // Because second parameter is OUT so register it
      stmt.registerOutParameter(2, java.sql.Types.INTEGER);

      //Use execute method to run stored procedure.
      System.out.println("Executing stored procedure..." );
      stmt.execute();

     int count=stmt.getInt(2);
     System.out.println(count);
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample


text:
Q: Discord.py unable to get certificate Do I have to install/generate/download new certificate inside my system or is it possible for me somehow to disable certificates inside the python? (ubuntu 18, python 3.7, discord.py latest)
[INFO]  [2019.03.05 - 22:58:02]   Initializing Discord...

SSL handshake failed on verifying the certificate
protocol: <asyncio.sslproto.SSLProtocol object at 0xf4a9f8ec>
transport: <_SelectorSocketTransport fd=12 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
  File "./build/Lib/asyncio/sslproto.py", line 625, in _on_handshake_complete
  File "./build/Lib/asyncio/sslproto.py", line 189, in feed_ssldata
  File "./build/Lib/ssl.py", line 763, in do_handshake
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1051)

SSL error in data received
protocol: <asyncio.sslproto.SSLProtocol object at 0xf4a9f8ec>
transport: <_SelectorSocketTransport closing fd=12 read=idle write=<idle, bufsize=0>>
Traceback (most recent call last):
  File "./build/Lib/asyncio/sslproto.py", line 526, in data_received
  File "./build/Lib/asyncio/sslproto.py", line 189, in feed_ssldata
  File "./build/Lib/ssl.py", line 763, in do_handshake
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1051)

[ERROR] [2019.03.05 - 22:58:02]
2019.03.05 - 22:58:02:
  Top:  file: [sv_custom.py], method: init()
  Root: file: [connector.py], line 974, cause: in _create_direct_connection [File "./../source/aiohttp.whl/aiohttp/connector.py", line 927, in _wrap_create_connection]
  aiohttp.client_exceptions.ClientConnectorCertificateError:
  Cannot connect to host discordapp.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1051)')]

This is done from the python that is inside the game client. If I do the same from the system's python (3.6) - no errors, connection is fine. "They say" it could be because the game client does not see "root certificates" or something like that.
Update:
Found out how to check certificates.
(with ssl error)
Initializing Discord...
DefaultVerifyPaths(cafile=None, capath=None, openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/local/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/local/ssl/certs')

(this works fine)
igor@Linbox:~/Downloads$ python3.6 -c "import ssl; print(ssl.get_default_verify_paths())"
DefaultVerifyPaths(cafile=None, capath='/usr/lib/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/lib/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/lib/ssl/certs')

Guess that is my problem that capath is empty.

A: Unexpectedly the solution appeared quite simple:
ssl.get_default_verify_paths() for the python with the ssl error was pointing to: openssl_capath='/usr/local/ssl/certs' while the "native" python from the system showed openssl_capath='/usr/lib/ssl/certs'.
DefaultVerifyPaths(
  cafile=None,
  capath=None,
  openssl_cafile_env='SSL_CERT_FILE',
  openssl_cafile='/usr/local/ssl/cert.pem',
  openssl_capath_env='SSL_CERT_DIR',
  openssl_capath='/usr/local/ssl/certs'
)

I've checked both locations:
'/usr/local/' - was empty (it had no ssl/certs folders)
'/usr/lib/ssl/certs' had a symlink to '/etc/ssl/certs'
So I made the same symlink:
inside '/usr/local/' added '/ssl/' + ln -s '/etc/ssl/certs' certs
Then I checked once again ssl.get_default_verify_paths()
DefaultVerifyPaths(
  cafile=None,
  capath='/usr/local/ssl/certs',  <-- not empty now
  openssl_cafile_env='SSL_CERT_FILE',
  openssl_cafile='/usr/local/ssl/cert.pem',
  openssl_capath_env='SSL_CERT_DIR',
  openssl_capath='/usr/local/ssl/certs'
)

The problem disappeared. It is working now.

A: According to https://github.com/Rapptz/discord.py/issues/423 if one goes to the python folder one's computer and runs the Install Certificates.command it works.
I tried this and DOES work.
Hope this helps both you and my reputation of StackOverflow :-)

A: In addition to @Igorz, I opened up the '/usr/local/ssl/cert.pem' file and added the certificates from the website I was trying to access. You can get the details on how to get those certificates from here.


text:
Q: Extract Grind-Anchors from Object-Detection API Model I'm currently trying to get my SSDLite Network, which I trained with the Tensroflow Object-detection API working, with iOS.
So I'm using the Open Source Code of SSDMobileNet_CoreML.
The Graph allready works with some limitations. For running on iOS I had to extract the FeatureExtractor from my Graph and where unable to keep Preprocessor, Posprocessor and MutlipleGrindAnchorBox, same as they did in SSDMobileNet_CoreML.
Here you can see the Anchors they have used.
So cause my Anchors seem to be a little different I tried to undestand how they got this array.
So I found in an GitHub Issue an explenation, where the User who created the Anchors explains how he got them.
He says:

I just exported them out of the Tensorflow Graph from the import/MultipleGridAnchorGenerator/Identity tensor

I allready found the matching tensor in my Graph but I don't know how to export the Graph and retrive the correct Anchor encoding.
Can sombody explain this to me?

A: I allready figured it out. A little below quote was a link to a Python Notebook which explains everything in detail.


text:
Q: python line strip \n and write line I have this python code,
open('%s.log'%hname,'w').writelines([ line for line in open('%s_tmp.log' %hname) if 'word' in line])

This prints the line same as in the %hname_tmp.log :
b'line contains blah\n'
b'This is the next line\n'

I would like to remove b' and \n' before writing to the new file. Something like this:
line contains blah
This is the next line

How can I do that ? I have tried
...writelines([line.rstrip() ...,
but this jams everything in the new log file in one line while still keeping the \n'.

A: Open the output file as binary:
open('%s.log'%hname, 'wb').writelines([ line for line in open('%s_tmp.log' %hname) if 'word' in line])

or decode the bytes objects before writing:
open('%s.log'%hname, 'w').writelines([line.decode('ascii') for line in open('%s_tmp.log' %hname) if 'word' in line])

If your original log file contains those characters, you wrote binary data to that log file instead. You can re-interpret those lines as bytes objects by using the ast.literal_eval() utility function:
from ast import literal_eval

with open('%s.log'%hname, 'wb') as outfile:
    outfile.writelines(literal_eval(line.rstrip()) for line in open('%s_tmp.log' %hname) if 'word' in line)

literal_eval() takes strings that represent Python literals and turns them back into Python objects just like the Python compiler would.

A: You are reading the file as binary.  Try opening with 'rt'.
open('%s.log'%hname,'wt').writelines([ line for line in open('%s_tmp.log' %hname, 'rt') if 'word' in line])


text:
Q: magento setup configuration plugin Is it posible to create or maybe there are alredy some extension or file where you can make all backend configurations?
e.g. add/rename storeviews, websites, set shipping method add category/product attributes, build category trees etc.
I'm working with a lot of magento projects and it would be crazy helpful for me to have such extension where you can add all configuration in one to five files and just install it via "Magento Connect Manager". Meanwhile it would be helpful for customer if i could send config *.zip with all config that needs to be set.

A: You can do this by creating queries to update the core_config_data table in your database.
The core_config_data table contains all the settings under System - Configuration in the backend.
This is what I do when I import a production database in my local development environment. I just update the config settings (like baseurl) with a sql query script.


text:
Q: angular-block-ui doesn't execute my html as a custom message I want to block my UI and show a spinner while it is blocked.
I tried to use the following :

blockUI.start("
Minions are Working!
");

// some code that fetches data from server

blockUI.stop();

here 'dots-loader' is taken from the css provided by : http://www.css-spinners.com
on suceess, it does block the ui and display the message, but it displays my html as text.
is there any way to achieve this spinner thing inside the blockUI custom message??

A: although this is not a good solution to customize a library file but I have to do this to achieve loading image instead Loading text.Because angular-block-ui.ng.html has only Loading.. see below link
https://github.com/McNull/angular-block-ui/blob/master/src/angular-block-ui/angular-block-ui.ng.html
here the html

 {{ state.message }}

in your project open angular-block-ui.js file or min file. go to below the file and found this code below.
// Automatically generated.
// This file is already embedded in your main javascript output, there's no need to include this file
// manually in the index.html. This file is only here for your debugging pleasures.
angular.module('blockUI').run(['$templateCache', function($templateCache){
  $templateCache.put('angular-block-ui/angular-block-ui.ng.html', '

{{ state.message }}

');
}]);

now add your code
Minions are Working!

after {{state.message}} finally it look like .
 $templateCache.put('angular-block-ui/angular-block-ui.ng.html', '

{{ state.message }}

Minions are Working!

');
    }]);

then just give a blank space text
blockUI.start(' ');

hope you will find better solution. Thanks


text:
Q: If a class implements addition and concatenation, which magic methods should be used for what? I have a class that is basically an optimised generator (like range). It implements __getitem__, __iter__ and __contains__. It also needs to implement addition of its items (immutable numbers) with that of another instance:
def addition(self, other):
    for x in zip(self, other):
        yield sum(x)

and concatenation of two instances:
def concatenation(self, other):
    yield from self
    yield from other

(The real methods return instances of subclasses that implement this in their __iter__ method, with necessary optimisations to reduce the complexity of __contains__ where possible, but I simplified it for the example.)
Types such as str, list and tuple implement concatenation with __add__. Types such as int and float implement addition with __add__. I can't implement both with __add__.
What magic methods should I use for addition and concatenation if a class implements both?


text:
Q: Error when Trying to use Rticles to generate example R markdown: pdflatex not found Ubuntu 20.04 I was trying to generate one of the example rticles outputs in pdf, and got the same error pdflatex not found. This was on Ubuntu 20.04 focal fossa.

A: I first followed Yihue's troubleshooting site, but got the same error found here, here, and here . In R on Ubuntu 20.04, I first installed tinytex using devtools::install_github('yihui/tinytex'). I then tried to do library(tinytex) and tinytex::tlmgr_update() which returned an error Error in system2("tlmgr", args, ...) : error in running command. I assumed this was because I was missing something on Ubuntu 20.04. It seems that as of July 14, 2020, Ubuntu 20.04 or rticles does not ship with Texlive, which is necessary for output. I thus ran sudo apt install texlive-full at the command line and was able to run the example.