text:
Q: C# DLL COM that calls web service not working in Excel VB I currently have a project guideline to try to make C# DLL as a COM to be usable in Excel as well as other platforms. Currently it calls web services and does calculations such as getting a gravity prediction from a web service. Everything is working fine except for when I need to use class methods that are utilizing web services. I get an error in Excel stating it could not establish a SSL/TSL connection to the service and I cannot seem to find a way around this. Any help forward would be greatly appreciated as I am a life long developer, but working it into Excel is brand new to me. Below is how I am handling it in the code.
GravityResultObject.cs
public class GravityObjResult
{
    public string lat { get; set; }
    public string latDms { get; set; }
    public string lon { get; set; }
    public string lonDms { get; set; }
    public string eht { get; set; }

    public string predictedGravity { get; set; }
}

static void Main(string[] args)
{
}

public static async Task<string> TestGravApi(float lat, float lon, float eht)
{
    GravityObjResult gResult = new GravityObjResult();

    using (var httpClient = new HttpClient())
    {
        string url = String.Format("my-api-here-gp?lat={0}&lon={1}&eht={2}", lat, lon, eht);
        var json = await httpClient.GetStringAsync(url);

        if (json != null)
        {
                gResult = JsonConvert.DeserializeObject<GravityObjResult>(json);
                // Now parse with JSON.Net
                return gResult.predictedGravity;
            }
        }
        return String.Empty;
    }
}

GPredict.cs
public class GPredict
{
    public float Lon { get; set; }
    public float Lat { get; set; }
    public float Elip { get; set; }

    public float Grav { get; set; }

    public GPredict(float lon, float lat, float elip)
    {
        Lon = lon;
        Lat = lat;
        Elip = elip;
    }

    public GPredict()
    {
    }

    public float SetLON(float a)
    {
        Lon = a;
        return Lon;
    }

    public float SetLAT(float a)
    {
        Lat = a;
        return Lat;
    }

    public float SetELIP(float a)
    {
        Elip = a;
        return Elip;
    }

    public string GetG()
    {
        string gReturn = String.Empty;
        try
        {
            var task = WebRequestCall.TestGravApi(Lat, Lon, Elip);
            gReturn = float.Parse(task.Result).ToString();
        }
        catch (Exception e)
        {
            gReturn = e.ToString();
        }

        return gReturn;
    }
}

DynamicCalcWrapper.cs
public class DynamicCalcWrapper : DynamicObject
{
    Calculator calc;

    GPredict gPredict;

    public DynamicCalcWrapper()
    {
        calc = new Calculator();
        gPredict = new GPredict();
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = null;

        switch (binder.Name)
        {
            case "add":
                result = (Func<double, double, double>)((double a, double b) => calc.add(a, b));
                return true;
            case "sub":
                result = (Func<double, double, double>)((double a, double b) => calc.sub(a, b));
                return true;
            case "SetLON":
                result = (Func<float, float>)((float a) => gPredict.SetLON(a));
                return true;
            case "SetLAT":
                result = (Func<float, float>)((float a) => gPredict.SetLAT(a));
                return true;
            case "SetELIP":
                result = (Func<float, float>)((float a) => gPredict.SetELIP(a));
                return true;
            case "GetG":
                result = (Func<float, string>)((float a) => gPredict.GetG().ToString());
                return true;
        }
        return false;
    }
}

Testing the result in Excel VB:
Sub T()
    Dim getG As New GPredict
    getG.Lon = 145#
    getG.Lat = 41.11
    getG.Elip = 33

    Dim result As String
    result = getG.getG()
    MsgBox result
End Sub

Note that I have the regular getter / setter for the properties, but also have a secondary way to set it since I have to allow Fortran based code to work with this and there are some restrictions on how long param settings are and such.

A: I would like to note that prior to posting my code above in the sample, I also had tried it first pointing directly to the url in the context "https://" it was till throwing the error. I was able to find out I had to add the following settings to get it to run by adding the code lines for ServicePointManager below:
public static async Task<string> TestGravApi(float lat, float lon, float eht)
    {
        GravityObjResult gResult = new GravityObjResult();

   ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
   | SecurityProtocolType.Tls11
   | SecurityProtocolType.Tls12
   | SecurityProtocolType.Ssl3;

        using (var httpClient = new HttpClient())
        {
            string url = String.Format("https://{my-url-here}/api/gravd/gp?lat={0}&lon={1}&eht={2}", lat, lon, eht);
            var json = await httpClient.GetStringAsync(url);

            //sends from object to string json
            //string output = JsonConvert.SerializeObject(product);
            if (json != null)
            {
                gResult = JsonConvert.DeserializeObject<GravityObjResult>(json);
                // Now parse with JSON.Net
                return gResult.predictedGravity;
            }
        }

        return String.Empty;
    }


text:
Q: Add multiple work items in YouTrack commit message With the following commit I can add YouTrack work item to the type Development:
#DEV-1 work Development 15m

How can I add to two multiple work items? I tried the following:
#DEV-1 work Development 15m Documentation 15m
#DEV-1 work Development 15m, Documentation 15m
#DEV-1 work Development 15m work Documentation 15m
#DEV-1 work Development 15m, work Documentation 15m

A: Unfortunately, it's neither possible to execute a single command that adds multiple work items nor execute several commands from a single VCS commit message.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Panel help with little program I'd like to show the output of this program into one large Panel, but when I surround this code with Panel[ ], it doesn't seem to work. Why is that?
listA = {};
listB = {};
"Verzameling A : " InputField[Dynamic[Null, AppendTo[listA, #] &]]

"Verzameling B : " InputField[Dynamic[Null, AppendTo[listB, #] &]]

listAShow := Sort[ DeleteDuplicates[listA]];
listBShow := Sort[ DeleteDuplicates[listB]];

"Verzameling A =" Dynamic[listAShow]
"Verzameling B =" Dynamic[listBShow]

unie := Union[listAShow, listBShow];
doorsnede := Intersection[listAShow, listBShow];

toonOpl = False;
Row@{Checkbox[Dynamic[toonOpl]], "Toon bewerkingen"}
Dynamic[If[toonOpl,
  Column@{
    Row@{"Unie van A en B = ", unie}
    , Row@{"Doorsnede van A en B = ", doorsnede}
    }, {}]]

Button["Reset alles", listA = {}; listB = {}]

Thanks all!

A: Just put all the code lines which display output into a Column:
listA = {};
listB = {};
listAShow := Sort[DeleteDuplicates[listA]];
listBShow := Sort[DeleteDuplicates[listB]];
unie := Union[listAShow, listBShow];
doorsnede := Intersection[listAShow, listBShow];
toonOpl = False;

Panel@Column@{
   "Verzameling A : " InputField[Dynamic[Null, AppendTo[listA, #] &]],
   "Verzameling B : " InputField[Dynamic[Null, AppendTo[listB, #] &]],
   "Verzameling A =" Dynamic[listAShow],
   "Verzameling B =" Dynamic[listBShow],
   Row@{Checkbox[Dynamic[toonOpl]], "Toon bewerkingen"},
   Dynamic[If[toonOpl,
     Column@{Row@{"Unie van A en B = ", unie},
       Row@{"Doorsnede van A en B = ", doorsnede}}, {}]],
   Button["Reset alles", listA = {}; listB = {}]}


text:
Q: For Loop to Foreach Hi there I have a for loop process and i want it to convert to foreach loop, but I cant get it working, can someone please help me?
int pallet = 1;
int[] res = {5,1};

foreach (int element in res)
{
  var resu = res.Length;
  if (resu < pallet)
    { }
  else { }
}

for (int i = 1; i <= res.Length; i++)
{
  if (i <= pallet)
    { }
  else { }
}

A: Nothing here really makes any sense, you are filling out an array but not using the contents. In your for loop you are using the index and comparing it to the pallet, not the actual array value ( res[i-1] ). Since you do not have any index in the foreach loop you have the actual element of the array being returned.  I believe that you are probably wanting something like this, but I could be wrong.
Your for Loop:
for (int i = 0; i < res.Length; i++)
{
  if (res[i] <= pallet)
    { }
  else { }
}

Your Foreach Loop:
foreach (int element in res)
{
  if (element <= pallet)
    { }
  else { }
}

A: I think this may solve your problem:
int pallet = 1;
int[] res = { 5, 1 };

foreach (int element in res)
{
  var resu = res.Length;
  if (resu < pallet)
    { }
  else { }
}

int i = 0;
foreach (int element in res)
{
  if (i <= pallet)
    { }
  else { }
  i++;
}

A: *

*foreach loop: Your origin code is wrong. You can fix it to:

foreach (int element in res)
{
  var resu = element;
  if (resu < pallet)
    { }
  else { }
}

*Convert to for loop. I dont know why you want i to begin at 1, but I do base on your origin code: To access and get value at a specific index of an array (begin at 0), you can use yourArray[yourIndex]. In this, your start index of the array is 1, you have to use res[i-1] instead of res[i]:

for (int i = 1; i <= res.Length; i++)
{
  if (res[i-1] <= pallet)
    { }
  else { }
}


text:
Q: Conflict in if statement using !in_category() && !has_post_format() I am quite new to WordPress and PHP. I have a problem with posting specific posts on the front page (but I don't use static page option, using the index.php).
I have 2 categories (blog and tips) and currently, I am using 2 formats (standard and aside). Blogs are only assigned to standard and tips are only for the aside format. I want to display them in loop with posts which are in the Blog category & standard format.
<?php if ( have_posts()) : ?>

    <?php if( !in_category('Blog') && !has_post_format()) : ?>
        <?php $i=1; while (have_posts() && $i<5 ) : the_post();?>
            <?php   get_template_part( 'content', get_post_format() );?>
        <?php $i++; endwhile; ?>
    <?php else : ?>

      <?php while (have_posts()) : the_post();?>
        <?php   get_template_part( 'content', get_post_format() );?>
      <?php endwhile; ?>

    <?php endif; ?>

  <?php do_action( 'E2R_posts_navigation' ); ?>

<?php else : ?>
  <?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

The problem is that the !in_category('Blog') && !has_post_format() are excluding each other and getting into else condition (displays all posts) and I can't find the problem (before I used instead of 'Blog', 'Tips' but it did not work either). When I put the condition for !has_post_format() in the while loop, then it filters correctly but the numbering then does not work properly.
The post formats are defined as:
add_theme_support(
  'post-formats', array(
    'aside',
    'image',
    'video',
    'quote',
    'link',
  )
);

A: I have found solution for this problem by position change of the $i iteration. It looks like:

              <?php if( !is_category('Blog')) : ?>
                  <?php $i=1; while (have_posts() && $i<5 ) : the_post();?>
                    <?php if( !has_post_format()) : ?>
                        <?php get_template_part( 'content', get_post_format() );?>
                        <?php $i++ ;?>
                    <?php endif;?>
                  <?php endwhile;?>
               <?php endif;?>

I got back to the point: ok, here it was displaying correctly but the number of the post was incorrect (the number of standard-blog posts minus number of aside-tip posts). so I said increment $i only if the post has no format -> !has_post_format() -> is standard. The syntax and functionality of this WordPress functions is weird. but it works for me.


text:
Q: Is there a way to optionally import a package?
Possible Duplicate:
Conditional "if a package is available"

I'm pretty lazy, and have my own .sty files which import a bunch of commonly used features. But, sometime system installations fail to provide one, for example Ubuntu's LaTeX doesn't have the mathtext package. So, is there a way to have a \usepackage command that won't cause (Xe)LaTeX to fail if a package isn't found?


text:
Q: The most elegant way to encapsulate WinAPI callbacks inside a class I am thinking about elegant way to encapsulate WinAPI callbacks inside a class. Suppose I am making a class handling asynchronous I/O. All Windows callbacks should be stdcall functions, not class methods (I need to pass their addresses to ReadFileEx WinAPI function for example). So, I cannot just pass method addresses as a callback routines to WinAPI functions.
What is the most elegant way to encapsulate functionality of this type inside a class so that the class have events OnReadCompleted and OnWriteCompleted (I am using Delphi as a primary language, but I guess the situation must be the same in C++ because class methods are different from simple methods by the fact, that the first hidden parameter of them is this link. Of course this class is not a singleton and there can be many of them created by app at the same time.
What do you think would be the good way to implement this?

A: I doubt this is in any way elegant but, IMO, the easiest is to convert the address of a method of a class to a procedure address and pass it to the winapi. Sure, it's a hack, but the VCL does the very same with classes.MakeObjectInstance, if only for a specific construct.. See this question for a source for this kind of implementaion and some other, more OO ways to handle the situation.

A: You can use static keyword for that. But it's available only in new Delphi versions.
Like this:
type
  TMyThread = class
  private
    // ...

    class function ThreadProc(Param: Pointer): DWord; stdcall; static; // <- WinAPI call back

    function Execute: DWord; // <- actual callback
  public
    constructor Create;
    // ...
  end;

{ TMyThread }

constructor TMyThread.Create;
begin
  // ...
  FHandle := CreateThread(nil, 0, @ThreadProc, Self, 0, FID);
end;

class function TMyThread.ThreadProc(Param: Pointer): DWord;
begin
  Result := TMyThread(Param).Execute;
end;

function TMyThread.Execute: DWord;
begin
  MessageBox(0, 'Hello from thread', 'Information', MB_OK or MB_ICONINFORMATION);
  Result := 0;
end;

Here: ThreadProc is WinAPI callback routine. It requires to have some form of custom argument, where you can pass Self. It can not access instance members. That's why it's just a wrapper for real callback (Execute), which is part of class and can access its fields and methods.


text:
Q: Unable to load "lpsolve55.dll" in VS2015 on 64-bits OS For a project I am working on, I need to solve a mathematical model. I chose to do this using Microsoft.Solver.Foundation and the SolverFoundation.Plugin.LpSolve plugin. Both associated .dll files for these extension seem to work fine, as VS2015 recognizes and references them without a problem and compiles and runs my program without errors.
This is however up untill I try to actually solve my optimization, which needs "lpsolve55.dll" to work. I have downloaded this dll and put it in my project's bin/Debug folder, but for some kind of reason VS2015 just doesn't recognize it. I.e.

*

*I can't reference it by simply browsing to it from my "Add Reference" tab.

*It's impossible to (un-)register it via the regsvr32 cmd-prompt application, as it doesn't have any DLL (Un-)registry entry points.

*The TlbImp.exe cmd-prompt application can't handle it.

So basically, after discovering the above (after trying the most-common internet solutions), I still feel quite dissatisfied to get the error message while I try to solve the optimization -

Unable to load DLL 'lpsolve55.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

The wierd part is also that I have another project in which I solve a similar problem, where there are absolutely no problems at all using lpsolve55.dll....
Some quick facts:

*

*I reference .NET framwork 4.5.2. I have changed it to 4.5 as well as 4.0, but this didn't change anyting.

*For as far as I can tell, the bin/debug folder of my projects are identical.

*I am working on a fully updated windows 10 OS, 64 bits, while using visual studio 2015.

My question would thus be whether or not some of you have encountered a similar problem and if you were able to solve it in some way.
Highly appreciated!

A: After some careful analysis, I have found the answer to the problem. To be honest, as most things are, it was quite simple in the end. The lpsolve55.dll wasn't recognized because I didn't have my new bin-folder in the Path, which I did have with my old project. I simply forgot.
On a further note however, after the lpsolve55.dll directory was added to the path, I still got an error telling me there was no model to be found that could solve my directive. Since the error occured when I was calling the LPSolverDirective(), some research landed me on the following page:
http://lpsolve.sourceforge.net/5.5/MSF.htm
Above page gives a complete and stable way of how to acces lpsolve55.dll using the LPSolverPlugin straight out of Microsoft.Solver.Foundation.dll. After following the method in the link that involves editing my projects' bin/Debug and bin/Release folders, I got the LP model up and running within no-time.
Morale of the story - read the documentation. I am a bit of a beginner in programming entire multi-project solutions and using customly-added dlls, but hopefully this helps someone else experiencing the same. In the end, I learned a lot by simply trying different methods of getting it to work, so no time was wasted.


text:
Q: Tratar un mensaje de entrada con "emojis" Tengo un bot en Telegram escrito en Python que procesa los mensajes que recibe. Una de las funciones es escribir el mensaje en un fichero de texto "log.txt" e imprimirlo en la consola.
Durante varios días funcionó bien hasta que alguien introdujo emoticonos en el texto y el bot se cae.
Tengo la cabeza loca de todo lo que he leido y de aplicar las mil cosas que recomiendan por ahí. Tengo UTF-8 en todas las variables y en el texto del programa, por si alguien piensa que me falta.
La soluciones parece que apuntan a bien:

*

*Convertir el texto

*Hacer que el sistema tolere este tipo de información

*Directamente eliminar los emojis del mensaje.

El código es muy sencillo, pero aún así lo pongo:
 f = open('log.txt', 'a')
 f.write(mensaje + "\n")
 f.close()
 print (mensaje)

Cuando intento imprimir un mensaje que contiene Emojis en el IDLE obtengo el siguiente error

UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 46-46: Non-BMP character not supported in Tk

A: Aparentemente recibes mensajes con codificación  UTF-8 que es lo que retorna telegram.message.text, de la biblioteca python-telegram-bot (que supongo que usas).
El problema con los Emojis es que son caracteres definidos fuera del primer plano Unicode (Plano 0 o Basic_Multilingual_Plane) con valores entre 0000 y FFFF. Los Emojis se sitúan en el Plano 1 o Supplementary Multilingual Plane junto a otros símbolos como notaciones musicales o matemáticas.
Un ejemplo de cadena que puedes recibir es
s = "Yo \U0001F497 \U0001F40D...\U0001F601 y las cigüeñas."

Que codificada (UTF-8) seria
b'Yo \xf0\x9f\x92\x97 \xf0\x9f\x90\x8d...\xf0\x9f\x98\x81 y las cig\xc3\xbce\xc3\xb1as.'

Correctamente impresa seria

Yo  ... y las cigüeñas.

Tkinter, framework sobre el que se construye el IDLE, no soporta caracteres fuera del plano 0, de ahí el error obtenido al intentar imprimir en el IDLE:

UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 46-46: Non-BMP character not supported in Tk

También tendrás problemas con CMD, que tiene por lo general mal soporte para caracteres no BMP. Si tu CMD/PowerShell tiene el mapa por defecto (como CP850) directamente tendrás un error  del tipo:

UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f601' in position 11: character maps to < undefined >

Con otros mapas como CP65001 no obtendrás el error pero si la fuente no soporta estos caracteres no se mostrara correctamente.
Con una terminal/emulador de terminal que use codificación Unicode para stdout junto a una fuente con soporte para estos caracteres podrás imprimirlo sin problemas. Por ejemplo en Konsole (KDE):

Una posible solución si no se puede configurar o usar una terminal con este soporte es  eliminar estos caracteres directamente. Hay varias formas de hacerlo (se puede hacer algo como lo propuesto por  Martijn Pieters en su respuesta  a un problema similar en SO usando str.translate), una muy simples es:
>>> import unicodedata
>>> s = "Yo \U0001F497 \U0001F40D...\U0001F601 y las cigüeñas."
>>> print(''.join(c for c in unicodedata.normalize('NFC', s) if c <= '\uFFFF' ))
Yo  ... y las cigüeñas.

Esto deja el string sin mucho sentido, posiblemente sea mejor sustituir los Emojis por otro carácter valido, generalmente �.
>>> import unicodedata
>>> s = "Yo \U0001F497 \U0001F40D...\U0001F601 y las cigüeñas."
>>> print(''.join(c if c <= '\uFFFF' else '\uFFFD' for c in unicodedata.normalize('NFC', s)))
Yo � �...� y las cigüeñas.

A unas malas o con fines de debugging se puede también codificar la cadena e imprimir el bytearray:
print(s.encode())
print(s.encode("unicode_escape"))

A la hora de guardar el archivo de log lo ideal es guardar el string tal cual o a lo sumo con los caracteres unicode escapados. De esta forma no perdemos la información de los Emojis:
with open("log.txt", "a", encoding="utf-8") as f:
    f.write(s + "\n")

Siempre recordando que de imprimir su contenido en la terminal hay que proceder igual que antes.


text:
Q: Passing a string parameter as a runtime Argument I want to open the particular path through the batch file. And I want to pass one node in path at run time. If I give input Google, I want to pass the string argument here. It will open the path
want to pass one node in path at run time . if i give input Google.i
want to pass the string argument here. it will open the path
C:\Program Files (x86)\google\Common

How can I achieve this?
My batch file:
@echo off
echo test variables
set input =
set /p input ="Choice"
echo C:\Program Files (x86)\%input%\Common
cd C:\Program Files (x86)\"%input%"\Common
pause

A: There are the following issues in your code:

*

*there is a SPACE between the variable name and the = sign at the set commands, so it becomes a part of the variable name; hence the variable input remains empty/undefined;

*there are quotes within the path at the cd command, which are forbidden characters there;

Here is the corrected version:
@echo off
echo test variables
set "input="
set /p "input=Choice"
echo "C:\Program Files (x86)\%input%\Common"
cd "C:\Program Files (x86)\%input%\Common"
pause

I put quotes around the path at the cd command. Although not necessary for cd, many other commands cannot handle paths containing spaces if the "" are missing.

To use the first command line argument instead of user input, remove the set commands and replace %input% by %~1. The ~ ensures that any surrounding quotes are removed. Type call /? in the command prompt for details on this.

A: Are you saying you want to run your batch file like this.
C:\>mybatch.bat Google

If so then your batch file just changes to this.
@echo off
echo test variables
echo C:\Program Files (x86)\%1\Common
cd C:\Program Files (x86)\%1\Common
pause


text:
Q: android menus clickable spans or textviews Are the android menus "clickable spans" or "clickable textviews" or other? Like these:

And the "Done" in the second image, what is that?
EDIT: Is the 2nd image showing a dialog or a popup?

A: Yes a TextView can be clickable you just have to attach an onClickListener to it.
The "Done" element is a button (one of android built-in widgets).


text:
Q: How to avoid try-catch in android studio when i'm sure ther won't be null? I have some code.
String id = new UserJSONModel( new JSONObject(SharedPreferenceManager.read(
SharedPreferenceManager.AUTH, "")).getJSONObject("user")).getId();

I'm preety sure that AUTH strored in Shared Preferences isn't null becouse i store it after retrieving token from it and remove it on logout. I don't want to do try-catch on entire block of code so i put "if null" but android studio still wants me to use try-catch.
String auth = SharedPreferenceManager.read(SharedPreferenceManager.AUTH, "");
       if (auth == null) {

       } else {
          UserJSONModel user = new JSONObject(auth);
          String id = eser.getId();
       }

A: Android studio lets warn and force you to use try/catch when there is a method which could throw an exception , so instead of trying to avoid try/catch , think that one of your user may somehow  face null and instead of letting you app crashes you better handle it for a better user experience

A: Short answer. throws always require try/catch block. It's Java's rule.
Explanation on why it needs it.
JSONObject will throw a JSONException if auth is not the right json format. Null check will not cut it because Android Studio has no way of knowing if the format of auth is valid. That's why it wants you to surround new JSONObject with a try/catch block.
The try/catch block is from JSONObject's contructor. If you don't want to use try/catch block then you can use a different way to parse/stringify your json. Like Gson library. Or use Kotlin, throws doesn't require try/catch in Kotlin.


text:
Q: do i need to install virtualenvwrapper-win for Django I'm going to use Django for my final project so when i'm following the documentation it mentioned that we need to install virtualenvwrapper-win.Is it must to install virtualenvwrapper-win before installing Django? or not?

A: From the docs:
"virtualenv and virtualenvwrapper provide a dedicated environment for each Django project you create. While not mandatory, this is considered a best practice and will save you time in the future when you're ready to deploy your project."
So my advice to you: just do it:)


text:
Q: which OSI layer handles? some file transfer is in progress. the connection break s and then
later after some time is restored. then on the file transfer continues
from the point where it left off, which OSI layer handles this?
presentation, application, TCP, IP, Sesssion

A: First of all, TCP/IP is not OSI (see here). And if the connection really breaks, TCP won't be able to allow for continuation of transfer, it has to be done at a higher level (which is not defined in the TCP stack).

A: You are using FTP client which works at application layer.When any connection is created a session is maintained as per the capabilities of the application.Session management is done at session layer.So when FTP is able to resume the transfer that is because of session layer. OSI model is only a reference model  and each layer has different set of protocols. To have more in-depth understanding of the flow in OSI model layers i have created an example. You can refer to this link to understand more.
https://thinkingmonster.wordpress.com/2016/08/20/understanding-osi/

A:
which OSI layer handles this

The OSI session layer would handle it, if you were using OSI layers.

A: Well, layers are always referred as per OSI model, no matter wether its actually being used as specific stack. I totally agree with @thinkingmonster's answers. To add more on this I would say its the Transport layer ( layer4 PDU as per the OSI ref model) and layer 2 in TCP/IP stack.
This is typically handled by Error recovery mechanism using Sequence and Acknowledgement field in TCP header.TCP achieves reliability in both directions, using the Sequence Number field of one direction combined with the Acknowledgment field in the opposite direction.

This is just a little overview to have an idea, you might want to refer the Doc to have full handshake cycle with client and server.


text:
Q: Passing a List of Conditions to a WHERE-clause in JOOQ My question is very simple, really, I just want to know what boolean operator is used in the generated SQL when passing a List of Conditions to a WHERE-clause using JOOQ.
For example:
List<Condition> conditions = new ArrayList<>();
conditions.add(MY_TABLE.MY_COLUMN1.equal("Foo").and(MY_TABLE.MY_COLUMN2.equal("Far"));
conditions.add(MY_TABLE.MY_COLUMN1.equal("Boo").and(MY_TABLE.MY_COLUMN2.equal("Bar"));
DSL.selectFrom(MY_TABLE).where(conditions).fetch();

Is the resulting SQL this:
SELECT * FROM MY_TABLE WHERE (MY_COLUMN1='Foo' AND MY_COLUMN2='Far') OR (MY_COLUMN1='Boo' AND MY_COLUMN2='BAR');

or this:
SELECT * FROM MY_TABLE WHERE (MY_COLUMN1='Foo' AND MY_COLUMN2='Far') AND (MY_COLUMN1='Boo' AND MY_COLUMN2='BAR');

A: The conditions are AND-connected. While the Javadoc on SelectWhereStep.where(Condition...) doesn't mention this (which should be fixed), the underlying implementation is that of SelectQuery.addConditions(Condition...), which specifies usage of Operator.AND.
So the resulting query will be your second example:
SELECT * FROM MY_TABLE
WHERE (MY_COLUMN1='Foo' AND MY_COLUMN2='Far')
  AND (MY_COLUMN1='Boo' AND MY_COLUMN2='BAR');


text:
Q: Ubuntu suddenly at 1024x768 resolution and 'unknown monitor' after reboot Did a reboot after changing my computer's hostname, and suddenly only one of my monitors gets an image - and is now stuck at 1024x768 resolution, with display settings saying 'unknown monitor'.
Before reboot I had 4 monitors working with max resolutions and correctly identified, the primary one a widescreen running 3440x1440.
I have no idea what caused this. Before reboot I remember doing 2 things that "changed things":

*

*Struggled with trying to install Steam (client refused to start after installing through Ubuntu Software). Ended up doing sudo apt purge steam and sudo apt autoclean && sudo apt autoremove a couple of times.

*(unrelated to 1) Changed computer hostname (edited /etc/hostname and /etc/hosts)
Anyone have an idea what may have caused this, and how I can fix it?

A: Got it! All I needed to do was run sudo ubuntu-drivers autoinstall and reboot.
Thanks to Pilot6 over at Ask Ubuntu for the solution.


text:
Q: wcftestclient fails, but only on remote machine I've got a wcf "self-hosted" service up and running and when communicating across machines i get The remote server returned an unexpected response: (405) Method not allowed. message.
This only seems to happen when running the WCF test client connecting to a remote machine. When running on the server, everything communicates fine.
i'm thinking it has something to do with security, but i'm not sure where to look.
Can anyone point out what i'm missing or doing wrong?
below is my server config file
<system.serviceModel>
        <protocolMapping>
            <remove scheme="http" />
            <add scheme="http" binding="customBinding" bindingConfiguration="gzipCompression" />
        </protocolMapping>
        <bindings>
            <customBinding>
                <binding name="gzipCompression">
                    <gzipMessageEncoding />
                    <httpTransport maxReceivedMessageSize="2147483647" />
                </binding>
            </customBinding>
        </bindings>
        <extensions>
            <bindingElementExtensions>
                <add name="gzipMessageEncoding" type="Compression.GZIP.GZipMessageEncodingElement, Compression, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            </bindingElementExtensions>
        </extensions>
        <behaviors>
            <!--<serviceBehaviors>
                <behavior name="CadServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"
                        httpGetBinding="" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>-->
        </behaviors>
        <services>
            <service behaviorConfiguration="CadServiceBehavior" name="CadServiceLibrary.CadServiceContract">
                <endpoint address="com" binding="customBinding" bindingConfiguration="gzipCompression"
                    name="com" contract="CadServiceLibrary.CadServiceContract" />
                <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
                    name="mex" contract="IMetadataExchange" />
                <endpoint binding="wsHttpBinding" bindingConfiguration="" name="ws"
                    contract="CadServiceLibrary.CadServiceContract" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost/CadServices" />
                        <add baseAddress="https://localhost:450/CadServices" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>

A: I have seen this before although not sure if it is your problem:
Instead of localhost, put your server's name or IP address. If IP address, make sure the same IP address is selected in IIS (I assume you are hosting this in IIS).
When localhost is used, I have had difficulty in the past accessing it from remote machines - although listening on localhost works fine with TCP.


text:
Q: Can't display datetime from v-for I'm trying to show the datatime in a v-for, but it just keeps showing the same time over and over.
Is there a way to do this?
v-for -

{{ location_time }}  New Location

JS -
  data() {
    return {
      location_time: new Date().toLocaleTimeString(),
    }
  },

A: Use a method to lookup time.  Not sure where you are storing the time, but you can look up timezone from coords if needed.

{{ getTime(location) }}  New Location

methods: {
    getTime(location) {
      // lookup your timezone, etc here.
      return new Date(location.theTime).toLocaleTimeString()
    }
}


text:
Q: Python Tkinter Avoid using "root" name in lower level function Inspired by this 300+ vote closed Q&A: Best way to structure a tkinter application?, I'm looking to avoid explicitly using root in a function within a class. I think it should be implicitly declared through self or parent or something like that. Here is the code in question:
I have this code...
        self.label_this = tk.StringVar()
        self.label_last = tk.StringVar()
        self.label_total = tk.StringVar()

        tk.Label(count_frame, textvariable=self.label_this, \
                 font=(None, MON_FONTSIZE)).pack(anchor=tk.W)
        tk.Label(count_frame, textvariable=self.label_last, \
                 font=(None, MON_FONTSIZE)).pack(anchor=tk.W)
        tk.Label(count_frame, textvariable=self.label_total, \
                 font=(None, MON_FONTSIZE)).pack(anchor=tk.W)
        self.update_cnt_labels()

Then later on...
        ''' Get list of Window ID's on monitor now '''
        new_windows = self.windows_on_monitor(new_windows)
        new_windows_cnt = len(new_windows) / WIN_CNT
        if self.old_windows_cnt == new_windows_cnt :
            FlashMessage (self.label_this, "No new windows to remove...", \
                          3, 750, 250)
            self.update_cnt_labels()
            return

Then later on...
class FlashMessage:
    def __init__(self, widget, message, count=5, on=500, off=300):

        self.delay_show (1, widget, message)
        for i in range(count):
            self.delay_show (on, widget, "")
            self.delay_show (off, widget, message)

    def delay_show(self, ms, widget, message):
        root.after(ms, widget.set(message))
        root.update_idletasks()

I want to avoid using root in the last two lines and use self or something similar.
My program call chain is something like:

*

*the traditional: root = tk.Tk()

*bunch of mainline initialization stuff.

*the class: ResizingCanvas(mycanvas)

*mainline function: popup(event) which is bound to <ButtonPress-1>

*Dynamically formatted menu.tk_popup(event.x_root, event.y_root)

*the class: RemoveNewWindows()

*the function: remove()

*the class: FlashMessage() (show above)

*the function: self.delay_show() (shown above)

Each class and function has haphazard self, positional parameters, *args and **kwargs which mostly serve no purpose. Indeed even the __init__ above might be unnecessary. This is a result of copying code all over stack overflow.
Every second word in the program seems to be self but the word parent  is only used in the class ResizingCanvas(). Do I have to propagate parent down the call list and use it somehow?

A: You can call after and update_idletasks on any widget. There are many such functions that can be called on any widget but which have a global effect.
In your case, you'll need to pass some widget into the FlashMessage constructor and save the reference. You can then use the reference to call the functions.
You're passing something called widget that doesn't actually contain a widget. You need to rename it to something more appropriate (eg: var), and then pass in an actual widget.
(Note: you also are calling after incorrectly, which I've fixed in the following example)
For example:
class FlashMessage:
    def __init__(self, widget, var, message, count=5, on=500, off=300):
        self.widget = widget
        ...

def delay_show(self, ...):
    self.widget.after(ms, var.set, message)
    self.widget.update_idletasks()

Then, whenever you create an instance of FlashMessage you need to add a widget as the first parameter.
For example, assuming that count_frame is defined in the context where you create an instance of FlashMessage and it is an actual widget, it might look something like this:
if self.old_windows_cnt == new_windows_cnt :
    FlashMessage (count_frame, self.label_this, "No new windows to remove...", \
                  3, 750, 250)
    self.update_cnt_labels()
    return


text:
Q: operator std::string: why the object cannot output? Why this code cannot compile?
#include <string>
#include <iostream>

struct Foo
{
    operator std::string () const
    {
        return std::string("Hello world !");
    }
};

int main(void)
{
    Foo f;

    std::cout << f << "\n";
}

while this one does:
#include <string>
#include <iostream>

int main(void)
{
    std::cout << std::string("Hello world !") << "\n";
}

and this one too:
#include <string>
#include <iostream>

struct Bar
{
    operator int ()
    {
        return 42;
    }
};

int main(void)
{
    Bar b;

    std::cout << b << "\n";
}

I thought this was the same thing, because of operator std::string, but g++ does not compile neither clang++.


text:
Q: Volley post request not sending data properly I'm trying to send a base64 encoded string to a server over volley but its not sending properly. When i use httpbin this is the response
"args": {},
I/System.out:   "data": "",
I/System.out:   "files": {},
I/System.out:   "form": {  "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmN...(image base64)
I/System.out:   },

where the image data is in the form. However i need it in data.
public static String rawOutput = "dadsdas";
    private Button buttonChoose;
    private Button buttonUpload;
public String image;
    private ImageView imageView;
    private Button postText;

    private EditText editTextName;

    private Bitmap bitmap;

    private int PICK_IMAGE_REQUEST = 1;

    private String UPLOAD_URL ="https://httpbin.org/post";

    private String KEY_IMAGE = "Content-Type";
    private String KEY_NAME = "name";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_image);
        buttonChoose = (Button) findViewById(R.id.buttonChoose);
         postText = (Button) findViewById(R.id.postText);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);
        imageView  = (ImageView) findViewById(R.id.imageView);
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        byte[] imageBytes = baos.toByteArray();
        System.out.println(imageBytes);
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage() throws JSONException {
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
//        JSONObject jsonBody = new JSONObject();
//        jsonBody.put(getStringImage(bitmap), "");
        //final String mRequestBody = jsonBody.toString();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        loading.dismiss();
                        System.out.println(s);
                        Toast.makeText(PostImage.this, s , Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        loading.dismiss();
                        String json = null;

                        NetworkResponse response = volleyError.networkResponse;
                        if(response != null && response.data != null){
                            switch(response.statusCode){
                                case 400:

                                    json = new String(response.data);
                                    if(json != null) System.out.println(json);
                                    System.out.println(json.getClass().getSimpleName());
                                    break;
                            }
                            //Additional cases
                        }
                        Toast.makeText(PostImage.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
//            @Override
//            public String getBodyContentType() {
//                return "text/plain; charset=utf-8";
//            }
//            @Override
//            public byte[] getBody() {
//                byte[] body = new byte[0];
//                try {
//                    body = ("/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVz.......(image data here)");
//
                    //} catch (UnsupportedEncodingException exception) {
                     //   Log.e("ERROR", "exception", exception);
                        // return null and don't pass any POST string if you encounter encoding error
                    //return null;
                    //}
                    return httpPostBody.getBytes();
                }

//            @Override
//            public String getBody() throws AuthFailureError {
//                image = getStringImage(bitmap);
//                System.out.printf(image);
//                String params= "";
//                params=  image;
//                return params;
//
//            }
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                image = getStringImage(bitmap);
//                System.out.printf(image);
//                Map<String,String> params = new Hashtable<String, String>();
//                params.put("", image);
//                return params;
//            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
                return params;
            }
        };
        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //Adding request to the queue
        requestQueue.add(stringRequest);
        System.out.println(stringRequest);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting the Bitmap to ImageView
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onClick(View v) {

        if(v == buttonChoose){
            showFileChooser();
        }
        if(v == buttonUpload){
            try {
                uploadImage();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    public void postText(View v) {
        try {
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String URL = "http://api.getquesto.com:8080/upload";
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("Text:", "A leaf is an organ of a vascular plant and is the principal lateral appendage of the stem.[1] The leaves and stem together form the shoot.[2] Leaves are collectively referred to as foliage, as in \"autumn foliage.\"[3][4]\n" +
                    "\n" +
                    "\n" +
                    "Diagram of a simple leaf.\n" +
                    "Apex Midvein (Primary vein) Secondary vein. Lamina. Leaf margin Petiole Bud Stem\n" +
                    "Although leaves can be seen in many different textures and sizes, typically a leaf is a thin, dorsiventrally flattened organ, borne above ground and specialized for photosynthesis. In most leaves, the primary photosynthetic tissue, the (palisade mesophyll), is located on the upper side of the blade or lamina of the leaf[1] but in some species, including the mature foliage of Eucalyptus,[5] palisade mesophyll is present on both sides and the leaves are said to be isobilateral. Most leaves have distinctive upper (adaxial) and lower (abaxial) surfaces that differ in colour, hairiness, the number of stomata (pores that intake and output gases), epicuticular wax amount and structure and other features.\n" +
                    "\n" +
                    "Broad, flat leaves with complex venation are known as megaphylls and the species that bear them, the majority, as broad-leaved or megaphyllous plants. In others, such as the clubmosses, with different evolutionary origins, the leaves are simple, with only a single vein and are known as microphylls.[6]\n" +
                    "\n" +
                    "Some leaves, such as bulb scales are not above ground, and in many aquatic species the leaves are submerged in water. Succulent plants often have thick juicy leaves, but some leaves are without major photosynthetic function and may be dead at maturity, as in some cataphylls, and spines). Furthermore, several kinds of leaf-like structures found in vascular plants are not totally homologous with them. Examples include flattened plant stems called phylloclades and cladodes, and flattened leaf stems called phyllodes which differ from leaves both in their structure and origin.[4][7] Many structures of non-vascular plants, such as the phyllids of mosses and liverworts and even of some foliose lichens, which are not plants at all (in the sense of being members of the kingdom Plantae), look and function much like leaves.");
            final String mRequestBody = jsonBody.toString();
            String json = null;
            StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);

                    Toast.makeText(PostImage.this, response , Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("VOLLEY", error.toString());
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                        return null;
                    }
                }
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("Content-Type","text/plain");
                    return params;
                }
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }
            };

            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}`

does anyone know how to make it send through data?


text:
Q: how customize django graphql-jwt how customize backend authenticate for graphql-jwt? If i user BaseBackend and return user i get exception
"  graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'is_anonymous' "
class MyBackend(BaseBackend):
    def authenticate(self, request, *profile):
        user = User()
        user.social_id = int(profile.get('user_id'))
        user.expires_at = profile.get('expires_at')
        user.last_verification_code = "{:04}".format(random.randrange(1, 10**4))
        user.set_unusable_password()
        user.save()
        token = get_token(user)
        authenticate(username=user.full_name, password=user.password)
        login(request, user, backend='graphql_jwt.backends.JSONWebTokenBackend')
        return user


text:
Q: Rails has_many : Why does create_model not work? I think I'm missing something easy here... but can't figure it out.
class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me
  has_many :events
end

class Event < ActiveRecord::Base
  attr_accessible :start, :end, :all_day, :url
  belongs_to :user
end

u1 = User.create name: "Bob", email: "bob@what.com", password: "asdfasdf"
u1.create_event(start: 3.days.from_now)

-->
undefined method `create_event' for #<User:0x007f918cbbf7b8>

However,
u1.events << Event.create!(start: 3.days.from_now)

works!

A: You have defined has_many association:
has_many :events

So, if you want to create object you can use these methods:
# create new object, but not insert to database
u1.events.build(...)

# create new object and auto call `save` method to insert to database
u1.events.create(...)

You use u1.create_event, this will correct when you define has_one association:
has_one :event

So, you will have these methods to create object:
# create new object, but not insert to database
u1.build_event(...)

# create new object and auto call `save` method to insert to database
u1.create_event(...)

A: Don't see create_event defined on User. You can also use
u1.events.build(:start => 3.days.from_now)
u1.save

Fascinated to see that
u1.events << Event.create!(start: 3.days.from_now)

works. Although, I do think it is a bit obtuse and may not be immediately clear to a casual reader of the code.


text:
Q: not able to create AVD to execute appium scripts I am trying to use android virtual device as emulator for my appium scripts but while creating AVD I am not getting any option to select under CPU drop down
I have installed android studio bundle and have installed system images for Android 7.1.1. Below are images for same:

Please help me how can I resolve this issue.

A: You can clearly see the message in the CPU drop down saying "No System image installed for this target".
Just install the remaining unchecked System Images(Except Android TV and Android Wear) for Android 7.1.1 and try. It should work.


text:
Q: DIV Not showing in Chrome when changing style attribute Okay, so, I'm using JQuery to show/hide a 'Processing' div element on my page.  Below is the basic code:
function ShowLoading(){
    $(divLoadingPanel).show();
}

function HideLoading(){
    $(divLoadingPanel).hide();
}

Inside of my various Javascript functions I call ShowLoading() and HideLoading() as necessary.  When viewing the page in FireFox, everything works correctly.  When viewing it in Chrome, the loading panel is never seen.  HOWEVER, if I debug and break at the line after the panel should be
displayed, it's there.  It will display fine when walking the code manually, but not if I don't use a breakpoint and the debugger.  That's got me baffled.  Here's the code for the div itself:

    Processing...

And, finally, here's the class info for the panel:
.Loading_Panel {
    position:fixed;
    top: 50%;
    left: 50%;
    width:300px;
    height:150px;
    margin-top: -75px;
    margin-left: -150px;
    background: #E9F2FA;
    border-radius: 10px;
    border: 1px solid #1C4E7C;
}

Any help would be appreciated.

A: Change your code to:
 function ShowLoading(){
     $("#divLoadingPanel").show();
 }

 function HideLoading(){
     $("#divLoadingPanel").hide();
 }


text:
Q: change the layout of my chrome browser? Specifically the space above the tabs I'm running Chrome (recent version) in a Mac OSX.
So as a LAMP stack/software developer I have the requisite 117 open tabs in Chrome, and also I occasionally need to move the window around as I usually have 72 applications running.  It's part of the "programmer's code of honor " (or torture).
So, this is a minor detail but is there any way to double the window margin above the Chrome tabs for my "gotta move it now" attitude?  If so that would be great and I could stop playing microsurgeon ;)

A: No, there isn't any way to change the layout of that part of the window. Even Chrome themes can't modify it; they can only change colors and patterns.
If it helps any, there's a somewhat larger draggable area above the "new tab" button, right around here:


text:
Q: Run selenium tests in docker container I want to build a docker image from the sources of my javascript project. I wrote some tests with the Mocha Framework. The tests should run during the build docker build process because I want to automate the build with Jenkins.
The tests should use the Firefox webdriver. I installed Xvfb in the docker image to provide a virtual display for the Firefox process.
But everytime I run the build all tests fail and I get error messages like the following:
Uncaught WebDriverError: Unable to parse new session response: {"error":"unknown error","message":"connection refused"}
  at WebDriverError (node_modules/selenium-webdriver/lib/error.js:27:5)
  at client_.send.then.response (node_modules/selenium-webdriver/http/index.js:477:17)
  at ManagedPromise.invokeCallback_ (node_modules/selenium-webdriver/lib/promise.js:1379:14)
  at TaskQueue.execute_ (node_modules/selenium-webdriver/lib/promise.js:2913:14)
  at TaskQueue.executeNext_ (node_modules/selenium-webdriver/lib/promise.js:2896:21)
  at asyncRun (node_modules/selenium-webdriver/lib/promise.js:2820:25)
  at node_modules/selenium-webdriver/lib/promise.js:639:7
  at process._tickDomainCallback (internal/process/next_tick.js:129:7)
From: Task: WebDriver.createSession()
  at Function.createSession (node_modules/selenium-webdriver/lib/webdriver.js:329:24)
  at Driver (node_modules/selenium-webdriver/firefox/index.js:386:38)
  at Builder.build (node_modules/selenium-webdriver/builder.js:467:16)
  at Object.<anonymous> (test/e2e/driver.js:10:69)
...

When I run the tests outside of the docker container on my local machine everything works fine.
I initialize the webdriver with the following commands:
var webdriver = require('selenium-webdriver');

var capabilities = webdriver.Capabilities.firefox();
capabilities.set('marionette', true);
var driver = new webdriver.Builder().withCapabilities(capabilities).build();

Are there any best practices on how to run selenium tests headlessly inside of a docker container?

A: I fixed the problem by running the gulp task that starts the selenium-standalone server and the tests with xvfb-run:
CMD xvfb-run ./node_modules/gulp/bin/gulp.js test


text:
Q: form_for with :slug instead of :id <%= form_for [current_user, @task] do |f| %>

gives users/:id/tasks but I would need users/:slug/tasks as I am using:
resources :users, param: :slug do
  resources :tasks, only: [:index, :new, :create]
end

but if I use:
<%= form_for [current_user.slug, @task] do |f| %>

I get: NoMethodError: undefined method 'jemelle_visits_path' for
how to get users/jemelle/tasks instead?

A: I think you need to override the to_param method of your model:
https://apidock.com/rails/ActiveRecord/Base/to_param

user = User.find_by_name('Phusion')
user_path(user)  # => "/users/1"

You can override to_param in your model to make user_path construct a path using the user's name instead of the user's id:
class User < ActiveRecord::Base
  def to_param  # overridden
    name
  end
end

user = User.find_by_name('Phusion')
user_path(user)  # => "/users/Phusion"


text:
Q: How do I load a file in a parent directory using http-server? Setup

*

*example/lib/d3/d3.js

*example/src/scatterPlotVersion3/index.html

*example/css/styles.css

*http-server (https://github.com/nodeapps/http-server)
index.html
<link rel="stylesheet" type="text/css" href="../../css/styles.css"/>
<script type="text/javascript" src="../../lib/d3/d3.js"></script>

After going to localhost:8080. I get the following errors:
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (styles.css, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (d3.js, line 0)
[Error] ReferenceError: Can't find variable: d3 global code (localhost, line 16)

How do I fix this?

A: The solution I see as of now is running http-server in parent directory and then on running server accessing file in child directory.
for say: I have a src folder and inside that I have example folder having index.html file. src also contains abc.js which I want to use in index.html.

*

*Run http-server in parent directory

*Access file like this http://127.0.0.1:8080/example/index.html


text:
Q: AwsBackUp supports cross region copy in terraform Does terraform support aws backup feature for cross region copy (https://www.terraform.io/docs/providers/aws/r/backup_plan.html )?
As I read the document I can see that it does support.
But I get the following error:

Error: Unsupported argument
    on backup_plan.tf line 11, in resource "aws_backup_plan" "example":
    11:         copy_action = {
  An argument named "copy_action" is not expected here.

My terraform file for your reference
resource "aws_backup_plan" "example" {
    name = "example-plan"
    rule {
        rule_name = "MainRule"
        target_vault_name = "primary"
        schedule = "cron(5 8 * * ? *)"
        start_window = 480
        completion_window = 10080
        lifecycle {
            delete_after = 30
        }
        copy_action {
            destination_vault_arn = "arn:aws:backup:us-west-2:123456789:backup-vault:secondary"
        }
    }
}

But when I remove the block
copy_action {
            destination_vault_arn = "arn:aws:backup:us-west-2:123456789:backup-vault:secondary"
        }

It works just fine
Thanks

A: I assume you are running a version of the Terraform AWS Provider of 2.57.0 or older.
Version 2.58.0 (released 3 days ago) brought support for the copy_action:

resource/aws_backup_plan: Add rule configuration block copy_action configuration block (support cross region copy)

You can specify in your code to require at least this version as follows:
provider "aws" {
  version = "~> 2.58.0"
}


text:
Q: Android Drag and drop between 2 fragments I have 2 fragments.
I want to drag a view from fragment one and drop it to another view in fragment two.
What i do now is i start dragging (using drag and drop api) inside fragment one , then i hide fragment one then i show  fragment two which has a drag listener event on some view.
I use fragment transactions of add and show and hide to make sure that the fragments are not destroyed or recreated , i never use replace for transaction.
However the onDrag method in drag listener interface inside fragment two is never called when i hide fragment one and show fragment two.
I have done something similar before that worked , except that fragment two was overlapping fragment one and both appeared on UI , and when i start dragging inside fragment one i only hided it then the drag listener inside fragment two was active .
So the difference in the case that worked was that i only hided fragment one by transaction.
However in the case which is not working i hide fragment one and show fragment two by transaction.
Don't know why are the results different.
For further details on my case i'm using BottomNavigationView and it has 3 fragments , i'm trying to drag and drop between 2 of those fragments.

A: I managed to solve this by sending the view object via event bus to fragment two ( after the user in my case long pressed on the view in fragment one ).
Then i switched fragments as mentioned in the question.
Then i started using the drag and drop api from fragment two event bus receiver that contains my view object.


text:
Q: CloudKit share workflow ends with: To open it, you'll need the latest version of "app_name" I'm trying to create a CKShare on a set of CKRecords using CloudKit. I've made it through most of the workflow:

*

*create a 'root_record' that all shared records will identify as
parent

*add several records and identify 'root_record' as parent

*create CKShare on 'root_record' and present the share dialog with
UICloudSharingController

*include mandatory itemTitleForCloudSharingController & failedToSaveShareWithError

*include - (void)application:(UIApplication *)application
userDidAcceptCloudKitShareWithMetadata: in appdelegate

*clicked backgroundmodes > remote notification in capabilities

I get the share dialog on device A, text or email the share to device B as expected. On device B, I get:
Open "My_Title_String"? > Not Now | Open
But when I choose 'Open', I get:
Update "App_Name" | sharer shared this. To open it, you'll need the latest version of "app_name". > Got To App Store | Not Now
I've tried upping the build number, deleting app + reinstalling & installing from TestFlight, but I can't get the app to invoke on Device B so - (void)application:(UIApplication*)application userDidAcceptCloudKitShareWithMetadata: never gets called.
Any advice on where I've gone wrong?

A: I hadn't included
CKSharingSupported
entry in my Info.plist.
I can't find the documentation of this flag anywhere in Apple's docs, but found it in another posting and it did the trick. Hope this helps someone else save some time.


text:
Q: Stack overflow silenced on linux? On Linux I have a code that use a array declared inside the main function with a sixe of 2MB + 1 byte
#include <stdio.h>
#include <stdlib.h>

#define MAX_DATA (2097152)  /* 2MB */

int main(int argc, char *argv[])
{
    /* Reserve 1 byte for null termination */
    char data[MAX_DATA + 1];

    printf("Bye\n");

    return 0;
}

When I compiled on Linux with gcc I run it without any problem. But on Windows I get a runtime error. At moment of run it I have 5GB of free memory.
For solve the problem on Windows I need specify other stack size:
gcc -Wl,--stack,2097153 -o test.exe test.c

or declare the data array outside the main function.
Because that the program compiled on linux was linked without change the stack size?
Why it run ok on Linux but fail on Windows?
I use the same source code and the same gcc instructions:
gcc -Wall -O source.c -o source

Because malloc implementation on linux i think is not reliable because it can return a not null pointer even if memory is not available.
I think that in the program that is running on the Linux, it maybe silently ignore a stack problem?.
Is possible that the program that is running on Linux that was not linked changing the stack size, but not fail at runtime unlike Windows, is silently ignoring a stack problem?
Also, why if I declare the array outside the main function it Works ok on Windows? In case it use heap why I not need free it?

A:
Why does it run fine on Linux but fails on Windows?

Because the default stack size for a process or thread is system dependant:

*

*On Windows, the default stack reservation size used by the linker is 1 MB.

*On Linux/Unix, the maximum stack size can be configured through the ulimit command. In addition, you can configure the stack size when creating a new thread.

Because malloc implementation on linux i think is not reliable because it can return a not null pointer even if memory is not available.

I suppose that you are talking about the overcommit issue. To overcome this, you can use calloc and check the return value. If you do this at the very beginning of your application, you can immediately exit with an appropriate error message.


text:
Q: Spectral representation of a BCS gap function I am playing with the spectral representation of a BCS gap function and I have trouble verifying causality properties. I find a divergence and I don't know what is the problem.
Assume the gap function is written $\Delta^{\text{BCS}}(\omega) = \Delta_1(\omega) + i\Delta_2(\omega)$ with $\Delta_1$ and $\Delta_2$ the real and imaginary parts, respectively. Thus, causality implies
$$ \Delta^{\text{BCS}}(\omega) = \int_{-\infty}^{\infty}\frac{d\omega'}{\pi} \frac{\Delta_2(\omega')}{\omega'-\omega}, \ \Delta_1(\omega) = P \int_{-\infty}^{\infty} \frac{d\omega'}{\pi} \frac{\Delta_2(\omega')}{\omega'-\omega}, \ \Delta_2(\omega) = P\int_{-\infty}^{\infty} \frac{d\omega'}{\pi} \frac{\Delta_1(\omega')}{\omega'-\omega}, $$
where $P$ is the principal part. I think this is pretty standard, but I'm not so sure about the principal part. In this paper, they omit it.
For the BCS gap function, I assume a frequency-dependent gap function of the form
$$\Delta_1(\omega) = \left\{ \begin{array}{cc} \Delta_0 & \text{for} \ \omega \in ]-\omega_c, \omega_c[ \\ 0 & \text{otherwise,} \end{array}\right.$$
so a constant gap function in frequencies, with a cutoff of $\omega_c$.
From the causality equation, I find
$$ \Delta_2(\omega) = - \frac{\Delta_0}{\pi} \ln \Big \lvert \frac{\omega-\omega_c}{\omega+\omega_c} \Big \rvert. $$
I calculated the principal part like
$$
\pi \Delta_2(\omega) = \lim_{\epsilon,\epsilon'\rightarrow0^+} \left[ \int_{-\infty}^{-\omega_c-\epsilon} \frac{d\omega'}{\omega'-\omega} \ln\left[ \frac{\omega'-\omega_c}{\omega'+\omega_c} \right] + \int_{-\omega_c+\epsilon}^{\omega-\epsilon'} \frac{d\omega'}{\omega'-\omega} \ln \left[ \frac{\omega_c - \omega'}{\omega_c+\omega'}\right] + \int_{\omega+\epsilon'}^{\omega_c-\epsilon} \frac{d\omega'}{\omega'-\omega} \ln \left[ \frac{\omega_c - \omega'}{\omega_c+\omega'} \right] + \int_{\omega_c+\epsilon}^{\infty} \frac{d\omega'}{\omega'-\omega} \ln \left[ \frac{\omega'-\omega_c}{\omega'+\omega_c} \right] \right].
$$
Now, if I try to recalculate $\Delta_1$ from the right causality equation and from $\Delta_2$, it does not quite work. First, I found from WolframAlpha that I can use
$$\int_c^d \frac{d\omega'}{\omega'-\omega} \ln \left[\frac{\omega' - \omega_c}{\omega' + \omega_c} \right] = \ln\left[ \frac{d-\omega}{c-\omega} \right] \ln\left[ \frac{\omega-\omega_c}{\omega+\omega_c} \right]
    - \sum_{k=1}^{\infty} \frac{1}{k^2}\left( \frac{1}{(\omega-\omega_c)^k}-\frac{1}{(\omega+\omega_c)^k} \right) \left( (\omega-d)^k - (\omega-c)^k\right). $$
It seems to be true for any domain, but I somehow doubt it. Now to calculate the integral, I apply the principal part like above, use the last expression to calculate each parts and if I assume $\omega \in ] -\omega_c, \omega_c[$, I find
$$
\Delta_1(\omega) = -\frac{\Delta_0}{\pi^2}\ln \left[ \frac{\omega_c+\omega}{\omega_c-\omega}\right] \ln[-1] + \lim_{b\rightarrow\infty} \sum_{k\in 2\mathbb{Z}+1} \frac{2b^k}{k^2} \left( \frac{1}{(\omega-\omega_c)^k}- \frac{1}{(\omega+\omega_c)^k} \right),
$$
which is clearly divergent in the second term. Moreover, since $\ln[-1] = (2n+1)\pi i, \ n \in \mathbb{N}$, the first term looks like the imaginary part although there is an arbitrary $n$ and also I did take the principal part so it shouldn't be there (otherwise it can look like the general equation, the first above).
I've been trying this to much and don't really see any weak points I can work on, which is why I'm kindly asking your help. Perhaps I should post this on the Mathematical Stack Exchange? Although I could find anything, I does feel like this should be covered in some superconductivity courses. Thank you!


text:
Q: Logging Identifiers across methods I have some ids (id from database, example 34645) that I currently log as "[34645] - something happended" using something like:
log.info("[" + id + "]" + foo);

Some logs, like "server starting", "database connection bla" dont have an id and thus doesn't log any and that's fine.
However, when I have an id I call methods that also log, but don't have the id, like:
lookup(name) {
  //do some lookup and stuff
  log.info("[" + name + "]" has some info we use somewhere: " + result);
}

Is there a (smart) way to get the id logged inside lookup() without passing id to lookup() or refactor class hierarchies? There are different threads logging so setting/unsetting id-values for logback to use will probably be difficult to get right.

A: as per request and I like credits, you can use MDC for that thing.
Info on that is here: http://logback.qos.ch/manual/mdc.html
Thanks :)


text:
Q: Is it possible to include external content with php? Is it SEO friendly? I need to include an external page into my website. How SEO friendly is this? And which will be the right code to use? I came a accross a few different codes and I'm not sure which to use...

A: Your question as is does not target a specific problem and no code is provided.
You can fetch anything you want and integrate into your website, using output buffers, file_get_contents(), SOAP, REST or cURL.
Search engines do not recognize the fetched content as external, but your page load time might increase if you do not buffer the content which decreases SEO value.
The better question is, does the site you want to fetch from allow using of their content, what licence does it have?


text:
Q: Spring data redis - Hash of Map is retrieved as Map, how to fix this? I am using Spring Data Redis and using hash operations to save the Map<String, Long> as a hash in Redis.
Suppose hash is "some hash", hashkey is "unique key" & hash value is "Map<String, Long>".
 Map<String,Long > data= new HashMap<>());
 data.put("k", 21474836470); //value = Integer.MAX*10

 hashOperations.put("some hash", "unique key", data);

 Map<String,Integer> result = hashOperations.get( "some hash", "unique key");

The problem here is the result is Map<String, Integer> instead of Map<String, Long>.
When the value in a map stored in Redis is greater than Integer.MAX, then I will get the wrong value in the result map.

I am able to save 10 times of Integer.MAX value through Redis-CLI. Seems the range of Redis integer is different from Java Integer.
Through Redis CLI I can get a large value of an integer, but on Java, the return type is Java integer, which will not work for Long value.
I am using Jackson2JsonRedisSerializer as a hash value and value serializer.
How do I fix this?

A: I tested with a value greater than Integer.MAX and Spring is able to convert it into a Long value.
For values less than Integer.MAX it is converting to Integer.
For values greater than Integer.MAX it is converting to Long.


text:
Q: binary search in sorted array Hi i am trying to carry out a binary search in a sorted array by using the input by the user by means of a text box.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace arra3 {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] arr = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

        int low, high, user_input, mid;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            user_input = Convert.ToInt32(textBox1.Text);

            while (low <= high)
            {
                mid = (low + high) / 2;

                if (arr[mid] < user_input)
                {
                    low = mid + 1;
                    continue;
                }
                else if (arr[mid] > user_input)
                {
                    high = mid - 1;
                    continue;
                }

                else
                {
                    MessageBox.Show(mid.ToString());
                }
            }
            MessageBox.Show("-1".ToString());

        }
    }
}

But I keep getting either -1 as an output or enter in an infinite loop of 0 if i enter a zero.
Any help please?

A: I have initialized low and high variables and added return statement after the match is found.
Here is the corrected code (notice the comments):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace arra3 {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] arr = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

        int low, high, user_input, mid;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            user_input = Convert.ToInt32(textBox1.Text);
            low = 0;  // <- HERE
            high = arr.Length;  // <- HERE

            while (low <= high)
            {
                mid = (low + high) / 2;

                if (arr[mid] < user_input)
                {
                    low = mid + 1;
                    continue;
                }
                else if (arr[mid] > user_input)
                {
                    high = mid - 1;
                    continue;
                }

                else
                {
                    MessageBox.Show(mid.ToString());
                    return;  // <- HERE
                }
            }
            MessageBox.Show("-1".ToString());

        }
    }
}


text:
Q: Entity Framework: include foreign key ID in entity? I have read in many places that one should (usually) have the foreign key id in an entity because it is a database detail, and in fact, EF manages it pretty well by adding an EntityName_Id column to the corresponding table.
public class Order
{
    public decimal Total { get; set; }
    public int? InvoiceId { get; set; }
    public Invoice Invoice { get; set; }
}

public class Invoice
{
    public ICollection<Order> Orders { get; set; }
}

In this example, an Order has an optional relationship with Invoice. When showing info about Order, I am interested in knowing whether or not it has an Invoice.
The problem is that if I don't have the ´InvoiceId´ property in my entities, I have to check the whole related entity just to check if it exists, whereas having that property in my entity would allow me to check it for null, which is "free" in the sense that the entity is already loaded.
Is that the only use of having foreign key Id properties in entities? Am I missing something here?

A: You can check entity framework documentation to see answer for your question:
https://msdn.microsoft.com/en-US/data/jj713564.aspx
It says:

With foreign key associations, you can use either method to change,
  create, or modify relationships. With independent associations, you
  cannot use the foreign key property.

Use cases provided in article:

*

*Update foreign key relationship -- this can cause issues if you update navigation property and foreign key at the same time and reference different objects.

By assigning a new value to a foreign key property, as in the
  following example.
course.DepartmentID = newCourse.DepartmentID;

*Remove foreign key relationship. This only works if there is no associated object with FK property, that  is in state 'Added'.

The following code removes a relationship by setting the foreign key
  to null. Note, that the foreign key property must be nullable.
course.DepartmentID = null;

Apart from these cases you can use it to check if your reference is not null/null without really lazy-loading related entity like you said:
var isNull = course.DepartmentID == null;

I believe it's pretty much it. From my point of view, benefits from using FK property are too small to rely on them.


text:
Q: How to evaluate any given expression How do you, given any string expression, populate a tree?
I have an assignment that I am stuck on.
I need to evaluate the following expression (( 5 * 10 ) /2 - (( 2 + 3) + 6)) using any data structure.
Using a stack, I am able to verify that the string is well formed. But how can I add the various values into a tree and then evaluate them in order.
Please give me any hints you may have on how I can read the string  ((( 490 * 9 ) / 2)/5/6 - (( 2/4 + 3) + 6 * 5))
For instance, How do I get the (-) to be the root of the three when it is the 15th substring in the input expression? How do I make sure that the (/)6 expression happens after (/)5 etc.

A: What you are looking for is provided here: http://www.codeproject.com/Articles/88435/Simple-Guide-to-Mathematical-Expression-Parsing

A:
evaluate any string [representing a mathematical] expression

You need to do three things:

*

*define a type for the abstract syntax tree representing your language

*write a recursive descent parser for your syntax

*write an interpreter for your syntax

You can do this very easily.
I'll use Haskell notation, since it is concise, but you can translate it if you wish.
A type for your language:
data Exp = Op BinOp Exp Exp
         | Lit Int

data BinOp = Plus
           | Times
           | Div
           | Sub

now, we can write an interpreter for expressions in this language:
eval :: Exp -> Int
eval (Lit n)      = n
eval (Op o e1 e2) =
   let v1 = eval e1
       v2 = eval e2
   in case o of
       Plus  -> v1 + v2
       Times -> v1 * v2
       Sub   -> v1 - v2
       Div   -> v1 / v2 -- note, may fail!

Ok. So that's the evaluator for terms in your language. Now write a recursive descent parser...

A: The parenthesis denote the order of operations so similarly to how you used the stack to make sure everything matched you can parse out those matches and use them as elements in the tree to create the hierarchy for evaluation where the operators are the children of each breadth-wise level of parenthesis matches.

A: Edit the second: op clarified, see other answers

A: The other answers here cover reading the expression tree into memory, but they don't cover evaluating the tree once you've built it.
The general strategy for evaluating the tree is that the tree should consist of nodes and leaves, where nodes are operators with children, and leaves are the constant values.  For example, the expression (((490 * 9) / 2) / 5 / 6 - ((2 / 4 + 3) + 6 * 5)) converts to the tree

                      -
                  /      \
                 /        \
              div          +
             /   \       /   \
          div     6     +     *
         /   \        /  \   / \
      div     5      div  3 6   5
     /   \          /   \
    *     2        2     4
  /   \
450    9

To evaluate this tree, you start at the root.  You first recursively evaluate the left subtree and the right subtree, and then apply the operator to the results of the two subtree evaluations.  Each leaf (number) evaluates to itself.
In this case, you would start at the root (-), evaluate the left subtree down to 73.5, evaluate the right subtree down to 33.5, and subtract to get a final result of 40.
As a more precise example, let's look at the nodes on the far left of the tree, after several layers of recursive calls have been made.  The leaf 450 evaluates to 450, the leaf 9 evaluates to 9, and the node (* 450 9) (writing nodes of the tree in Lisp-like prefix notation) evaluates to 4050.  So, from the node (/ (* 450 9) 2), the left recursive call evaluates to 4050 and the right recursive call evaluates to 2, meaning that the overall node evaluates to 2025.  As long as you make the recursive calls from the nodes before combining the values, and make sure each leaf evaluates to itself, tree evaluation is straightforward.


text:
Q: Android: How can I centerCrop the background of a view? I don't want to insert an imageview into my view, I just want to set a bitmap as the background of my view. But I want the bitmap centerCropped. By default the bitmap background is stretched to fit the bounds of the view.

A: You can do this by implementing a custom background drawable.
I implemented a subclass of BitmapDrawable that centerCrops the Bitmap (basically overriding the onDraw(Canvas) mehthod).
code:
package com.github.premnirmal;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;

/**
 * A subclass of bitmap drawable that scales the bitmap to CenterCrop
 * Copyright Prem Nirmal 2016 MIT License
 * @author PremNirmal
 */
public class CenterCropBitmapDrawable extends BitmapDrawable {

  private final int viewWidth, viewHeight;

  public CenterCropBitmapDrawable(Resources res, Bitmap bitmap, int viewWidth, int viewHeight) {
    super(res, bitmap);
    this.viewWidth = viewWidth;
    this.viewHeight = viewHeight;
  }

  @Override public void draw(Canvas canvas) {
    final Matrix drawMatrix = new Matrix();
    final int dwidth = getIntrinsicWidth();
    final int dheight = getIntrinsicHeight();

    final int vwidth = viewWidth;
    final int vheight = viewHeight;

    float scale;
    float dx = 0, dy = 0;
    int saveCount = canvas.getSaveCount();
    canvas.save();
    if (dwidth * vheight > vwidth * dheight) {
      scale = (float) vheight / (float) dheight;
      dx = (vwidth - dwidth * scale) * 0.5f;
    } else {
      scale = (float) vwidth / (float) dwidth;
      dy = (vheight - dheight * scale) * 0.5f;
    }

    drawMatrix.setScale(scale, scale);
    drawMatrix.postTranslate(Math.round(dx), Math.round(dy));
    canvas.concat(drawMatrix);

    canvas.drawBitmap(getBitmap(), 0, 0, getPaint());

    canvas.restoreToCount(saveCount);
  }
}


text:
Q: Individual Customer Backup from Multi Customer DB We have a multi customer database, that's about 95gb in size.  One of the customers is requesting a monthly backup of their data.  We have a script that strips out all records from all tables that are not related to the specified ID.
So we restore backup of DB to a new DB, run our script to strip it down, this leaves us with a DB containing 1 customer instead of 100ish.  But the DB is still 95gb in size even though it should now be 90%+ empty.
I've tried many different combinations of taking it offline, then back online, backing it up after the strip down, various different combinations of DBCC SHRINKDATABASE and DBCC SHRINKFILE, etc.
The best I've done so far is about 9 hours worth of shrinking to get the file down to about 15gb.  The most each shrink ever takes off is 10-20%, even when I specify to leave 0 free space behind.
Several of the tables contain columns with the image datatype, and I think that has something to do with it, but I still can't seem to find a reliable solution to this.
Ultimately the goal is to have a Plan/Job that will run once a month to restore a backup to a new DB, strip it down, shrink it down, then back that up to a folder and delete the new DB.  But we really would like to make this happen in less than 9-12 hours if possible.
Any help would be appreciated.

A: I suspect that the restore process is creating a 95 GB database. from shrinkdatabase:
The database cannot be made smaller than the minimum size of the database. The minimum size is the size specified when the database is originally created, or the last size explicitly set by using a file size changing operation such as DBCC SHIRNKFILE or ALTER DATABASE. For example, if a database is originally created with a size of 10 MB in size and grows to 100 MB, the smallest the database can be reduced to is 10 MB, even if all the data in the database has been deleted.
I would change the way you are doing this by writing a script that creates a new database and does a select into for the customer data


text:
Q: is it possible to override the source when using rust command to update I am using rustup to update the rust version, is it possible to specify the source in the command line like this?
rustup update --source http://rustup.com

I already know how to config the mirror url in .cargo/config, I just want to switch the source in temporary in the command lne. Seems no way to do this from official document:
➜  .cargo rustup update --help
rustup-update
Update Rust toolchains and rustup

USAGE:
    rustup update [FLAGS] [toolchain]...

FLAGS:
        --force             Force an update, even if some components are missing
        --force-non-host    Install toolchains that require an emulator. See https://github.com/rust-
                            lang/rustup/wiki/Non-host-toolchains
    -h, --help              Prints help information
        --no-self-update    Don't perform self update when running the `rustup update` command

ARGS:
    <toolchain>...    Toolchain name, such as 'stable', 'nightly', or '1.8.0'. For more information see `rustup help
                      toolchain`

DISCUSSION:
    With no toolchain specified, the `update` command updates each of
    the installed toolchains from the official release channels, then
    updates rustup itself.

    If given a toolchain argument then `update` updates that
    toolchain, the same as `rustup toolchain install`.


text:
Q: excluding files in a fileset not working I am making a war of a project but i want that classes within that war be picked from specified location and also a jar file A.jar to be picked from custom location i am doing something like this ....
<target name="war" depends="a-jar">
    <war destfile="D:/JBOSSHOME/project.war" webxml="${project-location}/web/WEB-INF/web.xml">
        <fileset dir="${project-location}/web" >
        <exclude name="${project-location}/web/WEB-INF/lib/A.jar"/>
        <exclude name="${project-location}/web/WEB-INF/classes/**/*.class"/>
        </fileset>
        <lib dir="${jarsLocation}"></lib>
        <classes dir="D:/JBOSSHOME/project/build/classes"/>
    </war>
</target>

but in the resultant war i am getting 2 A.jar files and also classes are getting copied from ${project-location}/web/WEB-INF/classes instead of the classes dir that i have provided...
Any help would be much appreciated...

A: The exclude shouldn't include the root directory of your file set:
<fileset dir="${project-location}/web" >
    <exclude name="WEB-INF/lib/A.jar"/>
    <exclude name="WEB-INF/classes/**/*.class"/>
</fileset>


text:
Q: Reverse proxy with additional logic using CherryPy Is it possible to run a CherryPy application as a reverse proxy, to intercept ALL requests and rewrite them depending on the URL and other logic?
My aims:

*

*intercept all requests and perform home-rolled authentication

*rewrite the requests to different services (perhaps on different ports) depending on the URL

*return the result

All the examples I find refer to putting CherryPy behind a reverse proxy like Apache.
I would imagine there's a hook function that can be overridden
I've looked the CherryProxy package, but the documentation is sparse, and it looks like it's just using CherryPy hooks anyway.


text:
Q: Publishing asp.net core I have a problem when publishing my web application to IIS.
The application works fine when running it locally, after the publishing I get the following error when accessing view which requires connection to the database (MYSQL):

In the publishing profile the following string is added:
server=localhost;userid=USERNAME;password=PASSWORD;database=mydb;SslMode=none.

The IIS server is running locally, on the same machine as the database.
The issue seems to be happening everytime I use the database context.
Should the "Entity Framework Migrations" (the database used is the same) be enabled in the publishing profile, and if so how do I define the Connection string (as the one from the "Databases" option doesn't work)?
When developer mode is activated (through VS), the error isn't there anymore..


text:
Q: How to get JSON object without converting in Retrofit 2.0? I need download json object from REST server without converting by GSON. But not understand how make in Retrofit 2.0 bata 1

A: Simply use JsonElement as your pojo. For example
In your FlowerApi interafce:
    @GET("/flower")
    Call<JsonElement> getFlowers();

In your main class:
    Call<JsonElement> getFlowersCall = httpApiClass.getFlowers();

    getFlowersCall.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Response<JsonElement> response, Retrofit retrofit) {
            JsonElement jsonElement = response.body();
            Log.d(TAG, jsonElement.toString());
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d(TAG, "Failed: " + t.getMessage());
        }
    });

Actually, the response is still converted to JsonElement by the Gson converter, but you can get something that is close to the raw response.

A: 1   compile 'io.reactivex:rxjava:1.0.+'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
    compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.5.0'
2  OkHttpClient client = new OkHttpClient();
     // client.interceptors().add(new UrlInterceptor());
        client.interceptors().add(new LoggingInterceptor());
        AppApi api = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                        // add a converter for String
                .addConverter(String.class, new ToStringConverter())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build()
                .create(AppApi.class);

A: We can get JsonObject (com.google.gson) and parse this as well as standard JSONObject (org.json)
Interface FlowerApi
@GET("/flower")
Call<JsonObject> getFlowers();

In rest handler use
FlowerApi api = ApiFactory.createRetrofitService(FlowerApi.class);
Call<JsonObject> call = api.getFlowers();
retrofit.Response response = call.execute();
if (response.isSuccess()) {
   JsonObject object = (JsonObject) response.body();
}

Api Factory class help a create retrofit service easy
public class ApiFactory {

    private static final int TIMEOUT = 60;
    private static final int WRITE_TIMEOUT = 120;
    private static final int CONNECT_TIMEOUT = 10;

    private static final OkHttpClient CLIENT = new OkHttpClient();

    private static final String BASE_URL = "flowers.com";

    static {
        CLIENT.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        CLIENT.setWriteTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        CLIENT.setReadTimeout(TIMEOUT, TimeUnit.SECONDS);
    }

    @NonNull
    public static <S> S createRetrofitService(Class<S> serviceClass) {
        return getRetrofit().create(serviceClass);
    }

    @NonNull
    private static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(CLIENT)
                .build();
    }
}

In build.gradle
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'


text:
Q: How can I find a number of connected components in implicit graph? I have a CS problem which is stated like that:
Given a sheet of paper with some cells cut out, represented by chars (either '.' (cut) or '#' (not cut)), I need to find how many pieces will form.
Example:
##..#####.
.#.#.#....
###..##.#.
..##.....#
.###.#####

Answer for the example above is 5.
One piece will form:
....
.##.
....

Two pieces will form:
....
.#..
..#.

Common sense suggests me to find a way to represent a sheet with a graph (each number sign is a vertex, and two vertices are connected if they share a side). However, it is unclear to me how to do it. I found out that there are implicit graphs (graphs defined by a function which returns all neighbors of given vertex). A function like this is trivial to implement in the case.
The question is: How should I modify DFS algorithm to find components in this kind of graph?

A: *

*When we loop over the edges from a vertex, we use implicit edges instead of stored edges.

*It is useful to represent vertices as their two-dimensional coordinates (row, col).
The pseudocode can be as follows:
dRow = [-1,  0, +1,  0]
dCol = [ 0, -1,  0, +1]
...later, when we want to move from vertex (row, col)...
for dir in [0..4):
    nRow = row + dRow[dir]
    nCol = col + dCol[dir]
    if vertex (nRow, nCol) is in rectangle bounds:
        try to move from vertex (row, col) to vertex (nRow, nCol)

That's in the place where a classic DFS implementation would have a loop like:
for each vertex u in {neighbors of vertex v}:
    try to move from vertex v to vertex u