text:
Q: How do I get IIS working and accessible outside my network behind a router? My machine is running Windows 7 Ultimate. Here's what I've done (successfully) so far:

*

*Installed IIS 7.5 with PHP over FastCGI

*Got it working! When I go to http://localhost/index.php , my PHP scripts run fine.

*Ran ipconfig to find out that my local IP address is 192.168.1.102. I confirmed that http://192.168.1.102/index.php functions exactly like the localhost address above.

*Went into my router administration (I have a Linksys WRT54G2) and set up port forwarding on port 80 to 192.168.1.102. Now port 80 is forwarding to my machine.

*Set up an inbound rule in Windows Firewall to allow all activity on port 80.

*Found out what my outside IP address is from Google. Let's call it XXX.XX.XX.XX.

However, when I try to go to http://XXX.XX.XX.XX/index.php from my own machine, or from a computer far away and not on my network, either way... I get nothing. It tries to connect for awhile (unsuccessfully) but eventually just gives up.
Here's what I'm wondering:

*

*What am I missing? What did I forget/overlook? How do I get this working and accessible outside my own local network?

*Assuming I do get this working, how can I then use a port other than port 80? What changes would I need to make (e.g. IIS, Windows Firewall, router administration, etc.) in order to make that possible?

Thanks very much in advance!

A: This sounds like an HTTP.SYS issue that you are having.
Below is an excerpt from Scott Hanselman's blog that describes how to expose IISExpress outside of localhost. The blog post is longer which also describes how to all wire up SSL. But I believe the commands that I have posted below which I pulled from his post will help you resolve the issue you are having.

First, we need to tell HTTP.SYS at the kernel level that it's OK to
  let everyone talk to this URL by making an "Url Reservation." From an
  administrative command prompt:
netsh http add urlacl url=http://<LocalComputerName>:80/ user=everyone
Next, as I want to
  be able to talk to IIS Express from outside (folks on my network, etc.
  Not just localhost) then I need to allow IIS Express through the
  Windows Firewall. I can do that graphically from Windows, or type:
netsh firewall add portopening TCP 80 IISExpressWeb enable ALL

You may not need the last command since you state that you already created a firewall rule.

A: *

*(Access from outside your network) Many residential ISPs (and some business ISPs) will block inbound traffic on certain service ports, like port 80 or 25. This is generally to keep you from running business services on a residential line due to bandwidth usage. The alternative is to run it on another port (see below).

*(Access from inside your network) The situation you're describing sounds like hairpin NAT. Here is a good high-level overview of Hairpin NAT. You will need to add NAT rules to your router to always make traffic destined for your external IP, port 80 go through your router and not directly from host to host inside your network. Caveat: Your router may not actually be able to do this.

*Change the port binding in IIS, then restart the website.

A: I had the same problem.  Windows Firewall is blocking access.  Turn it off and check it again.  My guess is that it will work.


text:
Q: Is SSL Certificate required when using custom protocols between client and server (Not HTTPS)? I have a project that I'm working on, it's a desktop application that is communicating with a server I built over TCP. I want to make the connection secure and encrypted by using SSL (TLS) but I'm not sure, is SSL Certificate required when using SSL in custom protocols? Is it just for HTTPS since it require it?
In addition, I'd like to know what is the role of the SSL Certificate in the encryption process of the stream between the 2 endpoints? Is it just for verifying the 2 endpoints?
Thanks in advance.

A:
... is SSL Certificate required when using SSL in custom protocols?

A certificate is used to identify the server, i.e. to make sure that the client is connecting to the expected server and not to some man in the middle. TLS provides also other methods to do this kind of check, like using a pre-shared secret between client and server, see Wikipedia: TLS-PSK for more.

I'd like to know what is the role of the SSL Certificate in the encryption process of the stream between the 2 endpoints? Is it just for verifying the 2 endpoints?

The primary role of the certificate is to provide authentication. With RSA key exchange the certificate additionally is used to transport the information for the symmetric encryption key from the client to the server - by encrypting the pre-master secret with the servers public key taken from the certificate so that the server can decrypt it with the matching private key. But note that RSA key exchange is considered obsolete and that in modern key exchange methods (Diffie-Hellman) the certificate is not used.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability to guess a number Les's have the next situation:
There is a system who asks for certification.
For that , the system sends you a seed of 16 bits , and you need to response with a  result of 24 bit.
Each time, the seed is different and uniformly.
What is the probability to keep wrong in the guess for N times, with the next algorithm:
Each time you get the seed, randomise a uniformly 24 bit value and hope for good.
What is the probability to not succeed after 100000000 (N) trials.
Is it $(1-\frac{1}{2^{24}})^N$ or $(1-\frac{1}{2^{40}})^N$ ?
For your information, a success is to give the correct response (nevertheless what is the seed)
Thanks a lot !!


text:
Q: Text Disappearing When Window Opens So, I have a form for a sign up, and in the design, it looks like this:

And here's the XAML for that:
<Rectangle x:Name="signInBox" Fill="#FF5F5F6E" HorizontalAlignment="Center" Height="450" Margin="0,0,0,0" Stroke="Black" VerticalAlignment="Center" Width="640" StrokeThickness="3" Visibility="Visible"/>
<TextBlock x:Name="signUpText" HorizontalAlignment="Center" Margin="0,-350,0,0" TextWrapping="Wrap" Text="Sign up for Horizon Chat" VerticalAlignment="Center" FontFamily="Muli" FontSize="36" Foreground="White"/>
<!-- For the username box -->
<TextBox x:Name="nameSignUpBox" HorizontalAlignment="Center" Margin="0,-150,0,0" TextWrapping="Wrap" VerticalAlignment="Center" Width="370" FontFamily="Muli" FontSize="26" BorderThickness="2" MaxHeight="61" MaxWidth="686"/>
<TextBlock x:Name="nameSignUpBoxDescription" HorizontalAlignment="Center" Margin="456,334,738,544" TextWrapping="Wrap" Text="Username" VerticalAlignment="Center" FontFamily="Muli" FontSize="18" Foreground="#FFDADADA"/>
<!-- For the email box -->
<TextBox x:Name="emailSignUpBox" HorizontalAlignment="Center" Margin="0,0,0,0" TextWrapping="Wrap" VerticalAlignment="Center" Width="370" FontFamily="Muli" FontSize="26" BorderThickness="2" MaxHeight="61" MaxWidth="686"/>
<TextBlock x:Name="emailSignUpBoxDescription" HorizontalAlignment="Center" Margin="456,408,778,468" TextWrapping="Wrap" Text="Email" VerticalAlignment="Center" FontFamily="Muli" FontSize="18" Foreground="#FFDADADA"/>
<!-- For the password box -->
<PasswordBox x:Name="passwordSignUpBox" HorizontalAlignment="Center" Margin="0,150,0,0" VerticalAlignment="Center" Width="370" FontFamily="Muli" FontSize="26" BorderThickness="2" MaxHeight="61" MaxWidth="686"/>
<TextBlock x:Name="passwordSignUpBoxDescription" HorizontalAlignment="Center" Margin="455,484,742,393" TextWrapping="Wrap" Text="Password" VerticalAlignment="Center" FontFamily="Muli" FontSize="18" Foreground="#FFDADADA"/>

Then, when the program starts, it undergoes some changes, like changing the window size to fit that box, and making that visible, and all that. Here's the code for that:
BrushConverter brushconverter = new BrushConverter();
this.Background = (Brush)brushconverter.ConvertFrom("#FF9C9C9C");
this.Width = 640;
this.Height = 450;
this.ResizeMode = ResizeMode.NoResize;
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = this.Width;
double windowHeight = this.Height;
this.Left = (screenWidth / 2) - (windowWidth / 2);
this.Top = (screenHeight / 2) - (windowHeight / 2);

Now, all that just has to do with the window, because in my case, I already have all the stuff visible. So, when I do launch the program, I get everything except the small text above the boxes (Username, Email, and Password). Here's that:

Now, my guess is that it moves the text somewhere during the resize, since when I don't resize the window, it's still there (like in the designer). However, it is still a problem if it is moving my text to a different place. How can I fix this?
EDIT: I tried to resize the designer window, and here's the before and after of resizing it about 100px:
Before:

50%:

And after:

A: Using @shadow32 I re-organized the controls into a viewbox and created a purely xaml solution for your dynamic sizing requirement.
I also cleaned up the XAML, less is more heh.
Hopefully you can use this approach, try to keep the layout in the designer if at possible.
It makes for a more maintainable solution.
    <Window x:Class="WpfApp1.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            mc:Ignorable="d"
            Title="Window1" Height="450" Width="800">
        <Window.Resources>
            <!--SET THE TEXT STYLING, AVOID REPEATING THE SAME STYLE-->
            <Style TargetType="TextBlock">
                <Setter Property="FontFamily" Value="Muli" />
                <Setter Property="TextWrapping" Value="Wrap" />
                <Setter Property="Foreground" Value="#FFDADADA"/>
                <!--MARGIN SPACES OUT THE DATA ENTRY FIELDS-->
                <Setter Property="Margin" Value="0,5,0,0"></Setter>
            </Style>
        </Window.Resources>
        <!--ROOT CONTAINER CONTROL WITH MARGIN TO CENTER-->
        <DockPanel Margin="50,0" >

            <!--SIDE BORDER AND BACKGROUND-->
            <Border BorderBrush="Black" BorderThickness="1,0" Background="#FF5F5F6E">

                <!--VIEWBOX FOR SCALING-->
                <Viewbox VerticalAlignment="Top">

                    <!--DOCK PANEL FOR WRAPPING HEADER AND DATA ENTRY CONTROLS-->
                    <DockPanel >

                        <!--HEADER WITH MARGIN TO PAD THE TOP-->
                        <TextBlock x:Name="signUpText"
                                   Text="Sign up for Horizon Chat"
                                   Foreground="White"
                                   Margin="0,10,0,0"
                                   DockPanel.Dock="Top"
                                   FontSize="20"/>

                        <!--STACKPANEL FOR ORDERING CONTROLS-->
                        <StackPanel DockPanel.Dock="Bottom" Margin="5,0">

                            <!--TOP PADDING TEXTBLOCK-->
                            <TextBlock />

                            <!-- For the username box -->
                            <TextBlock x:Name="nameSignUpBoxDescription"
                                       Text="Username" />
                            <TextBox x:Name="nameSignUpBox" />

                            <!-- For the email box -->
                            <TextBlock x:Name="emailSignUpBoxDescription"
                                       Text="Email" />
                            <TextBox x:Name="emailSignUpBox" />

                            <!-- For the password box -->
                            <TextBlock x:Name="passwordSignUpBoxDescription"
                                       Text="Password" />
                            <PasswordBox x:Name="passwordSignUpBox" />

                            <!--BOTTOM PADDING TEXTBLOCK-->
                            <TextBlock />
                        </StackPanel>
                    </DockPanel>
                </Viewbox>
            </Border>
        </DockPanel>
    </Window>


text:
Q: How do I get Route attribute to work in .net core api? So I added a controller to a blank asp.net CORE Api.
    public class IsAliveController : ControllerBase
    {
        [HttpPost]
        [HttpGet]
        [Route("isalive")]
        public object Get()
        {

            return "I'm alive";
        }
    }

Then I try to access it via https://localhost:44361/isalive
and I get no response. Do I need to make some modifications to my Startup.cs?

A: First why have you declared your method both as a get and a post request? you can remove the post attribute.
By default your routing must start with your controller name, add this:
[Route("[controller]")]
[ApiController]
public class IsAliveController : ControllerBase
{
    [HttpGet]
    public object Get()
    {
        return "I'm alive";
    }
}

Now when you call https://localhost:44361/isalive you will receive the expected response.

A: Found the issue. The template I choose (using Visual studio 2019)  was:

Asp.net core web app > Web Application

The startup file in this template is missing a line that I needed to add:
 app.UseEndpoints(endpoints =>
    {
        //Add this line
        endpoints.MapControllers();
    });

After adding that line the endpoint works without any changes to the controller.

A: There are two solutions to your problem:
#1 Your controller Name is IsAlive and you have added a route attribute on your action method as isAlive, so this would work only if you call using this Url
https://localhost:44361/isalive/isalive

#2 Remove the Route attribute from the action method
public class IsAliveController : ControllerBase
{
    [HttpGet]
    public object Get()
    {
        return "I'm alive";
    }
}

and you will be able to access using Url
https://localhost:44361/isalive


text:
Q: Ember-cli addon dev, how to differentiate addon dev from application dev When you create an ember-cli addon, you are supposed to be able to run a dummy app.
If a component need to access it's vendor folder you access "public/" in production.
While developping the ember app that use the addon you access :
app.options.project.nodeModulesPath + "/"+ this.name+"/vendor/"
However, when you run the ember-cli addon server (the dummy app) you need only "vendor/".
this.getEnv() will return developpement while developping an addon, or an app using the addon.
How can I, in index.js, differentiate app dev from addon dev ?

A: Suppose we are in the included hook, you can check this.isAddon() to determine where are you now. Say if you are in the consumer ember app now, you can then invoke path.dirname(require.resolve('ADDON_NAME/package.json')) to get the absolute path of your ember add-on.
One thing to notice, this.isAddon() might not a public API (though it's stable enough, it's still not listed in API doc). If you concerned about this, you can use this.parent.name() to achieve the same goal, when you run with the dummy app, this.parent.name() always returns dummy.
BTW, this.parent is the same thing as app.project where app is the first argument of included hook.


text:
Q: How to change the text of a Label - Tkinter I am creating a math game and want a score count in the top corner.

A: Yes, you need the command argument, but you also need a function for the command argument to run. Something like this would work:
from tkinter import *

def increment_score():
    global score
    score += 1 # update variable
    score_addition_easy_number.config(text=score) # update screen

root = Tk()

score = 0
root7 = Frame(root)
score_addition_easy_label = Label(root7, text="Score count: ")
score_addition_easy_label.pack(side=LEFT)
score_addition_easy_number = Label(root7, text=score)
score_addition_easy_number.pack(side=LEFT)
root7.pack()

a_e_answer_2 = Button(root, text="8", font=("times", 30, "bold"), padx=190, command=increment_score)
a_e_answer_2.pack()

root.mainloop()


text:
Q: Is there a way to alt-tab without the switcher interface appearing on screen? Sometimes I like to rapidly alt-tab between two programs in order to verify that something appears identically in both. For example, at the moment I have two P4Merge windows open each displaying on-disk changes to a file; the two files are ones that must be kept in sync. (They are not identical files, but changes to them must correspond.)
So I give first one program focus, then the other, and then I repeatedly alt-tab between them so as to satisfy myself visually that I see the same thing in both places. But every time I alt-tab, an enormous black box (the alt-tab switcher interface) covers part of the screen. This is distracting, and detrimental to the visual check I'm trying to perform. If only the interface didn't appear, alt-tabbing would be an ideal tool for the check I want to make.
I would like to be able to alt-tab without anything appearing over the application displayed on-screen. Is there a way to do this?

A: I figured out that what I want can be achieved by moving one instance of the app to a virtual desktop.

*

*Create a virtual desktop with Windows Key + Ctrl + D

*Open Task View using Windows Key + Tab

*Right-click one of the app instances and "move to" the new virtual desktop (probably called Desktop 2)

Now Windows Key + Control + left/right arrow flips between the desktops. And it doesn't pop anything up on screen.


text:
Q: Calculate GSAP eased tween duration given desired starting velocity I have a sequence of two GSAP tweens. The second tween is dependent on the first. The first tween moves an element to the right using Power3.easeIn. When this first tween ends, I calculate the instantaneous velocity of the element so I know how fast it was moving right at the end of the tween.
The second tween then needs to move a child of this element to the right using Power2.easeOut. This tween should start at the same velocity that the previous tween ended with. The distance that the child moves during this tween is fixed. How can I calculate the duration of the second tween such that it starts with the desired velocity?
EDIT: Here is a jsbin demonstrating what I'm attempting to do.

A: If I understand your question properly, this is EXACTLY what GSAP's ThrowPropsPlugin is for. Not only can it track the moment-by-moment velocity of any property of any object, but it can then create a tween that begins with that precise velocity and then glides to a stop naturally and you can even tell it where it should stop (or provide a range or snapping points...lots of options).
The ThrowPropsPlugin.to() method does the magic of figuring out the duration for you. All you do is feed in the target and end value (or range or snapping points).
The docs are at http://greensock.com/docs/#/HTML5/GSAP/Plugins/ThrowPropsPlugin/ where you'll find several examples too.
Here's a codepen demo based on your example: https://codepen.io/anon/pen/wGGdmq
ThrowPropsPlugin.to(child, {x:{velocity:ThrowPropsPlugin.getVelocity(parentElement, "x"), end:250}, ease:Power2.easeOut});

Notice you can change the duration of the first tween as well as the x position and the child will still animate properly. (That's what you were looking for, right?)
Disclaimer: ThrowPropsPlugin is a membership benefit of Club GreenSock so it is not in the public GSAP downloads.


text:
Q: Visual Studio 2013 not starting unless file is selected to load I am running VS 2013 ultimate on win 8.1  Parallels and everything was working fine, now does not.  I have repaired the install, and have even uninstalled and reinstalled VS 2013.  WHen I run devenv.exe the initial VS loading screen shows and just spins.  When I look at Task Manager, I only see VS running as a background process and eating up the CPU.
When I select a solution file or xml file as an example and choose the VS 2013, VS comes up and loads the file.  Any ideas of how to get this working would be GREATLY appreciated.

A: I was able to get the IDE to come up in safemode, so I figured it was one of the third party addins.  It seems like the Productivity Power Tools addin was the culprit in my situation.


text:
Q: Подойдет ли переходник, SSD для материнской платы переходник PCI-E M.2 NGFF for SSD Bulk и
SSD SAMSUNG 970 EVO Plus MZ-V7S250BW 250Гб.
Будут ли работать в связке с материнской платой Gigabyte GA-Z68P-DS3 rev.1 ???


text:
Q: android - json generated listview onClick only shows last item I have a map which shows markers from json file from web.
    I made a search listview from the same file.
    What I want to do is after click on any result map zooms on the marker associated with that result.
    But now when I click on any result it only zoom on ONE marker which is the last item in my json file.
Here's my code:
    public class MapAcWithMarker extends FragmentActivity
            implements OnMapReadyCallback {

        static final LatLng TEHRAN = new LatLng(35.697291, 51.392378);
        private GoogleMap mMap;
        public ArrayList<Locations> locationsList;
        public ListView listView;
        private View parentView;
        public DataAdapter adapter;
        ArrayList<Locations> arrayListTemp=new ArrayList<>();
        EditText inputSearch;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_recyc);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
            //  AsyncTaskGetMarker asyncTaskGetMareker= new AsyncTaskGetMarker();
            new AsyncTaskGetMarker().execute();

            locationsList = new ArrayList<>();
            parentView = findViewById(R.id.parentLayout);
            inputSearch = (EditText) findViewById(R.id.inputSearch);
            listView = (ListView) findViewById(R.id.listView);
            listView.setVisibility(View.INVISIBLE);

            inputSearch.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                    if(keyCode== KeyEvent.KEYCODE_DEL){
                        listView.setVisibility(View.GONE);
                    }

                    return true;
                }
            });

            inputSearch.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2, int count) {

                    listView.setVisibility(View.VISIBLE);

                    if(count==0){
                        listView.setVisibility(View.INVISIBLE);

                    }
                    String searchString= inputSearch.getText()
                            .toString().toLowerCase(Locale.getDefault());
                    int realText= searchString.length();
                    arrayListTemp.clear();
                    for (int i =0 ; i <locationsList.size(); i++){
                        try {
                            String pname= locationsList.get(i).getPname()
                                    .toString();

                            String bicycleno= locationsList.get(i).getBicycleno()
                                    .toString();

                            if(realText<=pname.length() && realText<= bicycleno.length())

                                if (searchString.equalsIgnoreCase(pname.substring(0,
                                        realText)) ||
                                        searchString.equalsIgnoreCase(bicycleno.substring(0, realText))

                                        ) {

                                    arrayListTemp.add(locationsList.get(i));

                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
 Log.d("@w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
  adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
  listView.setAdapter(adapter);
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }

                @Override
                public void afterTextChanged(Editable arg0) {

                }
            });
            RequestInterface api = JsonClient.getApiService();

            /**
             * Calling JSON
             */
            Call<StopList> call = api.getJSON();

            /**
             * Enqueue Callback will be call when get response...
             */
            call.enqueue(new Callback<StopList>() {
                @Override
                public void onResponse(Call<StopList> call, Response<StopList> response) {
                    //Dismiss Dialog
                    //  dialog.dismiss();

                    if (response.isSuccessful()) {
                        /**
                         * Got Successfully
                         */
                        locationsList = response.body().getLocations();

                        /**
                         * Binding that List to Adapter
                         */
                        adapter = new DataAdapter(MapAcWithMarker.this,
                                locationsList);
                        listView.setAdapter(adapter);

                    } else {
                        Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<StopList> call, Throwable t) {
                    Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
                }
            });

        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(TEHRAN, 10));

            new AsyncTaskGetMarker().execute();
        }

        class AsyncTaskGetMarker extends
                AsyncTask<String, String, JSONArray> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected JSONArray doInBackground(String... params) {

                String json = null;
                JSONArray jsonarray = null;
                HttpURLConnection conn = null;
                BufferedReader reader = null;
                try {

                    URL url = new URL("https://api.myjson.com/bins/1879ab.json");
                    conn = (HttpsURLConnection) url.openConnection();
                    conn.connect();
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    reader = new BufferedReader
                            (new InputStreamReader(in));

                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    reader.close();
                    String response = builder.toString();
                    JSONObject jsonObject = new JSONObject(response);
                    jsonarray = jsonObject.getJSONArray("stops");
                    // jsonarray = new JSONArray(response);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return jsonarray;
            }

           protected void onPostExecute(final JSONArray jsonarray) {
            try {
                final SparseArray<LatLng> positions =
                        new SparseArray<>();
                mMap.clear();
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String name = obj.getString("name");
                    String pname = obj.getString("pname");
                    String bicycleno = obj.getString("bicycleno");

                    Double lat = obj.getDouble("lat");
                    Double lang = obj.getDouble("lang");
                    final LatLng position = new LatLng(lat, lang);

                    String title = "name: " + name;
                    mMap.addMarker(new MarkerOptions()
                            .position(position).title(title));

                    positions.put(i, position);

}
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                            if (positions.get(position) != null)
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position), 15));

                        }
                    });

            } catch (JSONException e) {
                e.printStackTrace();
            }
            }

        }

    }

A: inside onPostExecute you have:
position = new LatLng(lat, lang);
String title = "name: " + name;

mMap.addMarker(new MarkerOptions()
                        .position(position).title(title));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position,15));
                    }
                });

so under position you have always last called position. This variable is used by every onClick set (in line: newLatLngZoom(position,15))
for fix this create position only locally inside method, you dont need globalLatLng position` variable declared on top of file
final LatLng position = new LatLng(lat, lang);
//rest of code as above

edit: also these
lat = obj.getDouble("lat");
lang = obj.getDouble("lang");

keep them local only inside one loop of for inside onPostExecute
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");

you should remove these declarations inside MapAcWithMarker class (on top)
//below to remove
public Double lat;
public Double lang;
public LatLng position;
//these are not used anywhere
public int selectionId= -1;
Marker markers;

next edit:
whole code of postExecute method
protected void onPostExecute(final JSONArray jsonarray) {
    try{
        final SparseArray<LatLng> positions = new SparseArray<>();
        mMap.clear();
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject obj = jsonarray.getJSONObject(i);

            String name = obj.getString("name");
            String pname = obj.getString("pname");
            String bicycleno = obj.getString("bicycleno");

            Double lat = obj.getDouble("lat");
            Double lang = obj.getDouble("lang");

            final LatLng position = new LatLng(lat, lang);
            String title = "name: " + name;

            mMap.addMarker(new MarkerOptions()
                    .position(position).title(title));

            positions.put(i, position);
        }

        // set once, outside for loop
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if(positions.get(position)!=null)
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position),15));
            }
        });
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

I've inspected your code more carefully and... is a mess. you are not notifying adapter about new data/json (even if data in adapter matching parsed json on positions, titles etc. you should refresh layout). also every objects parsed from JSON are added to map as a Marker with mMap.addMarker(...) method, but I don't see any mMap.clear(); method called, so points may duplicate, when JSON is downloaded again (added this line above)
another edit - you have only one item drawn on list because you have inside onTextChanged method
for (int i =0 ; i <locationsList.size(); i++){
    ...
    adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
    listView.setAdapter(adapter);
    ...
}

creation of adapter should be done once, outside for loop. check after loop but before initiation that arrayListTemp have more items
for (int i =0 ; i <locationsList.size(); i++){
    ...
}

Log.d("@w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);

lot of bugs...


text:
Q: Upgrade from 18.04 to 20.04 stucked with `Problem executing scripts APT::Update::Post-Invoke-Success` I'm currently stuck in the upgrade from 18.04 to 20.04 and can't move on.

*

*Text: An upgrade might not succeed. Do you want to continue anyway?

*I press [y]es

*Some third party entries in your sources.list were disabled. […] To continue please press [ENTER]

*I press [ENTER]

*Error "appstreamcli: symbol lookup error: appstreamcli: undefined symbol: AS_APPSTREAM_METADATA_PATHS" appears a few times between "Hit http://security.ubuntu.com/ubuntu focal-security InRelease" and "Hit http://ch.archive.ubuntu.com/ubuntu focal InRelease". This follows:

E:Problem executing scripts APT::Update::Post-Invoke-Success 'if
/usr/bin/test -w /var/cache/app-info -a -e /usr/bin/appstreamcli;
then appstreamcli refresh-cache > /dev/null; fi', E:Sub-process
returned an error code

Restoring original system state

Aborting
Reading package lists... Done
Building dependency tree
Reading state information... Done
=== Command terminated with exit status 1 (Thu Apr 30 11:54:41 2020) ===

Now if I press [r] ("to resurrect window") the loop begins again.

PS: There also seem to be the official issue 1873713 but it seems that there isn't any documented solution, yet.
PPS: I'm also wondering about seeing While scanning your repository information no entry about eoan could be found. during this upgrade loop. Because Eoan Ermine seem to be 19.10 whereas I was updating from 18.04 LTS to 20.04 LTS. Which itself looks like ubuntu-release-upgrader bug 1851040.

A: I commented out if /usr/bin/test -w /var/cache/app-info … in the file /etc/apt/apt.conf.d/50appstream.
Afterwards GDM showed up and didn't let me sign in (although I'm using lightdm).
I was able to complete the installation although I got stuck a second time and had to kill the update process. I'm sure it would have been better if I would have used
sudo do-release-upgrade -f DistUpgradeViewNonInteractive

instead (note the DistUpgradeViewNonInteractive option!). It's an advice from @user.dz but you should only do it if you can accept that /etc and ~/.config will be overriden.
Also if you are running into this bug:
Check
sudo appstreamcli refresh-cache

(Also an advice from @user.dz)


text:
Q: Metropolis Hastings for Posterior of Bivariate Normal As an exercise, I am trying to implement metropolis hastings to draw samples from the posterior distribution of a bivariate normal:
$$
(X,Y) \sim N \left( (0,0)\begin{bmatrix}1 & \rho \\ \rho & 1 \end{bmatrix}\right)
$$
to estimate the parameter $\rho$. The setup is as follows:

*

*We have a Jeffreys prior for $\rho$, that is, the distribution of $\rho$ is proportional to $1/(1-\rho^2)^{1/2}$.

*We compute the posterior distribution for $\rho$, and arrive at the fact that:
$$
f(\rho | \{(x_i,y_i)\}_{i=1}^{n}) =\propto \frac{1}{2\pi^2}\frac{1}{{1-\rho^2}} \prod_{i=1}^n\exp\left(\frac{-1}{2(1-\rho^2)}[x_i^2 -2\rho x_iy_i+y_i^2]\right)
$$
We draw samples from a uniform random walk kernel. That is, given an estimate $\rho_m$, we draw an estimate:
$$
\rho^* \sim \mathrm{Unif} (\rho_n-0.1, \rho_n + 0.1)
$$
The acceptance function is thus given by:
$$
\alpha = \min \left(1, \frac{f(\rho^*|\{(x_i,y_i)\}_{i=1}^{n})}{f(\rho_m|\{(x_i,y_i)\}_{i=1}^{n})}\right)
$$
Where $(x_i,y_i)_{i=1}^n$ are samples that have been drawn before running the chain. We start with $\rho_0 = 0.1$.
I have implemented this using the following R code:
gensamples <- function (rho, N){ #Draw correlated normals
      X1 = rnorm(N)
      X2 = rnorm(N)
      X3 = rho*X1 + sqrt(1-rho^2)*X2
      Y1 = X1
      Y2 = X3
      samples = matrix(c(Y1,Y2),nrow = N, ncol=2)
      return (samples)
}

l_ratio <- function(samples,rho,rho_) #Likelihood ratio
  return (
    exp(
    sum(
    -1/(2*(1-rho**2))*(samples[,1]**2-2*rho*samples[,1]*samples[,2]+samples[,2]**2)
  +
    1/(2*(1-rho_**2))*(samples[,1]**2-2*rho_*samples[,1]*samples[,2]+samples[,2]**2)
  )
  )
  )

prior_ratio <- function(rho,rho_)
  return (
    (1/(1-rho**2)**(1/2))
    /
    (1/(1-rho_**2)**(1/2))
          )

posterior_ratio<- function(samples,rho,rho_){ #Use Bayes Formula
  return(l_ratio(samples,rho,rho_)*prior_ratio(rho,rho_))

}

samples = gensamples(rho = 0.2,1000)
burn_in = 10000
iterations = burn_in + 1000
rho_0 = 0.1
rho = rho_0
s = c(0)
for (i in 1:iterations){
  rho_ = runif(1, min = rho -0.1, max = rho+0.1)
  alpha = min(1, 1/posterior_ratio(samples,rho,rho_))
  if (runif(1)<alpha){
    rho = rho_
  }
  if (i >burn_in)
    s = c(s,rho)
}
n = seq_along(s)
m = cumsum(s)/n
m2 = cumsum(s*s)/n
v = (m2 -m*m)*(n/(n-1))
plot(m,type = 'l')
plot(v,type = 'l')

However, it is giving me issues. A quick look at plots tells me the chain converges, but it seems to be very biased. If I use $0.2$, like in the sample above, the usual estimate comes out to about $0.1$-$0.15$. Could anyone let me know if I'm doing something wrong in the calculation?

A: The posterior should be
$$f(\rho | \{(x_i,y_i)\}_{i=1}^{n}) \propto \frac{1}{{(1-\rho^2})^{n+1/2}} \exp\left(\frac{-1}{2(1-\rho^2)}\sum_{i=1}^n[x_i^2 -2\rho x_iy_i+y_i^2]\right)$$
and the part $(1-\rho^2)^{n}$ is missing from the likelihood ratio in the R code.
The proposal being $\mathrm{Unif} (\rho_n-0.1, \rho_n + 0.1)$, there is a positive probability that the simulated value stands outside $(-1,1)$ for values of $\rho_{n}$ close enough to $\pm 1$. The target density in the R code should therefore be set to zero outside $(-1,1)$ to accommodate such entries.
There is thus an issue with the likelihood function as coded since, if I use instead
library(mvtnorm)
l_ratio <- function(samples,rho,rho_)
  return(
   exp(
    sum( dmvnorm(samples,sigma=matrix(c(1,rho,rho,1),2),log=TRUE)) -
      sum( dmvnorm(samples,sigma=matrix(c(1,rho_,rho_,1),2),log=TRUE))
      )
  )

I recover an MCMC sample converging to the generating value of $\rho$. In the R code provided in the question, it should be
l_ratio <- function(samples,rho,rho_) #Likelihood ratio
  return (
          sum(.5*log(abs(1-rho_**2))+
        1/(2*(1-rho**2))*(samples[,1]**2-2*rho*samples[,1]*
                            samples[,2]+samples[,2]**2)
        - .5*log(abs(1-rho**2))-
          1/(2*(1-rho**2))*(samples[,1]**2-2*rho*samples[,1]*
                            samples[,2]+samples[,2]**2)
      )
  )


text:
Q: How do I get the Apple Wireless Keyboard Working in 10.10? So I've gone and bought a Magic Mouse and Apple Wireless Non-Numeric Keyboard.
The magic mouse worked out-of-the-box almost perfectly, except for the forward/back gesture which still isn't functioning, whereas the keyboard didn't.
It has constant trouble with the bluetooth connection. Only the 7, 8 and 9 buttons and volume media keys correspond correctly with the output.
Pressing every single key on keyboard has this output:
789/=456*123-0.+
When I use Blueman the keyboard can be setup and shows up in "Devices" but I get a warning when I click "Setup"; "Device added successfully, but failed to connect" (although removing the keyboard and setting it up as a new device doesn't incur this error).
Using gnome-bluetooth I have encountered no error messages but it connects properly less often than Blueman and I can still only type the aforementioned output.
What am I not doing? Where is this going wrong?
EDIT:
I have read this
http://ubuntuforums.org/showthread.php?t=224673
inside out several times to no avail. It seems these commands don't work for me with the apple peripherals
sudo hidd --search
hcitool scan
Fortunately I have the luxury of a 1TB hard drive, near limitless patience and no job.
I have installed a fresh Ubuntu 10.10 64bit (albeit smaller than mine) and after updating and restarting for the first time, I set up my devices in exactly the same way as I have learnt on my original install
I succeeded once again with the mouse and, to my joy, with the keyboard also. Though I could not seem to find Alt+F2 and had to reconfigure that and several other keyboard shortcuts, the keyboard is working and in a spectacular fashion.
Still, this leaves me with the issue of my original install.
I returned to it with some new found knowledge but failed again.
Perhaps I have a missing dependancy? I did uninstall bluetooth after the initial set up and reinstalled it recently for the pupose of these peripherals.
Maybe it's because I'm running 64bit?
This is still not solved, but easily avoided by not changing too much from the original install.
Just hide stuff or turn it off, don't uninstall too much.

A: OK folks, I went through a lot of pain to get both my Apple Keyboard and Apple Magic Trackpad working on Ubuntu 10.10. I tried several solutions, including the ones mentioned here and others that required editing files that don't exist (e.g. /etc/default/bluetooth), and while some seemed to work at first, none were stable over time. After much trial and error, here is what I did to get both working, automatically reconnecting after restart and/or powering down the devices, with multi-touch capabilities on the trackpad. Getting each of those to work separately was painful enough, and this is how I finally got them all to work at the same time.
For the record, the bluetooth documentation and support for the "new" bluetooth kernel in 10.10 is junk, and the linux, bluetooth, and ubuntu team needs to do a far better job of providing documentation and support if they want people to take their operating system seriously as a consumer product. It should not be this hard, and it should not require trial and error based on informal community suggestions rather than documentation provided by the people who created the software, to do simple things like this.
Note that this is copied from my original post, with attachments, at https://prodigyone.com/in/doc/docs.php?nid=333&view=1

The problems appeared to be a) conflicting bluetooth software and b) a bug in bluez whereby it was not saving link keys in /var/lib/bluetooth.../linkkeys. Workarounds for both are below.

Step 1: Remove all bluetooth software and reboot
1a: Make a copy of your /etc/init.d/bluetooth script. You will need it if you choose option B in step 2 below. If you don't have it, you can use the one attached here
1b: Purge any installed package with the term "blue" in it

sudo apt-get purge bluez blueman gnome-bluetooth bluez-utils

1c: Remove or rename any config files that still remain

mv /var/lib/bluetooth /var/lib/bluetooth.old

1d: Remove any software repositories other than the normal 10.10 repositories (i.e. don't use brian-rogers or other builds)

Step 2- Option A: To connect without auto re-connect
This will allow you to connect without saving the link keys (I am guessing that it's a bluez bug that is failing to write the link keys to /var/lib/bluetooth/.../linkkeys, as the instruction to save the key there is contained in the bluez code). In other words, every time you end your connection, or reboot the computer, you will have to reconnect.

sudo apt-get install bluez blueman

Note that I did not install gnome-bluetooth, bluetooth-compat, bluez-utils, etc. I believe you'll be fine if you install gnome-bluetooth INSTEAD of blueman, but do not install both. It wouldn't work for me if both were installed.
After installation, reboot.

Step 2- Option B: Build bluez and blueman from scratch
This will allow you to connect and to automatically reconnect after reboot or after powering down the devices, which is everything I wanted to do (note that I was unable to get "hcitool putkey" to work-- not sure if that's a bug or a user error-- but it appears that I didn't needed it).

Step 2 Option B: First: Download, unpack, compile and install bluez and blueman from source.
I used the attached source code bluez 4.87 and blueman 1.21

wget xxx.tar.gz (where xxx.tar.gz is the location of the source tarball)
tar zxf xx.tar.gz
cd  to the directory created from above step
./configure
make
sudo make install

During the configure step, pay attention to the output, because it may require installation of other packages. You can install these using the synaptic package manager, or using sudo apt-get install. Just make sure that in doing so, you do not install any package with "blue" anywhere in its name.
Originally, I had thought that I would fix the bluez code that was failing to write the /var/lib/.../linkkeys file. However, it appears to be working in the latest source (4.87 as of today), so I didn't need to fix anything.
Note: I'm not sure it is necessary to install blueman from source. If you can install it without overwriting / undoing your source-build of bluez, I would think that should work fine. But I didn't try that.

Step 2 Option B: Second, configure your system to start bluetoothd automatically
Chown and chmod the script from step 1a, then copy it to /etc/init.d

sudo chown root bluetooth
sudo chmod bluetooth 755
sudo cp bluetooth /etc/init.d

Now link it to each of the startup modes

sudo ln -s /etc/init.d/bluetooth /etc/rc5.d/S25bluetooth
sudo ln -s /etc/init.d/bluetooth /etc/rc0.d/K74bluetooth
sudo ln -s /etc/init.d/bluetooth /etc/rc2.d/S25bluetooth
sudo ln -s /etc/init.d/bluetooth /etc/rc4.d/S25bluetooth
sudo ln -s /etc/init.d/bluetooth /etc/rc6.d/K74bluetooth
sudo ln -s /etc/init.d/bluetooth /etc/rc1.d/K74bluetooth
sudo ln -s /etc/init.d/bluetooth /etc/rc3.d/S25bluetooth

Step 2 Option B: Finally, reboot

Step 3: Configure the keyboard

3a: Prepare to connect
The blueman applet should appear after your installation + reboot. Click on it and leave its window open

3b: Connect
Turn off all bluetooth devices except for your computer. Then hold the power button on the keyboard down for several seconds, until the green light turns off. Wait a moment, and if the green light doesn't start flashing, hit the power button once quickly.
If at any point it says that the keyboard is asking for authorization, choose to always give it permission.
Once you see the keyboard in the blueman window (hit Search if you do not-- this may take a few tries; you basically have to have blueman searching for the keyboard at the same time that the keyboard green light is flashing), click on it and choose pair.
During this time, it may help to hit the Return button a few times on the keyboard. I would advise against hitting other keys, however, as they may mess up the pairing process.
When prompted to pair, type in any 4 or 6 digit pin, hit return, and then do the same on your Apple keyboard. It should say "success". At this point, your keyboard may or may not work, for one of two reasons:
PROBLEM #1: keyboard was connected as a number pad only (e.g. it would type numbers instead of 'j', 'k', etc)
Solution, from How do I get the Apple Wireless Keyboard Working in 10.10?:
Press fn-F6 twice to disable numlock. To switch numlock off permanently after log-in go to System -> Preferences -> Keyboard -> Layout -> Layout Options -> Miscellaneous compatibility options -> turn on "Default numeric keypad keys"
PROBLEM #2: keyboard won't type anything at all, even after it is successfully connected
Solution: restart bluetooth, or, reboot. See below on restarting bluetooth.

3c: confirm that your link key is saved for next time
check that /var/lib/bluetooth/.../linkkeys contains your device with some string of hex values next to it. If it does not, the device will not be recognized after reboot.

Step 4: Configure the magic trackpad

Step 4a: Follow the same steps as step 3, except use a PIN of '0000' (and obviously you won't need to type the matching pin in on the mouse).

Step 4b: multi-touch driver
You should have basic mouse functionality now. To use multi-touch functionality, you need to override the default driver in xorg.conf. This is described in "https://wiki.ubuntu.com/Multitouch/AppleMagicTrackpad#Support on Ubuntu 10.04 (Lucid Lynx)", and I have copied some of the key steps below:

sudo lsinput

note the vendor and product. my Apple trackpad vendor/product is: 0x5ac/0x30e. Then, edit /etc/X11/xorg.conf and add the following to the bottom of it (change the matchUSBID value if your vendor/product is different):

Section "InputClass"
     Identifier "Magic Trackpad"

     MatchUSBID "05ac:030e"

     Driver "synaptics"

EndSection

Step 4c: Reboot the computer so it reloads the xorg settings.

AND THAT'S ALL FOLKS! HOPEFULLY YOU ARE ALL SET NOW!
Below are some instructions for generic bluetooth-related functions:

Generic Bluetooth Functions: Restarting Bluetooth

*

*Easiest option (if your startup scripts are set up)

/etc/init.d/bluetooth start|stop|restart

*Harder option (without scripts):

sudo bluetoothd --udev
  not sure what the udev does, but that's what the default install does
  killall bluetoothd

*If all else fails, reboot

Generic Bluetooth Functions: using hciconfig and hcitool

*

*hciconfig --help

*hcitool --help

A: I managed to make this work, by updating bluez to a newer version found in Brian Rogers repository.
add-apt-repository ppa:brian-rogers/ppa
apt-get update
apt-get install bluez

After this it paired at first time, however it looked like there ware multiple keypresses. After a reboot, it is working flawlessly.

A: http://ubuntuforums.org/showpost.php?p=9842686&postcount=98

Press fn-F6 twice to disable numlock. To switch numlock off permanently after log-in go to System -> Preferences -> Keyboard -> Layout -> Layout Options -> Miscellaneous compatibility options -> turn on "Default numeric keypad keys"

For those of you still looking... I had this same problem. Here is the solution!

A: solution for your problem is here: http://ubuntuforums.org/showthread.php?t=224673 (probably near last posts where people write about latest model apple keyboards )


text:
Q: Bash extended globbing brackets break array initalization I used the statement echo *([!min]).css to get all filenames in the current directory with the .css extension, except for the ones with .min.css extension. That worked on the bash.
However, when I use this to initialize an array in a bash script like that
files=(*([!min]).css)

it doesn't work anymore. Bash says there is an unexpected opening bracket somewhere. My editor's syntax highlighting also looks like the brackets of the glob inside the array initialization are not correct, however I wasn't able to get it right.
Any advice? Thanks.
EDIT: I use GNU Bash 4.3.033 on ArchLinux.

A: To use extended globs, you must enable the extglob shell option. Put it at the start of your script, just below the shebang:
#!/usr/bin/env bash
shopt -s extglob
#...
files=( !(*.min).css )
#...

Note that shell options are not inherited, so even though you may have extglob enabled in the interactive bash you run the script from, you still have to explicitly enable it in the script.


text:
Q: Multiprocessing a python function that contains a for loop So I have a script that converts XML files to CSV, this script has a function that contains nested loops, juste 2 loop to be precise :
FichList = [ f for f in os.listdir(FilenamePath) ]

def SplitFichierR50 (l_FichList):
    for filename in FichList:
            if filename.count(".xml") ==1:
                    print(filename)
                    tree = etree.parse(FilenamePath+"/"+filename)
                    for mes in tree.xpath("/R50/PRM/Donnees_Releve"):
                            l_ID_PRM =mes.getparent()[0]
                            EN_TETE=mes.getparent().getparent()[0]
                            l_ID_FLUX = EN_TETE[0]
                            l_LIB_FLUX = EN_TETE[1]
                            .
                            .
                            .

Etc... until having all the XML data and writing it in the CSV file, this script works fine, but I have to optimize the execution of it to make it work faster, so I used the multiprocessing module adding this to the script :
if __name__ == '__main__':
  jobs = []
  for i in range(10): # I want to use 10 CPUs
  p = multiprocessing.Process(target=SplitFichierR50,args=(FichList,))
  jobs.append(p)
  p.start()

It does execute the script on 10 CPUs but it does the same thing 10 times for the same file.

Here in the screenshot I used just 3 CPU but we can see that it's the same file 3 times.
I want to execute each iteraion of the loop on a different CPU.
Please help !!

A: This is hard for me to independently test but it appears that you have a bug. First off, your SplitFichierR50 function takes in a list l_FichList but it isn't used in the function. In fact, every single one of the processes is simply going to go through every file in FichList. That is why you are seeing so many duplicate file processing messages. You need to partition out the filenames in FichList so that each process is handling a different set of files.
For example, something like this:
if __name__ == '__main__':
    jobs = []
    num_processes = 10
    step = int(math.ceil(float(len(FichList))/float(num_processes)))
    for i in range(0, len(FichList), step):
        p = multiprocessing.Process(target=SplitFichierR50,args=(FichList[i:i+step],))
        jobs.append(p)
        p.start()

Make sure to import math and to correct the SplitFichierR50 function to use the passed in list.


text:
Q: Setting nosignal option for CURL command line? From the libcurl documentation, I understand NOSIGNAL has to be set to 1 when using multi-thread program.
However, if I am calling curl from a command line, I don't see a NOSIGNAL switch/option. How do I set nosignal when calling curl directly?

A: You can't: as you said, there is no such option documented by cURL help (and you can also verify that there is no reference to CURLOPT_NOSIGNAL within the command-line source code - see src/tool_operate.c).
Now the question is why you would need this, as asked by Celada. Using libcurl in a multi-threaded context makes sense (i.e. you may want to create/reuse curl handles from several threads) - and you should then follow the best practices, but I don't see the point with the CLI tool.


text:
Q: How to check if a user is logged in. Angular 12.1.2 My backend sets a JWT after successful register/login, however what will be the most efficient way to check if a user is logged in? Check if the user has the signed cookie?

A: This is more of a logic not tied to Angular. You can store your JWT token in local storage and create a GET request that requires the same token to be passed to return the user profile for example. Throw an error if the service receives no/invalid token. You can call this service at the component CanActivate level.
As a security recommendation, make sure to pass the token in a custom header to protect your app from CSRF attacks.


text:
Q: Exception raised when try to run web application using postgres database when I run start.bat file of tomcat on linux with postgres database. It gives following error after changed in postgres_hba.conf file.
           C3P0PooledConnectionPoolManager[identityToken->2u13c99u1fd86im176rze7|779becbd]-HelperThread-#1--WARN -com.mchange.v2.resourcepool.BasicResourcePool:com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@1de8b573 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:

org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections

A: The error message is fairly clear. You have tried to open more database connections than you have configured in postgresql.conf. Even the shortest search of your logs and the manuals would have made this clear.


text:
Q: How to install an unavailable document class for LyX on Mac I am new to LyX so I'm sorry if this question is really naive.
I'm using LyX on a MacBook and I'm hoping to use the AEA document class on it. Since it is not available automatically, seems that I need to somehow install it on my own. All the help pages I can find talks about layouts and stuff that I, as total layman, have no idea what they are. Can somebody please show me how I can do it with simple language?

A: I was struggling with this myself, until I came across this article. I had to make a few adaptations for my setup as follows (for the purposes of this post, the unavailable document class I wanted to install was called clv2, for which I had a clv2.cls file):
Step 0:
This was not mentioned in the article, nor do I know if it's absolutely necessary, but I quit LyX before I started this process.
Step 1:

Copy the clv2.cls file in your latex directory. To find where it is go to LyX > Tools > TeX Information > LaTeX Classes > Show path. For me it was /Users/sylvie/Library/texmf/tex/latex/lyx/.

When I did LyX > Tools > TeX Information > LaTeX Classes > Show path, I saw /usr/local/texlive/2011/texmf-dist/tex/latex
There was no lyx directory there, so I had to create one for myself. Then I copied clv2.cls into /usr/local/texlive/2011/texmf-dist/tex/latex
Step 2:

Make a .layout file with the same name (clv2.layout)

This was very straightforward. I wanted an article (not a manuscript) though, so my layout file looked like this:
#% Do not delete the line below; configure depends on this
# \DeclareLaTeXClass[clv2]{article (clv2)}
# Input general definitions
Input stdclass.inc

Step 3:

Copy the clv2.layout file into your package content. For me it was Applications > LyX > Contents > Resources > layouts > clv2.layout

My package content was located at /Users/ashwin/Library/Application Support/LyX-2.0/layouts, so that's where I copied clv.layout to
Step 4:

Open a terminal and on the command prompt write sudo texhash (LaTeX will be reconfigured)

This was very straightforward. I was asked for my password, which is normal.
Step 5:

Open LyX, and then go to LyX > Reconfigure, and Restart Lyx

Again, this was very straightforward. No hitches here.
Step 6:

Go to Document > Settings > Document Class > manuscript (clv2)

Since I wanted an article and therefore changed clv2.layout, I found an article (clv2) in my list of document classes.
Hope this helps

A: This seems to work for me:

*

*Install full version of MacTeX

*Run sudo texhash in terminal.

*Click LyX->Tools->Reconfigure

This enabled most of the unavailable articles which are already downloaded by MacTeX itself.

A: I found the 6 step answer above to be very helpful. I did have a few hiccups related to the way Mac likes to try to be smarter than the user, so I thought I'd share in case others are having similar troubles. I tend to be pretty computer dense, so maybe this will be helpful for others who struggle.

*

*Most of the folders needed for these operations are hidden by Apple, so you won't find them just by clicking around. I found the LaTeX path as described in step 1 and then actually FOUND that folder on my mac by using Go > Go to Folder in the Finder and searching for the first folder, which for me was /usr. To find the LyX layout folder (step 3), searching for the whole path was the ticket.

*The other tricky part was making the layout files in the right format. I used mac's default simple text editor TextEdit, but again, it tried to outsmart me. It automatically saves as a .rtf file, even if you name it classname.layout. Because Mac hides extensions, you might not even notice. This is why I made my mac show all extensions. Also, you can't just change the .rtf extension to .layout because .rtf has formatting information in there that will mess things up. So in TextEdit go to Format > Save as Plain Text and it will save it as a .txt file. Then you can change the extension to .layout. If you haven't made mac show extensions, you'll have to do this by right clicking on the file and selecting "Get Info" and changing the name and extension within that.
I know this is all pretty basic, but some of us (me!) need that level of instruction. Hope it helps.


text:
Q: Can't add lines to my table despite the good formatting Json (DataTables) I want to fill a table (DataTables) with an AJax request
My request ajax returns Json but impossible to fill the table, I have this error:
DataTables warning: table id=dt-table - Requested unknown parameter '0' for row 1, column 0. For more information about this error, please see http://datatables.net/tn/4
My table:

            Invoice

My JS:
var table = $('#dt-table').DataTable({});

$(document).on("click", ".button", function() {

    var inputVal = $(this).text();
    var selectVal = $('#select option:selected').val();

    $.post("/ajax/invoice.php", {find: inputVal, column: selectVal}).done(function(data){
      console.log(data)
      table.rows.add(data).draw();
    });

});

The ajax response:
[{"invoice":"AZERT"},{"invoice":"JFKDH"},{"invoice":"DKHFVEP"}]

My request:
$column = $_POST['column'];

    $request = $bdd->prepare("SELECT invoice from table_master WHERE $column = :find");
    $request->execute(array(
      ':find' => $_POST['find']
      ));

    $result = $request->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($result);

I do not see where the problem comes from, I look at the DataTables documentation and my json is normally properly formatted
https://datatables.net/reference/api/rows.add()

A: You need to define taht you're gonna use invoice parameter as your column source like :
var table = $('#dt-table').DataTable({"columns":[{ "data": "invoice"}]});

A: I'm not familiar with php but I ran into the same issue when I was trying to update some cells on a row click from a modal popup. I ended up setting the datatable properties inside of my post callback. I also had to destroy my table prior to recreating it. Here's my LoadData function callback:
         .done(function (result) {
                if (result.isError) {
                    window.location.href = result.newUrl;
                }
                else {
                    var html = '';
                    $('#searchTable').dataTable().fnDestroy();
                    $('#searchTableBody').empty();

                    if (result.TransactionDetails.lenght == 0) {
                        html += '
No Records Found
';
                    }
                    else {

                        $.each(result.TransactionDetails, function (i, item) {

                            html += '
' + item.x + '	' + item.y + '	' + item.z + '	' + item.a + '	' + item.b + '	' + item.c + '	' + item.d + '	<input type="button" data-toggle="modal" data-target="#detailsModal" class="table-btn" id="btnViewDetails" value="View Details" /><input type="button" id="btnEditAmt" data-toggle="modal" class="table-btn" data-target="#amtModal" value="Edit Amount" />
';
                        });
                    }
                    $('#searchTableBody').append(html);

                    var table = $('#searchTable').DataTable({
                        searching: false,
                        paging: true,
                        columnDefs: [
                            {
                                "targets": [0],
                                "visible": false,
                                "searchable": false
                            },
                            {
                                "targets": [1],
                                "visible": true,
                                "searchable": true
                            },
                            {
                                "targets": [7],
                                "orderable": false
                            }
                        ]
                    })

                    $('#searchTable').show();
                    $('#loaderLoadData').fadeOut();
                }

        })

It only worked via the Api calls. fnDestroy() is key. Make sure you destroy it before recreating it. Also notice I set the DataTable properties inside of the done function.


text:
Q: How to redirect to a specific tab using Laravel I am using the Laravel application for my project where I have 3 different tabs in a view.
The tabs on view file-
tab1
tab2
tab3

Now, I have a form and I want to redirect to a specific tab after submitting it.
In Controller, I am returning like this-
 return redirect()->route('home')->with('message','sucessfull');

Now, I don't know how to redirect to a specific tab. Can you please help me to know it?

A: To redirect to a specific tab, you have to use URL hash.
For Tab 1-
return redirect(route('home').'#tab1')->with('message','sucessfull');

For Tab 2-
return redirect(route('home').'#tab2')->with('message','sucessfull');


text:
Q: Error when trying to create an envelope using Microsoft Flow - probably a timeout We've been creating DocuSign envelopes via Microsoft Flow using the REST API. Today, we started to get an error "Http request failed: the timeout was reached.". Microsoft Flow retried 4 times, but with the same response. The timeout seems to be 2 minutes.
Looking at the DocuSign logs, it looks like it only received some of the first file before timing out. The BadRequest log indicates that the body is improperly formatted. I can see that only some of the Base64 encoding of the first document appears in the log.
I then tried submitting the same data via Postman. It succeeded within 57 seconds. Is there any reason why a submission from Microsoft Flow (or some other system) would be so much slower?
Request:

*

*URI: https://demo.docusign.net/restapi/v2/accounts/xxxxxx/envelopes

*Method: POST

*X-Docusign-Authentication: (username, password, integrator key)

*Content-Type: application/json

*Body:

{
    "documents": [
        {
            "documentId": "538",
            "name": "My Document Name",
            "fileExtension": ".docx",
            "documentBase64": "xxxxx",
            "transformPdfFields": true
        },
        {
            "documentId": "537",
            "name": "Another Document",
            "fileExtension": ".docx",
            "documentBase64": "xxxx",
            "transformPdfFields": true
        }
    ],
    "status": "Sent",
    "emailSubject": "xxxx",
    "recipients": {
        "signers": [
            {
                "recipientId": "1",
                "clientUserId": "1002457",
                "email": "lmckenzie@petstock.com.au",
                "name": " Ford",
                ".5routingOrder": "1",
                "tabs": {...
                }
            }
        ]
    },
    "eventNotification": {
        "includeDocumentFields": "false",
        "envelopeEvents": [
            {
                "envelopeEventStatusCode": "Completed"
            },
            {
                "envelopeEventStatusCode": "Declined"
            },
            {
                "envelopeEventStatusCode": "Voided"
            },
            {
                "envelopeEventStatusCode": "Sent"
            }
        ],
        "url": "https://xxx",
        "requireAcknowledgment": "false",
        "includeSenderAccountAsCustomField": "true",
        "loggingEnabled": "true",
        "includeDocuments": "false",
        "signMessageWithX509Cert": "true"
    }
}

Response:

Duration: 2m
Start time: 2018-05-23T05:01:02.2710043Z
End time: 2018-05-23T05:03:02.384625Z
Status: BadRequest
Client request ID: c3cef685-7c70-41d0-8cbd-67237b56a7f1
Error: {
    "error": {
        "code": "BadRequest",
        "message": "Http request failed: the timeout was reached."
    }
}


text:
Q: Updating elements of an external JSON file upon addition of data to page I have three files 1)index.html 2)data.json 3)app.js loaded on WAMP server I wanted to add data from my JSON file into a table on the HTML file which I was able to do. The functionality I also need is to update the JSON file as i update the HTML table(using ADD, SAVE and DELETE buttons) and save this table data to the external JSON file.
Here are my code snippets:
1) data.json:
{"user":[{"goal":"HTML essential training","type":"Beginner", "date":"20/07/2016"},{"goal":"CSS essential training","type":"Beginner", "date":"30/07/2016"},{"goal":"CSS core concepts","type":"Intermediate", "date":"10/08/2016"},{"goal":"Javascript essential training","type":"Beginner", "date":"20/08/2016"},{"goal":"Object Oriented JS","type":"Advanced", "date":"30/08/2016"}]}

2) app.js
  var request= new XMLHttpRequest();
         request.open('GET', 'data.json');
         request.onreadystatechange=function(){
          if((request.readyState===4)&&(request.status===200)){
              items=JSON.parse(request.responseText);
              console.log(items);

              for(var key in items){if (items.hasOwnProperty(key)) {
                    for (var i in items[key]) {if (items[key].hasOwnProperty(i)){
                        console.log(items[key][i]);
                        var output="
<input type='checkbox' name='record'>	" + items[key][i].goal + "	" + items[key][i].type +  "	" + items[key][i].date + "
";
                        console.log(output);
                        $("table tbody").append(output);
                        output='';
                    }}
                }}

        }
      }

request.send();  $('.save_button').click( function() {

                var table = $('#goal_table').tableToJSON({ignoreColumns:[0]});
                // Convert the table into a javascript object
                console.log(table);
                alert(JSON.stringify(table));

 for(var key in items){if (items.hasOwnProperty(key)) {
                    for (var i in items[key]) {if (items[key].hasOwnProperty(i)){
                        console.log(items[key][i]);
                        delete items[key][i];
                    }}
                }}

 console.log("items after deleting");
 items[key].length=0;
 console.log(items[key]);

 for(var key in table){if (table.hasOwnProperty(key)) {
                    for (var i in table[key]) {if (table[key].hasOwnProperty(i)){
                        console.log(table[key][i]);
                        items.push(table[key][i]);
                    }}
                }}
});

I don't understand how to accomplish this and seem to have encountered a road block. I'm a beginner to JS and JSON and the above code snippets were what i could manage. Please help!


text:
Q: A border between div and footer I have a problem, I have an empty div, taking 100% of the screen, and a footer.
A border is appearing between them (it's a part of the body, so I guess there is some space between the both divs).

The css is :
body {
    height: 100%;
    width: 100%;
    margin: 0 auto;
    padding: 0 auto;
}

body {
    background-color: #292a2b;
}

.emptydiv {
    width: 100%;
    height: 100%;
    background-color: black;
    margin-top: 50px;
}

h1 {
    /*editing h1 just to add margin on the top; in this way the navbar won't hide it!*/
    text-align: center;
    color: white;
}
/* footer*/
#githublogo,
#instagram-logo {
    width: 50px;
    height: 50px;
}

footer {
    background-color: rgb(0, 0, 0);
    color: white;
    margin : 0;
    padding: 0;
}

footer a {
    text-decoration: underline;
}

I tried to add padding 0 and margin 0 to both div, didn't work, what should I try ? THanks !


text:
Q: What is the alternative solution if node response not have json array name My JSON RESULT

This is my JSON output. Here array name not available

[{"item":"WATER"},{"item":"DFG"},{"item":"2InchPipe"},{"item":"5InchPipe"}]
Android Code

But I want to display the item in the android spinner. I was used volley method for getting all item from JSON.

 RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
    StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
           String getitem=
            try{
                JSONObject jsonObject=new JSONObject(response);

                    JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");
                    for(int i=0;i<jsonArray.length();i++){
                        JSONObject jsonObject1=jsonArray.getJSONObject(i);
                        String country=jsonObject1.getString("Item");
                        CountryName.add(country);
                    }

                spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
            }catch (JSONException e){e.printStackTrace();}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    requestQueue.add(stringRequest);

I have doubt in this line
JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");

Finally i got a solution using following code
  JsonArrayRequest requestQueue = new JsonArrayRequest(URL,
  new Response.Listener<JSONArray>() {
  @Override
  public void onResponse(JSONArray response) {
  for (int i = 0; i < response.length(); i++) {
  try {
  JSONObject obj = response.getJSONObject(i);
  String country = obj.getString("item");
  CountryName.add(country);
  spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,
  android.R.layout.simple_spinner_dropdown_item, CountryName));
  }
  catch (JSONException e) {
  e.printStackTrace();
  }
  }
  }
  }, new Response.ErrorListener() {
  @Override
  public void onErrorResponse(VolleyError error) {
  }
  });
  }
   MySingleton.getmInstance(MainActivity.this).addToRequestQue(requestQueue );

A: You can direct pass you output in Array:
JSONArray jsonArray=new JSONArray (response);
 for(int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject1=jsonArray.getJSONObject(i);
                    String country=jsonObject1.getString("Item");
                    CountryName.add(country);
                }


text:
Q: Possible Values of # of Ordered Factorization of Integers I was trying to find the number of ordered factorizations of integers into parts $\gt 1$. Starting with $0$, the number of ordered factorizations of $n$ forms this sequence. Interestingly, and in accordance with my program, the values seem to repeat themselves infinitely. While some values repeat, others don't appear at all. It seems that the sequence of possible values of the number of ordered factorizations of an integer appears here, forming the sequence: $$1, 2, 3, 4, 8, 13, 16, 20, 26, 32, 44, 48...$$
In this OEIS entry, they are named "Gozinta numbers". It's not surprising to see that these values solely depend on the exponents of the prime factors of $n$. In this paper, $H(n)$ counts the number of such ordered factorizations, closed-form formula as well as recurrence are given:
$$H(n) = \sum_{j=1}^q \sum_{i=0}^{j-1} (-1)^i \binom {j}{i} \prod_{b=1}^k \binom {r_b +j - i - 1}{r_b} = \sum_{d|n}H(d) , H(1) = 1$$
with $q = \sum_{i=1}^k r_i$, and $n = p_1^{r_1}p_2^{r_1}p_3^{r_3}...p_k^{r_k}$
Can someone shed light on how the sequence of possible values of $H(n)$ is generated? How can I generate these values myself, perhaps using the formulas I mentioned or any other way.

A: The first thing to say is $$\sum_n H(n)n^{-s}=\sum_{k\ge 0} (\zeta(s)-1)^k= \frac1{2-\zeta(s)}$$
$H(n)$ is the Dirichlet inverse of $2_{n=1}-1$.
$\frac{\zeta(s)}{2-\zeta(s)}=2\frac1{2-\zeta(s)}-1$ gives that
$$\sum_{d| n} H(d)=2 H(n)-1_{n=1}$$
The Tauberian theorem gives that $$\sum_{n\le x} H(n) \sim \frac{x^r}{-\zeta'(r) r}$$ where $r>1$ is the unique solution of $\zeta(r)=2$.
About your question of enumerating in increasing order the elements of $H(\Bbb{N})$ : There is a natural preorder on the exponents of integers, ie. on the sequence $e$ of non-negative integers such that $n=\prod_j p_j^{e_j}$:
$e\ge e'$ if there is a permutation of the primes such that $e_j-e'_{\sigma(j)} \ge 0$ for all $j$. The class of $e$ is obtained by taking a permutation of the primes such that $e_\sigma$ is decreasing.
Then $e\ge e'\implies H(\prod_j p_j^{e_j})\ge H(\prod_j p_j^{e_j'})$.
Given $e$ you can enumerate all the $H(n)$ such that $H(n)<H(e)$: find $k$ such that $H(2^k)>H(n)$, find $J$ such that $H(\prod_{j\le J} p_j)>H(n)$, then enumerate the classes such that $\sum_j e_j' < \max(k,J)$.


text:
Q: clamav installation with pcre in Amazon Linux When we install ClamAV in our Amazon Linux ElasticBeanstalk instance with yum install clamav it gets installed without PCRE support, although the libraries are present in the instance.
LibClamAV Warning: cli_loadldb: logical signature for Win.Trojan.ssid18332-1
uses PCREs but support is disabled, skipping
LibClamAV Warning: cli_loadldb: logical signature for Win.Ransomware.Locky-4
uses PCREs but support is disabled, skipping
LibClamAV Warning: cli_loadldb: logical signature for Html.Exploit.CVE_2016_0184-1
uses PCREs but support is disabled, skipping

However PCRE is installed in the machine:
# yum install pcre
...
Package pcre-8.21-7.7.amzn1.x86_64 already installed and latest version
Nothing to do

Scanning is also very slow.
How can I force ClamAV to use/recognize the installed PCRE libraries in my Elastic Beanstalk machine?
Thanks!


text:
Q: Scala: convert map to case class Let's say I have this example case class
case class Test(key1: Int, key2: String, key3: String)

And I have a map
myMap = Map("k1" -> 1, "k2" -> "val2", "k3" -> "val3")

I need to convert this map to my case class in several places of the code, something like this:
myMap.asInstanceOf[Test]

What would be the easiest way of doing that? Can I somehow use implicit for this?

A: Jonathan Chow implements a Scala macro (designed for Scala 2.11) that generalizes this behavior and eliminates the boilerplate.
http://blog.echo.sh/post/65955606729/exploring-scala-macros-map-to-case-class-conversion
import scala.reflect.macros.Context

trait Mappable[T] {
  def toMap(t: T): Map[String, Any]
  def fromMap(map: Map[String, Any]): T
}

object Mappable {
  implicit def materializeMappable[T]: Mappable[T] = macro materializeMappableImpl[T]

  def materializeMappableImpl[T: c.WeakTypeTag](c: Context): c.Expr[Mappable[T]] = {
    import c.universe._
    val tpe = weakTypeOf[T]
    val companion = tpe.typeSymbol.companionSymbol

    val fields = tpe.declarations.collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor ⇒ m
    }.get.paramss.head

    val (toMapParams, fromMapParams) = fields.map { field ⇒
      val name = field.name
      val decoded = name.decoded
      val returnType = tpe.declaration(name).typeSignature

      (q"$decoded → t.$name", q"map($decoded).asInstanceOf[$returnType]")
    }.unzip

    c.Expr[Mappable[T]] { q"""
      new Mappable[$tpe] {
        def toMap(t: $tpe): Map[String, Any] = Map(..$toMapParams)
        def fromMap(map: Map[String, Any]): $tpe = $companion(..$fromMapParams)
      }
    """ }
  }
}

A: This works well for me,if you use jackson for scala:
def from[T](map: Map[String, Any])(implicit m: Manifest[T]): T = {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.convertValue(map)
}

Reference from:Convert a Map<String, String> to a POJO

A: Two ways of doing this elegantly. The first is to use an unapply, the second to use an implicit class (2.10+) with a type class to do the conversion for you.
1) The unapply is the simplest and most straight forward way to write such a conversion. It does not do any "magic" and can readily be found if using an IDE. Do note, doing this sort of thing can clutter your companion object and cause your code to sprout dependencies in places you might not want:
object MyClass{
  def unapply(values: Map[String,String]) = try{
    Some(MyClass(values("key").toInteger, values("next").toFloat))
  } catch{
    case NonFatal(ex) => None
  }
}

Which could be used like this:
val MyClass(myInstance) = myMap

be careful, as it would throw an exception if not matched completely.
2) Doing an implicit class with a type class creates more boilerplate for you but also allows a lot of room to expand the same pattern to apply to other case classes:
implicit class Map2Class(values: Map[String,String]){
  def convert[A](implicit mapper: MapConvert[A]) = mapper conv (values)
}

trait MapConvert[A]{
  def conv(values: Map[String,String]): A
}

and as an example you'd do something like this:
object MyObject{
  implicit val new MapConvert[MyObject]{
    def conv(values: Map[String, String]) = MyObject(values("key").toInt, values("foo").toFloat)
  }
}

which could then be used just as you had described above:
val myInstance = myMap.convert[MyObject]

throwing an exception if no conversion could be made. Using this pattern converting between a Map[String, String] to any object would require just another implicit (and that implicit to be in scope.)

A: I don't love this code, but I suppose this is possible if you can get the map values into a tuple and then use the tupled constructor for your case class.  That would look something like this:
val myMap = Map("k1" -> 1, "k2" -> "val2", "k3" -> "val3")
val params = Some(myMap.map(_._2).toList).flatMap{
  case List(a:Int,b:String,c:String) => Some((a,b,c))
  case other => None
}
val myCaseClass = params.map(Test.tupled(_))
println(myCaseClass)

You have to be careful to make sure the list of values is exactly 3 elements and that they are the correct types.  If not, you end up with a None instead.  Like I said, not great, but it shows that it is possible.

A: Here is an alternative non-boilerplate method that uses Scala reflection (Scala 2.10 and above) and doesn't require a separately compiled module:
import org.specs2.mutable.Specification
import scala.reflect._
import scala.reflect.runtime.universe._

case class Test(t: String, ot: Option[String])

package object ccFromMap {
  def fromMap[T: TypeTag: ClassTag](m: Map[String,_]) = {
    val rm = runtimeMirror(classTag[T].runtimeClass.getClassLoader)
    val classTest = typeOf[T].typeSymbol.asClass
    val classMirror = rm.reflectClass(classTest)
    val constructor = typeOf[T].decl(termNames.CONSTRUCTOR).asMethod
    val constructorMirror = classMirror.reflectConstructor(constructor)

    val constructorArgs = constructor.paramLists.flatten.map( (param: Symbol) => {
      val paramName = param.name.toString
      if(param.typeSignature <:< typeOf[Option[Any]])
        m.get(paramName)
      else
        m.get(paramName).getOrElse(throw new IllegalArgumentException("Map is missing required parameter named " + paramName))
    })

    constructorMirror(constructorArgs:_*).asInstanceOf[T]
  }
}

class CaseClassFromMapSpec extends Specification {
  "case class" should {
    "be constructable from a Map" in {
      import ccFromMap._
      fromMap[Test](Map("t" -> "test", "ot" -> "test2")) === Test("test", Some("test2"))
      fromMap[Test](Map("t" -> "test")) === Test("test", None)
    }
  }
}

A: Here's an update to Jonathon's answer for Scala 3 (which no longer has TypeTag). Be aware that this won't work for case classes nested inside of other classes. But for top-level case classes it seems to work fine.
import scala.reflect.ClassTag

object Reflect:

  def fromMap[T <: Product : ClassTag](m: Map[String, ?]): T =

    val classTag = implicitly[ClassTag[T]]
    val constructor = classTag.runtimeClass.getDeclaredConstructors.head
    val constructorArgs = constructor.getParameters()
      .map { param =>
        val paramName = param.getName
        if (param.getType == classOf[Option[_]])
          m.get(paramName)
        else
          m.get(paramName)
            .getOrElse(throw new IllegalArgumentException(s"Missing required parameter: $paramName"))
      }
    constructor.newInstance(constructorArgs: _*).asInstanceOf[T]

And a test for the above:
case class Foo(a: String, b: Int, c: Option[String] = None)
case class Bar(a: String, b: Int, c: Option[Foo])

class ReflectSuite extends munit.FunSuite:

  test("fromMap") {

    val m = Map("a" -> "hello", "b" -> 42, "c" -> "world")
    val foo = Reflect.fromMap[Foo](m)
    assertEquals(foo, Foo("hello", 42, Some("world")))

    val n = Map("a" -> "hello", "b" -> 43)
    val foo2 = Reflect.fromMap[Foo](n)
    assertEquals(foo2, Foo("hello", 43))

    val o = Map("a" -> "yo", "b" -> 44, "c" -> foo)
    val bar = Reflect.fromMap[Bar](o)
    assertEquals(bar, Bar("yo", 44, Some(foo)))
  }

  test("fromMap should fail when required parameter is missing") {
    val m = Map("a" -> "hello", "c" -> "world")
    intercept[java.lang.IllegalArgumentException] {
      Reflect.fromMap[Foo](m)
    }
  }

A: commons.mapper.Mappers.mapToBean[CaseClassBean](map)

Details: https://github.com/hank-whu/common4s


text:
Q: Creating Email Application with Rails and Sendgrid I'm currently trying to create an email application using Rails and Sendgrid. This application should have the basic features of sending emails. Does anyone know how to do so?

A: Unless you are constrained to using your own server, I suggest starting with Heroku's SendGrid Package. It's free and fairly easy to setup and get started. Here's the Getting Started Guide.
After you setup sendgrid, you use ActionMailer as you normally would.


text:
Q: Calculations inside html using javascript I'm trying to multiply the "quantity" inputted by the user by 1 item chosen from a dropdown list (the prices of the items must be saved in an array). Also, when the user chooses a different item a picture on the right changes. I'm having a problem making the quantity*item function since I'm a total beginner in JavaScript/HTML. Please no jQuery code, purely JavaScript/HTML. Below is a piece of the code. Anyone can help me fix it please? Thanks.
JavaScript:
function swapImage(dropdown){
    var value= dropdown.options[dropdown.selectedIndex].value;
    var edit_save = document.getElementById("imageToSwap");
    edit_save.src = value;
    alert(value);
}

var priceList = new Array(4);
pricelist[0]=10;
pricelist[1]=12;
pricelist[2]=14;
pricelist[3]=11;

function calculateTotal(dropdown){
    var total=priceList[dropdown.selectedIndex]*number;
}

HTML:

<select id="dlist" onchange="swapImage(this)">
    <option value=gnar.png>Gnar Hoodie €10</option>
    <option value=blitz.png>Blitz T-Shirt €12</option>
    <option value=corki.png>Corki Hoodie €14</option>
    <option value=graves.png>Graves T-Shirt €11</option>
</select>

Quantity of the item
<input type="number" name="Quantity" min="1" required="">

Total Price:

A: I made a http://jsfiddle.net/p5rmpjet/7/. I changed it up a bit so the prices are stored in your ids in your html instead of adding them to your JS every time you have a new item.
function swapImage(e){
   var image = document.getElementById("imageToSwap");
   console.log(image);  //image tag
   image.src = e.value;
}

function updatePrice(quantity){
   var edit_save = document.getElementById("dlist");
   console.log(edit_save.options[ edit_save.selectedIndex].id); //price of item

   var quantity = document.getElementById("quantity").value;
   console.log(quantity);

   var price = edit_save.options[edit_save.selectedIndex].id;

   var total = quantity * price;
   console.log(total);
   document.getElementById("totalprice").innerHTML = total;
 }

 function updateItem(price){
    var price = edit_save.options[edit_save.selectedIndex].id;
 }

NOTE: Updated fiddle with a second function on the onchange event for selecting items http://jsfiddle.net/p5rmpjet/7/


text:
Q: Get next SharePoint ID in a list using JQuery Hello and thanks in advance for the help.
I Have a list with 2 columns, Title and IntakeID. I'm attempting to get the next ID in the SharePoint list and input it to the IntakeID field in the newform.aspx.
I have been successful with my script with the exception that each time I add a new item, each item ID is appended.
For example:
Last Item ID added in list = 6
Add New item the 1st time: value =7
Add New item 2nd time: value = 78
Add New item 3rd time: value = 789
Add New item 4th time: value = 78910
Any help would be greatly appreciated. Thanks!
All I want to return is just the next ID which is 7 in this example.
<script src="http://MYSharePoint.com/sites/TestSite/SiteAssets/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        ExecuteOrDelayUntilScriptLoaded(GetListItemId, "sp.js");
    });

    function GetListItemId() {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        var list = web.get_lists().getByTitle('Separation Intake Form');
        var query = SP.CamlQuery.createAllItemsQuery();
        allItems = list.getItems(query);
        context.load(allItems);
        context.executeQueryAsync(Function.createDelegate(this, this.successGetListItemId));
     }

     function successGetListItemId() {
         var TextField = "";
         var ListEnumerator = this.allItems.getEnumerator();
         while (ListEnumerator.moveNext()) {
             var currentItem = ListEnumerator.get_current();
             TextField += currentItem.get_item('ID');
         }
         alert("Adam Testing next ID: " + TextField);
         $("input[title='IntakeID']").val(TextField);
         $("input[title='IntakeID']").attr("readonly","true").css('background-color','#F6F6F6');
     }
</script>

A: In your loop under successGetListItemId(), you're looping through all items in the list and appending ID to the string, which is why you're ending up with: 78910.
Simplest way to fix this is by changing this line to set rather than append:
TextField = currentItem.get_item('ID');

Assuming they are ordered right, you'll end up with the last used id.
That said, the above is not very efficient. If there are 5k items in the list, all 5k are returned. Not to mention that if you hit 5,001+, you'll run into the SP list item limit.
To be more efficient, adjust the CAML query to order the list descending based on ID, then return the top 1 item:
var query = new SP.CamlQuery();
query.set_viewXml('<View Scope="Recursive"><Query><OrderBy><FieldRef Name="ID" Ascending="FALSE" /></OrderBy></Query><RowLimit>1</RowLimit></View>');

Code in successGetListItemId() should work just fine at this point.


text:
Q: All terminals in i3 WM share the same input I am trying out i3 tiling window manager on Ubuntu 20.04.
All terminals started with $mod+Enter share the same input: i.e. if I type something on one terminal, the same gets printed on another. This is not an expected behavoir :)
What's strange, if I start terminator with $mod+d, I do not see terminator in pstree output, and resulting terminal behaves the same. Turns out they are all terminators - seeing this by terminator-specific interface.
Used just sudo apt-get install i3 to install i3.
$ i3 --version
i3 version 4.17.1 (2019-08-30) © 2009 Michael Stapelberg and contributors

How can I get them working separately without echoing input on all of the terminals?


text:
Q: Java Graph (Structure) Deep copy Well, I have some class (Vertex), that contains HashSet in it; and at some point, I need to deep copy that element;
I wrote some code, but sometimes it doesn't work; I'm working on this bug for several days and can't fix it... If anybody has enough time to read the code and find it, I'll be very grateful. Thank you in advance.
Well, here is function:
public Vertex getCopy(Vertex copyFrom, Vertex copyTo, HashSet<Vertex> created){

    copyTo.setId(copyFrom.getId());
    copyTo.setColor(copyFrom.getColor());
    copyTo.setCount(copyFrom.getCount());
    copyTo.setDepth(copyFrom.getDepth());
    copyTo.setDistance(copyFrom.getDistance());
    copyTo.setHeurist(copyFrom.getHeurist());
    copyTo.setVisited(copyFrom.isVisited());
    copyTo.setPath(copyFrom.getPath());

    created.add(copyTo);

    HashSet<Vertex> copyToNeighs = new HashSet<Vertex>();
    HashSet<Vertex> copyFromNeighs = new HashSet<Vertex>();
    copyFromNeighs.addAll(copyFrom.getNeighbours());

    Iterator<Vertex> it = copyFromNeighs.iterator();

    while (it.hasNext()){
        Vertex curr = it.next();

        if (!created.contains(curr)){
            Vertex newOne = new Vertex();
            newOne = getCopy(curr, newOne, created);
            copyToNeighs.add(newOne);
        } else {
            Iterator<Vertex> itr = created.iterator();
            while (itr.hasNext()){
                Vertex tmp = itr.next();
                if (tmp.equals(curr)){
                    copyToNeighs.add(tmp);
                    break;
                }
            }

        }
    }

    copyTo.setNeighbours(copyToNeighs);

    return copyTo;
}

and i want this method to copy from CopyFrom to CopyTo.
here is How i call this method:
Vertex newOne = new Vertex();
Vertex newCurr = new Vertex();
HashSet<Vertex> seen1 = new HashSet<Vertex>();
HashSet<Vertex> seen2 = new HashSet<Vertex>();
newOne = newOne.getCopy(tmp, newOne, seen1);
newCurr = newCurr.getCopy(curr, newCurr, seen2);

other methods (like .getNEighbours(), .addNeighbours())work properly, I've tested them hundreds of time;

A: created is the wrong concept.  You have a set of nodes in the "from" graph, and you're creating a set of new nodes in the "to" graph.  created.add(copyTo) will add a new node, from the "to" graph, to the set.  But when you go through created.iterator to see if a node is already there, you're looking for a node from copyFromNeighs, which is a node in the "from" graph.  It looks to me like this will never succeed.  Or else the result will be that you'll have nodes in the "to" graph pointing to nodes in the "from" graph.
Basically, I believe you need created to be a HashMap<Vertex,Vertex>, not a set.  The "key" of the HashMap would be a node in the "from" graph, and the "value" would be the corresponding node in the "to" graph.  Then, when you look at the neighbors of a "from" node, you get the corresponding "to" node (if it's already been copied) from the map, and add that to the neighbors of your newly created "to" node.

A: The simplest way to create a deep copy is to serialize into memory and then deserialize, see this question: How do you make a deep copy of an object in Java?

A: you need more consistent way to map source vertices onto resulting vertices. Declare created as hashmap, not hashset. Create new vertex only when  created.get(oldVertex)==null.


text:
Q: Element that calls the function JS Could someone say how to select and element that called current function?
function Myfunc() {
  element.style.padding = '16px';
}

//---
<button onclick="Myfunc()">Click Me!</button>

I ask how to do it without giving an id or class to the element, and without:
function Myfunc(this) { }

A: You can explicitly pass the element as the argument of the function, you can refer to the event object, or you can inline the code (this last one is not a good option but it works nonetheless):

function clickFunc1(element) {
  element.style.padding = '16px'
}

function clickFunc2() {
  event.target.style.padding = '16px'
}
<button onclick="clickFunc1(this)">ClickMe 1</button>
<button onclick="clickFunc2()">ClickMe 2</button>
<button onclick="this.style.padding = '16px'">ClickMe 3</button>

A: Use this.style.padding:

function Myfunc(element) {
  element.style.padding = '16px';
}
<button onclick="Myfunc(this)">Click Me!</button>
<button onclick="Myfunc(this)">Click Me 2!</button>
<button onclick="this.style.padding = '16px'">Click Me Without function!</button>

A: You can use it like this:

function Myfunc(element) {
element.style.padding = '16px';
}
<button onclick="Myfunc(this)">Click Me!</button>

A: Method 1

function foo(target){
  target.style.padding = '16px';
}
<button onclick="foo(this)">Click me!</button>

Method 2 (Better)

document.querySelector("button").addEventListener("click", function(event){
  const element = event.target;
  element.style.padding  = '16px';
});
<button>Click me!</button>

A: You can go with event.
<button onclick="Myfunc(event)">Click Me!</button>

Then e.target is you clicked element.
function Myfunc(e) {
  e.target.style.padding = '16px';
}

JSFiddle