Q: Fast way to strip_tags in whole document Our website is currently under attack by some scriptkiddies that are adding HTML code to their motto's and other database tables (they have access too) and we would like to use strip_tags to filter the HTML out of it, we use a lot of queries on our website so I was wondering if there was a way to apply these rules to a whole document.
Some of our queries look like this:
<?php echo $users->UserInfo($username, 'motto'); ?>

While others look like:

'.$campaign['caption'].'

A plug-in for PHP would be good to, we use Windows Server 2008 R2 SP1 with IIS.

A: The easiest way would be to create a wrapper object around the actual db abstraction object(s).
For example, if there is an object of type "db" that provides you some convienance functions such as "select" and "update", you could write a class that extends "db" and overrides the "select function".  It might look something like this (its an example as you have not provided enough info on your specific implementation).
class db2 extends db
{
    public function select($tableName, $whereClause)
    {
        $result = parent::select($tableName, $whereClause);
        return strip_tags($result);
    }
}

Then you would replace your object that instantiated "db" and instead instantiate "db2".
$db = new db($connectionParams);

should be replaced with
$db = new db2($connectionParams);

Now all your existing queries should use the new function which removes the tags.


Q: Lua5.2 embedded in C++ I'm trying for the first time to have Lua embedded in C++. I've been searching for 2 days now, but most of internet tutos use lua5.1, which is incompatible with lua5.2. So I read a bit of lua documentation, example source code, and I end up with this :
main.cpp :
#include "luainc.h"
#include <iostream>

int main(){
    int iErr = 0;
    lua_State *lua = luaL_newstate ();  // Open Lua
    luaopen_io (lua);    // Load io library

    if ((iErr = luaL_loadfile (lua, "hw.lua")) == 0)
    {
       std::cout<<"step1"<<std::endl;

       if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
       {
          std::cout<<"step2"<<std::endl;

          lua_getglobal (lua, "helloWorld");    // Push the function name onto the stack

            if (lua_type(lua, lua_gettop(lua)) == LUA_TNIL) {
                // if the global variable does not exist then we will bail out with an error.
                std::cout<<"global variable not found : helloworld"<<std::endl;

                /* error so we will just clear the Lua virtual stack and then return
if we do not clear the Lua stack, we leave garbage that will cause problems with later
function calls from the application. we do this rather than use lua_error() because this function
is called from the application and not through Lua. */

                lua_settop (lua, 0);
                return -1;
            }

          // Function is located in the Global Table
          /* lua_gettable (lua, LUA_GLOBALSINDEX);  */ //lua5.1
          lua_pcall (lua, 0, 0, 0);
       }
    }

    lua_close (lua);

    return 0;
}

hw.lua :
-- Lua Hello World (hw.lua)
function helloWorld ()
   io.write ("hello World")
end

luainc.h :
#ifndef __LUA_INC_H__
#define __LUA_INC_H__

extern "C"
{
   #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lua.h>
   #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lauxlib.h>
   #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lualib.h>
}

#endif // __LUA_INC_H__

I have no error, the output is :
step1
step2

which should mean that my "helloworld" function has been found. But as I can not see "Hello World" in the output, I suspect that the function has not been called. What am I doing wrong ?
This is how I compile my program :
g++ main.cpp -L/usr/local/include -I/usr/local/include -llua

A: First, why not #include "lua.hpp", which comes with Lua and does mostly what your luainc.hdoes?
There are two problems with your code:

*

*You don't emit any error message when luadL_loadfile fails.

*You use lua_pcall to call helloWorld but does not test its return value.
When you change lua_pcall to lua_call you get this error message:

attempt to index global 'io' (a nil value)

This means that you forgot to set the global io after calling luaopen_io. Just add lua_setglobal(lua,"io")and it works. Unlike Lua 5.1, Lua 5.2 does not set globals automatically when you open libraries, unless the library itself does it, which is discouraged.
You'll probably be better off calling luaL_openlibs to open all standard Lua libraries with no surprises.
You may as well use luaL_dofile instead of luaL_loadfile and save the first lua_pcall. You still have to check the return value.


Q: How to create composite index which contains the (latitude,longitude) and other datatype column in PostgreSQL? DDL:
CREATE TABLE test
(
    longid bigint NOT NULL DEFAULT nextval('test_longid_seq'::regclass),
    longitude double precision,
    latitude double precision,
    create_ts_long bigint,
    CONSTRAINT test_pkey PRIMARY KEY (longid)
)

We can use this to create the gist index :
CREATE INDEX ll_idx
    ON test USING gist
    (ll_to_earth(latitude ::double precision, longitude ::double precision))
    TABLESPACE pg_default;

But there is a scenario that I want to find the nearest records of the specific time(create_ts_long).
So how to create such composite index? Thanks in advance!

A: Install the btree_gist contrib module.
Then you have a gist_int8_ops operator class that you can use to create a GiST index on a bigint column.


Q: On Mouse Over doesn't fire triggers in ContentTemplate I have some textboxes and I want to change some of their properties when I put the mouse over them. In this case, I want to change the BorderBrush and BorderThickness.
This is my XAML ControlTemplate, it's inside a Window.Resource tag:
  <Style TargetType="{x:Type TextBox}">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBoxBase}">
                    <Border
                      Name="Border"
                      Padding="4"
                      BorderBrush="#ccc"
                      BorderThickness="1">
                        <ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
                        <Border.Background>
                            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                                <GradientStop Color="#FFC4C4C4" Offset="0.0" />
                                <GradientStop Color="#FFF8F8F8" Offset="0.10" />
                            </LinearGradientBrush>
                        </Border.Background>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver">
                            <Setter Property="BorderThickness" Value="1"></Setter>
                            <Setter Property="BorderBrush" Value="Orange"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

This piece of code should set the properties I wrote inside the Trigger tag when the mouse cursor is over the textbox:
                   <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver">
                            <Setter Property="BorderThickness" Value="1"></Setter>
                            <Setter Property="BorderBrush" Value="Orange"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>

But this trigger simply don't get fired. Nothing happens.
Why? And how can I achieve this?

A: You could try this, add the Value property to your trigger and set it to true. Also need to add the target name to tell it to change the properties of border which is in your control template.
<Trigger Property="IsMouseOver" Value="true" >
      <Setter Property="BorderThickness" TargetName="Border" Value="1"></Setter>
      <Setter Property="BorderBrush" TargetName="Border" Value="Orange"></Setter>
</Trigger>

A: I think you need to specify border element name
<Trigger  Property="IsMouseOver" Value="true" >
  <Setter TargetName="Border" Property="BorderThickness" Value="1"></Setter>
  <Setter TargetName="Border" Property="BorderBrush" Value="Orange"></Setter>
</Trigger>


Q: What is the relationship between ethereum and solidity? I am new to the blockchain. As I study solidity language, I can not figure out how it makes a blockchain in the end.
I can map a contract to a class; but is it that every instance is a chain or what?

A: The relationship between Solidity and Ethereum is something like the relationship between Objective-C and iPhones. The former is a programming language used to write code that runs on the latter.
The actual implementation of the blockchain (the data structure, consensus protocols, etc.) is implemented in other languages (Go in the case of geth, Rust in the case of Parity).

A:
As I study solidity language, I can not figure out how it makes a blockchain in the end

The Solidity programming language serves the sole purpose of allowing for the development of smart contracts on an Ethereum-based blockchain network. These smart contracts are simply the logic (code) that is triggered by internal or external actors (respectively users or other code) within the blockchain network and interpreted and executed by the Ethereum Virtual Machine (EVM).
Solidity is not used to create the Ethereum blockchain network. The blockchain network must already be in existence for the smart contract logic to be deployed to the network. An Ethereum blockchain network can be created by any of the multiple Ethereum clients due to the unambiguous nature of the Ethereum protocols.

I can map a contract to a class; but is it that every instance is a chain or what?

Mappings in Solidity are a basic key/value data structure akin to a hash map. You can map keys of data type X to a value of data type Y. There is no explicit relation between Solidity mappings and the blockchain network itself.
Whenever a smart contract function is called, a transaction is subsequently created on the blockchain network that is representative of the executed function as well as the caller of that function. This transaction is persisted on the blockchain and serves as immutable proof that an action has taken place.


Q: Setting arguments in a kernel in OpenCL causes error I am a beginner in OpenCL and thus writing a simple program to double the elements of an array.
The kernel code is:-
__kernel void dataParallel(__global int* A, __global int* B)
{
    int base = get_local_id(0);
    B[base]=A[base]+A[base];
}

The local_work_size=32 as I am squaring 32 elements.
In my program I have declared an integer array which holds the elements to be squared.
int *A;
A=(int*)malloc(sizeof(int)*64);
for (i=0; i < 32; i++) {            A[i] = i;   }

platforms[i] stores the platform id, devices[j] stores the corresponding device id. Their types:
cl_platform_id* platforms;
cl_device_id* devices;

Creating context
cl_context context=clCreateContext(NULL,1,&devices[j],NULL,NULL,NULL);

Next comes the command queue
cl_command_queue cmdqueue=cmdqueue=clCreateCommandQueue(context,devices[j],NULL,&err);

Next I created 2 memory buffers, one to hold the input data and the other to hold the result.
cl_mem  Abuffer,Bbuffer;
Abuffer=clCreateBuffer(context, CL_MEM_READ_WRITE ,32*sizeof(int),NULL,&err);
Bbuffer=clCreateBuffer(context, CL_MEM_READ_WRITE ,32*sizeof(int),NULL,&err);

Then I copied the data of array A to Abuffer
ret=clEnqueueWriteBuffer(cmdqueue, Abuffer, CL_TRUE, 0, 32*sizeof(int), A, 0, NULL, NULL);
printf("%d",ret);//output is 0 thus data written successfully into the buffer

The kernel code was then read into a character string source_str and the program was created.
kernelprgrm=clCreateProgramWithSource(context,1,(const char **)&source_str,(const size_t *)&source_size,&err);
    if(!err)
    {
        printf("\nKernel program created successfully\n");
    }//Outputs -Kernel program created successfully

I then built the program using:
ret=clBuildProgram(kernelprgrm,1,&devices[j],NULL,NULL,NULL);//returns CL_SUCCESS

Getting buildinfo next
ret=clGetProgramBuildInfo(kernelprgrm,devices[j], CL_PROGRAM_BUILD_STATUS ,0,NULL,&size);//Returns success

Creating kernel
kernel = clCreateKernel(kernelprgrm, "dataParallel", &ret);
    printf("\nReturn kernel program=%d",ret);
    if(!ret)
    {
        printf("\nProgram created successfully!\n");
    }
    //Outputs -Program created successfully!

Now comes the devil:-
ret=clSetKernelArg(kernel,0,sizeof(cl_mem),(void *) Abuffer);
printf("\nKernel argument 1 ret=%d",ret);

ret=clSetKernelArg(kernel,1,sizeof(cl_mem),(void *) Bbuffer);
printf("\nKernel argument 2 ret=%d",ret);

Both return -38 meaning CL_INVALID_MEM_OBJECT.
P.S.:As per the errors pointed out i.e. use &Abuffer instead of Abuffer in the argument and after making the necessary changes, both return 0
size_t global_item_size = 32;
size_t local_item_size = 32;

Also ret = clEnqueueNDRangeKernel(cmdqueue, kernel, 1, NULL,&global_item_size, &local_item_size, 0, NULL, NULL); returns 0.
Trying to get the result
ret = clEnqueueReadBuffer(cmdqueue, Bbuffer, CL_TRUE, 0, 32*sizeof(int), B, 0, NULL, NULL);`
printf("\nB:-\n");
for (t=0; t < 32; t++) {
            printf("%d\t ", B[t]);
                }

This returns buildstatus=0 with core getting dumped for my AMD GPU (running AMD Accelerated Parallel Processing platform) and NVIDIA GPU whereas it works perfectly fine if the selected device is CPU using Intel(R) OpenCL platform.
Also I tried getting the build log using:
cl_build_status *status=(cl_build_status *)malloc(sizeof(cl_build_status )*size);
clGetProgramBuildInfo(kernelprgrm,devices[j], CL_PROGRAM_BUILD_STATUS ,size,status,NULL);
printf("\nBuild status=%d\n",*status);

//Getting build info if not successful
clGetProgramBuildInfo(kernelprgrm,devices[i], CL_PROGRAM_BUILD_LOG ,0,NULL,&size);
char *buildlog=(char*)malloc(size);
clGetProgramBuildInfo(kernelprgrm,devices[i], CL_PROGRAM_BUILD_LOG ,size,buildlog,NULL);
printf("\n!!!!!!!!!!!!!!!!!!!!!Program ended!!!!!!!!!!!\n");
printf("\n\nBuildlog:   %s\n\n",buildlog);

But it returns Buildlog:   Compilation started
Compilation done
Linking started
Linking done
Device build started
Device build done
Kernel <dataParallel> was successfully vectorized (4)
Done.

A: Here's what the OpenCL 1.2 spec has to say about setting buffers as kernel arguments:

If the argument is a memory object (buffer, image or image array), the arg_value entry will be a pointer to the appropriate buffer, image or image array object.

So, you need to pass a pointer to the cl_mem objects:
ret=clSetKernelArg(kernel,0,sizeof(cl_mem),(void *) &Abuffer);

A: Why are you using clEnqueueTask? I think you should use clEnqueueNDRangeKernel if you have parallel work to do. Also, just set the global work size; pass NULL for the local work group size. 32x32 is larger than some devices can do.


Q: Unity Singleton Pattern Its just a question that bugs me on Unity.
We often use Singleton objects like game managers and so and there are two ways to go for this.
One is to use a Singleton.cs c sharp class as follows:
using System;
using System.Linq;
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    static T instance;

    DateTime BirthTime;

    public static T Instance
    {
        get
        {
            if (instance == null)
                Initialize();

            return instance;
        }
    }

    private void Awake()
    {
        BirthTime = DateTime.Now;
    }

    public static void Initialize()
    {
        if (instance == null)
            instance = FindObjectOfType<T>();
    }
}

And then derive our GameManager As
GamaManager : Singleton<GameManager>

In popular opinion, this method is CPU consuming, particularly on mobile as Unity has to iterate through hierarchy of so many objects for using the Initialize method mentioned in singleton.
A simpler approach is to create private instance and initialize it in Start or Awake as:
GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Start()
    {
        Instance = this;
    }
}

But I think, its like writing same code again and again. Can anybody suggest a cleaner approach to this?

A: I'm not sure what you want exactly, but in singleton pattern I prefer make a main class like GameManager and set it as a singleton class by using this piece of code:
static GameManager _instance;
    public static GameManager instance {
        get {
            if (!_instance) {
                _instance = FindObjectOfType<GameManager>();
            }
            return _instance;
        }
    }

Or the piece of code that you wrote, after that define variables according to other sub managers type and access to them by GameManagersingleton.
For example:
public BulletManager myBulletManager;

and use it like this:
GameManager.instance.myBulletManager.Fire();


Q: Retrieving response message from WebService
In NetBeans I have to use the following code:
    public String launchRequest(String paramString)
       {
       URL localURL = new URL(paramString);
       Object localObject1 = new Socket(localURL.getHost(),  localURL.getPort());

       Object localObject2 = "GET " + paramString + " HTTP/1.0";
       localObject2 = (String)localObject2 + "\r\nAccept value: */*\r\n";
       localObject2 = (String)localObject2 + "Host value: " + localURL.getHost() + ":" + localURL.getPort() + "\r\n";
       Object localObject3 = new PrintWriter(((Socket)localObject1).getOutputStream(), true);
       ((PrintWriter)localObject3).println((String)localObject2);
       ((PrintWriter)localObject3).close();
       ((Socket)localObject1).close();

      return "OK";}

This code is supposed to call a webService created in C# that makes an insert operation in an Oracle Database.

The url that is passed looks like this: http://192.168.88.29:443/RaduPestrea/Services/Ort.asmx/ORTRequest?callBackDisabled=true&siren=328812656&capId=1325369

The problem is that the webService is not called. The getOutputStream() retuns an OutputStream that has no message from the WebService.
This is a part of the webService:
 namespace Services
         {
            ///
            /// Summary description for Service1.
            ///
            public class Ort : System.Web.Services.WebService
            {
              [WebMethod]
              public string ORTRequest(bool callBackDisabled, int siren, int capId)
              {
                 Try{
                  .......
              return "Success ReqId :" + reqNum;
                 Catch(Exception ex)
                 {
                     return ex.ToString();
                 }
            }
          }

The problem is I cannot modify this code. I hope the problem is from the URL I sent.
Any help is appreciated. Thank you.
Edit: Agreed it is not the most beautiful code. The task is, the Java code needs to call the WebService from that URL link. That link is supposed to make an insert in a database. There is no new record in database. I use the return statements from the WebService to make sure it is called but nothing is returned. I may be doing it wrong, is there anyway to check that the WebService has been called successfully ?
 If I use the following code, the web service is called and a new record is inserted in the database.

<code>
    localURL = new URL(paramString);
    localObject1 = "";
    localObject2 = localURL.openStream();
    localObject3 = new InputStreamReader((InputStream)localObject2);
    BufferedReader localBufferedReader = new BufferedReader((Reader)localObject3);
    String str1;
    while ((str1 = localBufferedReader.readLine()) != null)
    {
      String str2 = "";
      localObject1 = (String)localObject1 + str2;
    }
    return (String)localObject1;
</code>

A: First of all, it is a bad idea to use a Socket to make HTTP requests.  It is better to use an existing library class / method; for example:
new URL("https://example.com/foo/bar?param=xxx").openConnection();

This gives you some subclass of URLConnnection that you can use to form the request and get the reply from the server
There are alternative libraries for making HTTP / HTTPS requests. For example, the Apache HttpComponents libraries can be a good choice, if your requirements are complicated.
However, I suspect that the real reason that you are getting nothing back from your request, is that you are trying to talk to an "https" server (port 443) without using an SSL / TLS connection.  That ain't going to work.  The server is likely to just close the socket.
While it is possible to establish an SSL / TLS connection over a plain Socket (in theory) or use an SSLSocket, it is simpler to use a properly formed "https://..." URL and (for example) URL.openConnection() as above.
Moving past that, the header lines in your supposed request look syntactically invalid.  Both
    Accept value: ...

and
    Host value: ....

are wrong.  If really want to implement the HTTP message handling yourself, you need to read the HTTP 1.1 specification, and implement it to the letter.
And finally (as @EJP points out) your code isn't even reading the response.  Writing to an OutputStream is not going to "return" anything.  You need to read the response from an InputStream ... even if only to check that the request was accepted.

A:
The problem is that the webService is not called.

You haven't provided any evidence to that effect, and it is impossible to tell from the code you've posted.

The getOutputStream() retuns an OutputStream that has no message from the WebService.

This is meaningless. OutputStreams don't contain messages from the peer. They are used to send messages to the peer. This statement and your title are completely nonsensical.

Is there anyway to check that the WebService has been called successfully?

Yes. Read the response, and return it, instead of hardwiring "OK".
And you've just posted code that does exactly that.

Agreed it is not the most beautiful code.

It isn't even correct code. The HTTP headers are invalid, and it makes no attempt to read a response. It's just incompetent. Use the HttpURLConnection code you posted.


Q: How do I set duration of a video in ExoPlayer? I need to set duration of a video for a thumbnail to 5 seconds and loop it. I got the loop part, but I can't find documentation for setting specific duration
I tried exoPlayer.seek(duration) but that didn't work

A: You may use ClippingMediaSource:
ClippingMediaSource(MediaSource mediaSource, long startPositionUs, long endPositionUs)

Creates a new clipping source that wraps the specified source and provides samples between the specified start and end position.

You can convert to have a new media source and set this new media source for your ExoPlayer:
// Create a new media source with your specified period
val newMediaSource = ClippingMediaSource(mediaSource, 0, 5_000_000)


Q: Using Entry to search through a number of entries in a Listbox (tkinter) I want to use a search function which searches through a list of program names (chrome, thunderbird, adobe reader etc.)
I have a Listbox and then a load of program names added into the Listbox, I want the search feature, entry_1, to search through all of these names and then highlight the one which was searched for.
Is this possible?
Here is my code:

from tkinter import *

#definitions
root = Tk()
var_1 = StringVar(root)
label_1 = Label(root, text="Search:")
label_2 = Label(root, text="Subject specific programs below")
label_3 = Label(root, text="Subject:")
entry_1 = Entry(root) #this should search through the strings listed under listbox_2 configs
button_1 = Button(root, text="Install")
scrollbar_1 = Scrollbar(root)
listbox_2 = Listbox(root, yscrollcommand=scrollbar_1.set)
optionmenu_1 = OptionMenu(root, var_1, "Computing", "Engineering", "Physics")
string_1 = StringVar(root, name="Google Chrome")
string_2 = StringVar(root, name="Thunderbird")
string_3 = StringVar(root, name="Adobe Reader X")
string_4 = StringVar(root, name="WinRAR")
string_5 = StringVar(root, name="OpenOffice")
string_6 = StringVar(root, name="Program 1")
string_7 = StringVar(root, name="Program 2")
string_8 = StringVar(root, name="Program 3")
string_9 = StringVar(root, name="Program 4")
string_10 = StringVar(root, name="Program 5")
string_11 = StringVar(root, name="Program 6")

#configuration
root.title("Network Installation")
listbox_2.insert(1, string_1)
listbox_2.insert(2, string_2)
listbox_2.insert(3, string_3)
listbox_2.insert(4, string_4)
listbox_2.insert(5, string_5)
listbox_2.insert(6, string_6)
listbox_2.insert(7, string_7)
listbox_2.insert(8, string_8)
listbox_2.insert(9, string_9)
listbox_2.insert(10, string_10)
listbox_2.insert(11, string_11)
optionmenu_1.config(width=15)
scrollbar_1.config(command=listbox_2.yview)

#grid additions
label_1.grid(row=0, column=5)
label_2.grid(columnspan=6, row=1, column=0, sticky=E)
entry_1.grid(row=0, column=6)
button_1.grid(columnspan=2, row=7, column=5)
listbox_2.grid(rowspan=6, columnspan=6, row=2, column=0)
scrollbar_1.grid(rowspan=6, row=2, column=4, sticky=N+S)
optionmenu_1.grid(columnspan=3, row=0, column=1)
label_3.grid(row=0, column=0)

root.mainloop()

A: I know this was asked a long time ago but here's how to highlight the listbox items using a search entry box in Tkinter.
Explanation:

*

*all_listbox_items is the most important part. When the program first populates the listbox, it's important to capture those initial values and use the search entry box as a way to query these initial entries.

*add a textvariable to entry_1 and name it search_var.

*put a trace on search_var so if the values in the entry_1 change, we can trigger a function named highlight_searched.

*The function highlight_searched basically enumerates all the listbox items and checks to see if the searched text in entry_1 is in any of the items from the listbox. Where this is true, you use selection_set(i) (where i is short-hand for index) to select each item.

I'm not particularly happy with using enumerate. It's just easy. There surely is a better way to return the index of an item in a for loop. I'd love to hear a better solution to my enumeration suggestion.
Code:
from tkinter import *

#definitions
root = Tk()
var_1 = StringVar(root)
label_1 = Label(root, text="Search:")
label_2 = Label(root, text="Subject specific programs below")
label_3 = Label(root, text="Subject:")

def highlight_searched(*args):
  search = search_var.get()
  for i,item in enumerate(all_listbox_items):
    if search.lower() in item.lower():
      listbox_2.selection_set(i)
    else:
      listbox_2.selection_clear(i)
  if search == '':
    listbox_2.selection_clear(0, END)

search_var = StringVar()
search_var.trace('w', highlight_searched)
entry_1 = Entry(root, textvariable=search_var) #this should search through the strings listed under listbox_2 configs

button_1 = Button(root, text="Install")
scrollbar_1 = Scrollbar(root)
listbox_2 = Listbox(root, yscrollcommand=scrollbar_1.set)
optionmenu_1 = OptionMenu(root, var_1, "Computing", "Engineering", "Physics")
string_1 = StringVar(root, name="Google Chrome")
string_2 = StringVar(root, name="Thunderbird")
string_3 = StringVar(root, name="Adobe Reader X")
string_4 = StringVar(root, name="WinRAR")
string_5 = StringVar(root, name="OpenOffice")
string_6 = StringVar(root, name="Program 1")
string_7 = StringVar(root, name="Program 2")
string_8 = StringVar(root, name="Program 3")
string_9 = StringVar(root, name="Program 4")
string_10 = StringVar(root, name="Program 5")
string_11 = StringVar(root, name="Program 6")

#configuration
root.title("Network Installation")
listbox_2.insert(1, string_1)
listbox_2.insert(2, string_2)
listbox_2.insert(3, string_3)
listbox_2.insert(4, string_4)
listbox_2.insert(5, string_5)
listbox_2.insert(6, string_6)
listbox_2.insert(7, string_7)
listbox_2.insert(8, string_8)
listbox_2.insert(9, string_9)
listbox_2.insert(10, string_10)
listbox_2.insert(11, string_11)
optionmenu_1.config(width=15)
scrollbar_1.config(command=listbox_2.yview)

#grid additions
label_1.grid(row=0, column=5)
label_2.grid(columnspan=6, row=1, column=0, sticky=E)
entry_1.grid(row=0, column=6)
button_1.grid(columnspan=2, row=7, column=5)
listbox_2.grid(rowspan=6, columnspan=6, row=2, column=0)
scrollbar_1.grid(rowspan=6, row=2, column=4, sticky=N+S)
optionmenu_1.grid(columnspan=3, row=0, column=1)
label_3.grid(row=0, column=0)

all_listbox_items = listbox_2.get(0, END)

root.mainloop()

And anyone showing up to this question that might be looking for a search box that filters the listbox (as opposed to highlighting them like this question is asking) to show only the relevant items pertaining to the search, you can use this:
import tkinter as tk

root = tk.Tk()
def update_listbox(*args):
  search_term = search_var.get()
  listbox.delete(0, tk.END)
  for item in all_items:
    if search_term.lower() in item.lower():
      listbox.insert(tk.END, item)

search_var = tk.StringVar()
search_var.trace('w', update_listbox)
searchbox = tk.Entry(root, textvariable=search_var)
searchbox.pack(fill=tk.X, expand=False)

listbox = tk.Listbox(root)
for i in ['Adam', 'Lucy', 'Barry', 'Bob']:
  listbox.insert(tk.END, i)
listbox.pack()
all_items = listbox.get(0, tk.END)
root.mainloop()


Q: Parallelize with numba's prange and passing along a tuple I tried to parallelize as follows, closely following the documented example:
@numba.jit(nopython=True)
def foo(uIdx, grids):
    return uIdx

@numba.jit(nopython=True, parallel=True)
def bar(grid, grids):

    LIdxGrid = np.zeros(len(grid))

    for uIdx in numba.prange(len(grid)):
            LIdxGrid[uIdx] = foo(uIdx, grids)
    return LIdxGrid

if __name__ == '__main__':
    import numpy as np
    grid = np.arange(12)
    grids = (grid, grid)
    bar(grid, grids)

But it appears not to work. The issue seems to stem from passing along grids (without even using it in the final foo function). If I remove that reference in foo and bar, it works:
bar(grid, 0)
Out[47]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])

How do I work fix/around this issue?
The full traceback is
Traceback (most recent call last):
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/errors.py", line 491, in new_error_context
    yield
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 216, in lower_block
    self.lower_inst(inst)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 365, in lower_inst
    func(self, inst)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/parfor.py", line 119, in _lower_parfor_parallel
    index_var_typ)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/parfor.py", line 691, in call_parallel_gufunc
    sout, {})
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/parallel.py", line 251, in build_gufunc_wrapper
    cache=cache)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 460, in build_gufunc_wrapper
    return wrapcls(py_func, cres, sin, sout, cache).build()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 411, in build
    self._build_wrapper(wrapperlib, wrapper_name)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 372, in _build_wrapper
    arg_steps, i, step_offset, typ, sym, sym_dim)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 614, in __init__
    "argument #{1}".format(typ, i + 1))
TypeError: scalar type tuple(array(int64, 1d, C) x 2) given for non scalar argument #2
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-46-b6a12a1ce616>", line 3, in <module>
    bar(grid, grids)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 360, in _compile_for_args
    raise e
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 311, in _compile_for_args
    return self.compile(tuple(argtypes))
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 618, in compile
    cres = self._compiler.compile(args, return_type)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 83, in compile
    pipeline_class=self.pipeline_class)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 871, in compile_extra
    return pipeline.compile_extra(func)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 365, in compile_extra
    return self._compile_bytecode()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 802, in _compile_bytecode
    return self._compile_core()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 789, in _compile_core
    res = pm.run(self.status)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 251, in run
    raise patched_exception
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 243, in run
    stage()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 676, in stage_nopython_backend
    self._backend(lowerfn, objectmode=False)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 626, in _backend
    lowered = lowerfn()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 613, in backend_nopython_mode
    self.flags)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 990, in native_lowering_stage
    lower.lower()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 135, in lower
    self.lower_normal_function(self.fndesc)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 176, in lower_normal_function
    entry_block_tail = self.lower_function_body()
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 201, in lower_function_body
    self.lower_block(block)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 216, in lower_block
    self.lower_inst(inst)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/errors.py", line 499, in new_error_context
    six.reraise(type(newerr), newerr, tb)
  File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/six.py", line 659, in reraise
    raise value
numba.errors.LoweringError: Failed at nopython (nopython mode backend)
scalar type tuple(array(int64, 1d, C) x 2) given for non scalar argument #2
File "<ipython-input-44-ec97cbf0b87b>", line 9:
def bar(grid, grids):
    <source elided>
    LIdxGrid = np.zeros(len(grid))
    ^
[1] During: lowering "id=7[LoopNest(index_variable = parfor_index.317, range = (0, grid_size0.315, 1))]{51: <ir.Block at <ipython-input-44-ec97cbf0b87b> (9)>}Var(parfor_index.317, <ipython-input-44-ec97cbf0b87b> (9))" at <ipython-input-44-ec97cbf0b87b> (9)
-------------------------------------------------------------------------------
This should not have happened, a problem has occurred in Numba's internals.

A: The support for reference counted items (like np.ndarrays) is quite new (since numba 0.39) and I am not sure if working with tuples of ref. counted items already  works. Afaik tuples of ref. counted items are not yet supported. So to make sure your code works, you must replace the tuple with a list:
if __name__ == '__main__':
    import numpy as np
    grid = np.arange(12)
    grids = [grid, grid]
    bar(grid, grids)

AND make sure you have numba version 0.39 installed! Otherwise this won't work as well.
Of course a list is not a tuple, so this is only a workaround. But there is no other way to solve this problem, as long as tuples of ref. counted items are not fully supported.


Q: isDst in Time Zone in C language I am trying to figure out on making a time from the values i choose (dynamically)
I tried giving a date of 31st march 03:10pm and trying to go back a month with 03:10Pm which is 28th Feb 03:10Pm. But i am getting a value as 04:10Pm.
I set the isdst = -1 to do this bit; but still it fails.
Any ideas.
Tm->tm_mon = ReportMonth;
  Tm->tm_mday = ReportEndDay;
Tm->tm_hour = TimeOfDay/60;
  Tm->tm_min  = TimeOfDay%60;
  Tm->tm_sec  = 59;
  Tm->tm_isdst = -1;


Q: Does not contain a definition for GetDataFromNumber But i have it defined? public void button2_Click(object sender, System.EventArgs e)
{
    string text = textBox1.Text;
    Mainform = this;

    this.Hide();

    GetSchedule myScheduleFinder = new GetSchedule();
    string result = myScheduleFinder.GetDataFromNumber(text);// says there is no definition
    if (!string.IsNullOrEmpty(result))
    {
        MessageBox.Show(result);
    }
    else
    {
        MessageBox.Show("Enter A Valid ID Number!");
    }
}

says it does not contain definition for it but on my GetSchedule .cs file i have it defined
public string GetDataFromNumber(string ID)//defined here
{

    foreach (IDnumber IDCandidateMatch in IDnumbers)
    {

        if (IDCandidateMatch.ID == ID)
        {
            StringBuilder myData = new StringBuilder();
            myData.AppendLine(IDCandidateMatch.Name);
            myData.AppendLine(": ");
            myData.AppendLine(IDCandidateMatch.ID);
            myData.AppendLine(IDCandidateMatch.year);
            myData.AppendLine(IDCandidateMatch.class1);
            myData.AppendLine(IDCandidateMatch.class2);
            myData.AppendLine(IDCandidateMatch.class3);
            myData.AppendLine(IDCandidateMatch.class4);
            //return myData;
            return myData.ToString();
        }
    }
    return "";
}

GetSchedule Class
public class GetSchedule
    {
        public GetSchedule()
        {
            IDnumber[] IDnumbers = new IDnumber[3];
            IDnumbers[0] = new IDnumber() { Name = "Joshua Banks", ID = "900456317", year = "Senior", class1 = "TEET 4090", class2 = "TEET 3020", class3 = "TEET 3090", class4 = "TEET 4290" };
            IDnumbers[1] = new IDnumber() { Name = "Sean Ward", ID = "900456318", year = "Junior", class1 = "ENGNR 4090", class2 = "ENGNR 3020", class3 = "ENGNR 3090", class4 = "ENGNR 4290" };
            IDnumbers[2] = new IDnumber() { Name = "Terrell Johnson", ID = "900456319", year = "Sophomore", class1 = "BUS 4090", class2 = "BUS 3020", class3 = "BUS 3090", class4 = "BUS 4290" };
    }
    public class IDnumber
    {
        public string Name { get; set; }
        public string ID { get; set; }
        public string year { get; set; }
        public string class1 { get; set; }
        public string class2 { get; set; }
        public string class3 { get; set; }
        public string class4 { get; set; }

       public static void ProcessNumber(IDnumber myNum)
            {
                StringBuilder myData = new StringBuilder();
                myData.AppendLine(myNum.Name);
                myData.AppendLine(": ");
                myData.AppendLine(myNum.ID);
                myData.AppendLine(myNum.year);
                myData.AppendLine(myNum.class1);
                myData.AppendLine(myNum.class2);
                myData.AppendLine(myNum.class3);
                myData.AppendLine(myNum.class4);
                MessageBox.Show(myData.ToString());
            }

        public string GetDataFromNumber(string ID)
        {
            IDnumber[] IDnumbers = new IDnumber[3];
            foreach (IDnumber IDCandidateMatch in IDnumbers)

            {

                if (IDCandidateMatch.ID == ID)
                {
                 StringBuilder myData = new StringBuilder();
                 myData.AppendLine(IDCandidateMatch.Name);
                 myData.AppendLine(": ");
                 myData.AppendLine(IDCandidateMatch.ID);
                 myData.AppendLine(IDCandidateMatch.year);
                 myData.AppendLine(IDCandidateMatch.class1);
                 myData.AppendLine(IDCandidateMatch.class2);
                 myData.AppendLine(IDCandidateMatch.class3);
                 myData.AppendLine(IDCandidateMatch.class4);
                 //return myData;
                 return myData.ToString();
    }
}
return "";

}
        }
}

}

A: Did you make sure GetDataFromNumber is inside the class definition, and not after the closing brace?

A: Check that the GetSchedule class is in the same namespace that you are trying to call it from, or that it is referenced.
It looks from your updated post like your function GetDataFromNumber is in a class called IDNumber - is this the problem?
Try:
IDnumber myNumber = new IDnumber();
myNumber.GetDataFromNumber(text);

A: The problem is because you are creating web forms and copying the code from one page to another. When you do this you have to be careful and make sure that you don't change the first directive in the page. It tells the web for what behind the code page it should look for where it should find the definitions and behind code logic. The reason you are having this problem is cause when you copied and pasted from one page to another it brought the directive for the other page which more than likely you do not have the functions you are calling within your page defined. So just make sure you changed the first line in your web page to point to the right .cs file and class from which it inherits.


Q: fwrite function not working I am trying to write a simple program that opens the content of a binary file into a buffer and the searches that buffer for the occurrence of string which is '+' characters. It seems like to does find these characters even though my algorithm is a little flaky. Once it finds them it changes the character to some other character. Then it writes the same buffer back to file. It does not work as I tried opening the file in a hex editor and could not find the new string with the new characters. The file that gets modified prints out the string that I am trying to modify using fread and fwrite.
Here is the code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

using namespace std;

char XyZ[] = "++++++++++++++++++++++++++";    //26 count

int main()
{
    int error = 0;
    FILE * pFile;
    unsigned int lSize;
    char * buffer;
    size_t result;
    int i = 0, j = 0;
    bool bfound = false;
    int count = 0;
    int startLocation = 0;

    pFile = fopen ( "E:\\DEVS\\Projects\\JustTesting\\FOpen\\Release\\Test.exe",   "rb+" );
    if (pFile==NULL)
    {
        cout << "Unable to open Test.exe" << endl;
        cout << GetLastError() << endl;
    }
    else
    {
        cout << "Successfully opened the file" << endl;

        // obtain file size:
        fseek (pFile , 0 , SEEK_END);
        lSize = ftell (pFile);
        rewind (pFile);

        cout << "Number of file size is " << lSize << endl;

        // allocate memory to contain the whole file:
        buffer = (char*) malloc (sizeof(char)*lSize);
        if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

        // copy the file into the buffer:
        result = fread (buffer,1,lSize,pFile);

        cout << "Total bytes read into our buffer is " << result << endl;
        if (result != lSize)
        {
            cout << "Error in reading the file" << endl;
        }
        else
        {
            for(i = 0; i < lSize; i++)
            {
                if(buffer[i] == '+')    // '+'
                {
                    //cout << "Found first one" << endl;

                    startLocation = i;
                    //j = i + 1;
                    //cout << "Found the next one" << endl;
                    while(buffer[++i] == '+')
                    {
                        buffer[i] = '@';

                        cout << "Found the next one" << endl;
                        count++;
                    }
                }
            }
            cout << "Found our string with count " << count << endl;

        }
        //for(int k = startLocation; k < startLocation + 5; k++)
        //  buffer[k] = '@';

        int value = fwrite (buffer , 1 , lSize , pFile );
        cout << "bytes written to file is :" << value << endl;
        fclose (pFile);
        free (buffer);
    }
    return 0;
}

A: The first problem is your while:
while(buffer[++i] == '+')

So you've found your +, but in the while you first increase the position and then test whether the value is still +. That fails if you only have one + (and if you have several, the first is not overwritten). Instead, replace it with:
for ( ; (buffer[i] == '+') && (i < lSize) ; i++)

The next problem is that after fread, the file position is at the end. Your call to fwrite will thus append the modified buffer. To actually overwrite the file you first need to call rewind(pFile); again.
A final note on fread/fwrite: you read and write lSize items, each 1 byte in size. That's pretty slow (try it with a one megabyte file). Instead you likely want the opposite:
result = fread(buffer, lSize, 1, pFile);

Note that result will then merely have 1 on success. The same applies for fwrite.

A: Note that you would be trying to write the modified contents at the end of the file. Besides, switching between read and write operations need certain function calls in between to switch the operation mode. Try adding
fseek( pFile, 0, SEEK_SET );

right before doing fwrite. Note that there may still be something wrong

A: You open the file in rb (for reading), then write to it... I am not sure it will do what you want.


Q: Questions about CoreData and pre-populated models To pre-populate CoreData in my app upon first launch, I have included a PreModel.sqlite file that was previously created by the app from data that it downloaded from a web service, which includes images.
To populate the model, I do this:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSLog(@"creating new store");

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"PreModel.sqlite"];

    if(![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {

        NSString *sqlitePath = [[NSBundle mainBundle] pathForResource:@"PreModel" ofType:@"sqlite"];
        if (sqlitePath) {
            NSError *error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:sqlitePath toPath:[storeURL path] error:&error];
            if (error) {
                NSLog(@"Error copying sqlite database: %@", [error localizedDescription]);
            }
        }
    }

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

It seems to work. But I have 2 questions:

*

*If the sqlite file is just a database file and does not actually contain any images, how is the app finding and loading the images on first launch?

*Even on subsequent runs of the app I see "creating new store" logged every time. Why is _persistentStoreCoordinator always nil? I am clearly setting it in the code.

A: *

*It's possible to store images in a database file, usually as binary blobs (which look like instances of NSData in Core Data). If you can provide more info about your model or the code that stores/loads the images, we can be more specific.

*"Creating new store" is expected to get logged every time the app is launched in this instance. Even though the SQLite file is persistent on disk, you can't expect data structures in your code to stick around when your app is terminated - you need to create a new persistent store object for your program every time it launches.
Think of it like assigning NSInteger x = 10, then expecting to be able to quit and relaunch your program while maintaining that x has the value 10. That's not how programs work - you'd need to reassign x = 10 before you can expect to read x and get 10 back. The variable _persistentStoreCoordinator works the same way here.


Q: Jupyter Notebook gets killed when using MaxPool layers I am training a neural-net model using Keras-CPU. It works fine when I don't add any MaxPool layers, but my jupyter kernel dies whenever I use a MaxPool layer.
My whole data size is around 480 MB. My system has 128GB of memory, and it doesn't take more than 5-10 GB of memory when ran without MaxPool layers. My batch size is also small (32), and there is no significant increase in memory usage when I run the training.
CPU usage goes up for a few seconds and then it drops back. There is an attached metric regarding the info of a single epoch; it just prints the start of the epochs:

Epoch 1/2

and after that, my kernel dies.
Here is the architecture of the network:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 382)               0
_________________________________________________________________
embedding_1 (Embedding)      (None, 382, 100)          490600
_________________________________________________________________
conv1d_1 (Conv1D)            (None, 382, 64)           12864
_________________________________________________________________
max_pooling1d_1 (MaxPooling1 (None, 191, 64)           0
_________________________________________________________________
conv1d_2 (Conv1D)            (None, 191, 128)          16512
_________________________________________________________________
max_pooling1d_2 (MaxPooling1 (None, 95, 128)           0
_________________________________________________________________
flatten_1 (Flatten)          (None, 12160)             0
_________________________________________________________________
dense_1 (Dense)              (None, 64)                778304
_________________________________________________________________
dropout_1 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_2 (Dense)              (None, 128)               8320
_________________________________________________________________
dense_3 (Dense)              (None, 1)                 129
=================================================================
Total params: 1,306,729
Trainable params: 1,306,729
Non-trainable params: 0

Here is the method where I train my neural network:
def get_nnn(train_data_shape, max_val, emb_shape, drop_out, pre_batch_size, pre_batch_epoch,\
           final_batch_size, final_batch_epoch, ls_start, lr_end,class_weight, lr_decay_pat,\
                      lr_decay_rat,num_conv,conv_kernels,conv_neurons,train_data,                              train_lbl,test_data,test_lbl,loss_type='binary_crossentropy',\
           act='sigmoid',use_emb=True,use_max_pool=True,custom_methods=[]):

    #A lot of params

    nnet = Input(shape=(train_data_shape,))
    inp = nnet

    if use_emb:
        nnet = Embedding(max_val+1, emb_shape)(nnet)

    for i in range(num_conv):
        nnet = Conv1D(conv_neurons[i],conv_kernels[i], padding='same',activation='relu')(nnet)
        if use_max_pool:
            #Adding MaxPool here
            nnet = MaxPooling1D(pool_size=2)(nnet)
    nnet = Flatten()(nnet)
    nnet = Dense(64, activation='relu')(nnet)
    nnet = Dropout(drop_out)(nnet)
    nnet = Dense(128, activation='relu')(nnet)

    batch_size = final_batch_size
    epochs = final_batch_epoch

    lentrain = train_data.shape[0]

    exp_decay = lambda init, fin, steps: (init/fin)**(1/(steps-1)) - 1
    steps = int(lentrain / batch_size) * epochs
    lr_init, lr_fin = ls_start, lr_end
    lr_decay = exp_decay(lr_init, lr_fin, steps)

    output = Dense(1, activation=act)(nnet)
    model = Model(inputs=inp, outputs=output)

    model.compile(loss=loss_type, optimizer=Adam(lr=ls_start, decay=lr_decay),
                  metrics=['accuracy',precisioned,recalled,f1]+custom_methods)

    reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=lr_decay_rat,
                              patience=lr_decay_pat, min_lr=lr_end)

    print(model.summary())

    model.fit(train_data, train_lbl,
              epochs=pre_batch_epoch,
              batch_size=pre_batch_size,
              class_weight=class_weight,
              validation_data=(test_data, test_lbl),
              callbacks=[reduce_lr])

    model.fit(train_data, train_lbl,
              epochs=epochs,
              batch_size=batch_size,
              class_weight=class_weight,
              validation_data=(test_data, test_lbl),
              callbacks=[reduce_lr])

    return model


Q: mongodb - Multiple LET and AS assignments to use within the same pipeline How to perform multiple let and as and use them within the same pipeline. I have the following query but assignment defaults to userTo. Both userFrom and userTo are from users collection
{
  $lookup: {
    from: "users",
let: {
  userFrom: "$from",
},
as: "userFrom",
let: {
  userTo: "$to",
},
as: "userTo",
pipeline: [
  {
    $match: {
      $expr: {
        $or: [
          {
            $eq: [
              "$$userFrom",
              "$_id"
            ]
          },
          {
            $eq: [
              "$$userTo",
              "$_id"
            ]
          }
        ]
      }
    }
  },

A: You are not using them correctly. as specifies the name of the output array of the $lookup. There is only 1 result set per lookup so only 1 as would be needed.
let specifies the variables you want to use in the sub-pipeline. You can put them in an object if you want to use multiple variables.
Your code should look like this:
db.collection.aggregate([
  {
    $lookup: {
      from: "users",
      let: {
        userFrom: "$from",
        userTo: "$to"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $or: [
                {
                  $eq: [
                    "$$userFrom",
                    "$_id"
                  ]
                },
                {
                  $eq: [
                    "$$userTo",
                    "$_id"
                  ]
                }
              ]
            }
          }
        }
      ],
      as: "userLookup"
    }
  }
])


Q: Triggering method from a started jar File which was loaded via Runtime...exec("..") in a java file this is what I want to do:
I need to start two jar Files from out of a java file and i want to call a method from the firstly started jar file, when i read a specific status from the second jar file. I figured out how to read the outsputstream from that jar files. (I also know, that its not the jar file who's printing out, but the classes inside the jar file. I just fomulated the question in this way to clearly explain that I use a java file in which I start two jar files)
long l = System.currentTimeMillis();
Process theProcess1 = Runtime.getRuntime().exec("java -jar \"C:/test.jar\"");

inStream = new BufferedReader(new InputStreamReader( theProcess1.getInputStream() ));
...

I can now read the jar file's output.
On a special keyword I want the firstly started jar to run a certain method (non static).
e.g.:
if(theProcess2 output a certain statuscode)
{
   start a certain Method from executed jar file "in" theProcess1

}

I think it could be possible by using the theProcess1 output, but I don't know how to read this stream in the jar File. (The jar file doesn't know that it was started via the java file.
Any Ideas?

A: You can't access another java process classloader class definitions.
See this question for how to load a jar properly : How to load a jar file at runtime
Once your jar is loaded, you can use Class.forName to access the second jar desired class
EDIT :
Here is a little snippet to help you read process standard output.
//open a buffered reader on process std output
    InputStreamReader ir = new InputStreamReader(theProcess1.getInputStream());
    BufferedReader in = new BufferedReader(ir);

   //read it line per line
    String line;
    while ((line = in.readLine()) != null) {

       System.out.println(line);

    }


Q: vbs open, loop through message, close application I have solved a few of these issues with the code below. The part where I'm getting stuck is looping back through the message popup. If the answer is Yes, I want it to loop back to the top; if the answer is No, I want it to exit the loop and close the program; if the message box times out, I want it to exit the loop and close the program as well. Please see my code below. Thank you in advance for your help.
Dim PromptTime, DelayTime, StrAppPath, AppExec, MsgTxt, intAnswer, intRet

Set objShell = CreateObject("WScript.Shell")

PromptTime = 5
DelayTime = 4
StrAppPath = "C:Windows\"
AppExec = "Notepad.exe"
MsgTxt = "Are you still using Notepad?"
intMsgTimeout = 5
Set WshShell= CreateObject("WScript.Shell")

objShell.Run chr(34) & StrAppPath & AppExec & chr(34), 1, "False"
Do
WScript.Sleep (1000 * 1 * PromptTime)
'intAnswer = MsgTxt(MsgTxt, vbYesNo, "Please select Yes or No")
intResult = WshShell.Popup(MsgTxt, intMsgTimeout, "Warning!", vbYesNo)

Select Case WshShell
Case vbYes
If intResult = vbYes Then Do

Case vbNo
If intResult = vbNo Then Exit Do

'Case Else
If intResult = Else Then Exit Do

End Select
Loop

taskKill = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & taskKill & "\root\cimv2")

Set processlistFull= objWMIService.ExecQuery _
("Select * from Win32_Process Where name = 'Notepad.exe'")

For Each killPro In processlistFull
killPro.Terminate()
Next

Set objShell = Nothing
Set objWmi = Nothing
Set objQResult = Nothing

A: I discovered a method of doing this through 'Loop While' and removing the Select Case:
Do
WScript.Sleep (1000 * 1 * PromptTime)
Loop While WshShell.Popup("Are you still using Syteline?", 5, "Please select yes or no", vbYesNo) = vbYes


Q: MIPS32 Stackframe broken? So here the code as wished:
PROGRAM 1
.text
  .globl main
  main:
    li     $t0, 10
    mtc1    $t0, $f12
    cvt.s.w $f12, $f12               # 10.0 as single in $f12
    jal     printFloat

    li      $v0, 4001               #sys_exit
    syscall

printFloat:
        addi    $sp, $sp, -4            #opens the stack frame
        sw      $ra, 0($sp)             #saves the return adress

        cvt.d.s $f12, $f12              #converts the single to double
        la      $a0, strDouble          #arguments needed for printf ("%f" in $a0, upper 32 bit of the float in $a2, lower ones in $a1)
        mfc1    $a1, $f12
        mfc1    $a2, $f13
        jal     printf
        jal     fflush

        la      $a1, strBreakLine       #arguments needed for printf (Adress of String in $a1, "%s" in $a0)
        la      $a0, strStringOut
        jal     printf
        jal     fflush

        lw      $ra, 0($sp)             #restores the return adress
        addi    $sp, $sp, 4             #pops the stack frame
        jr      $ra

.data
strDouble:      .asciiz "%f"
strStringOut:   .asciiz "%s"
strBreakLine:   .asciiz "\n"

phm15fix@ci20:~$ gcc -o test -g test1.s
phm15fix@ci20:~$ ./test
10.000000

PROGRAM 2
.text
.globl main
main:
        li     $t0, 10
        mtc1    $t0, $f12
        cvt.s.w $f12, $f12               # 10.0 as single in $f12
        jal     printFloat

        li      $v0, 4001               #sys_exit
        syscall

printFloat:
        addi    $sp, $sp, -4            #opens the stack frame
        sw      $ra, 0($sp)             #saves the return adress

        cvt.d.s $f12, $f12              #converts the single to double
        la      $a0, strDouble          #arguments needed for printf ("%f" in $a0, upper 32 bit of the float in $a2, lower ones in $a1)
        mfc1    $a1, $f12
        mfc1    $a2, $f13
        jal     printf
        jal     fflush
        jal     printNewLine

        lw      $ra, 0($sp)             #restores the return adress
        addi    $sp, $sp, 4             #pops the stack frame
        jr      $ra

printNewLine:
        addi    $sp, $sp, -4            #opens the stack frame
        sw      $ra, 0($sp)             #saves the return adress

        la      $a1, strBreakLine       #arguments needed for printf (Adress of String in $a1, "%s" in $a0)
        la      $a0, strStringOut
        jal     printf
        jal     fflush

        lw      $ra, 0($sp)             #restores the return adress
        addi    $sp, $sp, 4             #pops the stack frame
        jr      $ra

.data
strDouble:      .asciiz "%f"
strStringOut:   .asciiz "%s"
strBreakLine:   .asciiz "\n"

phm15fix@ci20:~$ gcc -o test -g test1.s
phm15fix@ci20:~$ ./test
10.000000
Bus error

PROGRAM 3
.text
.globl main
main:
        li     $t0, 10
        mtc1    $t0, $f12
        cvt.s.w $f12, $f12               # 10.0 as single in $f12
        jal     function

        li      $v0, 4001               #sys_exit
        syscall

function:
        addi    $sp, $sp, -4            #opens the stack frame
        sw      $ra, 0($sp)             #saves the return adress

        jal     printFloat

        lw      $ra, 0($sp)             #restores the return adress
        addi    $sp, $sp, 4             #pops the stack frame
        jr      $ra

printFloat:
        addi    $sp, $sp, -4            #opens the stack frame
        sw      $ra, 0($sp)             #saves the return adress

        cvt.d.s $f12, $f12              #converts the single to double
        la      $a0, strDouble          #arguments needed for printf ("%f" in $a0, upper 32 bit of the float in $a2, lower ones in $a1)
        mfc1    $a1, $f12
        mfc1    $a2, $f13
        jal     printf
        jal     fflush
        jal     printNewLine

        lw      $ra, 0($sp)             #restores the return adress
        addi    $sp, $sp, 4             #pops the stack frame
        jr      $ra

printNewLine:
        addi    $sp, $sp, -4            #opens the stack frame
        sw      $ra, 0($sp)             #saves the return adress

        la      $a1, strBreakLine       #arguments needed for printf (Adress of String in $a1, "%s" in $a0)
        la      $a0, strStringOut
        jal     printf
        jal     fflush

        lw      $ra, 0($sp)             #restores the return adress
        addi    $sp, $sp, 4             #pops the stack frame
        jr      $ra

.data
strDouble:      .asciiz "%f"
strStringOut:   .asciiz "%s"
strBreakLine:   .asciiz "\n"

At the end of every program is the specific output.
The first program works fine.
In the second program I made an extra function for printing a new line. If I run this I get a "bus error".
And in the third program I made a dummy function to simulate another stacklevel.
There is also a "bus error" and the number i want to print is not printing.
I think there are some problem with our stack.
I used the debugger and if I load my return-address from stack I have the wrong address in my $ra and i dont know why. If it jumps to this address i get the "bus error".
Here are the functions:
PRINT_DOUBLE:
        addi    $sp, $sp, -4
        sw      $ra, 0($sp)

        la      $a0, strDouble
        mfc1    $a1, $f12
        mfc1    $a2, $f13
        jal     printf
        nop
#       lw      $a0, stdout
#        jal     fflush
        jal     BREAK_LINE

        lw      $ra, 0($sp)
        addi    $sp, $sp, 4
        jr      $ra

BREAK_LINE:
        addi    $sp, $sp, -4
        sw      $ra, 0($sp)

        la      $a0, strBreakLine
        jal     PRINT_STRING

        lw      $ra, 0($sp)
        addi    $sp, $sp, 4
        nop

        jr      $ra

PRINT_STRING:
        addi    $sp, $sp, -4
        sw      $ra, 0($sp)

        add     $a1, $a0, $zero
        la      $a0, strStringOut
        jal     printf
        la      $a0, stdout
        lw      $a0, 0($a0)
        jal     fflush

        lw      $ra, 0($sp)
        addi    $sp, $sp, 4
        nop
        jr      $ra

A: I've looked over your program and most of it looks fine. I think your stack save/restore is fine. But, I see at least one other problem.
After every jal printf, you're doing an immediate jal fflush, so fflush will get printf's first argument [which is a string pointer] instead of a file descriptor pointer (e.g. stdout).
Under the mips ABI, the $a0-$a3 registers may be modified/destroyed by the callee. So, after printf returns $a0 can be anything.
All three programs seem to have this problem. IMO, if program 1 is working, it's just the luck of the draw (i.e.) whatever ends up in $a0 is harmless enough. That is, whatever is in it, points to a memory location that isn't a file descriptor but fflush tries to interpret it as one and lucks out.
Also, for fflush, $a0 should point to an address that is word [4 byte] aligned. If it's not, that could be the source of the bus error.
To fix this, change all fflush calls to:
lw     $a0,stdout
jal    fflush

That should probably work, but, depending on what the gcc assembler does, you may have to do:
la     $a0,stdout
lw     $a0,0($a0)
jal    fflush

I've seen that the buserror appears if I try to jump back from a function For example I jump to PRINT_DOUBLE, there I jump to BREAK_LINE and there I jump to PRINT_STRING If I jump then back to BREAK_LINE all is fine, but back from BREAK_LINE to PRINT_DOUBLE I get the buserror

I've desk checked your code and [once again] seems fine. One way to debug this is to [using gdb] is to single step [with stepi] within your functions and put breakpoints after the the jal printf [or jal fflush].
Before and after each jal, note the $sp value. It must be the same. Do this for all your functions. Also, when returning from a function, note the $sp value, then the value from the lw [which goes into $ra]. They should all match the "expected"
Further, $sp must be 4 byte aligned at all times. Actually, according to a mips ABI document I've seen [possibly dated], it says that stack frames must be 8 byte aligned. That may be overkill at this point, but I mention it.
If you do lw from unaligned, that's an alignment exception, which will probably show up as SIGBUS. Further, check the $ra value [before doing the jr $ra]. It also must be the "expected" value and be 4 byte aligned.
In other words, exactly which instruction produces the exception?
Another thing you can do is to comment out some function calls. Start with the jal fflush. Then, comment out jal printf [in your sub-functions]. I note that you do a "naked" printf call at the outset, which seems fine. Keep doing this until the program stops faulting. This ought to help localize the area/call.
You didn't state whether you were running this in a simulator like spim or mars or real H/W [possibly running linux]. I suspect real H/W. But, you could verify your logic by running under a simulator [I prefer mars] and provide dummy functions for printf and fflush that just do jr $ra. Note that neither spim nor mars can link to .o files. They work purely from source, so you can only use your .s
If you're running on real H/W, gdb ought to be able to provide detailed information on the source of the exception. If not, create a C function that sets up a signal handler for SIGBUS using sigaction [see the manpage]. Then, put a breakpoint on the signal handler.
One of the arguments to the signal handler is a pointer to a siginfo_t struct that has additional information. Note that for SIGBUS, the si_code field will have a BUS_* value that may have more information.The third argument, although void * is a pointer to something that can give you the register values at the time of the exception.
In another answer I gave: mips recursion how to correctly store return address for a function another OP had a similar problem. My answer added some special stack alignment and check code that may give you some ideas.


Q: override form method from dll class i want to build dll file that deals with system.windows.forms.form how can i override any form method from dll class such as (WndProc)?
public partial class MyDll
{
    public MyDll(System.Windows.Forms.Form form)
    {
        // i want to override WinProc form from my dll file.
    }
}

my project is a "ClassLibrary" not a "WindowsFormsApplication"

A: You can easily override the method in this way:
protected override void WndProc(ref Message m){...}

Here you can find some examples: http://msdn.microsoft.com/library/system.windows.forms.control.wndproc%28v=vs.110%29.aspx

A: If you pass the form as a parameter you have the instance of the class, not the definition. You have to create your own Form, override the method as mentioned before and then pass this new Form to your MyDll constructor. for example:
Create a new class library project. Add two files:
- MyDllClass.cs
- MyForm (add new->Window Form)
public partial class MyForm : Form
{
     protected override void WndProc(ref Message m)
    {
        //your code here
        base.WndProc(ref m);
    }
}

Then in MyDllClass.cs you will have
public MyDllClass(Form your_form_here)
{
    //your code here
}


Q: Spring boot one to one with foreign key I am want to store room details and room types in my db. I have created an entity for Room as follows.
@Data
@Entity
public class Room {

        @Id
        private String room_id;

        private Boolean status;

        private Double price;

        private Long type;

        private Long occupancy;

        @OneToOne(fetch = FetchType.LAZY, optional = true)
        @JoinColumn(name = "type_id", nullable = false)
        private RoomType roomType;

}

I have create a RoomType entity as follows:
@Data
@Entity
public class RoomType {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String type;
}

To save a Room Entity in my DB, the following is the request body format need to be given
{
  "room_id": "string",
  "status": true,
  "price": 0,
  "roomType": {
    "id": 1,
    "type": "string"
  }
}

I want to have the request body as follows
{
  "room_id": "string",
  "status": true,
  "price": 0,
  "roomType": 1  # This the roomType foreign key
}

I want to have one to one relationship, so when retrieving the Room details, I will get the roomType values also in the following format.
   {
      "room_id": "string",
      "status": true,
      "price": 0,
      "roomType": {
        "id": 0,
        "type": "string"
      }
    }

Or Is there any better way to handle this type of problem in spring boot??

A: I think there are two different concepts in here:

*

*The inner representation of a Room in your service (The classes you use and their relations)

*The outer representation (The one exposed by your API)

If you want those two representation to be the same, you could just serialize/deserialize data using the Room class directly (which I assume is what you are currently doing). For example:
@Controller
class MyController {
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public Room createRoom(@RequestBody Room room) {
        // Here room will be automatically deserialized from the request body
        // Do stuff with the received room in here
        // ...
        // Here the returned room will be automatically serialized to
        // the response body
        return createdRoom;
    }
}

However, if you don't want the inner and outer representations to be the same, you can use the DTO pattern (Data Transfer Object). Example in Spring here.
Now, you would have three different classes, Room and it's DTOs:
public class RoomRequestDTO {
        private String room_id;
        private Boolean status;
        private Double price;
        private Long type;
        private Long occupancy;
        private Integer roomType; // This is now an Integer

       // Setters and Getters ...
}

public class RoomResponseDTO {
        private String room_id;
        private Boolean status;
        private Double price;
        private Long type;
        private Long occupancy;
        private RoomType roomType;  // This is a RoomType instance

       // Setters and Getters ...
}

Now, your controller would receive RoomRequestDTOs and send RoomResponseDTOs:
@Controller
class MyController {
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public RoomResponseDTO createRoom(@RequestBody RoomRequestDTO roomReqDTO) {
        Room room = ... // Convert from DTO to Room
        // Do stuff with the received room in here
        RoomResponseDTO roomRespDTO = ... // Convert to the DTO
        return roomRespDTO;
    }
}

This approach also has the advantage that you can now change the inner representaion of Room without afecting the API. This is, you could decide to merge the Room and RoomType classes in one, without affecting the outer representation.
Note: In the example I have linked, they use the ModelMapper library. If you do not desire to introduce that dependecy, you could simple add a contructor and a method to the DTOs as such
public RoomResponseDTO(Room room) {
    // Manually asign the desired fields in here
    this.id = room.getId();
    // ...
}
public Room toRoom() {
    Room room = new Room();
    // Manually asing the desired field in here
    room.setId(this.id);
    // ...
    return room;
}

However, this approach would make you have to change these methods whenever you want to change the representations of Room. The ModeMapper library does this for you.


Q: Mocha: Can't stub function in file that was already required in another test file I'm using Mocha to run a test suite on fileToTest.js with requires greeting.js
// --fileToTest.js--

const { greeting } = require('./greeting');

module.exports = () => greeting();

// --greeting.js--

module.exports.greeting = () => 'hi!';

By itself, this test file successfully stubs greeting.
// --test2.js--
let parent;
const sinon = require('sinon');
const chai = require('chai');
const greeting = require('../../greeting.js');

const { expect } = chai;

describe('stubbed /hi', () => {
  before(async () => {
    sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!');
    parent = require('../../parent.js');
  });

  after(async () => {
    greeting.greeting.restore();
  });
  it('should say bye', async function () {
    expect(parent()).to.be.equal('bye!');
  });
});

However if I run a test suite and have another test file that requires fileToTest.js, like test1.js below, the first test above (test2.js) won't stub greeting.
// --test1.js--
const chai = require('chai');
const fileToTest = require('../../fileToTest.js');

const { expect } = chai;

describe('not stubbed /hi', () => {
  it('should say hi', () => {
    expect(fileToTest()).to.be.equal('hi!');
  });
});

It seems once test1.js requires fileToTest, mocha doesn't reload the fileToTest on the test2.js's require. So fileToTest is stuck with the old greeting function.
Whats the proper way to stub a function in this situation?
Repo

A: This answer worked. I had to delete the cache.
  before(async () => {
    delete require.cache[require.resolve('../../fileToTest.js')]; // <------

    sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!');
    fileToTest = require('../../fileToTest.js');
  });


Q: I get "Incorrect argument" error when i try to run a simple test on couchbase nodejs server var couchbase = require("couchbase");

var cluster = new couchbase.Cluster('127.0.0.1:8091');
var bucket = cluster.openBucket('beer-sample', function(err) {
    if (err) {

        throw err;
    }

    bucket.get('aass_brewery-juleol', function(err, result) {
        if (err) {

            throw err;
        }

        var doc = result.value;

        console.log(doc.name + ', ABV: ' + doc.abv);

        doc.comment = "Random beer from Norway";

        bucket.replace('aass_brewery-juleol', doc, function(err, result) {
            if (err) {

                throw err;
            }

            console.log(result);

            process.exit(0);
        });
    });
});

Here is my file. It's the example from here : http://docs.couchbase.com/developer/node-2.0/hello-couchbase.html
So when i try to run the server with "nodejs test1.js"  i get "Incorrect argument" error.
At bucket.js, module.js and in cluster.js into node_modules/couchbase/lib/
I have installed couchbase and i have full nodejs installed. I'm new in this and i cant understand where is my mistake. Maybe something with the versions of the couchbase or the node version i dunno.
Here is my full error which i get into the terminal:
Error: Incorrect argument
at New Bucket (home/anton/node_modules/couchbase/lib/bucket.js:213:16)
at Object<anonymus> (home/anton/PhpstormProjects/couchbase/test1.js:6:22)
at Cluster.openBucket (home/anton/node_modules/couchbase/lib/cluster.js:37:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

A: The "Canonical" format for connecting to a cluster is couchbase://host where host in your case is localhost.
Depending on the version you're using, newer enhancements may have been added to allow for the common host:8091 antipattern, but would still be incorrect.
Chances are your code can still work if you upgrade to a newer version - but you should still use the couchbase:// variant (without the port).


Q: Return previous row when using boolean indexing Question
How do I return the previous row, as well as the row meeting a condition, when using boolean indexing?
Example:
sodf = pd.Series([9,10,10,9,10,11])
sodf

0     9
1    10
2    10
3     9
4    10
5    11
dtype: int64

Boolean condition:
sodf[sodf == 11]

5    11

Desired output:
4    10
5    11

A: You can get the index of sodf==11 and then get the loc value -1 onwards.
Here's how to do it.
import pandas as pd

sodf = pd.Series([9,10,10,9,10,11])

x = sodf[sodf == 11].index[0]
print (sodf.loc[x-1:])

Output will be:
4    10
5    11

If you just want the value of the previous row, then you can also give
print (sodf.loc[x-1])

The output will be just the value as this is a pd.Series with one column:
10

A: Try something like this:
i = sodf[(sodf == 9)].index
i = i.union(i-1)
i = i[i>=0]

sodf[i]

Output
0     9
2    10
3     9
dtype: int64


Q: Something changed: no longer able to SSH to home: xFinity I need some help understanding the current situation that I am having with my home network.
My home network is very simple:  My ISP is xFinity with a Dynamic IP that doesn't change very frequently. Last IP change occured 6 months ago. It comes into an Arris SB6183 modem that I own. From the Arris, it goes into a Linksys E8540 WiFi 6 Router (or a Netgear R6250 DD-WRT due to troubleshooting). From here, I only have 2 computers:  one Linux Desktop, and one personal Windows laptop that I use for web-browsing.
The Linux Desktop machine (LAN IP is 192.168.1.200) has SSHD Service on Port 22. The Router port forwards incoming SSH 22 connection from Internet to Port 22 on 192.168.1.200. Router firewall (SPI) is disabled.
Everything stopped working about 2 weeks ago. I am not able to SSH from outside into my Linux Desktop machine. If I am on the internal LAN, then SSH works just fine.
Using CanYouSeeMe.org shows me that Port 22 cannot connect:  "Reason:  connection timed out"
Here is what I tried:

*

*Removed the Router and Laptop and plugged in the Linux Desktop
straight into the Arris modem. SSH attempts still shows "Request
timed out"

*Made sure that UFW Firewall on Linux is off. No Fail2Ban.

*Replaced the Linksys E8450 with Netgear R6250 DD-WRT. No change.

*Called xFinity Customer Support and asked "Is Comcast blocking external incoming IPs to Port 22 ?" they responded "We don't block Port 22"

*Contacted Comcast Customer Security Assurance and Abuse and asked them to verify if my profile has some Security Profile/Screen in place or some sort of flag. They responded NO.

Then, finally I put a Port Forwarding rule on the router: incoming connection on port 2222 go to SSH 22 on Linux Desktop. And this works!! If I initiate external SSH connection attemps on port 2222 I do indeed connect to my Linux desktop.
In a related news, my Reolink Security APP on my Android Samsung phone no longer connects to my Home Camera over Cellular Data. It connects fine if my Phone connets to the Lan over WiFi.
What are your thoughts ? Does it look like my ISP is blocking incoming connections ? Any help greatly appreciated!


Q: Reading from file line by line known structure but length is unknown I'm sorry to ask this question, because I found similar answered questions, but I'm having difficulty to understand how to read lines of unknown length but the structure is the same.
Each line is structured by the following: name:id:buyingPrice:sellingPrice:profit:quantity
The names and IDs are strings while the rest are doubles.
My problem is I don't know how to setup a while that reads and stores each field, would it be possible to get a detailed explanation on how to accomplish this?
Here's my read of the file(just with strings) :
file = fopen("fileData.txt", "rt");

if(file != NULL){
    char lineSize[128] = "";

    while(fgets(line, 128, file) != NULL){
        fscanf("%s:%s:%s:%s:%s:%s", string1, string2, string3, string4, string5, string6);

    }
    fclose(file);

A: Have you thought about using strtok to parse the tokens after the fgets?

A: What I would use is the 'a' modifier for the scanf-format: Simply say 'fscanf("%as:%as:...", ...)', pass in the addresses of unallocated pointers and let fscanf malloc them for you.
This originated as a gnu extension, but AFAIK, it has made it into the C11 standart.


Q: Should I use the new HTML5 semantic elements? I'm in the process of upgrading my website, and this involves the decision of using the new HTML5 semantic elements
 over regular old
 elements.
I do plan on supporting IE7 and IE8, but I know that these versions don't support the above semantic elements. I've read up about 'plugins' like Modernizr, Initializr and HTML5shiv, and I know that older browsers will then support the new elements IF JavaScript is enabled, but what am I supposed to do if it's not?
By default, the  tag is given the class of no-js and if JavaScript is enabled, Modernizr/Initializr replaces this class with js. That's all well and good, but there are some things I'm uncertain about. So far, what is covered?
Sorted

*

*IF JavaScript is enabled, IE7 and IE8 are supported by Modernizr/Initializr.

*With a reset.css file, other older browsers support these new tags.

*Modern browsers are all fine.

Problems

*

*IF JavaScript is disabled, what am I supposed to do about IE8 and below? The no-js class is added to the  tag, so what exactly can I do with that?

*How can I use  to my advantage here? I don't want to make pages too large with coding.

So, aside from those questions, I also want to ask if it's really worth using these tags, when I can just use good ol'
 tags which would both support older browsers and also keep file sizes down by eliminating the required coding to make the new tags work in older browsers?
Thank you,
Dylan.

A: It's good practice to use both, for example

If you need to support those obsolete browsers, I wouldn't do anything more than that. The benefits, such as they are, are not worth the extra effort.

A:
I do plan on supporting IE7 and IE8, but I know that these versions don't support the above semantic elements. I've read up about 'plugins' like Modernizr, Initializr and HTML5shiv, and I know that older browsers will then support the new elements IF JavaScript is enabled, but what am I supposed to do if it's not?

If JavaScript is not enabled, then while the content of the new elements will be shown, CSS will not be correctly applied to them. While in theory you could use a noscript element to trigger a redirect to a version of the page not using the new elements (via a meta refresh tag within the noscript), then you'd be maintaining two versions of your site.
For example, given this page: Live Copy
<!DOCTYPE html>

<meta charset=utf-8 />
<title>HTML5 Elements</title>

This text should be green

...early versions of IE will show the text in the default color. Adding the HTML5 shiv prior to the style element:

...which as you know requires JavaScript, makes the text green: Live Copy

A: It's not necessary to follow the new semantic. New semantic is developed mostly for search engines, not for site functionality. If you really want to support IE, do it for IE.
If you really consider no-script cases and CSS is not enough for you, than all you can do is PHP/ASP magic.
One my friend works exclusively in Flash, because no js, totally client side, no cares about browsers... Who knows...

A:
Should I use the new HTML5 semantic elements?

Yes.

IF JavaScript is disabled, what am I supposed to do about IE8 and below?
  The no-js class is added to the  tag, so what exactly can I do with that?

You can do something like this,
HTML

     // Whole website coding here

      Use an upgraded browser

CSS
    .no-js #wrapper {
      display: none;
    }

    #old-browsers {
     display: none;
    }

    .no-js #old-browsers {
      display:block;
    }

How can I use  to my advantage here? I don't want to make pages too large with coding.
IE Consideration:
IE7 is 7 years old and most developers today do not support it. IE7 / IE8 users with js disabled is pretty low and you shouldnt develop for those exceptions. Instead you should give them a suggestion to upgrade with above method. You can use the noscript tag for the same usecase.

A: What you could do (and what a lot of big website's do) is to display a notice when javascript is disabled (optionally when the browser is IE7 or IE8 but you'll need a serverside check for that), that the website would not be displayed the way it is supposed to. See "How to detect if JavaScript is disabled?" on how to do so.
Only 5.3% (source) of internet users are using Internet Explorer < 8 and 0.25% to 2% (source) of the total users have Javascript disabled. You could spend a lot of time making a smooth solution for max 5% x 2% = 0,01% of your visitors or you could spend 5 minutes building the notice system I described.


Q: Why Doesn't CreateProcess() Work? I have a program that attempts to restart Explorer in Windows 7; it first ends the process, then starts it again.
Simple?
So it looks -- it indeed seems to work. However, I noticed something funny: When I try to start a program (say, XP's Power Calculator powertoy) under compatibility mode, it no longer works! Nothing happens -- the process is created and immediately quits.
If I run Explorer through the Run dialog of Task Manager, the program runs fine.
What's going on?!
#include <windows.h>
int main()
{
    PROCESS_INFORMATION pi;
    STARTUPINFO si = {sizeof(si)};
    TCHAR path[] = TEXT("explorer");
    DWORD f = 0; //I tried a variety of these flags; didn't work
    return CreateProcess(NULL, path, NULL, NULL, FALSE, f, NULL, NULL, &si, &pi);
}

Edit 1:

*

*The fact that it was 32-bit with WOW64 redirection disabled made no difference. I made it 64-bit and the issue was the same.

*I tried ShellExecute but it didn't work either.

Edit 2:
The same exact code just worked for me a couple of times, and then stopped working again... huh?

A: This isn't really an answer to the "why", but I managed to find out how to fix it myself:
Instead of copying environmental variables from the current process, if I copy them with CreateEnvironmentBlock, then it works.
I still haven't figured out what's causing it, though...


Q: Flicker in Gradient panel I have inherited a control from TPanel and in the Paint event handler, I have drawn the entire client rect using a gradient. This works perfectly fine until the user resizes.
When the panel is resized, the panel component flickers too much.
How can i avoid this flicker. I saw the gradients in MS office 2007, even if we resize the client area, there will not be a flicker. Please enlighten me on this.
Thanks in anticipation

A: You may want to look at this question How to eliminate the flicker on the right edge of TPaintBox (for example when resizing)
Good overview of options to avoid flicker and also for TPanel.
Edit :
I made a quick test in my Delphi XE version on windows 7.
With this code I cannot reproduce any flicker.
The inherited Paint is removed and the Paint routine is quite fast.
If you still can see flicker, the proposal from Simon can be implemented, but better keep the bitmap created for the lifetime of the component itself.
unit MainForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls;

type
  TGradientPanel = class(TPanel)
  protected
    procedure Paint; override;
  public
    constructor Create(AOwner: TComponent); override;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    sPanel : TGradientPanel;
  public
    { Public declarations }
 end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

Uses Math;

 procedure GradVertical(Canvas:TCanvas; Rect:TRect; FromColor, ToColor:TColor) ;
 var
   Y:integer;
   dr,dg,db:Extended;
   C1,C2:TColor;
   r1,r2,g1,g2,b1,b2:Byte;
   R,G,B:Byte;
   cnt:Integer;
 begin
    C1 := FromColor;
    R1 := GetRValue(C1) ;
    G1 := GetGValue(C1) ;
    B1 := GetBValue(C1) ;

    C2 := ToColor;
    R2 := GetRValue(C2) ;
    G2 := GetGValue(C2) ;
    B2 := GetBValue(C2) ;

    dr := (R2-R1) / Rect.Bottom-Rect.Top;
    dg := (G2-G1) / Rect.Bottom-Rect.Top;
    db := (B2-B1) / Rect.Bottom-Rect.Top;

    cnt := 0;
    for Y := Rect.Top to Rect.Bottom-1 do
    begin
       R := R1+Ceil(dr*cnt) ;
       G := G1+Ceil(dg*cnt) ;
       B := B1+Ceil(db*cnt) ;

       Canvas.Pen.Color := RGB(R,G,B) ;
       Canvas.MoveTo(Rect.Left,Y) ;
       Canvas.LineTo(Rect.Right,Y) ;
       Inc(cnt) ;
    end;
 end;

constructor TGradientPanel.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Self.ParentBackground := FALSE;
end;

procedure TGradientPanel.Paint;
var
  rect : TRect;
begin
  //inherited;  // Avoid any inherited paint actions as they may clear the panel background
  rect := GetClientRect;
  GradVertical( Self.Canvas, rect, clBlue, clRed);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  sPanel := TGradientPanel.Create( Self);
  sPanel.Parent := Self;
  sPanel.Top := 10;
  sPanel.Left := 10;
  sPanel.Width := 300;
  sPanel.Height := 300;
  sPanel.Anchors := [akLeft,akRight,akTop,akBottom];
  sPanel.Enabled := TRUE;
  sPanel.Visible := TRUE;
end;

end.

A: A way to reduce flicker is to draw the gradient to a temporary bitmap the draw the entire contents of the bitmap to the panel. This method assumes you have an OnPaint method and a canvas to draw on in your inherited panel.
So something like this (untested)
var bmp : Tbitmap;

procedure AfterConstruction;
begin
  bmp := TBitmap.Create;
end;

procedure Destroy()
begin
  if Assigned(bmp) then FreeandNil(bmp);
end;

//redraw you bmp gradient
procedure Panel1.OnResize();
begin
  if Assigned(bmp) then //ensure the bmp s created in your constructor
  begin
  try
    bmp.SetBounds(Panel1.Clientrect); //ensure the bmp is the same size as the panel
    //draw your gradient on the bmp
    Panel1.OnPaint();//repaint the tpanel

  finally
    bmp.Free;
  end;
end;

//paint to the panel
procedure Panel1.OnPaint()
begin
  Panel1.Canvas.Draw(0,0,bmp); //use the OnPaint method to draw to the canvas
end;
  end;
end;


Q: jsf cascading list How do I cascade the lists so if user changes selection in selectedCategory list it should update the selectedTo list.
Here is my snippet:
<h:selectOneMenu id="selectedCategory" value="#{converterBean.selectedCategory}">
  <f:ajax execute="selectedCategory" render="selectedFrom"/>
  <f:selectItems value="#{converterBean.categories}"/>
</h:selectOneMenu>
<h:selectOneListbox id="selectedFrom" value="#{converterBean.selectedFrom}" size="5">
  <f:selectItems value="#{converterBean.fromList}"/>
  <f:ajax execute="selectedCategory selectedFrom" render="selectedTo"/>
</h:selectOneListbox>
<h:selectOneListbox id="selectedTo" value="#{converterBean.selectedTo}" size="5">
  <f:selectItems value="#{converterBean.toList}"/>
</h:selectOneListbox>

I notice that it updates the selectedFrom list but does not cascade further to selectTo list.
As per suggestion to try render both selectedFrom and selectedTo for category selection the request posted from the page is:
POST http://localhost:8081/converter_web/faces/converter.xhtml HTTP/1.1
Accept: */*
Faces-Request: partial/ajax
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Referer: http://localhost:8081/converter_web/
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Host: localhost:8081
Content-Length: 1253
Connection: Keep-Alive
Pragma: no-cache
Cookie: JSESSIONID=DDDEA598A60CC468763C36B536513B41

converter_form=converter_form&converter_form%3AselectedCategory=temperature&converter_form%3AselectedFrom=mm&converter_form%3AselectedTo=cm&converter_form%3Avalue=0.0&javax.faces.ViewState=b%2BArKl5NJujWibUQzHf3dUG2JlT%2Bnq7KygA2%2FXpXXscCouBr5xT9Br%2BmoP78%2FvuPAYG%2Bi7Q0jFEKGqJpFgRo%2BDU4ZV251yac84pu3bZ71V9j%2BHvRPMkWw82S8q0v2p1jmn3msPXxvKrQQ1oVpr7pGBPXc2faQGXHW55Md%2BKSkspIgCxXx3x3T6NDaJ1%2BGTEFkyb1DE%2BdoQHQ4EjqV3jEC5mq56OlsHgEmkQ8TVCQM%2FPmAfUBWiQEHqBYzohXNfFpO3kfdrKjeTrq648UtGPYU88VJ9mtIOptYEfwFKN9y%2FG9MOBKEfRZ9XlJz2bPt1zmATIg3iRT1W7YVtmHq7e9g%2FUxsM82duMxFUWhoFPHfrFk4tt48LFH29Hk60y3eeFxqtg7g1JxPD1aQrLN9sxBduS53nFWObCms1YU40uvMT2yjX0kp4wM8YwqT2jTFDtLHcVBide1RGTnzFGzjOrbCJ8rIEmWfPa1yUMkXRBBsgpKWFIl0ueBQiCT%2BDoD9UXlNOQGS%2F5tIdP%2BVTO%2FkWiBo5X99SpKwKY8%2B2pqzJKDrPRXIwci52Wi%2Fo%2Fw%2B0TkpnVrtDaDl7w2eYjmq7bYZFRDjWy3Jtgc5V1DUF%2BhX3Bfiq7l%2Fq5YL4DYx0NBI2esfJ0LTFCqXu8aCk%2BWOPOWnOCSGA5Y9EGUXgzV6q%2Fp%2FFWa8Kj8E%2FeoB380eFwXAEiyyRGv&javax.faces.source=converter_form%3AselectedCategory&javax.faces.partial.event=change&javax.faces.partial.execute=converter_form%3AselectedCategory&javax.faces.partial.render=converter_form%3AselectedFrom%20converter_form%3AselectedTo&javax.faces.behavior.event=valueChange&javax.faces.partial.ajax=true

We would expect only selectedCategory be send but its sending all form fields in ajax call.  It though calls getCategories(), getFromList(), getToList() but when it calls getToList it uses category=temperature and from=mm.  from=mm is what is passed in POST request as selectedFrom=mm.
Regards,
Miten.

A: Change this:
  <f:ajax execute="selectedCategory" render="selectedFrom"/>

To this:
  <f:ajax execute="selectedCategory" render="selectedFrom selectedTo"/>

A: I added ajax listener as below so indicate that category change is being invoked so that getFromList will set selectedFrom to new item from its list instead of one being posted.  Then getToList will find correct category and from unit to query its to list.
<f:ajax execute="selectedCategory" render="selectedFrom"></f:ajax>

to
<f:ajax listener="#{converterBean.categoryChanged}" execute="selectedCategory" render="selectedFrom selectedTo"></f:ajax>


Q: How to find xpath for  with no class or unique identifier

Welcome
Hello welcome.

Welcome!!!
Good morning

A: You can just use the FirePath plugin that mozilla has.
Or if not then for the following code

Welcome
Hello welcome.

Welcome!!!
Good morning

The xpath for second p element will be : html/body/p[2]
For the span within it: html/body/p[2]/span

A: Use // slash to find all the elements present on the DOM with start with p tag
//p will return you all element present on the DOM in p tag
Hope it will help you :)


Q: With "azure-iot-sdk-java"; What is the expected lifetime of a DeviceClient instance I am developing a long-running program that sends data periodically to an Azure IoT Hub. I am using the com.microsoft.azure.sdk.iot.device/DeviceClient Java class to accomplish this.
It's basically working, which is nice, but I have some questions about the lifetime of the DeviceClient instance.
Should I instantiate exactly one DeviceClient instance at program startup, and then repeatedly call .sendEventAsync any time I have data to send? Or should I instantiate a new DeviceClient instance fresh from the connection string each time I want to send data? Or something in-between (e.g., send no more than 100 messages with a given DeviceClient instance, or let no DeviceClient instance live more than 72 hours)?
As I said, it's basically working, we've successfully sent many many events, but we have also seen some funny behavior. For example, after a few weeks the client silently stops sending (oof), or after some time the client claims send SUCCESS_OK, but the events don't arrive in the IoT hub for several hours (up to 16 (!)). I can definitely imagine these occurrences steming from my misuse of the library, so any hints about how to use it correctly would be much appreciated.
Thanks in advance for your time and consideration.

A: You should only have one long-living DeviceClient instance. Especially if you are using MQTT or AMQP as transport protocol, the DeviceClient will open the connection - and keep it open. Over that open connection it will send the messages. And also the for cloud-to-device messages / twin updates, the same channel is used.
Also, the client usually handles any connection-retry logic so you don't have to deal with that manually.


Q: How to run a rails migration as sql file My database admins do not want to control access to any drop/alter/create commands.  Is there anyway to emulate what rails is doing to the schema migrations table and convert the migrations themselves in a reliable way to fake rails out into thinking it has been ran and also handle rollbacks?  They want to run this from their end of course.  I have seen a few suggestions, but no wholistic approach. Perhaps the answer is it really shouldn't be done, which is what I think right now as I believe it will just cause headaches and unreliability down the road.