text:
Q: How to know if Android Wifi settings pane is on top? I need to know if the Wifi settings pane is on top. I found this way:
ActivityManager a = (ActivityManager)context.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningTaskInfo> t = a.getRunningTasks( 1 );
if ( t.get( 0 ).topActivity.getClassName().equals( "com.android.settings.Settings$WifiSettingsActivity" ) )
{
    return true; // Yes it is!
}
else
{
    return false; // No it's not!
}

Actually, it works fine. But in Android reference doc here it is written that we should not use this method (read the link for more details). So does somebody know how to perform this check in an other way? Note that I target SDK level 14 and higher.
Thanks!

A: Don't detect the settings pane, rather focus on why you would want to open the settings panel (you need WiFi connection and it is disabled, you need a particular SSID and the current one is not that one, ...).
For example, show your activity and if WiFi is disabled, show a popup to ask the user what he wants to do.


text:
Q: python web-crawling, requests.post does not return any content in server environment I'm trying to crawling the csv file in web.
Downloading file in web page works. Also, this code works well in local environment(Windows).
However, when I execute the code in the sever environment(Ubuntu) it returns no contents as the result below shows. How can I solve this? I can't figure out what is the problem.
def get_otp(bld, date):
    url="http://marketdata.krx.co.kr/contents/COM/GenerateOTP.jspx"
    header={'Referer': 'http://marketdata.krx.co.kr/mdi', "User-Agent": "Mozilla/5.0",
            "X-Requested-With": "XMLHttpRequest"}
    bld= "MKD/13/1302/13020101/mkd13020101"
    param={"name": "fileDown", "filetype" : "csv", "url": bld, "market_gubun": 'ALL',
           "sect_tp_cd": "ALL","schdate": date,
           "pagePath": "/contents/MKD/13/1302/13020101/MKD13020101.jsp"}
    return requests.get(url, headers=header, params=param).text

def get_file(otp):
    url="http://file.krx.co.kr/download.jspx?"
    header={"Origin": "http://marketdata.krx.co.kr",
            'Referer': 'http://marketdata.krx.co.kr/mdi',
            "Upgrade-Insecure-Requests": "1",
            "Host": "file.krx.co.kr",
            "User-Agent": "Mozilla/5.0"}
    param={'code':otp}
    byte_data = requests.post(url, headers=header, data=param)
    data=byte_data
    #df = pd.read_csv(BytesIO(byte_data))
    return data

bld= "MKD/13/1302/13020101/mkd13020101"
otp=get_otp(bld,"20201116")
ret=get_file(otp)
ret.heaers

Result
{'Date': 'Thu, 19 Nov 2020 08:37:01 GMT',
'Set-Cookie': 'SCOUTER=z368kb97coovj; Expires=Tue, 07-Dec-2088 11:51:08 GMT, JSESSIONID=9AC74CC81C757D3CD656EA4FD0D3A05D.102tomcat4; Path=/; HttpOnly',
 'Content-Length': '0',
'Content-Type': 'text/html;charset=UTF-8'}

A: I got it to work after changing to the bld and pagePath applicable to my example, and changing the base url from http://marketdata.krx.co.kr to https://global.krx.co.kr.
def get_otp(bld, page_path, date):
    url="https://global.krx.co.kr/contents/COM/GenerateOTP.jspx"
    header={'Referer': 'https://global.krx.co.kr/mdi', "User-Agent": "Mozilla/5.0",
            "X-Requested-With": "XMLHttpRequest"}
    param={"name": "fileDown", "filetype" : "csv", "url": bld, "market_gubun": 'ALL',
           "sect_tp_cd": "ALL","schdate": date, "pagePath": page_path}
    return requests.get(url, headers=header, params=param).text

def get_file(otp):
    url="https://file.krx.co.kr/download.jspx?"
    header={"Origin": "https://global.krx.co.kr",
            'Referer': 'https://global.krx.co.kr/mdi',
            "Upgrade-Insecure-Requests": "1",
            "Host": "file.krx.co.kr",
            "User-Agent": "Mozilla/5.0"}
    param={'code':otp}
    data = requests.post(url, headers=header, data=param).text
    return data

bld = "GLB/05/0503/0503050600/glb0503050600"
page_path = "/contents/GLB/05/0503/0503050600/GLB0503050600.jsp"
date = "20210714"

otp = get_otp(bld, page_path, date)
data = get_file(otp)

redpajama_set_name: RedPajamaStackExchange


text: Q: Removing Affiliate code from google analytics - android sdk I am using enhanced e-commerce to track all purchases. We are not setting any affiliate code in the ProductAction object. But still in the GA dashboard all transactions are shown in affiliate code with the value as "not-set". Is there any way to remove/disable the affiliate code tracking for enhanced e-commerce purchases?


text:
Q: HashMap giving wrong result       HashMap<Integer, Integer> hmap = new HashMap<>();
      hmap.put(1,(int)128);
      hmap.put(2,(int)128);
      if((hmap.getOrDefault(2, -1)!=hmap.getOrDefault(1, -1)) {
          System.out.println("wrong");

      }
      System.out.println(hmap.get(2)+" "+hmap.get(1));
      if(hmap.get(2)==hmap.get(1))
      {
          System.out.println("wrong2");
      }

The above code output on console is
wrong
In the above case, the output should be wrong2
If I typecast value to int then it shows the output as
wrong2
      HashMap<Integer, Integer> hmap = new HashMap<>();
      hmap.put(1,(int)128);
      hmap.put(2,(int)128);
      if((int)hmap.getOrDefault(2, -1)!=(int)hmap.getOrDefault(1, -1)) {
          System.out.println("wrong");

      }
      System.out.println(hmap.get(2)+" "+hmap.get(1));
      if((int)hmap.get(2)==(int)hmap.get(1))
      {
          System.out.println("wrong2");
      }

A: If you have an object, in your case Integer, you shouldn't use != or == in this case, you should use the method .equals(), as explained here https://www.geeksforgeeks.org/difference-equals-method-java/


text:
Q: Why is the UI not updated when I change an object reference in an interval and the change detection is onPush? Example:
@Component({
    selector: "app-ex3-component-a",
    templateUrl: "./ex3-component-a.component.html",
    styleUrls: ["./ex3-component-a.component.scss"],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class Ex3ComponentAComponent implements OnInit
{
    public config = {title: "Initial title."};

    public interval: Subscription;

    constructor() { }

    public ngOnInit(): void
    {
    }

    public changeTitle()
    {
        if (this.interval)
        {
            this.interval.unsubscribe();
            this.interval = null;
            return;
        }

        this.interval = interval(300)
        .pipe(
            map(() => ({...this.config, title: `From A (${Math.floor(Math.random() * 1000)})`})),
            tap((newConfig) => this.config = newConfig),
            tap(() => console.log(this.config.title))
        ).subscribe();
    }
}

HTML:

config.title={{config.title}}

<button (click)="changeTitle()">{{interval ? "Stop" : "Start changing"}}</button>

What happens:

*

*every 300 ms a new value is displayed in the console

*the UI only changes when I stop the interval

*if i set the interval to for example to 3 seconds, the same happens

I expect the UI to be updated as well as the console - but its not happening.

A: That's because when you useonPush, angular is looking for changes on Input parameters.
For more: onpush-change-detection-how-it-works
You can detect the changes manually (that's the recommended way) like this:
constructor(private cdr: ChangeDetectorRef)

this.interval = interval(300)
        .pipe(
            map(() => ({...this.config, title: `From A (${Math.floor(Math.random() * 1000)})`}))
        ).subscribe(newConfig => {
             this.config = newConfig;
             this.cdr.detectChanges();
             console.log(this.config.title);
         });

*

*Be aware that the code is not tested, maybe it has some typo's, but the main idea is correct.


text:
Q: Unicode characters saved as � using JDBC, but saved correctly using phpMyAdmin Here is how I create a connection:
Class.forName("com.mysql.jdbc.Driver");
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "PASSWORD");
properties.setProperty("useSSL", "false");
properties.setProperty("autoReconnect", "true");
properties.setProperty("useUnicode", "true");
properties.setProperty("characterEncoding", "UTF-8");
Connection connection =  DriverManager.getConnection("jdbc:mysql://localhost/coolpoop", properties);

PreparedStatement statement = connection.prepareStatement("SET NAMES 'utf8'");
statement.execute();
statement = connection.prepareStatement("SET CHARACTER SET utf8");
statement.execute();

Table:

Inserting:
PreparedStatement state = Mysql.conn().prepareStatement("insert into contents(campaignId, site_id, original_article_id, title, content) values(-1, -1, -1, ?, ?)");
state.setString(1, "acbdąčęėįšųū");
state.setString(2, "acbdąčęėįšųū");
state.execute();

Result:

What is wrong?
EDIT1:
If I insert through phpMyAdmin, all good:

A: In some cases, Java development tools (e.g., Eclipse) use a default character encoding of Cp1252 (a.k.a. windows-1252) for Java source files. That can cause strange encoding issues when working with Unicode characters because the source file encoding affects

*

*how string literals are interpreted, and

*the default character set used by the JVM when the project is run from within the IDE.

As in this case, a quick fix is to simply change the source file encoding to UTF-8.


text:
Q: Fork error: resource temporarily unavailable I have written this code in a project based on the client-server model but in one of my files I have this error: fork error resource temporarily unavailable.
this is the
Code:
#include "LibreriaFunzioni.c"
int main (int argc , char *argv[])
{
    int list_fd,list_fd2,fd,fd2,SocketFiglioSede;
    int i;
    struct sockaddr_in s_addr,s_addr2,c_addr,c_addr2;
    char buffer [4096];
    socklen_t len,len2;
    pid_t pid_Admin,pid_Client,pid;
    int logging =1,N_Portate;
    PORTATA *Menu = NULL;
    ORDINE Ordine;
    ORDINE OrdineID;

    Menu = CaricaMenuPortate(&N_Portate);
 //------------------ADMIN--------------------------------------
    /* create socket ADMIN*/
    if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation error");
        exit(1);
    }

    /* initialize address */
    memset((void *)&s_addr, 0, sizeof(s_addr));   /* clear server address */
    s_addr.sin_family = AF_INET;                  /* address type is INET */
    s_addr.sin_port = htons(2700);                   /* echo port is 7 */
    s_addr.sin_addr.s_addr = htonl(INADDR_ANY);   /* connect from anywhere */

    /* bind socket */
    if (bind(list_fd, (struct sockaddr *) &s_addr, sizeof(s_addr)) < 0) {
        perror("bind error");
        exit(1);
    }

    /* main body */
    if (listen(list_fd, 4096) < 0) {
        perror("listen error");
        exit(1);
    }
//-----------------------CLIENT-------------------------------------
    /* create socket CLIENT */
    if ( (list_fd2 = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation error");
        exit(1);
    }

    /* initialize address */
    memset((void *)&s_addr2, 0, sizeof(s_addr2));   /* clear server address */
    s_addr2.sin_family = AF_INET;                  /* address type is INET */
    s_addr2.sin_port = htons(2800);                   /* echo port is 7 */
    s_addr2.sin_addr.s_addr = htonl(INADDR_ANY);   /* connect from anywhere */

    /* bind socket */
    if (bind(list_fd2, (struct sockaddr *) &s_addr2, sizeof(s_addr2)) < 0) {
        perror("bind error");
        exit(1);
    }

    /* main body */
    if (listen(list_fd2, 4096) < 0) {
        perror("listen error");
        exit(1);
    }

    while(1){
      //---------GESTIONE ADMIN--------------------------------------------
        pid_Admin = fork();
        if(pid_Admin < 0) {
            perror (" fork error ");
            exit ( -1);
        }
        if(pid_Admin == 0)
        {
            len = sizeof(c_addr);
            if ((fd = accept(list_fd, (struct sockaddr *) &c_addr, &len)) < 0) {
                perror("accept error");
                exit(1);
            }

            close ( list_fd );
            if(logging)
            {
                inet_ntop(AF_INET, &c_addr.sin_addr, buffer, sizeof(buffer));
                printf("\nNUOVA SESSIONE con admin IP:PORTA => %s:%d su socket => %d\n", buffer, ntohs(c_addr.sin_port), fd);
                SpedisciTabella(fd, N_Portate, Menu);
            }

            close(fd);
            exit (0);
        }
     //-------------GESTIONE CLIENT----------------------------------------
        pid_Client = fork();
        if(pid_Client < 0) {
            perror (" fork error ");
            exit ( -1);
        }
        if(pid_Client == 0)
        {
            len2 = sizeof(c_addr2);
            if ((fd2 = accept(list_fd, (struct sockaddr *) &c_addr2, &len2)) < 0) {
                perror("accept error");
                exit(1);
            }

            close ( list_fd2 );
            if(logging)
            {
                inet_ntop(AF_INET, &c_addr.sin_addr, buffer, sizeof(buffer));
                printf("\nNUOVA SESSIONE con client IP:PORTA => %s:%d su socket => %d\n", buffer, ntohs(c_addr.sin_port), fd);
                SpedisciTabella(fd2, N_Portate, Menu);
            }
            pid = fork();
            if((pid<0))
            {perror ("Errore nella fork()"); exit (-1);}
            if(pid==0)
            {
                read(fd2, &Ordine, sizeof(Ordine));
                if(Ordine.sede == 1){
                    SocketFiglioSede = ConnettiAlServer("127.0.0.1", 2200);
                    FullWrite(SocketFiglioSede, &Ordine, sizeof(Ordine));
                    read(SocketFiglioSede,&Ordine, sizeof(Ordine));
                    printf("\nID %d",Ordine.ID);
                    printf("\nCOD %d",Ordine.SceltaP);
                    FullWrite(fd2, &Ordine, sizeof(Ordine));
                    printf("\n** (PADRE) Disconnetti client su socket ==> %d **\n", fd2);
                    close(SocketFiglioSede); /
                    exit(0);
                }// Chiudi processo

                if(Ordine.sede == 2){
                    SocketFiglioSede = ConnettiAlServer("127.0.0.1", 2300);
                    FullWrite(SocketFiglioSede, &Ordine, sizeof(Ordine));
                    read(SocketFiglioSede,&Ordine, sizeof(Ordine));
                    FullWrite(fd2, &Ordine, sizeof(Ordine));
                    close(SocketFiglioSede);
                    printf("\n** (PADRE) Disconnetti client su socket ==> %d **\n", fd2);
                    exit(0);
                }// Chiudi processo

            }
            close(fd2);
            exit (0);
        }
    }
    exit (0);
}

I try to correct the code but I fail all the time.
Can you help me?


text:
Q: Access property of another object in a class - PHP I have been looking hard for a solution on this and i can't solve it so i will ask my question here and hopefully it will help others searching for the same question.
I have a Class for an items based on "Armor" for example.
class Armor {
    public $name, $defense, $durability;
       function __construct($name, $defense, $durability){
       $this->name = $name;
       $this->defense = $defense;
       $this->durability = $durability;
   }
}

Then i create a bunch of objects like this:
$heavy_armor = new Armor("Heavy Armor", 250, 50);

Then in a totally different file and use, I have another class for Magic Items which will create a brand new Magic Item but the base i want to use is the already existing heavy armor. However, there is a catch. I am already extending a different MagicArmors class because i will be creating a lot of these new classes and i want the common properties that will be the same across all Magic Armors to stay in one place - the MagicArmors class. Example:
class MagicHeavyArmor extends MagicArmors {
    public function __construct() {
        $this->name = "Magic Heavy Armor";
// so here i want to point to the Defense and Durability of the $heavy_armor object
        $this->defense = 625; // Ideally i want $this->defense = $heavy_armor->defense * 2.5
        $this->durability = 87.5; // Same here - I want $this->durability = $heavy_armor->durability * 1.75
    }

So how do I make this work? The reason is that i will be creating a huge load of these and i want all of them to be able to looking for their base properties from other objects. And if i need to change a value of a property, to ease my life later.

A: The constructor should take the previous armor as a parameter, and can refer to its properties.
    public function __construct($armor) {
        $this->name = "Magic " . $armor->name;
        $this->defense = $armor->defense * 2;
        $this->durability = $armor->durability * 1.75;
    }

Then you create the object like this:
new MagicHeavyArmor($heavy_armor);


text:
Q: Why is .NET exception not caught by try/catch block? I'm working on a project using the ANTLR parser library for C#.  I've built a grammar to parse some text and it works well.  However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions.  The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.
The issue for me is that I can't replicate this issue anywhere else but in my full code.  The call stack shows that the exception definitely occurs within my try/catch(Exception) block.  The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it.  I wonder if non-debuggable assemblies inhibit exception bubbling?  The call stack looks like this; external assembly calls are in Antlr.Runtime:

    Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C#
    Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes
    Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes
    Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes
    Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes   C#
    Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C#

The code snippet from the bottom-most call in Parse() looks like:
     try {
        // Execution stopped at parser.prog()
        TimeDefParser.prog_return prog_ret = parser.prog();
        return prog_ret == null ? null : prog_ret.value;
     }
     catch (Exception ex) {
        throw new ParserException(ex.Message, ex);
     }

To me, a catch (Exception) clause should've captured any exception whatsoever.  Is there any reason why it wouldn't?
Update: I traced through the external assembly with Reflector and found no evidence of threading whatsoever.  The assembly seems to just be a runtime utility class for ANTLR's generated code.  The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception.  This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input.  This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.
Also, the rethrowing of ParserException is really irrelevant to this situation.  That is a layer of abstraction that takes any exception during parse and convert to my own ParserException.  The exception handling problem I'm experiencing is never reaching that line of code.  In fact, I commented out the "throw new ParserException" portion and still received the same result.
One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion.  I still received the same result.
Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.
Man, I'm still stumped!  I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5.  The external assembly is 2.0.  Also, some of my code subclasses a class in the 2.0 assembly.  Could a version mismatch cause this issue?
Update 2: I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario.  I was able to replicate the same unhandled exception when running consistently in .NET 2.0.
I learned that ANTLR has recently released 3.1.  So, I upgraded from 3.0.1 and retried.  It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.
Update 3:
I've replicated this scenario in a simplified VS 2008 project.  Feel free to download and inspect the project for yourself.  I've applied all the great suggestions, but have not been able to overcome this obstacle yet.
If you can find a workaround, please do share your findings.  Thanks again!

Thank you, but VS 2008 automatically breaks on unhandled exceptions.  Also, I don't have a Debug->Exceptions dialog.  The NoViableAltException that is thrown is fully intended, and designed to be caught by user code.  Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.
The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.

A: Regardless of whether the assembly has been compiled as a release build the exception should certainly 'bubble' up to the caller, there's no reason an assembly not being compiled in debug mode should have any affect on that.
I'd agree with Daniel is suggesting that perhaps the exception is occurring on a separate thread - try hooking the thread exception event in Application.ThreadException. This should be raised when any unhandled thread exception occurs. You could adapt your code thus:-
using System.Threading;

...

void Application_ThreadException(object sender, ThreadExceptionEventArgs e) {
  throw new ParserException(e.Exception.Message, e.Exception);
}

 ...

 var exceptionHandler =
    new ThreadExceptionEventHandler(Application_ThreadException);
 Application.ThreadException += exceptionHandler;
 try {
    // Execution stopped at parser.prog()
    TimeDefParser.prog_return prog_ret = parser.prog();
    return prog_ret == null ? null : prog_ret.value;
 }
 catch (Exception ex) {
    throw new ParserException(ex.Message, ex);
 }
 finally {
    Application.ThreadException -= exceptionHandler;
 }

A: Are you using .Net 1.0 or 1.1?  If so then catch(Exception ex) won't catch exceptions from unmanaged code.  You'll need to use catch {} instead.  See this article for further details:
http://www.netfxharmonics.com/2005/10/net-20-trycatch-and-trycatchexception/

A: I'm with @Shaun Austin - try wrapping the try with the fully qualified name
catch (System.Exception)

and see if that helps.Does the ANTLR doc say what Exceptions should be thrown?

A: I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it.
In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by user code" and a callstack that looks like this:

         [External Code]
    >   TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes   C#
        [External Code]
        TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes    C#
        TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#
        TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#
        [External Code]

If you right click in the callstack window and run turn on show external code you see this:

        Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes
        Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes
    >   TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes   C#
        Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes
        Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes
        Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes
        TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes    C#
        TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#
        TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#
        [Native to Managed Transition]
        [Managed to Native Transition]
        mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes
        Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes
        mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes
        mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes
        mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes

The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled.
The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it.
Things to play with to see how this looks for those who didn't repro the problem:

*

*Go to Tools/Options/Debugging and
turn off "Enable Just My code
(Managed only)". or option.

*Go to Debugger/Exceptions and turn off "User-unhandled" for
Common-Language Runtime Exceptions.

A: Is it possible that the exception is being thrown in another thread? Obviously your calling code is single threaded, but maybe the library you are consuming is doing some multithreaded operations under the covers.

A: You can set up VS.Net to break as soon as any exception occurs. Just run your project in debug mode, and it will stop as soon as the exception is thrown.  Then you should have a better idea of why it isn't being caught.
Also, you can put some code in to catch all unhandled exceptions.
Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler);

 // Catch all unhandled exceptions in all threads.
 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);

A:
To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?

The only possibility I can think of is that something else is catching it before you and handling it in a way that appears to be an uncaught exception (e.g. exiting the process).

my try/catch block won't catch it and instead stops execution as an unhandled exception.

You need to find what is causing the exit process.  It might be something other than an unhandled exception.
You might try using the native debugger with a breakpoint set on "{,,kernel32.dll}ExitProcess".  Then use SOS to determine what managed code is calling exit process.

A: Personally I'm not convinced by the threading theory at all.
The one time I've seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different "Exception" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn't catch it because the type didn't match.
So in summary, is there another Exception type in a different namespace that is in a using in that class?
EDIT: A quick way to check this is make sure in your catch clause you fully qualify the Exception type as "System.Exception" and give it a whirl!
EDIT2: OK I've tried the code and concede defeat for now. I'll have to have another look at it in the morning if no one has come up with a solution.

A: Hmm, I don't understand the problem. I downloaded and tried your example solution file.
An exception is thrown in TimeDefLexer.cs, line 852, which is subsequently handled by the catch block in Program.cs that just says Handled exception.
If I uncomment the catch block above it, it will enter that block instead.
What seems to be the problem here?
As Kibbee said, Visual Studio will stop on exceptions, but if you ask it to continue, the exception will get caught by your code.

A: I downloaded the sample VS2008 project, and am a bit stumped here too.  I was able to get past the exceptions however, although probably not in a way that will work will great for you.  But here's what I found:
This mailing list post had a discussion of what looks to be the same issue you are experiencing.
From there, I added a couple dummy classes in the main program.cs file:
class MyNoViableAltException : Exception
{
    public MyNoViableAltException()
    {
    }
    public MyNoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, Antlr.Runtime.IIntStream input)
    {
    }
}
class MyEarlyExitException : Exception
{
    public MyEarlyExitException()
    {
    }

    public MyEarlyExitException(int decisionNumber, Antlr.Runtime.IIntStream input)
    {
    }
}

and then added the using lines into TimeDefParser.cs and TimeDefLexer.cs:
using NoViableAltException = MyNoViableAltException;
using EarlyExitException = NoViableAltException;

With that the exceptions would bubble into the fake exception classes and could be handled there, but there was still an exception being thrown in the mTokens method in TimeDefLexer.cs.  Wrapping that in a try catch in that class caught the exception:
            try
            {
                alt4 = dfa4.Predict(input);
            }
            catch
            {
            }

I really don't get why wrapping it in the internal method rather than where it is being called from handle the error if threading isn't in play, but anyways hopefully that will point someone smarter than me here in the right direction.

A: I downloaded your code and everything work as expected.
Visual Studio debugger correctly intercepts all exceptions. Catch blocks work as expected.
I'm running Windows 2003 server SP2, VS2008 Team Suite (9.0.30729.1 SP)
I tried to compile you project for .NET 2.0, 3.0 & 3.5
@Steve Steiner, debugger options you mentioned have nothing to do with this behavior.
I tried to play with these options with no visible effects - catch blocks managed to intercept all exceptions.

A: Steve Steiner is correct that the exception is originating in the antlr library, passing through the mTokens() method and being caught in the antlr library. The problem is that this method is auto-generated by antlr. Therefore, any changes to handle the exception in mTokens() will be overwritten when your generate your parser/lexer classes.
By default, antlr will log errors and try to recover parsing. You can override this so that the parser.prog() will throw an exception whenever an error is encountered. From your example code i think this is the behaviour you were expecting.
Add this code to your grammer (.g) file. You will also need to turn off "Enable Just My Code" in the debugging menu.
@members {

    public override Object RecoverFromMismatchedSet(IIntStream input,RecognitionException e,    BitSet follow)
    {
        throw e;
    }
}

@rulecatch {
    catch (RecognitionException e)
    {
        throw e;
    }
}

This is my attempt at a C# version of the example given in the "Exiting the recogniser on first error" chapter of the "Definitive ANTLR Reference" book.
Hope this is what you were looking for.

A: I can tell you what's happening here...
Visual Studio is breaking because it thinks the exception is unhandled.  What does unhandled mean?  Well, in Visual Studio, there is a setting in the Tools... Options... Debugging... General... "Enable Just My Code (Managed only)".  If this is checked and if the exception propagates out of your code and out to a stack frame associated with a method call that exists in an assembly which is "NOT YOUR CODE" (for example, Antlr), that is considered "unhandled".  I turn off that Enable Just My Code feature for this reason.  But, if you ask me, this is lame... let's say you do this:
ExternalClassNotMyCode c = new ExternalClassNotMyCode();
try {
    c.doSomething( () => { throw new Exception(); } );
}
catch ( Exception ex ) {}

doSomething calls your anonymous function there and that function throws an exception...
Note that this is an "unhandled exception" according to Visual Studio if "Enable Just My Code" is on.  Also, note that it stops as if it were a breakpoint when in debug mode, but in a non-debugging or production environment, the code is perfectly valid and works as expected.  Also, if you just "continue" in the debugger, the app goes on it's merry way (it doesn't stop the thread).  It is considered "unhandled" because the exception propagates through a stack frame that is NOT in your code (i.e. in the external library).  If you ask me, this is lousy.  Please change this default behavior Microsoft.  This is a perfectly valid case of using Exceptions to control program logic.  Sometimes, you can't change the third party library to behave any other way, and this is a very useful way to accomplish many tasks.
Take MyBatis for example, you can use this technique to stop processing records that are being collected by a call to SqlMapper.QueryWithRowDelegate.

A: Oh and in reference to what Kibbee said; if you select Debug|Exceptions in VS and just click all the boxes in the 'thrown' column it should pick everything up AFAIK as a 'first chance exception', i.e. VS will indicate when the exception is about to be processed by everything else and break on the relevant code. This should help with debugging.

A: The best option sounds like setting Visual Studio to break on all unhandled exceptions (Debug -> Exceptions dialog, check the box for "Common Language Runtime Exceptions" and possibly the others as well). Then run your program in debug mode. When the ANTLR parser code throws an exception it should be caught by Visual Studio and allow you to see where it is occurring, the exception type, etc.
Based on the description, the catch block appears to be correct, so one of several things could be happening:

*

*the parser is not actually throwing an exception

*the parser is ultimately throwing something that isn't deriving from System.Exception

*there is an exception being thrown on another thread that isn't being handled

It sounds like you have potentially ruled out issue #3.

A:
I traced through the external assembly with Reflector and found no evidence of threading whatsoever.

You can't find any threading does not mean there is no threading
.NET has a 'thread pool' which is a set of 'spare' threads that sit around mostly idle. Certain methods cause things to run in one of the thread pool threads so they don't block your main app.
The blatant examples are things like ThreadPool.QueueUserWorkItem, but there are lots and lots of other things which can also run things in the thread pool that don't look so obvious, like Delegate.BeginInvoke
Really, you need to do what kibbee suggests.

A: have you tried to print (Console.WriteLine()) the exception inside the catch clause, and not use visual studio and run your application on console?

A: I believe Steve Steiner is correct.  When researching Steve's suggestions, I came across this thread talking about the "Enable Just My Code" option in Tools|Options|Debugger|General.  It is suggested that the debugger will break in certain conditions when non-user code either throws or handles an exception.  I'm not exactly sure why this even matters, or why the debugger specifically says the exception was unhandled when it really was.
I was able to eliminate the false breaks by disabling the "Enable Just My Code" option.  This also changes the Debug|Exceptions dialog by removing the "User-handled" column as it no longer applies.  Or, you can just uncheck the "User-handled" box for CLR and get the same result.
Bigtime thanks for the help everyone!

A:
"Also, you can put some code in to
  catch all unhandled exceptions. Read
  the link for more info, but the basics
  are these two lines."

This is false. This used to catch all unhandled exceptions in .NET 1.0/1.1 but it was a bug and it wasn't supposed to and it was fixed in .NET 2.0.
AppDomain.CurrentDomain.UnhandledException

Is only intended to be used as a last chance logging saloon so you can log the exception before the program exits. It wont catch the exception as of 2.0 onwards (although in .NET 2.0 at least there is a config value you can modify to make it act like 1.1 but it isn't recommended practice to use this.).
Its worth noting that there are few exceptions that you cannot catch, such as StackOverflowException and OutOfMemoryException. Otherwise as other people have suggested it might be an exception in a background thread somewhere. Also I'm pretty sure you can't catch some/all unmanaged/native exceptions either.

A: I don't get it...your catch block just throws a new exception (with the same message). Meaning that your statement of:

The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.

is exactly what is expected to happen.

A: I agree with Daniel Auger and kronoz that this smells like an exception that has something to do with threads. Beyond that, here are my other questions:

*

*What does the complete error message say? What kind of exception is it?

*Based on the stack trace you've provided here, isn't the exception thrown by you code in TimeDefLexer.mTokens()?

A: I'm not sure if I'm being unclear, but if so, I'm seeing the debugger halt execution with an "Unhandled Exception" of type NoViableAltException.  Initially, I didn't know anything about this Debug->Exceptions menu item because MS expects you, at VS install time, to commit to a profile when you have no idea how they are different.  Apparently, I was not on the C# dev profile and was missing this option.  After finally debugging all thrown CLR exceptions, I was unfortunately unable to discover any new behavior leading to the reason for this unhandled exception issue.  All the exceptions thrown were expected and supposedly handled in a try/catch block.
I reviewed the external assembly and there is no evidence of multithreading.  By that, I mean no reference exists to System.Threading and no delegates were used whatsoever.  I'm familiar with that constitutes instantiating a thread.  I verify this by observing the Threads toolbox at the time of the unhandled exception to view there is only one running thread.
I have an open issue with the ANTLR folks so perhaps they've been able to tackle this issue before.  I've been able to replicate it in a simple console app project using .NET 2.0 and 3.5 under VS 2008 and VS 2005.
It's just a pain point because it forces my code to only work with known valid parser input.  Using an IsValid() method would be risky if it threw an unhandled exception based on user input.  I'll keep this question up to date when more is learned of this issue.

A: @spoulson,
If you can replicate it, can you post it somewhere? One avenue you could try is usign WinDBG with the SOS extensions to run the app and catch the unhandled exception. It will break on the first chance exception (before the runtime tries to find a handler) and you can see at that point where it is coming from, and what thread.
If you haven't used WinDBG before, it can be a little overwhelming, but here's a good tutorial:
http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx
Once you start up WinDBG, you can toggle the breaking of unhandled exceptions by going to Debug->Event Filters.

A: Wow, so of the reports so far, 2 worked correctly, and 1 experienced the issue I reported.  What are the versions of Windows, Visual Studio used and .NET framework with build numbers?
I'm running XP SP2, VS 2008 Team Suite (9.0.30729.1 SP), C# 2008 (91899-270-92311015-60837), and .NET 3.5 SP1.

A: If you are using com objects your project and try catch blocks not catch the exceptions you will be need disable Tools/Debugging/Break when exceptions cross AppDomain or managed/native boundaries(Managed only) option.


text:
Q: how to convert a zip file entry to ZipFile with c# asp ionic library? im using ionic library to read zip file in c#
i have many zip files in one zip file,i read the zip file but i can't read the subZip files
i have made this portion of code here:
foreach (var sessionEntry in subjectSessions.Entries)
{
    using (MemoryStream entryStream = new MemoryStream())
    {
        sessionEntry.OpenReader().CopyTo(entryStream);
        ZipFile sessionZIPFile = ZipFile.Read(entryStream);
    }
}

but it's not working,it always gives me the same exception
Cannot read that as a ZipFile,Ionic.Zip.BadReadException: Could not read block - no data!  (position 0x00000000)
i have tried calling extract on sessionEntry object,didn't work too
how can i read the subZip files?
thanks in advance

A: After you copied the extracted content to the stream and before you read it, you need to manually reset the stream position, like so
stream.Seek(0, SeekOrigin.Begin);


text:
Q: Lisp - List of lists with variable size I have to represent a board game using lisp. To do that i have to create a function that builds the board.
This function receives an integer that represents the number of sublist the original list as to have. each one of this sublists have a different size growing in 3*n proportion.
As an example ifthe function is called with the number 3, it will create a list with 3 sublists, the first with 3 position, the second with six and the third with 9.
Also, each of the positions need to be initialized with ´*.
To do this i think i have to make a recursive call to make-list, but i can't seem to do that right. i'be tried to use the 'dotimes' cycle to do that, but i didn't have any sucess with that.
So far i have:
(defun faz-tabuleiro (n_aneis)
    (make-list n_aneis :initial-element (...)

Wich creates the main list, but how can i represent the sublists inside with the right size?

A: Does this do what you want?
(defun make-table (n)
  (loop :for i :from 1 :to n
        :collect (make-list (* i 3) :initial-element "*")))

A: Map over a list of numbers being the length of the sublists. Use a function for this mapping which returns the right list initialized with the initial element.


text:
Q: How To Run IIS 7 App Pool As Built-In Admin? I am trying to give access to an App Pool to create some files in the website directory (inside inetpub) and I it keeps denying me access because it says the user doesn't have admin rights. I ran the AppPool as LocalSystem and it still failed. Doesn't LocalSystem have full control over folders? I ran it as AppPoolIdentity and gave the proper rights to those folders, and it doesn't work. The only way I can get it to work is by giving it a custom admin account... but that saves the username/pass in the web.config and that password expires every 90 days. We cannot have websites fail every 90 days.
Is there an easy way where I can run the AppPool as built-in admin without giving some custom account?

A: Only 18 months late.  Nevertheless, I think the problem is that your website runs with anonymous connections right?  Anonymous users connecting to your website will not run as admin.  This is configurable.
The following is applicable to IIS7 (I think it'll also be applicable to IIS6, though I have no access to that version; almost certainly not applicable to IIS5 and earlier).
So anyway, to change this setting in the IIS Manager, go to:

Sites > [Your Website]

In "Features" view under the IIS subsection

Authentication [Open Feature] > Anonymous Authentication [right-mouse "Edit..."] > Select: Application Pool Identity [OK]

This allows anonymous connections to work under an admin privileges on the OS level, giving you access to files and a whole lot more besides.
Either that, or I've not quite understood your problem.


text:
Q: Win7 Batch rename multiple image formats in folder with multiple periods in file name I want to rename thousands of images (several extensions; png, jpg, gif) in a certain folder with the folder name followed by a ascending number, but the problem is when images have multiple dots/periods in the filename, the name gets cut off after the first period, than the file gets a wrong extension. For example:
Folder name: galaxies and nebulae
Imageformates: *.gif, *.jpg, *.png, *.tiff
@echo off
setlocal EnableDelayedExpansion
rem get folder name and show it
for %%A in (.) do (
echo %%~nA
set fona=%%~nA
)
rem replayce blanks with underline, set suffix, set new folder name
set "blank= "
set "undl=_"
set suffix=100
set nfona=!fona:%blank%=%undl%!
rem search images and rename
for /F "delims=" %%i in ('dir /B /oe /od *.png *.jpg *.tiff *.gif') do (
set /A suffix+=1
ren "%%i" "!nfona!_!suffix:~1!.???"
)
pause

The problem is when a file has multiple periods like
text.word.age.region.png

it will be changed to
galaxies_and_nebulae_01.wor

because it gets cut off right after the first period and gets a new extension from the following three letters because of the wildcards (???). And I have no clue how to avoid this. Please no PowerShell or renaming programms like FART.

A: Try to replace:

*

*.??? to %%~xi == .extension

*ren "%%i"... to ren "%%~fi"...
With this ??? == 3/max/lenght you prevent work with your files.tiff == .????
@echo off && setlocal EnableDelayedExpansion

for %%A in (.)do echo/.\%%~nA\ & set "fona=%%~nA"
for /f tokens^=* %%i in ('dir /b /oe /od *.png *.jpg *.tiff *.gif
')do set/a "suffix+=1+100+0" && call ren "%%~fi" "!fona: =_!_!suffix:~-2!%%~xi"
echo=^| total files renamed in folder: !suffix:~-2! && timeout -1 & endlocal & goto :EOF

Read more about:

*

*Wildcards

*Substring

*For loop

*For loop/MS/Docs

A: You need to be careful when using delayed expansion. Expansion of FOR variables will be corrupted if the value contains ! and delayed expansion is enabled. This is important because ! is valid in file and folder names.
Also, you need to make sure that you don't already have file names that match your final file name format, else you might get rename collisions.
Here is a solution that avoids any need of delayed expansion, but the sequence numbers are not left padded with zeros to a constant width.
@echo off
setlocal disableDelayedExpansion

:: Get folder name with spaces replaced by underscore
for %%F in (.) do set "fldr=%%~nF"
set "fldr=%fldr: =_%"

:: Define the list of extensions to process - the leading space is important
set "ext= png jpg tiff gif"

:: Rename any files that already match the intended name format to something else so there cannot be any collisions
:: This code simply appends underscore to the base name
for %%X in (%ext%) do 2>nul ren "%fldr%_????????????????????????????????????????????????????????????????????????????????????????????????????.%%X" "??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????_.*"

:: List the files sorted by extension, then last modified date, and prefix each name with a sequence number followed by a colon
for /f "delims=" %%F in (
  'dir /b /oed %ext: = *.% ^| findstr /n "^"'
) do (
  %= Parse out the sequence number and file name and rename the file =%
  for /f "delims=: tokens=1,2" %%A in ("%%F") do ren "%%B" "%fldr%_%%A%%~xB"
)

Here is a variation that zero pads all sequence numbers to a constant width. Delayed expansion is toggled on and off in a way that protects file/folder names with !.
@echo off
setlocal disableDelayedExpansion

:: Define the list of extensions to process - the leading space is important
set "ext= png jpg tiff gif"

:: Get folder name with spaces replaced by underscore
for %%F in (.) do set "fldr=%%~nF"
set "fldr=%fldr: =_%"

:: Rename any files that already match the intended name format to something else so there cannot be any collisions
:: This code simply appends underscore to the base name. Add additional ? as needed if you have really long file names.
for %%X in (%ext%) do 2>nul ren "%fldr%_????????????????.%%X" "??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????_.*"

:: Count the number of files so we know how many digits are needed
for /f %%N in ('dir /b /oed %ext: = *.% ^| find /c /v ""') do set "seq=%%N"

:: Convert each digit to 0, then prefix with 1
setlocal enableDelayedExpansion
for %%D in (1 2 3 4 5 6 7 8 9) do call set "seq=!seq:%%D=0!"
endlocal & set "seq=1%seq%"

:: Rename the files. Note that delayed expansion must be toggled in case name contains !
for /f "delims=" %%F in ('dir /b /oed %ext: = *.%') do (
  set /a seq+=1
  set "file=%%F"
  set "ext=%%~xF"
  setlocal enableDelayedExpansion
  ren "!file!" "!fldr!_!seq:~1!!ext!"
  endlocal
)

If you don't care about the sort order, then it can be really simple using my hybrid batch/JScript regular expression renaming utility JREN.BAT:
@echo off
setlocal disableDelayedExpansion

:: Get folder name with spaces replaced by underscore
for %%F in (.) do set "fldr=%%~nF"
set "fldr=%fldr: =_%"

:: Temporarily rename existing PNG JPG TIFF and GIF to avoid possibility of rename collisions
call jren "\.(png|jpg|tiff|gif)$" "_$&"

:: Rename all PNG JPG TIFF and GIF to the folder name + a sequence number padded to 4 digits
call jren ".*\." "'%fldr%_'+$n+'.'" /j /npad 4 /fm "*.png|*.jpg|*.tiff|*.gif"


text:
Q: how to add border styles to first and last row of the table in material UI? I am using the combination of material UI and react table in my project. Here I got an ask to add an expandable row, I did that. After the user expands it, we will be listing table rows based on the data.
Here is the demo link for that
Currently, I got an ask to add the border-top and border-bottom to the first and last row to the list of rows we are showing after the expansion. Please refer to the attached screenshot to understand better. Assume that the black lines in the image is the border.

I tried to do that by using nth-of-type. But I can only able to differentiate the background colors of the row over here. I even tried first-child and last-child. It doesn't work.
Please help to resolve this issue. This link has the code of expandable component.

A: One of the possible solutions, is based on checking the index of the elements that are displayed within the expanded row.
If an element is passed that has an index of zero in the array that should be displayed in the expanded row, then we add a borderTop css property to that row.
Otherwise, if an element is passed that has the last index in the array which needs to be displayed within the expanded row, then we add a css property borderBottom to that row.
Here is working solution.
Another solution is to create a div element that will serve as a wrapper around the expanded row.
And add this css style to that div :
const myStyle = {
  borderCollapse: "collapse",
  width: "0px"
};

After that, you can add below pseudo css selector in your StyledTableRow component:
 "&:last-child": {
    borderBottom: "5px solid black"
  },
  "&:first-child": {
    borderTop: "5px solid black"
  }

Here you can check that solution.
The downside of this solution, although it is more elegant than the previous one, is that you will get the following table layout :

As you can see, adding a div will cause a sligltly different layout because that div will now be viewed as a single cell within the table so it will not occupy the whole width of the tabe row.


text:
Q: Is there a way to store registered devices FCM tokens in Firebase Console? I need to be able to see registered FCM tokens in Firebase Console so that I can send specific test notifications. Is there a way to setup Firebase to store the FCM tokens locally in the Firebase project?
If the solution is to add codes to the app, that may be a problem for me as I am using an external app developer to develop my app and he is currently unavailable to make any changes in the app.
So I am just looking for a way for me to easily see all registered FCM tokens within the Firebase Console.


text:
Q: How can I record values from another website and put it in a database to be used? For example, how would I go about designing a program that, upon the user inputting their location, will display a temperature listed on another website, which I can then manipulate using JavaScript.

A: Using JinqJs
If I understand correctly you want to query a web service to get the temperature for a given location.  Here is a sample using jinqJs
var weatherSvc = 'http://api.openweathermap.org/data/2.5/weather?q=Huntington,NY';

var result = jinqJs()
                    .from(weatherSvc)
                    .select(function(row){ return row.main.temp;});

See Fiddle Sample


text:
Q: Why is the length property of an array counting the number of chars in Typescript? I create an array and store strings in it but when i use the .length property with just one element in the array it counts the length of the string. With more than one element it counts the elements as usual.
private organizationArray: Array<string>;

const claims = jwtDecode<any>(token);
    this.claims = {
        email: claims['http://schemas.xmlsoap.org/ws/***/**/***/claims/emailaddress'],
        id: claims['http://schemas.xmlsoap.org/ws/***/**/*****/claims/sid'],
        name: claims['http://schemas.xmlsoap.org/ws/***/**/****/claims/name'],
        expires: new Date(claims['exp'] * 1000),
    };
this.organizationArray = claims['http://schemas.*****.**/**/****/**/*******/claims/organization'];
console.log( this.organizationArray.length)

Here i have 3 elements in the array:
CONSOLE LOG file:///app/app/services/jwt.service.js:55:20: 3

Here i have 1 elements in the array with 84 chars:
CONSOLE LOG file:///app/app/services/jwt.service.js:55:20: 84

claims returns
{"Id":"********-0000-0000-0000-********","Name":"NAME","AccessibleAreas":**},{"Id":"******-****-*****-****-******","Name":"Demo Inc.","AccessibleAreas":*}


text:
Q: I want to filter my product on the bases of rating, How can i do that? My Models
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()

    def no_of_ratings(self):
        ratings = Rating.objects.filter(product=self)
        return len(ratings)

    def avg_rating(self):
        ratings = Rating.objects.filter(product=self)
        sum=0
        for rating in ratings:
            sum += rating.rating
        if len(ratings)>0:
            return sum/len(ratings)
        else:
            return None

    def __str__(self):
        return self.title

class Rating(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])

    class Meta:
        unique_together = (('user', 'product'),)
        index_together = (('user', 'product'),)

serializer.py
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from .models import Product, Rating

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True, 'required': True}}

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user=user)
        return user

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields =('id', 'title', 'description', 'no_of_ratings', 'avg_rating')

class RatingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Rating
        fields = ('product', 'user', 'rating')

views.py
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from rest_framework.decorators import action
from django.contrib.auth.models import User
from .models import Rating, Product
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated, AllowAny
from .serializers import ProductSerializer, RatingSerializer

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.filter(product__rating__gte = 4 )
    serializer_class = ProductSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (AllowAny,)

class RatingViewSet(viewsets.ModelViewSet):
    queryset = Rating.objects.filter(rating__gte = 4)
    serializer_class = RatingSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (AllowAny,)

Hi, I'm new in Django Rest Framework, I want to filter my product on the bases of rating, but my filter doesn't work, I have two models classes Product and Rating every Product have a rating( Foreign key ), I want to list only +4 rated product, how can I achieve that, and can I filter results to get models with specific rating?

A: With queryset = Product.objects.filter(product__rating__gte = 4 ) you look up products and filter them by their field product but your product instances don't have this field or property.
In your views.ProducViewSet You should filter for something like
class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.filter(rating_set__rating__gte = 4 )
    # ...

instead. rating_set is the default name to access foreign keys in the other direction (from the model where it's not defined in) You can use the related_name parameter in the ForeignKey to set this to a custom name like product_rating. (Notice the use of single _, it wouldn't work with double __)


text:
Q: PHP Search and Pagination using PDO MySQL - SQLSTATE[42000]: Syntax error I am trying to figure out what is wrong.
Here is my code:
<?php
define("ROW_PER_PAGE",2);

require_once("config.php");

?>

        <?
        $search_keyword = '';
        if(!empty($_POST['search']['keyword'])) {
            $search_keyword = $_POST['search']['keyword'];
        }

        $sql = "SELECT * FROM finance WHERE `name_first` LIKE :keyword ORDER BY `fID` `DESC` ";

        /* Pagination Code starts */
        $per_page_html = '';
        $page = 1;

        $start=0;
        if(!empty($_POST["page"])) {
            $page = $_POST["page"];
            $start=($page-1) * ROW_PER_PAGE;
        }

        try {
            $limit=" limit " . $start . "," . ROW_PER_PAGE;
            $pagination_statement = $db->prepare($sql);
            $pagination_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
            $pagination_statement->execute();

            } catch (PDOException $e) {
                echo "Error : Check your error message.";
                file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        }

        $row_count = $pagination_statement->rowCount();

        if(!empty($row_count)){
            $per_page_html .= "
";
            $page_count=ceil($row_count/ROW_PER_PAGE);

            if($page_count>1) {
                for($i=1;$i<=$page_count;$i++){

                    if($i==$page){
                        $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page current" />';
                    } else {
                        $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page" />';
                    }

                }
            }

            $per_page_html .= "
";
        }

        try {
            $query = $sql.$limit;
            $pdo_statement = $db->prepare($query);
            $pdo_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
            $pdo_statement->execute();
            $result = $pdo_statement->fetchAll();

            } catch (PDOException $e) {
                echo "Error : Check your error message.";
                file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        }

        ?>

        <form name='frmSearch' action='' method='post'>

<input type='text' name='search[keyword]' value="<?php echo $search_keyword; ?>" id='keyword' maxlength='25'>

                    First Name
                    Last Name
                    Birth Date

            <?php
            if(!empty($result)) {
                foreach($result as $row) {
                ?>

                    <?php echo $row['name_first']; ?>
                    <?php echo $row['name_last']; ?>
                    <?php echo $row['birth_date']; ?>

                <?php
                }
            }
            ?>

        <?php echo $per_page_html; ?>
        </form>

I received error message says ...
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DESC' at line 1
I know some old style mysql code, but I am beginner for PDO.
Would you please tell me what is wrong / where to fix my code?
PHP: 5.6
MySQL: 5.6.37
I really appreciated your help.
Thank you.

A: Please remove the ` from the DESC part and it should work.


text:
Q: How i can get Rod sizes in Rod Cut using Recrsivly? I want to get rod size of maximum revenue in rod ct problem.
suppose there is 4 length of rod.
1 = 5
2 = 4
3 = 3
4 = 10

in this situation, maximum revenue will generate by 1,1,1,1 which is 20.
i got maximum revenue but how i can get rod size
here is the code.
#include<iostream>

using namespace std;

int Rod_Cut(int *,int);
int main()
{
    const int n=5;
    int arr[n]={0,5,4,3,10};
    int size[n]={0};

    cout<<Rod_Cut(arr,n)<<endl;

}

int Rod_Cut(int *arr, int n)
{
    if(n==0)
    {
        return 0;
    }

    int q=0;

    for(int i=1;i<n;i++)
    {

        q=max(q,arr[i]+Rod_Cut(arr,n-i));

    }

    return q;
}

A: Here is one approach:
You need to return the sequence used in each calculation. If the new value is better than what you have so far, you must save the new "best" sequence. In the end you return the best sequence found.
The proposal is not optimal (e.g. performance) but maybe it will give you some ideas. Then you can optimize the code to perform better.
Good luck.
int Rod_Cut(int *,int, vector<int>&);
int main()
{
    const int n=5;
    int arr[n]={0,5,8,3,10};
    int size[n]={0};

    vector<int> v;  // Create vector for the best sequence
    cout<<Rod_Cut(arr,n,v)<<endl;

    // Print the best sequence
    for(auto e : v)
    {
        cout << e << " ";
    }

}

int Rod_Cut(int *arr, int n, vector<int>& v)
{
    if(n==0)
    {
        return 0;
    }

    int q=0;

    vector<int> t;        // Temp vector for next call
    vector<int> st;       // The best sequence found at this level
    for(int i=1;i<n;i++)
    {
        int temp = arr[i]+Rod_Cut(arr,n-i,t);
        if (temp > q)
        {
            // A new better sequence has been found

            st.clear();        // clear the former best sequence
            for(auto e : t)    // add the new best sequence
            {
                st.push_back(e);
            }
            st.push_back(i);   // add i used at this level
            q = temp;
        }

        t.clear();   // Prepare for next call
    }

    // Copy the best sequence to the returned vector
    for (auto e : st)
    {
        v.push_back(e);
    }

    return q;
}


text:
Q: LibGDX: black rectangles instead of animation textures I use AssetManager to manage assets in my libgdx game. I have static images and animations. When I used emulator (Nexus 6, Api 29) to test the game it was fine, but once I emulated the game to my real phone (Samsung J5 2016, Api 25) it started showing black rectangles instead of some animations, but static textures were fine.
My animations are 800x800 px, 10 fps.
Here is an example of such texture. This code is in Loading screen:
assetManager.load(AssetDescriptors.BONUS_TEXTURE);

Here I instantiate animation, frame time = 0.1f. This code is in factory, that creates the object with such animation:
animationComponent.animation = new Animation<>(GameData.FRAME_TIME,
                assetManager.get(AssetDescriptors.BONUS_TEXTURE).getRegions());

And here I draw it. This is from the class that manages rendering:
batch.draw(animationComponent.animation.getKeyFrame(animationComponent.elapsedTime, true),
                position.x - dimension.width / 2f, position.y - dimension.height / 2f,
                dimension.width, dimension.height
        );

This works on emulator and doesn`t work on real device. Please tell me what can be wrong. Thank you for your help.
emulator emulator
phone - player, pot and gran animations phone - gran and pot animations

A: Many devices don't support textures with dimensions that are not a power of two. You should pack your textures with TexturePacker and keep the pot setting on.


text:
Q: Beamer: missing \endcsname inserted \end{frame} I am getting this error while compiling this code:
I have already tried checking the equations and looking for missing }, but without success.
This is the first time I am using the beamer environment. Here is a minimum example which reproduces the error.
\documentclass{beamer}

\usepackage[utf8]{inputenc}
\usepackage{default}

\begin{document}
\begin{frame}\frametitle{Onde Gravitazionali da sistemi binari}
\begin{columns}
\begin{column}
\begin{itemize}
   \item $P_{gw}=-\frac{dE_{orb}}{dt}$
   \item $\dot{\omega}_{gw} = \frac{12}{5}\, 2^{\frac{1}{3}} \left(\frac{G M_c}{c^3}\right)^{\frac{5}{3}}\omega_{gw}^{\frac{11}{3}}$
  \end{itemize}
  \end{column}
  \begin{column}
   \includegraphics[scale=0.4]{separation(t).png}
  \end{column}
 \end{columns}
\end{frame}

\end{document}

A: The column environment takes an argument for the width of the column:
\begin{column}{0.4\textwidth}


text:
Q: angular, why is page reloaded when changing state application I have a angular webapp that is using a pre-produced theme/framework called fuse (http://withinpixels.com/themes/fuse), this theme already has an app structure and code written to make the creation of apps easier.
We added some pages (which include sidemenu items), the problem is, when you tap one of the links in the sidebar, the whole page seems to be reloaded or at least a animate-slide-up is played 2 times on the index main div, I traced down one part of the problem to the configuration module of the page:
$stateProvider.state('app.pages_dashboard', {
        url      : '/dashboard',
        views    : {
            'main@'                       : {
                templateUrl: 'app/core/layouts/vertical-navigation.html',
                controller : 'MainController as vm'
            },
            'content@app.pages_dashboard': {
                templateUrl: 'app/main/dashboard/dashboard.html',
                controller : 'DashboardController as vm'
            },
            'navigation@app.pages_dashboard': {
                templateUrl: 'app/navigation/layouts/vertical-navigation/navigation.html',
                controller : 'NavigationController as vm'
            },
            'toolbar@app.pages_dashboard': {
                templateUrl: 'app/toolbar/layouts/vertical-navigation/toolbar.html',
                controller : 'ToolbarController as vm'
            },
        },
        bodyClass: 'login',
        needAuth: true,
        onStateChangeStart: function(event, state, auth, api) {
            console.log('onStateChangeStart on DASHBOARD');
            api.getUserCard.save({}, {}, function (response){
                if (!response.result) {
                    state.go('app.pages_claimcard');
                }
            });
        }
    });

and the configuration module of the app
angular
    .module('fuse')
    .run(runBlock);

/** @ngInject */
function runBlock($rootScope, $timeout, $state, $auth, api)
{
    console.log('INDEX.RUN loaded');
    // Activate loading indicator
    var stateChangeStartEvent = $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams)
    {
        // console.log('started change event');
        // console.log(toState);
        // console.log(fromState);

        // check if authentication needed
        if (toState.needAuth) {
            // redirect to login page
            if (!$auth.isAuthenticated()) {
                event.preventDefault();
                $state.go('app.pages_auth_login');
            }
        }

        if (toState.onStateChangeStart) {
          // THIS CAUSES ONE OF THE RELOADS
            // toState.onStateChangeStart(event, $state, $auth, api);
        }

        $rootScope.loadingProgress = true;
    });

    // De-activate loading indicator
    var stateChangeSuccessEvent = $rootScope.$on('$stateChangeSuccess', function ()
    {
        $timeout(function ()
        {
            $rootScope.loadingProgress = false;
        });
    });

    // Store state in the root scope for easy access
    $rootScope.state = $state;

    // Cleanup
    $rootScope.$on('$destroy', function ()
    {
        stateChangeStartEvent();
        stateChangeSuccessEvent();
    });
}

as you can see I commented the the toState OnStateChangeStart function, and that got rid of one the 'reloads' of the application, so basically have 2 questions:

*

*Why does the onStateChangeStart function on the toState state causes the page to reload?

*I have no idea what might be causing the other page reload, any ideas?

A: I found the problem, my states were defined as:
'app.pages.dashboard'

however there was never a declaration for
'app.pages'

so UI-router was trying its best to sort this mess, anyways, always remember to properly declare your states and everything should be fine.


text:
Q: JUnits ParametrizedTest vs TestTemplate I recently came across JUnit's feature of @TestTemplate, which provides the ability to use generalized test template description, inject it with different test parameters and thus parametrize test runs with context providers.
My question is - how is this @TestTemplate mechanism different from the one, achieved through @ParametrizedTest + @SourceValue? What could be considered as use-cases to prefer TestTemplate over ParametrizedTest?


text:
Q: setTimeout with multiple items I tried to have a setTimeout function on multiple li items which have ul and li again. The slide animation works fine, but I want to have a delay before closing slideUp again. But it doesn´t work. The slide goes down but not up again. I think it is because I have to have a indexed setTimeout function for every li ul (indexed). But I have no idea how to get it work. Can anyone point me in the right direction please? Thanks!
var menu = $('#menu').find('li').has('ul');
var timer;
menu.on('mouseenter', function(){
  clearTimeout(timer);
  $(this).find('>ul').stop().slideDown();
});

menu.on('mouseleave', function(){
  clearTimeout(timer);
  timer = setTimeout(function() {
    $(this).find('>ul').stop().slideUp();
  },1000);
});

A: The problem is you have multiple lis, they will cancel out the open ones. You need to either assign the timeout to each li or you need to see if their is another li open to close it.
var lis = $('#menu').find('li').has('ul');

lis.on('mouseenter', function(){
    var li = $(this);
    var timer = li.data("timer");
    clearTimeout(timer);
    $(this).find('>ul').stop().slideDown();
});

lis.on('mouseleave', function(){
    var li = $(this);
    var timer = setTimeout(function() {
            $(this).find('>ul').stop().slideUp();
        },1000);
    li.data("timer", timer);
});


text:
Q: I want the project to named something else. How can I safely rename the project? I have worked on my django project for quite a while, but realized I want the project to named something else.
How can I safely rename the project?

Edit:
How to change the name of a Django app? does not answer my question, as this question is to change the project name, not the app.

A: open your settings.py, urls.py, views.py or any other file that might rely on your project's name and then use the find&replace function in your text editor.

A: I would suggest using refactor feature of the IDEs. If you are using pyCharm, go to refactor->rename. It will provide you an option to rename the references as well. Select that and IDE will take care of all you references without complications.


text:
Q: URI is not hierarchical - Creating infafas connection using JDBC My question is very specific to the problem I am recently facing while connecting to Informatica Data Vault (IDV) using infa-fas driver in java.
To give a background : IDV is a file system and stores structured & unstructured data in a format similar to common databases like Oracle. To connect I am using the following code :
String username = buttonGroup.getSelection().getActionCommand(); // Selecting user from a radioButton
String pwd = new String(password.getPassword()); // Password from JPassword Field
String host = hostName.getText();   // Host and Database name resp.
String database = dbName.getText();
// URL for connecting to IDV
String url = "jdbc:infafas:"+"//"+username+":"+pwd+"@"+host+":8501"+"/"+database;
DriverManager.registerDriver(new com.informatica.fas.jdbc.Driver()); // Driver class

When I run this utility using Eclipse IDE, I am able to connect to the db and query as well. But when packaged as a jar, it gives the below error :
Please let me know where I am wrong or what modifications can be done.
java.lang.IllegalArgumentException: URI is not hierarchical
        at java.io.File.<init>(Unknown Source)
        at com.informatica.fas.jdbc.FASConnection.<init>(FASConnection.java:465)
        at com.informatica.fas.jdbc.FASDriver.connect(FASDriver.java:168)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at org.rbs.gui.TargetConnectionPanel$2.actionPerformed(TargetConnectionP
anel.java:165)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$300(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
        at java.awt.EventQueue$4.run(Unknown Source)
        at java.awt.EventQueue$4.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)


text:
Q: Running Rdevtool::test_that on buffer save in ESS My workflow:

*

*Hack away at an .R or test_*.R file

*Save buffer.

*Switch to window with *R* process

*hit C-p, RET. to re-evaluate devtools::test()
To me, this seems far too arduous.  Why can't I get R to run devtools::test() automatically when I save the buffer? Please help, my fingers can barely take the strain of the seven extra keystrokes!

A: This worked for a similar setup (switching to a shell buffer):
(defun devtools-test ()
  (interactive)
  (when (string-match (rx-to-string `(: ".R" eos) t) (buffer-name))
    (switch-to-buffer "*R*")
    (end-of-buffer)
    (insert "devtools::test()")
    (comint-send-input)))

(add-hook 'after-save-hook 'devtools-test)

Does that work for you?

A: For completeness, there are easier way to do this in recent versions of ESS.
The function/command ess-r-devtools-test now runs devtools::test.
So you could achieve this with (untested):
(add-hook 'ess-r-mode-hook
          (lambda ()
             (add-hook 'after-save-hook 'devtools-test nil 'local)))

In addition, there are many other useful functions under ess-r-devtools-* for build, install etc.
It's worth noting that calling ess-r-devtools-test with the universal argument will filter tests by the current file.
So calling C-u M-x ess-r-devtools from a file my-file.R will run devtools::test(filter="my-file").
This can be useful to bear in mind when choosing names for test files, or when rerunning only the current test file.

A: There is a ess-eval-linewise function which you can use.
Something like this (not tested):
(defun devtools-test ()
  (interactive)
  (when (and (equal ess-dialect "R")
             (string-match "^test.*\\.[Rr]$" (buffer-name)))
    (ess-eval-linewise "devtools::test()")))

(add-hook 'after-save-hook 'devtools-test)

I would not recommend this though, as for some packages tests take quite a while to run. You don't want them running on every save.
There will be a dedicated devtools functionality in ess soon. Follow this issue.


text:
Q: fancybox2 media helper not loading in window, launching vimeo site i don't understand why the fancybox2 media helper isn't loading my vimeo content into a fancyboc, instead it is launching my video on the vimeo site.
any help is greatly appreciated.
will
from my fancybox.js file
$('.fancybox-media-evcc')
                $(".fancybox").fancybox({
                    helpers : {
                    media : {}
                    }
                });
from my html file

A: This :

$('.fancybox-media-evcc') $(".fancybox").fancybox({ helpers : { media : {} } });

... is incorrect, it should rather be :
$('.fancybox-media-evcc').fancybox({
    helpers : {
      media : {}
    }
});

Or you could have both :
// for elements with class fancybox
$(".fancybox").fancybox();

// for elements with class fancybox-media-evcc
$('.fancybox-media-evcc').fancybox({
    helpers : {
      media : {}
    }
});


text:
Q: The better way to maintain css, js, font-cion, image's versions? I have few css files for a site and some css properties are shared through all of them. Plus there are also few js files. font icons file and images that I constantly updating. Whenever I tried to push to main repository, i had to make sure each file version are bumped using "?=number". I am seriously tired of doing this.
Is there a better way to do URL version bumps all together? Any help would be appreciated.
Additional info: I am using IIS7/8 and developing in windows system by using HG Mercurial. Back end  uses asp.net visual basic, mysql.

A: Since you're using ASP.NET, your .NET devs can set a variable that holds a common increment number that you can use as the number in the ?v=number part. So, you just change all of your CSS/JS files to consume the variable one time only. For example:
string version = ConfigurationManager.AppSettings["VersionNumber"];

If you're using bundling, there is a better answer here:
How to make bundles unminify and list individual files when using a cookieless static content server?


text:
Q: How do I pass my url params to async functions in javascript files separate from the route with Node.js? I'm just learning to code and I'm building an application for my business. I'm having an issue with passing url parameters on my show route.
I'm using Node.js and MySQL. The route is displaying 7 different reports and I broke each report into separate js files, exported the functions and am calling the functions on the show route to display the page. The problem is that my MySQL queries on each function are not dynamic because I can't access the url parameters in each of these separate js files.
I've tried creating a function on the routes.js page but the request is undefined as each req is declared within a route. I also tried using ${req.params.id} on the individual js files, but req is still undefined.
Here is my show route:
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month", function (req, res){
monthToMonth(function(arr){
    topSkuUnitsMonth(function(arr1){
        topSkuCogsMonth(function(arr2){
            productMix(function(arr3){
                ltmCogs(function(arr4){
                    topSkuCogsLTM(function(arr5){
                        topSkuUnitsLTM(function(arr6){
                            quarterComparison(function(arr7){
                                res.render("reports/show", {current: arr, math: math, units: arr1, cogs: arr2, mix: arr3, totals: arr4, yearCOGS: arr5, yearUnits: arr6, quarter: arr7});
                            })
                        })
                    })
                })
            })
        })
    })
})

});
Here is the monthToMonth function:
module.exports = function monthToMonth(callback){
var q = `select
    t1.client_id,
    DATE_FORMAT(t1.period, '%Y-%m') as period,
    ROUND(t1.shipped_COGS,0) as shipped_COGS_current_month,
    t1.shipped_units as shipped_units_current_month,
    t1.product_title as product_title_current_month,
    t1.asin as asin_current_month,
    ROUND(t2.shipped_COGS,0) as shipped_COGS_past_month,
    t2.shipped_units as shipped_units_past_month,
    t2.product_title as product_title_past_month,
    t2.asin as asin_past_month
    from all_months_ca t1
    join all_months_ca t2 on t1.asin = t2.asin
    where t1.client_id = 1 && t2.client_id  = 1 && (t1.shipped_units > 0 || t2.shipped_units > 0) && (DATE_FORMAT(t1.period, '%Y-%m') = '2019-05' && DATE_FORMAT(t2.period, '%Y-%m') = '2019-04')
    group by t1.asin
    order by shipped_COGS_current_month DESC;`
db.query(q, function(err, foundData){
    if(err) throw err;
    callback (foundData)
})

}
The MySQL query currently has the period and client_id hardcoded in the WHERE clause, but I need the url params to make the queries dynamic. How can I pass the parameters to these js. files?

A: Why not pass req object in each functions.
module.exports = function monthToMonth(req, callback){
var q = `select
   t1.req.params.id,
   DATE_FORMAT(t1.period, '%Y-%m') as req.params.month,
   ROUND(t1.shipped_COGS,0) as shipped_COGS_current_month,
   t1.shipped_units as shipped_units_current_month,
   t1.product_title as product_title_current_month,
   t1.asin as asin_current_month,
   ROUND(t2.shipped_COGS,0) as shipped_COGS_past_month,
   t2.shipped_units as shipped_units_past_month,
   t2.product_title as product_title_past_month,
   t2.asin as asin_past_month
   from all_months_ca t1
   join all_months_ca t2 on t1.asin = t2.asin
   where t1.client_id = 1 && t2.client_id  = 1 && (t1.shipped_units > 0 || t2.shipped_units > 0) && (DATE_FORMAT(t1.period, '%Y-%m') = '2019-05' &&    DATE_FORMAT(t2.period, '%Y-%m') = '2019-04')
   group by t1.asin
   order by shipped_COGS_current_month DESC;`
   db.query(q, function(err, foundData){
      if(err) throw err;
      callback (foundData)
   })

and call this function like -
 router.get("/clients/:id/reports/monthlyreport/:marketplace/:month", function (req, res){
  monthToMonth(req, function(arr){
  // call remaining function in same way.
  topSkuUnitsMonth(req, function(arr1){
})  })


text:
Q: jQuery - Return Values Matching a pattern to an Array My form has several
 elements which are added dynamically.  This is how one would look:

1

I need to set up a function so that when a button is clicked I get the id (the id's will be labeled numbox-1, numbox-2, etc) and the value of the p element for all of them on the page.
I need to pass the values to a php script that will process them, it would be nice if I could get the data as an array so I can use a for loop in php.
I have been using JSON to pass data, but Im not sure if that's the best way to go on this, please advise, thanks-

A: You can use .map() for this, for example:
var arr = $('.numbox').map(function(){
            return { name: this.id, value: this.innerHTML };
          });

Then you could pass this as the data argument, for example:
$.post("mypage.php", arr);

This would result in a POST of the name/value pairs, like this:
numbox-1=1&numbox-2=XX....

A: I'm not sure what you mean by 'checking' buttons, but maybe this will help a bit.
$(function(){
  $("#send-button").click(function(){
    var data = [];
    $('.numbox').each(function(){
      var $this = $(this);
      data.push( {
        id: $this.attr('id'),
        value: $this.html()
      } );
    });
    $.post('myurl.php', { numboxes: data });
  });
});

When #send-button is clicked, it creates a return array that contains objects for each numbox id and value.  It then posts that array to the server.

A: function getNumbox()
{
    var objNumbox = new Array();
    $('.numbox').each(function(index){
        objNumbox[index] = $(this);
    });
    return objNumbox;
}

//Test it out
$(document).ready(function(){
    var test = getNumbox();
    $(test).each(function(index){
        alert('ID: ' + $(test[index]).attr('id') + ' Text: ' + $(test[index]).text());
    });
});


text:
Q: Как отловить ошибку? Программа падает с ошибкой если открыт результирующий файл
>    Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/ProjectSED/main.py", line 580, in comparison
    wb.save(f'{self.path}/Результат.xlsx')
  File "C:\Users\User\PycharmProjects\ProjectSED\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save
    save_workbook(self, filename)
  File "C:\Users\User\PycharmProjects\ProjectSED\venv\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
    archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\zipfile.py", line 1251, in __init__
    self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:/Результат.xlsx'

надо сообщить пользователю что бы он закрыл файл перед работой, думаю сделать это виде исключения,
но не получается её отловить
df1 = pd.read_excel(self.filename, skiprows=2, header=None, usecols=[1, 2, 3, 14, 21]).drop(labels=[0,1,2,3,4,5],axis=0)
df2 = pd.read_excel(self.filename1, skiprows=2, header=None, usecols=[2, 3, 4, 5, 20]).drop(labels=[0,1,2,3,4,5,6,7,8,9,10],axis=0)
df3 = pd.read_excel(self.filename2, header=None, usecols=[3, 4, 5, 9, 12]).drop(labels=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14],axis=0)

result = df1.loc[df1.ne(df2.to_numpy()).any(axis=1)]
result2 = df2.loc[df2.ne(df1.to_numpy()).any(axis=1)]
result3 = df1.loc[df1.ne(df3.to_numpy()).any(axis=1)]
result4 = df3.loc[df3.ne(df1.to_numpy()).any(axis=1)]

datafr = pd.concat([d.reset_index(drop=True) for d in [result, result3]], axis=0)
datafr1 = pd.concat([d.reset_index(drop=True) for d in [datafr, result2, result4]], axis=1)

try:
datafr1.to_excel(f'{self.path}/Результат.xlsx', engine='openpyxl', sheet_name='Лист', startrow=2,
            startcol=0, header=None, index=False)

except ValueError as ve:
             print(ve)

но безрезультатно, что может быть не так?

A: Так и нужно ловить PermissionError, а не ValueError.

A: Разобрался в моём случае нужно было сделать так
df1 = pd.read_excel(self.filename, skiprows=2, header=None, usecols=[1, 2, 3, 14, 21]).drop(labels=[0,1,2,3,4,5],axis=0)
df2 = pd.read_excel(self.filename1, skiprows=2, header=None, usecols=[2, 3, 4, 5, 20]).drop(labels=[0,1,2,3,4,5,6,7,8,9,10],axis=0)
df3 = pd.read_excel(self.filename2, header=None, usecols=[3, 4, 5, 9, 12]).drop(labels=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14],axis=0)

result = df1.loc[df1.ne(df2.to_numpy()).any(axis=1)]
result2 = df2.loc[df2.ne(df1.to_numpy()).any(axis=1)]
result3 = df1.loc[df1.ne(df3.to_numpy()).any(axis=1)]
result4 = df3.loc[df3.ne(df1.to_numpy()).any(axis=1)]

 datafr = pd.concat([d.reset_index(drop=True) for d in [result, result3]], axis=0)
 datafr1 = pd.concat([d.reset_index(drop=True) for d in [datafr, result2, result4]], axis=1)

while True:
try:
  datafr1.to_excel(f'{self.path}/Результат.xlsx', engine='openpyxl',    sheet_name='Лист', startrow=2,
        startcol=0, header=None, index=False)

     break

except IOError:
  QtWidgets.QMessageBox.information(self, 'Message','У вас открыт файл "Результат" закройте файл ')


text:
Q: Redirect to url then again redirect to main url I know it is really confusing. Let me explain:
I want to open the urls on my site (http://domain.com) to a (http://domain.com/url='the submitted url') and then the submitted url is opened.
Eg: When we open any other site link from Google+ let the example
http://www.youtube.com/watch?v=WRpX7tkwejU
it redirects to
http://plus.url.google.com/url?sa=z&n=1333340186022&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWRpX7tkwejU&usg=whZv4BO7Gcrco_vivlnhaz27Wpk.
and then the original site is opened. I want some thing similar.

A: *

*On your site, replace any regular external link like http://example.com with, say, /redirect.php?url=http%3A%2F%2Fexample.com. Make sure to urlencode the original domain name.

*In redirect.php, redirect the user:
header('Location: ' . $_GET['url']);


text:
Q: Postgres pg_wals full whats best practice for removal of old WALs that were not removed automatically We had an outage on our postgresql-12 server at the weekend, we have pg_wals that reside on a partition that had become full. This then crashed the server due to the space running out.
We then moved the pg_wals to a different partition and started the server up.
I can see new pg_wals are generating but have some dating from a day or so ago which have not cleared.
DB PG Setting:
archive_command = on
archive_command = '/home/postgres/bin/walarchiving.bsh %p %f'
wal_keep_segments = 500

Can I remove the old WALs that pre-date the new start time of postgres? What is the best practice on old WALs after a PG crash.

A: Don't manually delete WAL segments. They get removed automatically if they are no longer needed. If that doesn't happen, something is blocking progress:

*

*perhaps the archiver is failing

*perhaps you have a stale replication slot
Remove the problem, and PostgreSQL will delete the old files after the next checkpoint.