text:
Q: Is there any way to enable remote desktop with a password but not require typing one in when at the physical machine? I'm running Windows 7 and would like to use remote desktop to connect to my home computer. As such i want to enable password security for remote desktop, but I do not want to have to enter a password to log into my computer if i'm physically at my computer. Is there any way to do this?
I am an administrator user and I want to have the same icons and configuration regardless of if i log in remotely or locally but i want only the remote connection to require a password. I read about being able to do something similar by adding another user account, but is there any way to do it so that the same icons and settings take affect regardless of how i log in?
Thanks.

A: Set up a LogMeIn free account and install the LogMeIn software on the computer. When accessing a passwordless computer, LogMeIn will require you to create and use a password for accessing the computer. This allows you to be "password free" when logging on locally, but requiring a password when logging on via LogMeIn, which should accomplish your objective.

A: You can use TweakUI and set it to automatically logon with user credentials when you boot.  If you login through Remote Desktop it will lock the computer, but you can do as joeqwerty suggested and use logmein instead of remote desktop.  I think it has an option not to lock the pc when you log off.  I would suggest having a local password so that if somebody gets your logmein credentials they still can't login to your machine.


text:
Q: Java - country / state / district dropdown in application level I need to implement drop downs for country, state and district.
For getting a list of state, I don't want to make a query to the DB.
i.e. When the server starts up, all the list of countries, states and districts should be loaded on to the memory using static class or methods. From there I should be able to fetch list of states and list of districts. For example, from one district, I should be able to find out from which state and which country it belongs to.
Every country, state and district, will have an id, title, shortcode.
My prime intention is to reduce the number of query request to the DB serve.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ROWNUM in CURSOR of oracle sql query is not working Please look at the below oracle function,
DROP FUNCTION get_mapper_requests;

CREATE OR REPLACE FUNCTION get_mapper_requests(p_status IN NUMBER, p_rownum IN NUMBER)
RETURN  SYS_REFCURSOR
AS

CUR_MED_MAPPER_STATUS SYS_REFCURSOR;

BEGIN

dbms_output.put_line('Status Value:'||p_status);

dbms_output.put_line('Row Count:'||p_rownum);

OPEN CUR_MED_MAPPER_STATUS FOR SELECT cmd_id,status FROM CDFDBA.MED_COM_MAPPER_CMDS WHERE
STATUS=p_status and ROWNUM < p_rownum;

RETURN CUR_MED_MAPPER_STATUS;

END;

The above function return all records even though if I pass any integer value to variable p_rownum. For ex if p_rownum=10, the function returns all records,
Calling block
DECLARE

 c SYS_REFCURSOR;

 v  VARCHAR2(1000);

 v1 VARCHAR2(1000);

BEGIN

 dbms_output.put_line('Hello');

 c := get_mapper_requests(0, 10);

 LOOP

    FETCH c INTO v,v1;

    dbms_output.put_line('Value from cursor: '||v||' '||v1);

 END LOOP;

 CLOSE c;

END;
/

Please support.

A: After you FETCH in the calling code I think you're missing
EXIT WHEN c%NOTFOUND;

Without that I'd assume you code just keeps calling DBMS_OUTPUT with the last fetched row until you get an error for filling the dbms output buffer.

A: declare
   cursor c is select * from <table_name> where rownum < 15;  -- SELECT ONLY 15 ROWS OF TABLE
   type t is table of c%rowtype index by pls_integer;
   tab t;
begin
   open c;
   loop
      fetch c bulk collect into tab limit 10;   -- FETCH cursor in chunks of 10
      dbms_output.put_line('X');
      exit when c%notfound;
   end loop;
end;


text:
Q: Using dedup to find unique hosts. How can I find an average for the selected time frame? The goal is to provide percent availability. I would like to check every 15 minutes if the unique count for server1, server2, and server3 is equal to 3 for each interval (indicating the system is fully healthy). From this count I want to check on the average for whatever time period is selected in splunk to output an average and convert to percent.
index="os" sourcetype=ps host="server1" OR host="server2" OR host="server3"
| search "/logs/temp/random/path" OR "application_listener"
| dedup host
| timechart span=30m count

The count should be 3 for each interval.

A: It's not clear how much of your requirements the example SPL solves, so I'll assume it does nothing.
Having dedup followed by timechart means the timechart command will only see 3 events - one for each host.  That doesn't make for a helpful chart.  I suggest using dc(host), instead to get a count of hosts for each interval.
The appendpipe command can be used to add average and percentage values on the end.
index="os" sourcetype=ps host="server1" OR host="server2" OR host="server3"
| search "/logs/temp/random/path" OR "application_listener"
| timechart span=30m dc(host) as count
| appendpipe [ stats avg(count) as Avg | eval Pct=round(Avg*100/3,2) ]


text:
Q: Why isn't my program adding a blank line after printing the .toString method? I am writing code to output parts of an ArrayList named Bikes using classes and if statements.
I added the new line characters after the print statements, but the output is still not seperated.

`
for(Bicycle c : Bikes){
            if(c instanceof MountainBike){
                ((MountainBike) c).setHeight(99);
                System.out.println("New Mountain Bike Info: ");
                System.out.println(c.toString() + "\n\n");
            }

            if(c instanceof TandemBike){
                ((TandemBike) c).setBetweenSpace(88);
                System.out.println("New Tandem Bike Info: ");
                System.out.println(c.toString() + "\n\n");
            }

            if(c instanceof RoadBike){
                ((RoadBike) c).setHandlebarType("NewType");
                System.out.println("New Road Bike Info: ");
                System.out.println(c.toString() + "\n\n");
            }

        }

`
This is what the output looks like despite the \n:
New Mountain Bike Info:
Cadence: 43
Gear: 2
Speed: 3
Seat Height: 99
New Tandem Bike Info:
Cadence: 37
Gear: 1
Speed: 2
Between Space: 88
New Road Bike Info:
Cadence: 40
Gear: 1
Speed: 1
Handelbars: NewType

A: Can you try below please?
String newLine = System.lineSeparator();
System.out.println(c.toString() + newLine + newLine);

The line break could depend on your system.
https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29
I suggest you debug and see what the lineSeparator is on your system.


text:
Q: Opening an application via C I am trying to write a simple C PROGAM which EXECUTE a Python SCRIPT (and let it running...) and closes itself.
I tried the following commands but in both cases the C PROGRAM is still alive...
popen("sudo python /home/pi/main.py", "r");
system("sudo python /home/pi/main.py");

Thanks!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Edited !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
I tried this command based on your comments but no success:
char *argv[] = {"/home/pi/main.py"};
execv("sudo python", argv);

Anyone could help? Thanks!
!!!!!!!!!!! Edit 2 !!!!!!!!!!!!!!
This is how I compile it:
gcc -Wall restart.c -o safekill

This is the C program
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

my_popen(char cmd[])
{
    FILE *fp;
    char path[1035];

    fp = popen(cmd, "r");

    if (fp == NULL)
    {
        printf("Failed to run command\n");
        exit(1);
    }

    //Read the output a line at a time - output it
    while (fgets(path, sizeof(path)-1, fp) != NULL)
    {
        printf("%s", path);
    }

    pclose(fp);

}

int main()
{
    my_popen("sudo killall python");
    sleep(1);
    my_popen("sudo killall raspivid");
    sleep(1);

    if(fork())
        printf("Am I here?");
        return 0;

    char *file = "restart";
    char *argv[] = {file, "-c", "sudo python main.py", NULL};
    execvp(file, argv);
}

Result: It prints am I here and doesn't start the python.
It is so frustrating.... :-(

A: You need to add the filename of the program itself to the argument list (argv[0]) and terminate the argument list with a NULL pointer.
Example:
#include <stdlib.h>
#include <unistd.h>

int main() {
    if(fork())
        return 0;
    char *file = "python";
    char *argv[] = {file, "-c", "import time; time.sleep(5); print 'Hello'", NULL};
    execvp(file, argv);
}

Expected behavior: Immediate (parent) program termination and a short Hello printed 5 seconds later by the child.
Maybe you need to workaround the sudo somehow, but this should get you started.


text:
Q: Not able to call managed bean method on submit button Here is my code of my .xhtml page
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                template="/WEB-INF/templates/admin/main_body_template.xhtml">

    <ui:define name="bodycontent">
        <h:panelGroup>
            <h:form class="form-horizontal" enctype="multipart/form-data">

Create New Module

                                      Select app

                                          <h:selectOneMenu class="form-control" required="required" value="#{moduleBean.appList}">
                                              <f:selectItem itemValue="0" itemLabel="-- Please select app --"></f:selectItem>
                                              <f:selectItem itemValue="1" itemLabel="AdMan"></f:selectItem>
                                              <f:selectItem itemValue="2" itemLabel="Neokala"></f:selectItem>
                                              <f:selectItem itemValue="3" itemLabel="Recrudesk"></f:selectItem>
                                              <f:selectItem itemValue="4" itemLabel="E-commerce"></f:selectItem>
                                              <f:selectItem itemValue="5" itemLabel="Restaurants"></f:selectItem>
                                              <f:selectItem itemValue="6" itemLabel="Account"></f:selectItem>
                                              <f:selectItem itemValue="7" itemLabel="MockExam"></f:selectItem>
                                          </h:selectOneMenu>

                                      Module name

                                          <h:inputText class="form-control" required="true" value="#{moduleBean.selected.moduleName}"></h:inputText>

                                      Upload image

                                          <h:inputFile class="form-control" id="file" value="#{moduleBean.imgFile}"/>

                                      Active

                                             <h:selectBooleanCheckbox class="nostyle" value="#{moduleBean.selected.active}"></h:selectBooleanCheckbox>

                                      Add-on

                                                <h:selectBooleanCheckbox class="nostyle" value="#{moduleBean.selected.addOn}"></h:selectBooleanCheckbox>

                                       <h:commandButton class="btn btn-primary nostyle marginR5" value="Save" action="#{moduleBean.create()}"></h:commandButton>
                                       <h:commandButton type="button" class="btn btn-warning nostyle cancel-btn-position" value="Cancel"></h:commandButton>

            </h:form>
        </h:panelGroup>
    </ui:define>

</ui:composition>

and below is my managedbean code.
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptegrainc.ymapps.supadm.managedbeans.masters;

import com.aptegrainc.ymapps.supadm.controller.masters.ModuleController;
import com.aptegrainc.ymapps.supadm.dto.ModuleVo;
import com.aptegrainc.ymapps.supadm.managedbeans.UserDataBean;
import static com.aptegrainc.ymapps.supadm.managedbeans.UserDataBean.setErrorMessage;
import static com.aptegrainc.ymapps.supadm.managedbeans.UserDataBean.setInfoMessage;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.http.Part;

/**
 *
 * @author Vaibhavi
 */
@ManagedBean(name = "moduleBean")
@ViewScoped
public class ModuleBean extends UserDataBean implements Serializable{

    private static final long serialVersionUID = 1L;

    private DataModel items;
    private ModuleVo current;
    private Part imgFile;
    private boolean createPanel = false;

    private ModuleController moduleController = new ModuleController();

    private String appList;

    public Part getImgFile() {
        return imgFile;
    }

    public void setImgFile(Part imgFile) {
        this.imgFile = imgFile;
    }

    public ModuleVo getSelected() {
        if (current == null) {
            current = new ModuleVo();
        }
        return current;
    }

    /**
     * Creates a new instance of ModuleBean
     */
    public ModuleBean() {

    }

    public String create() {
        System.out.println("current : " + current);
        System.out.println("---------"+current.getAppName()+current.getModuleName()+current.isActive()+current.isAddOn());
        if(checkError()){
            try {
                System.out.println("---------"+current.getAppName()+current.getModuleName()+current.isActive()+current.isAddOn());
                current.setActive(true);
                boolean val = moduleController.create(current);
                if(!val){
                    return "pretty:commonerror";
                } else if (val){
                    setInfoMessage("Module created successfully");
                }

                setCreatePanel(false);
                recreateModel();
                return "success";
            } catch (Exception e) {
                setErrorMessage(ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            }
        }

        return "fail";
    }

    public boolean checkError(){
        boolean flag = true;

        if(current.getModuleName() == null || current.getModuleName().equals("")){
            //setErrorMessage("Enter module name");
            flag = false;
        }
        return flag;
    }

    private void recreateModel() {
        items = null;
    }

    // Getters, Setters

    /**
     * @return the items
     */
    public DataModel getItems() {
        if (items == null) {
            List<ModuleVo> moduleVos = null;
            //moduleVos = moduleController.findAll();
            items = new ListDataModel(moduleVos);
        }
        return items;
    }

    /**
     * @param items the items to set
     */
    public void setItems(DataModel items) {
        this.items = items;
    }

    /**
     * @return the current
     */
    public ModuleVo getCurrent() {
        return current;
    }

    /**
     * @param current the current to set
     */
    public void setCurrent(ModuleVo current) {
        this.current = current;
    }

    /**
     * @return the moduleController
     */
    public ModuleController getModuleController() {
        return moduleController;
    }

    /**
     * @param moduleController the moduleController to set
     */
    public void setModuleController(ModuleController moduleController) {
        this.moduleController = moduleController;
    }

    /**
     * @return the appList
     */
    public String getAppList() {
        return appList;
    }

    /**
     * @param appList the appList to set
     */
    public void setAppList(String appList) {
        this.appList = appList;
    }

    /**
     * @return the createPanel
     */
    public boolean isCreatePanel() {
        return createPanel;
    }

    /**
     * @param createPanel the createPanel to set
     */
    public void setCreatePanel(boolean createPanel) {
        this.createPanel = createPanel;
    }

}

I have just called a method on submit button but its not calling even the method. I have checked the code many times but couldn't find any logical error. I am not getting why the bean method is not called.


text:
Q: select records with multi key list hi I have a list of primary keys of other tables in my field k in table A like this :
    id=1 and ref=2 and fun=1
    id=1 and ref=5 and fun=2
    id=2 and ref=1 and fun=1

and I have a table B which it's primary key is id,ref,fun
now I want to select all records from table B where primary key matches the values in table A
,
of course the
    select * from B where A.k

.. works
but get one record by one select
I ask for select all records from table B that matches A.k in table A.
thank you in advance.

A: MySQL will not treat the value of A.k as an expression to re-evaluate -- it's not substituted into the SQL and executed recursively. When you write WHERE A.k, it simply tests whether the contents of the k column is true or false.
You shouldn't put all the values in a single column. You should have separate columns for id, ref, and fun in table A. Then you can join the tables:
SELECT B.*
FROM B
JOIN A ON B.id = A.id AND B.ref = A.ref AND B.fun = A.fun

If you really want to have SQL expressions in a table column, you'll need to create dynamic SQL in a stored procedure.
SET @where = (SELECT GROUP_CONCAT(CONCAT('(', k, ')') SEPARATOR ' OR ')
              FROM A);
PREPARE stmt FROM CONCAT('SELECT * FROM B WHERE ', @where);
EXECUTE stmt;

See the MySQL documentation on Prepared Statements


text:
Q: Needing direction using REGEX in Notepad++ to find length of characters in line that also contains spaces I have a TEXT file where I have 4700 lines of a 30 character value.  The numerical characters are in position 1 through 8 and then there are only spaces supposedly after.  I am using REGEX in NOTEPAD++ to find 2 separate scenarios:

*

*I would like to find if there exists on any line of my text file the length of characters in position 1-8 that are less than 6.

*Are there any lines in my text file that have a length > 30.  I think I found the answer to this but would like some confirmation as I
am not picking up anything in my results.  Here is my what I'm using in NOTEPAD++ find these values:  .{30, }

Any help/direction would be appreciated. Thanks.
Here is a sample of what my file looks like:
332268-1
322335
322375
322393
322368-1
322381
322475
323912-1
322539
322641
322641
322514-1
322638
322978
322978
322638-1
287686
287735
322579
322643
323113
323257
331875
331875
322637-1
322720-1
322745-1
322679
322702
322971
324548
322971
333146-1

A: Number 1 would be ^\d{0,5}\s+\n
 ^ matches the beginning of the string or line
 \d digit
 {0,5} matches quantify or proceeding token
 \s whitespace
 + quantifier matches 1 or more
 \n is a new line

Number 2 would be ^.{31,}
 ^ matches the beginning of the string or line
 . matches any character but line breaks
 {31,} matches any line that is 31 characters or greater.


text:
Q: How to keep an ordered list on the App Engine DataStore, in a way each entity knows its position on the list? I have a ranking of people, based on points they earn. I need to tell each participant their position on the game for example,
 John (1) - 170 points, Mary (2) - 160 points, Sarah (3) - 110 points
So John's the first one, Mary's the seconds and Sarah's the third. Now if Mary wins 20 more points, she'll be the first and john will be the second.
I'm trying to avoid having to run a task on cron to list and recalculate everybody's position.
My first try was to maintain a separate set of entities (PersonRank) so I wouldn't run into transaction problems, this rank would have the same key name, so I could db.get() by key. This entity would have the person's calculated rank, so when a Person receives points, I'd have to check if the next Person on the line has fewer points than me, and exchange places with me so that's true.
The problem is that Sarah, on the example, may have won 100 points, and is now number one. On the previous algorithm, I'd have to "walk" among a lot of entities, which means a lot of DataStore gets and puts (updating each involved Entity to the new position).
My next guess is maybe some kind of linked list with ReferenceProperties, maybe using the key names to denote the position.
Any clues about how to implement this ?

A: Much more complex than I though, but hopefully some guys at Google already implemented this solution - http://googleappengine.blogspot.com/2009/01/google-code-jams-ranking-library.html

A: As you self-answered 3 years ago, Google implemented this solution, but they did that for Python exclusively. There is unofficial solution for java, someone re-writted Python solution and decided to share it:
http://toolongdidntread.com/google-app-engine/using-googles-datastore-to-implement-a-ranked-scoreboard/
People say it works fine, I did not use it yet though. I might decide to use it in next few months so I could write more about it then. Be aware that both Java and Python solutions can deal with 3 requests/sec only (!).
More reading here:
https://cloud.google.com/developers/articles/fast-and-reliable-ranking-in-datastore/
Basically, it says Google upgraded the code so it could deal with 300 requests/sec, and they said if you buy their premium-level support, they could help you with that, but they will not share the ready-to-go solution with the mere mortals. Also, all the code and references are in Python, but thats pretty obvious.
There is still no better solution than those mentioned here, at least I'm not aware of any.


text:
Q: Apply style on immediate parent element Is there a way to apply style on the parent selector based on the class specified in the child. I know this can be done in Javascript but I am trying to find a solution which can be applied on my css file. I tried:
div < .active {
    background:red;
}

but it selects/applies style only the child. I want the style to be applicable on the div parent here for example.
Any suggestions on this?
Thanks in advance.

A: There is No parent selector in CSS as of today. So the answer is No you cannot do it in CSS.. JavaScript is the only option

A: Try:
div > .active {
    background:red;
}

it is better to mention element also such as
div > div.active {
    background:red;
}


text:
Q: How to display an image saved on database in .NET Core API? I want to display an image saved to the database, I've been looking for tutorials and more, but they haven't really been of much help. I have an API controller and it is used by an MVC view and its respective controller. In the view there is a space to display text and the space where the image should be, the image is saved in the database as type varbinary and the text is a field of type varchar.
The model I have created:
public class ForumContentModel
{
    //some other fields
    //theme tables
    public string Content { get; set; }
    public byte[] ContentFile { get; set; } //this has the image
    public string FileType { get; set; }//the ext type of the image
    public string FileName { get; set; }//the name of the img

}

The API controller:
    [HttpGet]
    [Route("watchPost/{IdPost}")]
    public IActionResult verPost(int IdPost)
    {
        ForumContentModel forum = new ForumContentModel();//this model is used to "join" various
                                                          //models

        //get the data from the different tables with the id sending from the MVC controller
        var forumContent = db.Themes.Where(x => x.IdForo == IdPost).FirstOrDefault();

        //Content data from the post

        forum.Content = forumContent.Content;//the text part

        forum.ContentFile = forumContent.ContentFile;//the image
        return Ok(forum);
     }

The MVC controller:
    [HttpGet]
    public IActionResult watchPost(int Id)
    {
        ForumContentModel forumModel = new ForumContentModel();

        using(var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:44325/api/Forum/");

            var responseTask = client.GetAsync("watchPost/" + Id);

            responseTask.Wait();

            var result = responseTask.Result;

            if(result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<ForumContentModel>();
                readTask.Wait();

                forumModel = readTask.Result;
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Server error");
            }
        }

        return View(forumModel);
    }

The view where the data is displayed:
       <form asp-action="watchPost">

                    <textarea rows="4" asp-for="Content" class="form-control border-0" readonly="readonly"></textarea>

        </form>

I really don't know how to do this, I've been looking in some tutorials and almost all of them put in the source of the img attribute the name of the folder where the image is stored.
Any help is really appreciated.

A: Create a second ApiController for serving images.
Create a method returning an HttpResponseMessage and taking some kind of ID for the image as a parameter.
Inside that method construct a response and set the Content to a stream.
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(...);

Set the MIME type for the message, probably ONE of these:
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/svg+xml");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

Optionally set some headers to help caching:
response.Headers.CacheControl = new CacheControlHeaderValue
{
    Public = true,
    MaxAge = TimeSpan.FromDays(30)
};

Your view will need to generate an img tag pointing to this second controller/method.

A: You could refer to the following sample code:
Model: In my sample, I stored the file in database via the AppFile, you could change it to yours.
[Note] In your sample, the model's name is ContentForoModel, but in the controller, the model's name is ForumContentModel, please check your code and use the correct model.
public class AppFile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Content { get; set; }
}
public class ContentForoModel
{
    //some other fields
    //theme tables
    public string Content { get; set; }
    public byte[] ContentFile { get; set; } //this has the image
    public string FileType { get; set; }//the ext type of the image
    public string FileName { get; set; }//the name of the img

}

API controller: query the database based on the ID, and return the specified model.
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
    private readonly ApplicationDbContext _context;
    public TodoController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    [Route("watchPost/{IdPost}")]
    public IActionResult watchPost(int IdPost)
    {
        ContentForoModel forum = new ContentForoModel();//this model is used to "join" various
                                                          //models

        //get the data from the different tables with the id sending from the MVC controller
        var appfile = _context.AppFiles.Where(x => x.Id == IdPost).FirstOrDefault();

        //Content data from the post

        forum.Content = appfile.Name;//the text part

        forum.ContentFile = appfile.Content;//the image
        return Ok(forum);
    }

MVC Controller: You could change the url to yours.
    [HttpGet]
    public async Task<IActionResult> watchPost(int Id)
    {
        ContentForoModel forumModel = new ContentForoModel();
        if (Id == 0)
            Id = 1;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:44310/api/todo/");

            var responseTask = client.GetAsync("watchPost/" + Id);

            responseTask.Wait();

            var result = responseTask.Result;

            if (result.IsSuccessStatusCode)
            {
                var apiResponse = await result.Content.ReadAsStringAsync();
                //required using Newtonsoft.Json;
                forumModel = JsonConvert.DeserializeObject<ContentForoModel>(apiResponse);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Server error");
            }
        }

        return View(forumModel);
    }

View page: First, convert the byte array to base64 string, then, set the image src attribute.
@model WebApplication6.Models.ContentForoModel

        <form asp-action="watchPost">

                    <textarea rows="4" asp-for="Content" class="form-control border-0" readonly="readonly"></textarea>

                    @{
                        var base64 = Convert.ToBase64String(Model.ContentFile);
                        var Image = String.Format("data:image/gif;base64,{0}", base64);
                    }

        </form>

The result like this:


text:
Q: HttpClient with Proxy gives 403 on second call I have such code:
 static private async Task GetContent()
        {
            var proxy = new WebProxy
            {
                Address = new Uri($"http://178.33.236.108:8081"),
                UseDefaultCredentials = false,

                Credentials = new NetworkCredential(
                    userName: "xxx",
                    password: "xxx")
            };

            var httpClientHandler = new HttpClientHandler
            {
                Proxy = proxy,
            };

            var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
            HttpResponseMessage response = await client.GetAsync("https://somesite.com");

            client.DefaultRequestHeaders.Clear();

            HttpResponseMessage response2 = await client.GetAsync("https://somesite.com");
        }

On first request everything is ok, on second it throws 403 error (the same webpage). If I put Thread.Sleep(10000) between requests it still throws error so its not a matter of flooding.
If i restart app and run it again it behaves exactly the same way. Whats more weird even if I use different HttpClient object it would still give an error on second call...
Its some kind of Akamai protection.. but how does it works? If I use the same proxy in webbrowser it works perfect.. if i remove proxy from the code it works perfect too..
Does anybody have any ideas what can be 'buffered' in application? how to reset it?
Thanks.


text:
Q: invalid regular expression : illegal repetition in Java I'm practicing regular expressions in java and I have a problem with the line:
Pattern pattern = Pattern.compile("\"(.*?)\": {\"detected\": (.*?), \"version\": (.*?), \"result\": (.*?), \"update\": (.*?)}");

In netbeans I get the error:

invalid regular expression : illegal repetition

How can I fix the regular expression?

A: You need to escape the { and } characters with a backslash (\). To get the literal \, you need a double backslash (\\):
Pattern pattern = Pattern.compile("\"(.*?)\": \\{\"detected\": (.*?), \"version\": (.*?), \"result\": (.*?), \"update\": (.*?)\\}");

Otherwise, it looks like you have a strange (and illegal) repetition expression of the form {m,n}, as in \d{3,5} (3 to 5 digits).


text:
Q: How to change a jQuery method depending on value of a boolean I would like to change the jQuery method
parent()

to
children()

depending on the width of the user's screen.
Here's what I have (relevant code snippet):
var me         = $(this);
var generation = $(window).width() > 767 ? 'parent' : 'children';
if( !me.is(e.target) && !me.is($(e.target)[generation]() ) {
    me.removeClass(activeClass);
}

This is doing nothing no matter the screen size and also isnt throwing an error...
If I log the variable
    generation
to the console on the event the correct string returns according to the screen size check so I must be screwing up the way the method is being written in.
Anyone have insight here?

A: The problem might be that you are missing a )
[1] Try:
var me         = $(this);
var generation = $(window).width() > 767 ? 'parent' : 'children';
if (!me.is(e.target) && !me.is(($(e.target)[generation])())) {
    me.removeClass(activeClass);
}

[2] Or why not do:
var me         = $(this);
var generation = $(window).width() > 767;
if (!me.is(e.target) && ((generation == true && !me.is($(e.target).parent())) || (generation == false && !me.is($(e.target).children())))) {
    me.removeClass(activeClass);
}

[3] Or this:
var me = $(this);
if ($(window).width() > 767 && !me.is(e.target) && !me.is($(e.target).parent())) {
    me.removeClass(activeClass);
} else if (!me.is(e.target) && !me.is($(e.target).children())) {
    me.removeClass(activeClass);
}

[4] Or this:
var me    = $(this);
var check = $(window).width() > 767 ? $(e.target).parent() : $(e.target).children();
if (!me.is(e.target) && !me.is(check)) {
    me.removeClass(activeClass);
}

A: Why not simply use:
$(window).width() > 767 ? parent() : children();


text:
Q: Why does sbt assembly of a Spark application lead to "Modules were resolved with conflicting cross-version suffixes"? I am using CDH cluster with Spark 2.1 with Scala 2.11.8.
I use sbt 1.0.2.
While doing assembly, I am getting error as

[error] java.lang.RuntimeException: Conflicting cross-version suffixes in: org.scala-lang.modules:scala-xml, org.scala-lang.modules:scala-parser-combinators

I tried to override the version mismatch using dependencyOverrides and force(), but neither worked.
Error message from sbt assembly
[error] Modules were resolved with conflicting cross-version suffixes in {file:/D:/Tools/scala_ide/test_workspace/test/NewSp
arkTest/}newsparktest:
[error]    org.scala-lang.modules:scala-xml _2.11, _2.12
[error]    org.scala-lang.modules:scala-parser-combinators _2.11, _2.12
[error] java.lang.RuntimeException: Conflicting cross-version suffixes in: org.scala-lang.modules:scala-xml, org.scala-lang.
modules:scala-parser-combinators
[error]         at scala.sys.package$.error(package.scala:27)
[error]         at sbt.librarymanagement.ConflictWarning$.processCrossVersioned(ConflictWarning.scala:39)
[error]         at sbt.librarymanagement.ConflictWarning$.apply(ConflictWarning.scala:19)
[error]         at sbt.Classpaths$.$anonfun$ivyBaseSettings$64(Defaults.scala:1971)
[error]         at scala.Function1.$anonfun$compose$1(Function1.scala:44)
[error]         at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:42)
[error]         at sbt.std.Transform$$anon$4.work(System.scala:64)
[error]         at sbt.Execute.$anonfun$submit$2(Execute.scala:257)
[error]         at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]         at sbt.Execute.work(Execute.scala:266)
[error]         at sbt.Execute.$anonfun$submit$1(Execute.scala:257)
[error]         at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:167)
[error]         at sbt.CompletionService$$anon$2.call(CompletionService.scala:32)
[error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[error]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[error]         at java.lang.Thread.run(Thread.java:748)
[error] (*:update) Conflicting cross-version suffixes in: org.scala-lang.modules:scala-xml, org.scala-lang.modules:scala-par
ser-combinators
[error] Total time: 413 s, completed Oct 12, 2017 3:28:02 AM

build.sbt
name := "newtest"
version := "0.0.2"

scalaVersion := "2.11.8"

sbtPlugin := true

val sparkVersion = "2.1.0"

mainClass in (Compile, run) := Some("com.testpackage.sq.newsparktest")

assemblyJarName in assembly := "newtest.jar"

libraryDependencies ++= Seq(
  "org.apache.spark" % "spark-core_2.11" % "2.1.0" % "provided",
  "org.apache.spark" % "spark-sql_2.11" % "2.1.0" % "provided",
  "com.databricks" % "spark-avro_2.11" % "3.2.0",
  "org.apache.spark" % "spark-hive_2.11" % "2.1.0" % "provided")

libraryDependencies +=
     "log4j" % "log4j" % "1.2.15" excludeAll(
       ExclusionRule(organization = "com.sun.jdmk"),
       ExclusionRule(organization = "com.sun.jmx"),
       ExclusionRule(organization = "javax.jms")
     )

resolvers += "SparkPackages" at "https://dl.bintray.com/spark-packages/maven/"
resolvers += Resolver.url("bintray-sbt-plugins", url("http://dl.bintray.com/sbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}

plugins.sbt
dependencyOverrides += ("org.scala-lang.modules" % "scala-xml_2.11" % "1.0.4")
dependencyOverrides += ("org.scala-lang.modules" % "scala-parser-combinators_2.11" % "1.0.4")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5")
resolvers += Resolver.url("bintray-sbt-plugins", url("https://dl.bintray.com/eed3si9n/sbt-plugins/"))(Resolver.ivyStylePatterns)

A: tl;dr Remove sbtPlugin := true from build.sbt (that is for sbt plugins not applications).
You should also remove dependencyOverrides from plugins.sbt.
You should change spark-core_2.11 and the other Spark dependencies in libraryDependencies to be as follows:
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.1.0" % "provided"

The change is to use %% (= two percent signs) and remove the version of Scala from the middle part of a dependency, e.g. spark-core above.


text:
Q: Navbar not collapsing and expanding properly trying to work out navbars right now, but my code doesn't seem to work with them.
The collapse icon is staying next to the navbar-brand and then the navbar-links are sitting next to it.
    <!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css?family=Nunito:200,300,400,700" rel="stylesheet">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <link rel="stylesheet" href="app.css">

    <title>Website</title>

      TEST
      <button class="navbar-toggle" data-toggle="collapse" data-target="#nav-links">

      </button>

            HOME

            ABOUT

            TICKETS

A: you have to add navbar-toggler class instead of navbar-toggle to the button see the code:

      TEST
      <button class="navbar-toggler" data-toggle="collapse" data-target="#nav-links">

      </button>

            HOME

            ABOUT

            TICKETS

A: Problem is with your button change your class navbar-toggle to navbar-toggler
<button class="navbar-toggler" data-toggle="collapse" data-target="#nav-links">

</button>


text:
Q: Setting UIDatePicker countDownTimer default value to 1 minute I have a UIDatePicker with countDownTimer mode in my app.
I want the default date to be 0 hours, 1 minute. I've tried to do that by adding the line:
self.datePicker.date = Date()
but the result was the current time in a timer format. For example, if the time is 10:55am the timer shows 10 hours, 55 minutes.
How can I set the timer default value to 0 hours, 1 minute?
Thank you!

A: You just need to set the countDownDuration property. As the docs say,

Use this property to get and set the currently selected value when the date picker's mode property is set to countDownTimer.

pickerView.countDownDuration = 60


text:
Q: creating a named host for virtualbox accessible from host For my dev machine, I have windows 7 host with ubuntu guest. I run the guest as the server.
Every time I want to test from the host, I find my current guest IP address, and connect via that (for example, today it is 192.168.1.188:3000/). Of course, this changes every time I  connect to a different network.
I want to create a named address, dev.myapp.com that I can connect to from the host windows machine, or possibly any machine on the network (if that is possible, though it may be a security concern, somebody on the network would need to know my url name in order to access, so I'm not that concerned).
I've tried chaning the etc/hosts in ubuntu to include

127.0.0.1:3000 dev.myapp.com

but unfortunately, this isn't resolving from either the host or guest.
I'm using a bridged network adapter, promiscuous mode is deny.

A: I suggest you use Multicast DNS to fix this.
Ubuntu is using this by default via Avahi.
The Windows host needs an Avahi-client for it to discover other Avahi-services. If your host already uses some Apple software this is probably already there via a service called Bonjour. However, if this is not already installed then a small version of Bonjour is available for download here: Bonjour Print Services. After installation you should be able to access your guest via .local.
Note: The mDNS system seem to use the .local postfix by default. So, if your hostname is "dev.myapp.com", then the actual hostname will be "dev.myapp.com.local".


text:
Q: Authorization to run a Google Script for public with a protected worksheet I would like to publish a Google Sheet running with a script, so that when you click on "Submit", the data is sent to another PROTECTED Google Sheet.
I have tried to run the cript with an account that doesn't have access to the PROTECTED Google Sheet, but it doens't work.
Do you know if there's any function that could be use, in order to let people submit, even if they do not have access of the "output" sheet?

A: You can try to refer to this link for the documentation of Class Protection API that you can use to achieve your target:
https://developers.google.com/apps-script/reference/spreadsheet/protection


text:
Q: Contacts from Google not downloading to MBP Never had a problem before. Enabled my Google account on a new MBP yesterday, and asked to sync contacts. A day later, none of them have populated. Am I overlooking something? Any way to force a manual download (other than export/import, since that would defeat the purpose)?
EDIT: I went and disabled/re-enabled the account a few more times and it worked.

A: Disable and Re-enable the account can work in Contacts app preferences.


text:
Q: How to do a bounce animation on Android? I am not good at Android animation yet but I need to implement a bounce animation like this Animation :

I have been trying with
BounceInterpolator, android:interpolator="@android:anim/bounce_interpolator"
and translate +scale animations but I don't get the effect
Note: It will be much better if you could provide the explanation as well

A: What you are looking at is basically only two TranslateAnimations chained together in repeat mode. Since the white line leaves the screen to the left and the right it just looks like it is bouncing. The ObjectAnimator class should provide everything you need. Let's assume the white line is View v placed in the center of the screen.
Something like :
final ObjectAnimator animation = ObjectAnimator.ofFloat(v, "translationX", ...f);
    animation.setDuration(ms);
    animation.start();

should get you started, where the (...f) parameter is your positive float value that moves it to the right OR a negative value that moves it to the left on the X axis.
Personally I prefer the ViewPropertyAnimator Class, it can chain multiple animations together and is very easy to use. f.e.:
v.animate()
    .translationXBy(...f)
    .setInterpolator(new AccelerateDecelerateInterpolator())
    .setDuration(ms);

Same here with the (...f) parameter.
The Interpolator is optional, and just makes it look more realistic.
For future animations I recommend checking the docs for all available methods .
You could set a Animator.Listener, that allows you to perform actions f.e. when the animation is over. So f.e. once an animation to the right is over you can start the animation to the left and vice versa, and  but I'll rather leave you some work to find out how to repeat the animations than do all the work for you.
All I can add is, I would disadvise you to use an AnimationSet, which has a method setRepeatMode() which might be good for your Task, but from experience I can say, this is rather buggy and often does not work as expected.


text:
Q: Constrain constructor argument type with class generic I have an object which I want to map into several other structures based on its keys. Each key-value should be considered separately, so I want to map object into array of entries, map entries into policy objects and apply them all. So my goal is to use this object like this:
type ValuesMap = {key1: Value1; key2: Value2; ...};
const valuesMap: ValuesMap = getValues();
const results = Object.entries(valuesMap).map(([key, value]) => policyFactory.createPolicy(key, value).apply());

For this to work I want to create an abstract policy class and factory for those policies:
type Key = keyof ValuesMap;
type Value<K extends Key> = ValuesMap[K];
abstract class Policy<K extends Key> {
  constructor(protected readonly value: Value<K>) {}
  abstract apply();
}

class ConcreteKey1Policy extends Policy<'key1'> {
  //constructor of this class shall accept only Value1 argument; ts should raise error when this class is constructed with other type
  apply() {/*...*/}
}

//...
class PolicyFactory {
  private readonly constructorMap: {
    [K in Key]: new (value: Value<K>) => Policy<K>;
  } = {
    key1: ConcreteKey1Policy;
    key2: ConcreteKey2Policy;
    //same for all considered keys of ValuesMap
  };

  createPolicy<K extends Key>(type: K, value: Value<K>): Policy<K> {
    return new this.constructorMap[type](value); //error1
    switch(type) {
      case 'key1':
        return new ConcreteKey1Policy(value); //error2
      //...
    }
  }
}

I tried 2 approaches for factory class, one with map of possible keys and constructors for them, another with switch for a type arguement. Both raise typescript errors:

*

*when I try to create object form constructor map I get the error: type '"key1"' is not assignable to type 'K'. '"key1"' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint 'Key'

*when I try switch, for every concrete policy creation I get the error: Argument of type 'Value1 | Value2 | Value3 | Value4' is not assignable to parameter of type 'Key1'. Type 'Value2' is not assignable to type 'Value1'.
I think I understand both of those errors, however, I have no idea how I can overcome them. I need to use generics in factory, so value type is tied to the type of type, but when I use extends Key, I create a constraint of any subtype of Key - but what I need is any type of the union Key and no other type. How can I create such constraint? Maybe there is a simpler way to achieve what I need here?

A: It turns out to be fixed in newer typescript version. As you can see in the playground (thank you @colinD), it works from version 4.6.4 up. I updated ts version in my project from 4.4.4 to the latest and now it works.


text:
Q: How to get started with RxJava I have visited the following link:
https://github.com/ReactiveX/RxJava/wiki/Getting-Started
and have tried to get RxJava to work with Eclipse, however even after importing it using Maven it still won't find the Observer and Subscriber objects when trying to import them.
I am not too sure where to go from here as the getting started link doesn't explain it that thoroughly.

A: I am also learning RxJava now, here is the necessary jar files you need:
If using Maven, add this dependency into pom:xml (replace with latest version available):
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>1.0.11</version>
</dependency>

If you don't want to use Maven, I recommend you download the JAR file from Maven Repository:
http://mvnrepository.com/artifact/io.reactivex/rxjava
Regards,
Cristi


text:
Q: rrdtool info ds unknown_sec meaning The answer to this question is probably obvious, but I couldn't figure out what it means nor find the documentation for it. When I run rrdtool info, I get ds[source].unknown_sec = 0, and I am not sure what it exactly means...Any help or pointers would be appreciated!

A: Actually, I think I figured out what it means. If two data samples exceed the heartbeat value, then the entire interval between the two data samples are marked as unknown. So unknown_sec = 0 means there hasn't been two data samples that exceed the heartbeat value.

A: The unknown_sec is the number of seconds for which the value of the DS is Unknown.  This could be because the supplied value was Unknown, or was outside the specified range, or because the time since the last sample exceeds the heartbeat time (which marks everything since then as Unknown).
The amount of Unknown time in an interval is then used in combination with the xff fraction in the RRA definitions to determine if a consolodated data point stored in the RRA is Unknown.


text:
Q: fb:like url parameter value is removed. Title also incomplete I've added a facebook like button to my page but it doesn't record the given url properly. The problem is that the url displayed on my facebook profile, after I click the like button, is missing a parameter value. The title displayed next to the url is also missing some parts.
Here's how I configured my facebook like button:
<head>
.....
<meta property="og:title" content="Family Tree of John Doe"/>
<meta property="og:type" content="mySite:family_tree"/>
<meta property="og:url" content="http://www.mySite.com/edit/tree/visual?person=John_Doe_1"/>
<meta property="og:image" content="http://images.mySite.com/tree.png"/>
<meta property="og:site_name" content="mySite"/>
<meta property="fb:app_id" content="................"/>
<meta property="og:description" content="Site description"/>
....
<head>
<body>
.....
<fb:like href="http://www.mySite.com/edit/tree/visual?person=John_Doe_1" show_faces="true" width="450"></fb:like>
.....
</body>

In the profile page the like section has the title "Family Tree of" and the url it points to is "http://www.mySite.com/edit/tree/visual?person".
How do I solve this issue?


text:
Q: Clarification on the definition of the random variable of negative binomial distribution There is this passage in a textbook Stochastics by Hans-Otto, Georgi:

An urn contains red and white balls, where the proportion of red balls
is $0<p<1$. The balls are drawn with replacement. What is the
distribution of the waiting time until the $r$th success, i.e., until
we draw the $r$th red ball? Here, $r\in\mathbb{N}$ is a fixed number.
Since we must draw at least $r$ times, we consider the remaining
waiting time after $r$ draws, or equivalently, the number of failures
before the $r$th success; then the sample space is
$\Omega=\mathbb{Z_+}$. Which $P$ describes the situation?
On the infinite product space $\{0,1\}^\mathbb{N}$ we could define the
random variable
$$T_r(\omega)=\min\left\{k:\sum_{i=1}^{k}\omega_i=r\right\}-r$$
and obtain $P$ as the distribution of $T_r$.

My doubts are:
I understand $\min\left\{k:\sum_{i=1}^{k}\omega_i=r\right\}$ is the minimum value of draws to get the $r$th success. What I don't quite understand is why do we still need to take away $r$ in the end? Does that mean we can get a negative value for $T$? If yes, what does the negative value of $T$ represent?
What does the random variable $T$ ACTUALLY represent? Why do we have to take the minimum?
Also I don't quite understand how can the statement "the remaining waiting time after $r$ draws" to be equivalent to "the number of failures before the $r$th success". Should we erase the word "remaining"?  It doesn't make sense for me.
Can anyone please help me clarify these doubts?
Thanks.

A: There are two commonly understood parametrizations of a negative binomial random variable.  One counts the number of trials (in your example, a "trial" consists of a random draw of a ball) that have occurred when the $r^{\rm th}$ red ball is drawn.  The other counts the number of failures (in your example, a "failure" consists of a random draw of a white ball) that have occurred when the $r^{\rm th}$ red ball is drawn.
Clearly, if we call the first random variable $T$ and the second one $S$, then $$S = T + r,$$ which expresses the idea that if we have observed $T$ draws of a white ball when the $r^{\rm th}$ red ball is drawn, then the total number of balls drawn at that moment must be $S = T+r$, or equivalently, $T = S - r$.
Now, $S$ is the minimum index of the sum in your notation.  This sum cannot be less than $r$, since each $\omega_i \in \{0,1\}$, so $$\sum_{i=1}^k \omega_i \le k,$$ with equality occurring if and only if $\omega_i = 1$ for all $i \in \{1, 2, \ldots, k\}$.  So the smallest possible $k$ such that $S = r$ is $k = r$, which guarantees that the subtraction of $r$ does not make $T$ negative.  Put in words, $T$ counts the number of white balls drawn.  You could conceivably draw no white balls--every single one is red--but this is another way of saying that of the first $r$ balls drawn, all of them were red; hence in such a case $S = r$ and $T = r-r = 0$.  Everything works out.
Why do we take the minimum?  Because if $\sum_{i=1}^k \omega_i = r$, by no means does this guarantee that $\sum_{i=1}^{k+1} \omega_i > r$.  In words, the stopping rule is to count only those balls up until the $r^{\rm th}$ red ball.  If we continued to draw and get a white ball, the total number of red balls we observed is still $r$.  So to mathematically express this idea that we stop as soon as the $r^{\rm th}$ red ball is drawn, we take the minimum $k$ such that the sum equals $r$:  this is the notion that we count the fewest possible balls necessary to observe the required $r$ red balls, and no more.
As for your last question, the book phrases it poorly in my opinion.  The "waiting time" here is expressed in units of trials, not actual chronological time.  That is to say, it doesn't matter how long we wait between trials:  the "waiting time" the book describes is simply the number of draws we make.
That said, suppose $r = 3$ and we are counting the number of trials needed to observe the third red ball.  Suppose further that our random outcome was $$\{w, r, w, w, r, w, r\}.$$  We stop drawing once the third instance of $r$ is observed.  Here, we find $S = 7$ trials in total, $T = 4$ of which were white.  We have thus far thought of $T$ as the number of white balls drawn until the third red ball.  But you can also think of it as the number of trials after the third trial to observe the third red ball.  It makes no difference whether you count failures, or you count the extra trials after the third.


text:
Q: How to add dollar signs in Code Snippets of Visual Studio Code? $ (dollar signs) are removed from Snippets in Visual Studio Code
How to disable placeholders?
My vue-html.json file snippet
"body": ["<ActivityIndicator  v-if=\"$apollo.loading\" />"]

does not add $ and produces
<ActivityIndicator v-if="apollo.loading"  />

but instead it should produce
<ActivityIndicator v-if="$apollo.loading" />

A:   "description": {
    "prefix": "trigger",
    "body": [
      "<ActivityIndicator v-if=\"\\$apollo.loading\" />"
    ],
    "description": "description"
  }

In JSON the backslash itself needs to be encoded with \, which is why you need \\

A: "body": ["<ActivityIndicator  v-if=\"\\$apollo.loading\" />"]
You need to escape the $ symbol individually too


text:
Q: mv: prompt to rename or overwrite find /home/csuser/testfiles . -type f -name "*.c" -exec mv '{}' /home/csuser/src/ \;

The above command will simply overwrite files which have the same name. How can I make mv prompt me to either overwrite the existing file or replace it, for each file name which already exists at the target?

A: The manpage of the mv command (man mv) shows the following entry:
       -i, --interactive
              prompt before overwrite

So, using mv -i ... prompts before overwriting.

A: Here's a simple shell script wrapper to prompt you for each existing file.
find /home/csuser/testfiles . -type f -name "*.c" -exec sh -c '
    for file; do
        dest=$0/${file##*/}
        if [ -e "$dest" ]; then
            ls -ld "$dest" "$file"
            read -p "Enter new name for the second, or just ENTER to overwrite the first: " newname
            if [ "$newname" != "" ]; then
                dest=$0/${newname##*/}
            fi
        fi
        mv "$file" "$dest"
    done' /home/csuser/src/ {} +

We obscurely but conveniently pass in the destination directory as $0.


text:
Q: nginx: proxy tcp traffic depending on remote ip I want to use nginx to proxy tcp traffic to different backends depending on the ip address of the requester. So far I have the following setup in nginx.conf:
stream {
    server {
        listen 1025;
        if ($remote_addr != 10.0.99.18) {
            proxy_pass mailcatcher_production:1025;
        }
        if ($remote_addr = 10.0.99.18) {
            proxy_pass mailcatcher_others:1025;
        }
    }
}

But I get the following error when starting nginx:
[emerg] 1#1: "if" directive is not allowed here in /etc/nginx/nginx.conf:36
I think, it's not important, but I'm running nginx in docker and copy the nginx.conf at startup time into the container.

A: Try using the map module :
stream {
    map $remote_addr $mailcatcher {
        10.0.99.18 mailcatcher_others;
        default mailcatcher_production;
    }

    server {
        listen 1025;
        proxy_pass $mailcatcher:1025;
    }
}


text:
Q: shopify api billing address different from shipping address I'm working with the shopifys api and I came across this problem, I know that shopify uses the billing address country to validate credit card transactions, so the billing address country must match the credit card issuer country like it is said in this shopify forum post https://ecommerce.shopify.com/c/payments-shipping-fulfilment/t/need-help-with-shipping-billing-address-at-checkout-263790 but my problem is that I found that i can't create an order is the shipping address country field differs from the credit card issuer country, the api returns error 422 unprocesable entity if I do so, here is and example call to the api.
{
    "referring_site": "customLaravelShop.dev",
    "customer": {
        "first_name":"victor",
        "last_name":"alvarez",
        "email":"example@gmail.com"
    },
    "billing_address": {
        "first_name":"victor",
        "last_name":"alvarez",
        "address1":"qwerty",
        "phone":"+5812345678",
        "city":"london",
        "country":"IRELAND", // THIS SHOULD BE THE SAME COUNTRY AS THE THE CREDIT CARD ISSUER
        "zip":"1111"
    },
    "shipping_address": {
        "first_name":"victor",
        "last_name":"alvarez",
        "address1":"qwerty",
        "phone":"+584123607361",
        "city":"london",
        "country":"ENGLAND", // HERE IT LOOKS LIKE THE SHIPPING ADDRESS COUNTRY SHOULD BE THE SAME AS THE CREDIT CARD ISSUER
        "zip":"1111"
    },
    "email":"example@gmail.com",
    "line_items":[
        {
            "variant_id":11111111,
            "quantity":"1",
            "requires_shipping":true,
            "variant_title":"Default Title",
            "grams":1000
        }
    ],
    "note_attributes":[
        {
            "name":"Apron Polka Dot Check",
            "value":"Default Title x 1"
        }
    ],
    "shipping_lines":[
        {
            "code":"Shipping required",
            "price":"6.50",
            "title":"Shipping info"
        }
    ],
    "total_weight":1000,
    "subtotal_pricce":19.99,
    "total_price":"26.49",
    "order_number":"EXAMPLE-REALEX-ORDER-NUMBER-1234",
    "payment_gateway_names":["realex"],
    "processing_method":"realex",
    "reference":"EXAMPLE-REALEX-ORDER-REFERENCE-1234",
    "financial_status":"paid",
    "send_receipt":false,
    "transactions":[
        {
            "kind":"sale",
            "status":"success",
            "amount":"26.49",
            "gateway":"realex"
        }
    ]
}

I'm not sure if I'm missing something, but I think that the shipping address country field should not be related to the credit card issuer country, I can understand that the billing address country must match the credit card issuer country but billing and shipping are two very different things and sould not be related in this manner to each other


text:
Q: How do I mock non-global node variables _filename or __dirname in jest? __filename and __dirname are the absolute file paths in which a code is entered. Per Node.js documentation (and confirmed) these 2 special global variables are injected rather than being part of the  the global object so cannot be configured via globalThis/global within jest.
Example function: utils.ts
export const getFileAndDirName = () => ({
 relevantFile: __filename.split('/')?.[3],
 rootPath: __dirname,
})

Example test code which does not work: utils.test.ts
it('finds the file path where the function was executed', () => {
  globalThis.__filename = '/Users/me/work/utils/index.ts'
  expect(getFileAndDirName()).toEqual('utils')
  globalThis.__filename = '/Users/me/work/tests/index.ts'
  expect(getFileAndDirName()).toEqual('tests')
})

Alternatives/Work arounds:
I'm aware that I can refactor my code to still be able to test this:
export const safelyExtractThirdElement = (filePath = '') => filePath.split('/')?.[3]

export const getFileAndDirName = () => ({
 relevantFile: safelyExtractThirdElement(__filename),
 rootPath: __dirname,
})

This solution enables me to avoid mocking __filename... however ideally I wouldn't need to change my actual code and keep private internal utilities un-tested, and also this is a bit of a simplified arbitrary example compared to my own.
I can also hack my code for this to work, but I feel that testing should make code stronger not hackier:
__filename = globalThis.__filename || __filename // will probably work since globalThis.__filename is never defined.

With this strategy I can mock __filename and allow my code to read it but this is again hacking implementation.
Is there some ideal/not-so ideal strategy for mocking these special variables in jest?
The real question is if it is possible to mock __dirname or __filename or should I accept that these may not be mocked for node jest and circumvent that limitation?
Background: __filename, __dirname
The fact that this doesn't work does not surprise me: if we look at the Node.js documentation for __filename it indicates plainly that __filename and __dirname you may assume are globals but are NOT.
__dirname#

This variable may appear to be global but is not. See __dirname.

__filename#

This variable may appear to be global but is not. See __filename.

https://nodejs.org/api/globals.html#__dirname
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});

The question is if it is possible, how would one mock __filename or __dirname with jest. Jest documentation makes it pretty clear how to mock and temporarily set functions using globalThis, but what about these non-global globals?


text:
Q: Custom Array Serialization on Flex client I was wondering if it is possible to do custom serialization of Arrays/ArrayCollections in as3 via amf. To be more specific, i want to be able to pool objects on the client so that im not instantiating new objects every time i make a RemoteObject call. I tried using IExternalizable but that only lets me serialize the objects myself not instantiate them. The flash player is still instantiating objects itself and them letting me set the object state via readExternal. Thanks in advance.
/E

A: Convert Arrays and ArrayCollections to JSON and pass them around as a string?

A: AMF is completely built into the flash player, I don't think there's any way of messing with the parsing, BUT you could skip the native AMF, get a AMF (or something else) open source library and tamper with its parsing function.
I don't know if there IS a open source AMF library for flash since it has a native one, but who knows.

A: You can have your class implement IExternizable to do its own serialization.
Check out The Dark World of IExternizable


text:
Q: Function to get list of coordinates of all towers present on the transmission line I have geojson files of transmission line and towers which i have allocated on the map.
Towers are only visible if zoomLevel >=11.
Now I want a function or logic Of how to download the list of coordinates all towers of a particular transmission line.
Note:This project does not have any backend.Its  front-end only


text:
Q: Nginx custom error_page with php I'm new into nginx and in order to test it I'm migrating from Apache and all I got left is setting up the custom error pages.
These pages are php files (for multi language purposes), I have tried many of the methods from StackOverflow but I cannot figure out how to make it.
Some of them are:

*

*nginx-php-fpm-custom-error-pages

*nginx-fastcgi-for-php-error-page

*nginx-error-pages-one-location-rule-to-fit-them-all
So far I've created a file /etc/nginx/common/default-error-pages.conf to include it on the vhosts. This file contains:
error_page 400 /error/400.php;
error_page 401 /error/401.php;
error_page 403 /error/403.php;
error_page 404 /error/404.php;

error_page 500 /error/500.php;
error_page 503 /error/503.php;

location /error/ {
    alias /var/www/error/;
    autoindex on;
}

location ~ \.php$ {
    root /var/www/error/;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.2-fpm.sock;

    # fastcgi_intercept_errors on;
}

The php files are located in /var/www/error if I enable the autoindex I'm able to view them from the browser all the files but if I click in any of them the default 404 page is shown.
I have created a symlink of one of those files to a testing site and it gets executed correcly even the css loads as expected.
I've tried nesting the locations and including this config file at the top of the site server block.
If I change the extension of the php error files to html they are correctly served.
The nginx site is similar to this (file simplified):
server {
        listen 4430 ssl http2 default_server;
        listen [::]:4430 ssl http2 default_server;
        server_name test.local;

        root /var/www/html;
        index index.php index.html;
        # execute php files "helper"
        include common/php-files.conf;
        fastcgi_hide_header X-Powered-By;
        include common/default-error-pages.conf;

        location / {
                # autoindex on;
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }
}

How is supposed to be configured? I've changed it so many times that I don't know what else to try.
Nginx logs files don't reveal any unexpected error/configuration.
Thanks in advance

A: I got wrong the root as Richard Smith told in the comment below the post.
After changing it to the suggested one all worked perflectly.
I also nested the location blocks so the php files are correctly handled, as others are being processed with fastcgi_intercept_errors on; to catch the http errors.
So the config stays as:
error_page 403 /error/403.php;
error_page 404 /error/404.php;

error_page 500 /error/500.php;
error_page 503 /error/503.php;

location /error/ {
    root /var/www/;
    try_files $uri $uri/ =404;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_intercept_errors off;
    }
}


text:
Q: Regular expression without repeating numbers Can you help me to find out how I can build some regular expression to detect a valid sequence of numbers of 13 digits
first case:
1111111111111 -invalid
2222222222222 -invalid
333.....      -invalid

and same for the other digits, for this case I made this regex:
(^0+$)|(^1+$)|(^2+$)|(^3+$)|(^4+$)|(^5+$)|(^6+$)|(^7+$)|(^8+$)|(^9+$)

but I want to get this regex simplified, if there is a shorter way to get this validation.
second case:
9875978545111  - valid: only 3 1's
11118578954547 - valid: only 4 1's
85781111954547 - valid: only 4 1's
9875978111111  - invalid: 6 1's
1111119875978  - invalid: 6 1's
9871111115978  - invalid: 6 1's

If there is a sequence of digits that repeats at least 6 times must be invalid,
like the last case if there is a way to make it shorter
I have this regex: ([0-9]+1{6,}+)|(^1{6,}+[0-9]+)
case 3:
1212121212121
0101010101010
1231231231231

Pattern like theses must be invalid.
I have no idea how to write this regex.

A: Since plsql doesn't seams to support lookahead, you can use this regex (\d)\1{5,} and negate the match.

A: Case 1 - 13 of same digit:
(\d)\1{12}

Case 2 - more than 5 of same digit (you must negate the result):
(\d)\1{5}

Case 3 - TBA

A: Cases one and two:  repeating digits. This captures a digit and a repeat of that digit. The number in brackets defines the minimum length you want to match.
([0-9])\1{13}
([0-9])\1{6}

Case three: match a repeating sequence. Assuming you are still working with 13-digit numbers, the longest repeatable sequence would have 6 digits. This matches a repeating sequence of length 2-6.
([0-9]{2,6})\1

All cases require negation (positive match means invalid sequence).

A: First case
For 13 repeated digits you can use: ^(\d)\1{12}$, to match the lines with valid sequences. Therefore, just accept the lines where the regex do match anything. Live link for the example: https://regex101.com/r/4zi3ZZ/2

Second case
For more than 5 digits you can use: (\d)\1{5}, to match the lines with invalid sequences. Therefore, just accept the lines where the regex do not match anything. Live link for the example: https://regex101.com/r/vhoBCq/1

Third case
For the pattern search, you cannot do this with regex, because regex is to search patterns you know they exist. It cannot be used to extract patterns and research the string for the pattern it extracted. Regular Expressions are one of many Formal Languages out there. It cannot do every thing as it is limited. However, everything you cannot do with regex, you can do through programming.
So, you need to write a program for pattern search. Once you know what is the pattern, you can use: ^(pattern)\1+$, to match the lines with valid sequences. Therefore, just accept the lines where the regex do match anything. Live link for the example ^(123)\1+$ https://regex101.com/r/TCS46x/3


text:
Q: Java: why don't these variables initialize? I'm working on an example from Bruce Eckel's book and i was wondering why the initialized values don't stick when I output them?
class InitialValues2 {
    boolean t = true;
    char c = 'x';
    byte b = 47;
    short s = 0xff;
    int i =999;
    long l =1;
    float f = 3.14f;
    double d =3.14159;
    InitialValues reference;

    void printInitialValues() {
        System.out.println("data type       Initial values");
        System.out.println("boolean     " + t);
        System.out.println("char        [" + c + "]");
        System.out.println("byte        " + b);
        System.out.println("short       " + s);
        System.out.println("int         " + i);
        System.out.println("long        " + l);
        System.out.println("float       " + f);
        System.out.println("double      " + d);
        System.out.println("reference       " + reference);

    } //end printinitialvalues

    public static void main(String args[]) {
        InitialValues iv = new InitialValues();
        iv.printInitialValues();

        //new InitialValues().printInitialValues();

    } //end main

}

All the variables output 0 and null values.

A: I see one problem. The variables are declared in a class called InitialValues2, yet you are calling the printInitialValues() method on an object that is of the type InitialValues. It appears that you are never calling your printInitialValues() method.

A: class InitialValues {
    boolean t = true;
    char c = 'x';
    byte b = 47;
    short s = 0xff;
    int i =999;
    long l =1;
    float f = 3.14f;
    double d =3.14159;
    InitialValues reference;

    void printInitialValues() {
        System.out.println("data type           Initial values");
        System.out.println("boolean             " + t);
        System.out.println("char                [" + c + "]");
        System.out.println("byte                " + b);
        System.out.println("short               " + s);
        System.out.println("int                 " + i);
        System.out.println("long                " + l);
        System.out.println("float               " + f);
        System.out.println("double              " + d);
        System.out.println("reference           " + reference);

    } //end printinitialvalues

    public static void main(String args[]) {
        InitialValues iv = new InitialValues();
        iv.printInitialValues();

        //new InitialValues().printInitialValues();

    } //end main
}

You're class is called InitialValues2 You should rename it to InitialValues.

A: Your class name is InitialValues2 but you're creating an InitialValues object.  Replace "InitialValues iv = new InitialValues()" with "InitialValues2 iv = new InitialValues2()"

A: In the main method you are creating a new InitialValues, not an InitialValues2 (the class posted).

A: You are creating a InitialValues object and calling the constructor for it. But the values you want are in the InitialValues2 class. I am guessing there is some copy pasta error going on.
I may suggest changing your main method to:
public static void main(String args[]) {
    InitialValues2 iv = new InitialValues2();
    iv.printInitialValues();
}


text:
Q: Cannot import model from .models file to nested app sub_directory I suspect that I am not understanding something about django. I am trying to test the file scrape.py which calls an api and parses then writes the response to the model CMC in the models.py using sqlalchemy. I am trying to test it to see if the file itself will run but (here's where I think I'm going wrong) I am pressing the play button while having the scrape.py file pulled up in vscode. I suspect there is something here that Django won't allow but am not familiar enough with django to know if that is the case. It is throwing a ModuleNotFound error as described below but I suspect that it's doing that because I am calling it because when I type the dot after apis after import at the top of the file it shows a list of all the drop-down files in my apis app.
Here is my project tree:

(base) justinbenfit@MacBook-Pro-3 cds_website % tree
.
├── api
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   ├── admin.cpython-38.pyc
│   │   ├── apps.cpython-38.pyc
│   │   ├── models.cpython-38.pyc
│   │   ├── serializers.cpython-38.pyc
│   │   ├── urls.cpython-38.pyc
│   │   └── views.cpython-38.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── main.py
│   ├── management
│   │   ├── __init__.py
│   │   ├── commands
│   │   │   ├── __init__.py
│   │   │   ├── __pycache__
│   │   │   │   └── private.cpython-39.pyc
│   │   │   ├── private.py
│   │   │   └── scrape.py
│   │   └── test.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       ├── 0001_initial.cpython-38.pyc
│   │       └── __init__.cpython-38.pyc
│   ├── models.py
│   ├── serializers.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── cds_website
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   ├── settings.cpython-38.pyc
│   │   ├── urls.cpython-38.pyc
│   │   └── wsgi.cpython-38.pyc
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── requirements.txt

api is an app in a greater project called cds_website. The settings.py file in cds_website project directory contains the following installed apps:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework',
    'environ'
]

and my apps.py file in the api app contains the following class:
from django.apps import AppConfig

class ApiConfig(AppConfig):
    name = 'api'

CMC is a model in my models.py file. I am trying to import it into scrape.py. I have tried:
from ...models import CMC
from api.models import CMC
from ... import CMC
first one throws: ImportError: attempted relative import with no known parent package second one throws: ModuleNotFoundError: No module named 'api' third one throws: ImportError: attempted relative import with no known parent package
Here is a link to the code repo: https://github.com/Justinbenfit23/cds_website
Everything I have read indicates that at least one of these should work. Any direction appreciated!

A: I'm teste your project with from api.models import CMC and it's worked

A: The easiest way is to create ecrape_manage.py in cds_website-master
folder, content of ecrape_manage.py:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cds_website.settings")
import django
django.setup()
exec(open("api/management/commands/scrape.py").read())

and just run with python ecrape_manage.py


text:
Q: Quadrilateral side finding. Imagine a quadrilateral $ABCD$ where $AB$ is ∥ to $CD$ and ∠D is 2 times as large than ∠B.
We will add in 2 more variables, $a$ and $b$, where $a$ is the length of $AD$ and $b$ is the length of $CD$.
Our goal is to find the length of $AB$ in terms of $a$ and $b$
This is already very hard to visualise so I will be very happy if someone explains this to me, thanks!

A: First note that the corners of $ABCD$ rotate round it: the sides are $AB$, $BC$, $CD$ and $DA$. Hence if you know that the angle at $B$ is half the angle at $D$, you can start by drawing a sketch where you start by drawing $AB$, then put $B$ at, say, $60$ degrees to draw $BC$ (don't make $BC$ all that long, by the way), then you draw $CD$ parallel to $AB$ but stop when $D$ is twice $B$ and then join $D$ to $A$.
You get a trapezoidal shape.
When you have drawn it, you will visualize it just fine.


text:
Q: Prevent more than one animation in jquery solution breaks after spamming links I have 4 links on my page which fade their respective divs in and out as well as adjusting the containing div's height where necessary.
When the user spams these links the divs get out of sync or overlap each other. I have researched this and the two possible options are to use the .stop() method or a boolean variable which is checked onclick of each link.
I have tried implementing both without any joy. They do stop more than one function happening at once but after attempting to spam the links they will eventually break not fading anything in or out.
Could somebody explain what I have done wrong? Thanks
var animation_enabled;
animation_enabled = 0;

function open_labels_div(){
    if(animation_enabled == 1){
        return;
    }
    else{
        animation_enabled = 1;
        if($("#labels_div").is(':hidden')){
            if($("#charts_div").is(':visible')){
                $("#charts_div").fadeOut(400, function() {
                    $("#labels_div").fadeIn(400, function (){
                        $("#charts_div").css("display","none");
                        $("#labels_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
            else if($("#blank_charts_div").is(':visible')){
                $("#blank_charts_div").fadeOut(400, function() {
                    $("#labels_div").fadeIn(400, function (){
                        $("#blank_charts_div").css("display","none");
                        $("#labels_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
            else if($("#reorder_div").is(':visible')){
                var minus = $("#reorder_div").height()-100;
                $('#tab_content').animate({'height': '-='+minus},800,"linear", function() {
                    $("#reorder_div").fadeOut(400);
                    $("#labels_div").fadeIn(800, function (){
                        $("#reorder_div").css("display","none");
                        $("#labels_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
        }
    }
}

function open_charts_div(){
    if(animation_enabled == 1){
        return;
    }
    else{
        animation_enabled = 1;
        if($("#charts_div").is(':hidden')){
            if($("#labels_div").is(':visible')){
                $("#labels_div").fadeOut(400, function() {
                    $("#charts_div").fadeIn(400, function (){
                        $("#labels_div").css("display","none");
                        $("#charts_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
            else if($("#blank_charts_div").is(':visible')){
                $("#blank_charts_div").fadeOut(400, function() {
                    $("#charts_div").fadeIn(400, function (){
                        $("#blank_charts_div").css("display","none");
                        $("#charts_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
            else if($("#reorder_div").is(':visible')){
                var minus = $("#reorder_div").height()-100;
                $('#tab_content').animate({'height': '-='+minus},800,"linear", function() {
                    $("#reorder_div").fadeOut(400);
                    $("#charts_div").fadeIn(400, function (){
                        $("#reorder_div").css("display","none");
                        $("#charts_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
        }
    }
}

function open_blank_charts_div(){
    if(animation_enabled == 1){
        return;
    }
    else{
        animation_enabled = 1;
        if($("#blank_charts_div").is(':hidden')){
            if($("#labels_div").is(':visible')){
                $("#labels_div").fadeOut(400, function() {
                    $("#blank_charts_div").fadeIn(400, function (){
                        $("#labels_div").css("display","none");
                        $("#blank_charts_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
            else if($("#charts_div").is(':visible')){
                $("#charts_div").fadeOut(400, function() {
                    $("#blank_charts_div").fadeIn(400, function (){
                        $("#charts_div").css("display","none");
                        $("#blank_charts_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
            else if($("#reorder_div").is(':visible')){
                var minus = $("#reorder_div").height()-100;
                $('#tab_content').animate({'height': '-='+minus},800,"linear", function() {
                    $("#reorder_div").fadeOut(400);
                    $("#blank_charts_div").fadeIn(400, function (){
                        $("#reorder_div").css("display","none");
                        $("#blank_charts_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                });
            }
        }
    }
}

function open_reorder(){
    if(animation_enabled == 1){
        return;
    }
    else{
        animation_enabled = 1;
        if($("#reorder_div").is(':hidden')){
            var add = $("#reorder_div").height()-100;
            $('#tab_content').animate({'height': '+='+add},800,"linear", function() {
                if($("#labels_div").is(':visible')){
                    $("#labels_div").fadeOut(400);
                    $("#reorder_div").fadeIn(400, function (){
                        $("#labels_div").css("display","none");
                        $("#reorder_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                }
                else if($("#charts_div").is(':visible')){
                    $("#charts_div").fadeOut(400);
                    $("#reorder_div").fadeIn(400, function (){
                        $("#charts_div").css("display","none");
                        $("#reorder_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                }
                else if($("#blank_charts_div").is(':visible')){
                    $("#blank_charts_div").fadeOut(400);
                    $("#reorder_div").fadeIn(400, function (){
                        $("#blank_charts_div").css("display","none");
                        $("#reorder_div").css("display","inline-block");
                        animation_enabled = 0;
                    });
                }
            });
        }
    }
}

Labels

Charts

Blank Charts

Reorder

labels content

charts content

blank charts content

reorder content

A: Before starting an animation on one of these elements, add a call to jQuery.clearQueue().  This should clear the spammed animations before starting the next.
http://api.jquery.com/clearqueue/
$("#charts_div").clearQueue().fadeOut(400, function() {
    $("#labels_div").fadeIn(400, function (){
        $("#charts_div").css("display","none");
        $("#labels_div").css("display","inline-block");
        animation_enabled = 0;
    });
});

A: Sorry for the delay, I was working...
1st solution, based on your initial developments
Here I used the idea you got from the beginning: when you click on a li item, a javascript function is called. To reduce the code length, I made the following:

*

*Used only 1 function, the same for all buttons, which use variables (see comments in the script part)

*Used a link between the id I gave to the li items and the div items corresponding: the li item called itemA has a div called itemA_div (important for the script showing/hiding divs)

*Bind the function with jquery click() instead of your javascript onclick
Html markup:

Labels

Charts

Blank Charts

Reorder

labels content

charts content

blank charts content

reorder content

Script (with comments to help):
var animation_enabled;
animation_enabled = 0;

// On click event, call "changeDivs" function
$("#options_tabs ul li").click(changeDivs);

// changeDivs function
function changeDivs() {
    // If the flag is true, animation is running, so trying to launch another one
    if(animation_enabled == 1){
        return;
    } else {
        // If not currently animating, do the div visibility change
        animation_enabled = 1;

        // 1st - get the id of the li item clicked (calling the function, so I used this)
        var originItem = $(this).attr('id');
        // Then set a variable which is the content div that will be visible
        var destinationDiv = $("#" + originItem + "_div");

        // Here I will fadeOut all div inside tab_content which are not #myLiItemName_div, and wait the end of the fade with promise(), then fadeIn the div #myLiItemName_div
        $("#tab_content div:not(#" + originItem + "_div)").fadeOut(750).promise().done(function() {
            destinationDiv.fadeIn(800).promise().done(function() {
                animation_enabled = 0; });;
        });
    }
}

This jsfiddle show this working sample: http://jsfiddle.net/nrobert/8nCAJ/5/

2nd solution, using jquery UI
Using jquery UI "accordion" widget, it's very light:
Html part:

Labels

Labels content

Charts

Charts content

Blank Charts

Blank Charts content

Reorder

Reorder content

Script part:
$( "#options_tabs" ).accordion();

http://jsfiddle.net/nrobert/8nCAJ/2/


text:
Q: Render error ,Missing constraint in Constraint layout,Failed to initiate more classes .All Error at time All error occurs at same time I'm using latest version 3.0 but this error can't be solved I tried many ways

*

*style ->theme

*invalid cache

*Change API but all does not work kindly need for your help..
drag button in UI but button not show on UI and above error occur .
Xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.yousa.myapplication3.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"
        tools:layout_editor_absoluteX="69dp"
        tools:layout_editor_absoluteY="102dp" />

</android.support.constraint.ConstraintLayout>


text:
Q: Why can't I use Pandas in Jupyter even with "Requirement already satisfied"
Hey there. So I'm trying to learn Python for data manipulation. Obviously pandas is needed. I am using Windows 10 and have installed Jupyter through the console. I have had no problem getting into the jupyter notebook on my localhost and running basic commands like print. However, I cannot use pandas for some reason. Any guidance of where to look would be appreciated.

A: Is this a new kernel? If so, !pip runs pip using the system environment, not the kernel environment. Delete the ! at the beginning.


text:
Q: How to use snippet for remark method in linqpad? e.g,in visual studio i can type /// on top of method then system will generate
        /// <summary>
        ///
        /// </summary>
        /// <param name="xxx"></param>
        /// <returns></returns>

But it's not work for LINQPad. How to use snippet for remark method in linqpad ?
I've tried to search LINQPad Keyboard and Mouse Shortcuts but not answer.

A: JoeAlbahari's answer :

This feature is available in LINQPad 6, but not LINQPad 5. Note that it generates a simplified XML comment, i.e.:
///

from :
How to use snippet for remark method in linqpad? — LINQPad


text:
Q: How can I complete the "Yippee-ki-yay..." achievement from "The Dig" mission in Starcraft 2 without Vikings? The title pretty much sums it up. I am replaying some missions in Hard mode to complete achievements, and I am stuck with this one ("The Dig" mission in Hard mode).
I watched this video series:

. That strategy with Vikings seems nice, but I played this mission without unlocking Vikings first.

Has anyone completed this achievement without Vikings and would have a nice strategy?

A: There are alternative strategies listed here:

*

*using ghosts on the cliffs and pick off buildings with the drill

*using floating buildings to allow siege tanks to fire on the high ground on the northern base, continue with infantry support

A: The key is to, expand, wait, get a huge army and then make sure you get a foothold up the north ramp.
Start by getting at least two tanks and one bunker with 2 marine 1 marauder per ramp. Prioritize making SCVs. When you have your initial defense up start expanding, move your south bunker down, pretty far back, the longer the tanks up on the cliff can fire on the enemy before reaching the bunker the better. When you have your expansion up make an additional factory and two barracks (make some turrets so you don't have to worry about voidrays killing off tanks bevause your marines are out of position). From there just start massing units to the north. Marines, marauders and tanks.
When the drill has gotten to the last 1/5th of the door it's time to move out. Position your tanks in siege mode below the ramp. Move up the ramp and start blasting. Focus the drill on the colossi as they will eat up your infantry. You need to keep making units and rally them to  the ramp. If you lose your foothold on the top of the ramp you will have to mass up units again. Once you have settled in on the top of the ramp, start leapfrogging your tanks and blast any buildings and units with the drill. Once you get rolling you will probably be able to take out every protoss building before the drill is even finished.

A: I did it with a few floating barracks for spotting, and the drill to take down the buildings.
Keep the floating buildings on high ground, so that they can't be seen from the ground and slowly move in and take everything you see out with the drill. Target any air units first, and then everything that can shoot up. Whenever nothing dangerous is around, take down other buildings.

A: I got 25 barracks, and floated over the protoss base with 37500 hit points at my leisure and shift-queued the laser to take out all the buildings I could see.  I ended up losing a lot of barracks, but I had such an absurd amount that it didn't matter.

A: I got the achievement with a safe but somewhat boring and slow strategy: Turtle up with a boatload of siege tanks and missile turrets, and float a command center up to the northwest corner of the map to get vision on the Protoss buildings. Use the cannon to pick off the buildings (and the defending units), stopping to take out the archons/immortals/colossi that gather outside your base when they appear. Your tanks can handle zealots and stalkers, so don't waste cannon time on those.
The Protoss will continually rebuild the structures that you destroy, so you can probably just work your way back and forth in the top-left area of the map until you've blown up enough structures to unlock the achievement. Try building two command centres, and bring one back to base for repairs when it gets heavily damaged.
When controlling the cannon, remember to use the Shift key to queue up multiple targets. This will give you a few seconds to do other stuff around your base while you wait for the cannon. When scouting structures with your CC, you can use the Hold Position (H) command to stop it from moving around when taking hits and losing vision on buildings at the edge of the fog of war.
I'm sure other methods will get the job done faster, but this strategy was very safe and not very difficult.

A: A key thing to remember with this sort of mission is that you can get the achievement even if you fail the mission. So feel free to do an all-or-nothing blitz to kill their base, while doing only the minimum to secure your own. Once you kill 50 buildings, you can restart it and finish it cleanly, or just restore to a save.

A: I managed to do it with just Marines, Medics, Marauders and Siege Tanks. I put up two bunkers and four tanks at each ramp for defense, then built up my forces for the assault. I attacked the base directly to the north. The initial tactic is to place tanks in siege mode a little bit back from the protoss ramp so they are out of range of photon cannons. Then run your MMM ball halfway up the ramp so the tanks can start shooting down the cannons. Meanwhile keep the drill hotkeyed so that it can assist in taking down archons, collossi, void rays, and anything that's doing damage. Don't let your MMM ball run out of reach of your tanks.
When you've beaten back their initial defensive line you've got a foothold. Move your tanks up and keep on pressing in. Focus on taking down the pylons around unit producing buildings and keep your drill handy to zap the occasional pylon or counter-attacking heavy unit.
The real key to this strategy is you need to keep reinforcing. Keep your barracks and factory hotkeyed and move the rally point to deliver troops near the front as you move from left to right across the map. Before you've taken out the entire northern base you should have the achievement. Good luck!


text:
Q: How to overcome IN clause issue in oracle i am updating a table called table2 from table1 on column name Active_status.But the problem the result contains more than 1000.How to overcome this issue.I am using this query in a c# application.I heard we can use temp table ,if so how can i use or is there any better way.followingis my query
UPDATE table2
SET Active_status = 'N',
 MODIFIED_DATE    = SYSDATE
    WHERE t2_SLNO    IN
      (SELECT t2_SLNO
      FROM table2
      LEFT JOIN table1
      ON table2.t2_NAME       = table1.t1_NAME
      WHERE table1.t1_NAME IS NULL
      )
    AND Active_status <> 'N';

EDIT
I am doing this modification everday.By using a merge.But there are situations like table2 contain some dead data which i want to make status 'N' since the source of table1 and table2 is a remote database which is exposed by some other team.So thought of to do this work after my existing MERGE operation

A: As @aleksej suggested, you can use MERGE:
MERGE INTO table1 t
USING table2 s
ON(t.t1_NAME = s.t2_NAME)
WHEN NOT MATCHED UPDATE SET Active_status = 'N',
                            MODIFIED_DATE = sysdate
WHERE t.Active_status <> 'N'

And you can change you update to work like this:
UPDATE table1 t
SET t.Active_status = 'N',
    t.MODIFIED_DATE = sysdate
WHERE NOT EXISTS(SELECT 1 FROM table2 s
                 WHERE t.t1_NAME = s.t2_NAME)
  AND t.Active_status <> 'N'


text:
Q: How to add createReducer with old reducer function I like the new way to create reducer with createReducer but I am not able to find any migration path how you can migrate your old reducer to this new function.
I would like to add new state mutation in createReducer way and combine both reducer then overtime I move things.
any idea how to do?

A: Read Mixing Action Styles In NgRx State by Brandon Roberts.
import { createReducer, on, union } from '@ngrx/store';
import * as LegacyCounterActions from './legacy-counter.actions';
import * as CounterActions from './counter.actions';
export const initialState = 0;
type State = number;
const counterReducer = createReducer(initialState,
  on(CounterActions.increment, state => state + 1)
);
const CounterActionsUnion = union({...CounterActions});
type Actions =
  | LegacyCounterActions.Union
  | typeof CounterActionsUnion;
export function reducer(state: State | undefined, action: Actions) {
  switch(action.type) {
    case LegacyCounterActions.CounterActionTypes.Increment:
      return state + 1;
    default:
      return counterReducer(state, action);
  }
}