text:
Q: Regex to remove bracket but not its contents I would like to remove constant text and brackets from a String using regex. e.g.
    INPUT                  Expected OUTPUT
   var x = CONST_STR(ABC)  var x = ABC
   var y = CONST_STR(DEF)  var y = DEF

How to achieve this?

A: Try with regex:
(?<==\s)\w+\(([^)]+)\)

DEMO
which means:

*

*(?<==\s) - lookbehind for = and space (\s), the regax need to fallow these signs,

*\w+ - one or more word characters (A-Za-z_0-9) this might be upgraded to naming rules of language from code you are processing,

*\( - opening bracket,

*([^)]+) - capturing group (\1 or $1) for one or more characters, not closing brackets,

*\) - closing bracket,

Just remember that in Java you need to use double escape character \,
like in:
public class Test {
    public static void main(String[] args) {
        System.out.println("var y = CONST_STR(DEF)".replaceAll("(?<==\\s)\\w+\\(([^)]+)\\)", "$1"));
    }
}

with output:

var y = DEF

The $1 in replaceAll() is a call to captured groups nr 1, so a text captured by this fragment of regex: ([^)]+) - words in brackets.


text:
Q: Tagged type : type mismatch I try to use Tagged Type from scalaz to strengthen type safety.
I encountered a warning and an error that I don't understand.
Can you explain me both ?
Here is the output of the console :
scala> sealed trait PostId
defined trait PostId

scala> def PostId(l: Long) : Long @@ PostId = Tag[Long, PostId](l)
PostId: (l: Long)scalaz.@@[Long,PostId]
warning: previously defined trait PostId is not a companion to method PostId.
Companions must be defined together; you may wish to use :paste mode for this.

scala> case class Post(id: PostId)
defined class Post

scala> Post(PostId(2l))
<console>:26: error: type mismatch;
 found   : scalaz.@@[Long,PostId]
    (which expands to)  Long with AnyRef{type Tag = PostId}
 required: PostId
              Post(PostId(2l))

A: In your example, PostId is just a tag type.
The actual tagg-ed type (the type that you should manipulate) is Long @@ PostId.
The error is that you have defined Post to take an instance of PostId when you really meant to have it take an instance of Long @@ PostId, hence the type mismatch.
I suggest renaming PostId to PostIdTag and defining PostId as an alias to Long @@ PostId:
sealed trait PostIdTag
type PostId = Long @@ PostIdTag

def PostId(l: Long) : PostId = Tag[Long, PostIdTag](l)

Then you can keep your Post definition as is.
UPDATE: As it turns out, scalaz tagged types seem to only work with types <: AnyRef, ie one cannot create a tagged type from an AnyVal sub-type.
The solution then is to replace Long with java.lang.Long (which works transparently because scala will automatically convert  java.lang.Long values to Long):
sealed trait PostIdTag
type PostId = java.lang.Long @@ PostIdTag
def PostId(l: java.lang.Long) : PostId = Tag[java.lang.Long, PostIdTag](l)
case class Post(id: PostId)
Post(PostId(2l))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tmux stuck in copy-mode After performing a keyboard shortcut in tmux (I am not sure which), I am put into a state of perpetual copy-mode. I can type normally, but every time I hit the n key it prompts to gotoline input.
If I close the pane it happens even on the new pane I have created.
Any help on how to exit this once it happens would be great, as all documentation surrounding copy-mode states that when you hit Esc or q you should leave copy-mode.

A: Typically I get out of copy mode using Enter. On another machine with different desktop environment and different terminal, this doesn't work in tmux. But I did find a way.
If you look at the definition of the cancel key in copy mode ( Ctrl+c and Ctrl+Esc  ) that's defined as
bind-key    -T copy-mode    C-c               send-keys -X cancel

That means you can do Ctrl+b to enter command mode and then execute
send-keys -X cancel

This will take you out of copy mode.
Variation on the theme would be to change your key mode to vi ( unless you already use that or your EDITOR environment variable already set to it):
set -g mode-keys vi

This allows hitting q in copy mode to cancel the said mode

As for how to deal with the problem of n key and gotoline, I can't answer that. I'd suggest trying different terminal emulator or keyboard, since the issue may not be related to tmux at all.

A: You can check your current tmux key bindings by running tmux list-keys. If you see a binding that matches
bind-key -T root n <command>

then the n key is bound in the root table. This means that pressing n in the shell at all will cause <command> to be run. You can remove the binding by running
tmux unbind -T root n

I ran into this issue while using the tmux plugin tmux-copycat, which adds some alternative bindings for copy/paste functionality. Following the above instructions resolved it.


text:
Q: Continuous account lockout error for a domain user in Windows server 2003 DC Continuous account lockout error for a domain user in Windows server 2003 DC. Tried the account lockout and management tool and using the Lockoutstatus.exe I could get the details of client system name, reason ( Bad password) etc and verified the same by checking windows server security logs. The client OS is Windows 7 64bit and Alockout.dll is not compatible with Windows 7.
I tried the following steps.

*

*Cleared the credential manager.

*Unmapped the network drive.

*Verified that the user only login to domain from his PC ( Single session )

*I did a full antivirus scan and  Windows malicious removal tool .

*Installed all Windows updates.
I think some services may use his domain username for connecting to the network but I need to find out  which service / program trying the wrong password. Is there any way I could get the logs for the same ( I also checked the Windows 7  security logs but no information about the bad password etc) Any help would be appreciated.
Regards,
JK

A: A few random thoughts:

*

*Enable auditing of logon/logoff events on the client, and/or;

*Use Microsoft SysInternals Process Explorer and Process Monitor to monitor and investigate processes and what credentials they are using.  Process Explorer, for example, shows you the credentials used to launch a process, but you can also drill down and investigate credentials being used through impersonation (enable the lower pane view, set the lower pane to show handles, and then look for Token objects)

That's where I'd start...

A: I would also run netlogon service and review its logs. Also you can check out netwrix. They have a program call Account Lockout Examiner, with this program you can view the account on what ever workstation that they have logged into.  Oh and another point is: does the client have two NIC's? The reason why I ask is that I was having an issue with a laptop doing the same thing. They were both hitting the DNS for authentication at the same time, which caused our lock out issues on our end.
Account lock out examiner
Starting nelogon

A: I'm pretty sure I agree with @SimonCaitlin in your approach. Proces explorer could be a quick win for you. I just thought I'd add the following additional ideas.
You have two potential sources of this problem, the system or the user.
The system could possibly be trying to run a service in the context of that user. This should be listed in the services.msc console. Or you could try disabling services and see when the lockout stops happening.
If the lockout is happening when a particular user is logged in, then you can safely say its a process run by that user that is causing the lockout. If you have cleared credentials, disconnected drives, etc., you could try replacing the user's profile with a new one.
Oh, and Scheduled Tasks is another potential source of failed authentication requests from both a computer and user perspective. It could be a task configured to run in that user's context, or a script that is run which uses stored credentials by some other means, which is trying to authenticate with the domain controller. This has happened before and the regularity of lockout time was the giveaway.

A: Is there only one DC in the domain? Do you have access to the DC(s)?
Things to check:

*

*Programs that use AD creds.

*Persistent drive mappings.

*Scheduled Tasks.

*Disconnected RDP/TS Sessions.

*Outlook and Outlook Web Access

*Mobile email apps (If you're using something like Lotus Domino w/ Traveler for email for example)

*Wireless settings  (If you're using user authentication for wireless)

*Services running as user.

Using the LockoutStatus.exe you can see which DC(s) are getting the bad password attempts. Use EventCombMT.exe to analyze them for you:
For EventCombMT:
Double click "EventCombMT.exe" and click the "Searches" drop down menu then "Built In Searches" then "Account Lockouts".  What this is going to do is pre-populate some of the search criteria for you.  It is going to get a list of your domain controllers, check off the "Security" log box.  Check the boxes for "Success & Failure Audits" and lastly it is going to populate some of the "Event IDs".
(Note: Add the following Event IDs to the search line:  4625 4740 if you have Windows 2008 DCs)
You can also use the SysInternals Process Explorer and Process Monitor as others have said, but that will only help you if the issue is on the machine you're running it against. If the users credentials are elsewhere - the above steps will help.


text:
Q: How do I display category on a page separate from subcategory in Octobercms? Good day, I am new to Octobercms, trying to fix an issue. I have category and subcategory in my project, i have already implemented nested relationship for that and connected it to the product table via a pivot table. Right now when i drag the display list component and try to display the list of categories, it shows up with subcategories. I would love to have categories on one page connected to subcategories on another page. I don't really get how to use scope that shows up in the dropdown of the component. Any help to resolve this?
I have this as my scope but it doesnt seem to work
 public function scopeCategory($query)
{
    return $query->where('parent_id',0)

$cats = ::category()->parent_id()->orderBy('cat_title')->get();

};

i get this when i change the scope value
Illegal operator and value combination.

A: Solved it by adding this to my category model to show just categories with parent_id of 0
public function scopeCategory($query)
{
    return $query->where('parent_id', 0);
}


text:
Q: Does browser batch huge number of ajax requests? I would like to know if the browser batch huge number of ajax requests to a single server. I'm using jQuery and sending approx. 300 requests to server at a time. When I look at the firebug console, it appears as if the requests are going in batches. Is this done by jQuery or browser?
EDIT:
I understand that browser has a limit on maximum number of simultaneous connection to the server. Questions is can I rely on the browser to handle huge number of requests or I've to implement some queue for processing requests (say 5 requests at a time)

A: The browser has no way of grouping the AJAX requests into a single "batch" request, the server wouldn't know how to handle it. It will certainly buffer the requests, so that only two or so requests are processed at a time.

I'm using jQuery and sending approx. 300 requests to server at a time.

I hope you don't intend to do this in production. It would probably be better to programmatically batch process many things together.

A: The browser does limit the requests to a limited number of paraller request so it may appear that it is happening in batches. Garrett explains this better here How to perform Ajax requests, a few at a time
While with JQuery can also help in batching requests yourself using a "future" like method called $.when() that expects a few promises to be resolved, in this case your ajax requests
see Guillaume86 explains this here jQuery.when understanding.
Sorry that I'm not answering directly but this topics are well explained on the two Questions I referred to. Cheers.
While technically I answer your question, practically as Alexander said, it's good practice to try to minimise your client / server interactions to the minimum possible.

A: You can make the requests faster by settings header Connection: Keep-Alive;. Then the browser does not need to create new connection for every request.
But still it would be better to make server API that support some kind of batch.
e.g. for JSON-RPC:
{method:'batch.process', params: [{method:'...'},{method:'...'},...]}


text:
Q: Can't change DataContext WPF I am trying to use a MVVM pattern instead of putting all logic in the code-behind file, but I can't seem to get it working.
My view is this:
<Window x:Class="WpfApp4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp4"

    mc:Ignorable="d"
    xmlns:vm="clr-namespace:WpfApp4.ViewModel"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <vm:ViewModelMain />
</Window.DataContext>

<Grid>

</Grid>

And this is my ViewModel:
namespace WpfApp4.ViewModel
{
    class ViewModelMain
    {
    }
}

What am I doing wrong here?

A: Visual studio can be a bit temperamental sometimes with xaml warnings and errors. Try closing the window, and/or cleaning and rebuilding the project, or if all else fails close all windows and restart visual studio


text:
Q: Creating a FIFO Queue with Keypad Inputs I'm trying to implement a FIFO queue for keypad inputs but cannot seem to get it to work. I'm able to get the keypad inputs to appear on an LCD screen but that is all I'm able to do. I think the code is supposed to read a keypad input and push it into a queue, then pop the keypad input and read the value onto an LCD screen. Could anyone advise on why it doesn't display all the values I've pressed? Thank you.
#include "project.h"
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>

// Keypad Variables

char KeyPad[4][4] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'},
};

char ReadKeyPad();

// FIFO Variables

struct FIFO {
    char            key;
    struct  FIFO    *next;
};

struct FIFO KeyQueue[] = {
    {0, &KeyQueue[1]},  //[0]
    {0, &KeyQueue[2]},  //[1]
    {0, &KeyQueue[3]},  //[2]
    {0, &KeyQueue[4]},  //[3]
    {0, &KeyQueue[5]},  //[4]
    {0, &KeyQueue[6]},  //[5]
    {0, &KeyQueue[7]},  //[6]
    {0, &KeyQueue[8]},  //[7]
    {0, &KeyQueue[0]}   //[8]
};

struct FIFO *Head;
struct FIFO *Tail;
int KeyQueue_Size=0;
bool KeyQueue_IsEmpty();
bool KeyQueue_IsFull();
void KeyQueue_Push(char key);
char KeyQueue_Pop();
char ReadKeyPad();

int delay = 10;

int main(void)
{
    Head = Tail = &KeyQueue[0];
    char key;

    CyGlobalIntEnable; /* Enable global interrupts. */

    /* Place your initialization/startup code here (e.g. MyInst_Start()) */

    LCD_Start();
    LCD_ClearDisplay();
    LCD_Enable();

    for(;;)
    {
        /* Place your application code here. */
        key = ReadKeyPad();
        LCD_Position(1,8);
        LCD_PutChar(key);

        if (key !=0)
        {
            if (!KeyQueue_IsFull())
                KeyQueue_Push(key);
        }
        //task for poping key
        delay --;
        if(delay <= 0 && !KeyQueue_IsEmpty())
        {
            KeyQueue_Pop();
            switch (key)
            {
                case '1':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 1");
                break;
                case '2':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 2");
                break;
                case '3':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 3");
                break;
                case '4':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 4");
                break;
                case '5':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 5");
                break;
                case '6':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 6");
                break;
                case '7':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 7");
                break;
                case '8':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 8");
                break;
                case '9':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 9");
                break;
                case 'A':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed A");
                break;
                case 'B':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed B");
                break;
                case 'C':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed C");
                break;
                case 'D':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed D");
                break;
                case '*':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed *");
                break;
                case '#':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed #");
                break;
                case '0':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 0");
                break;
                delay = 10;
            }

            CyDelayUs(100);
        }

    }
}

bool KeyQueue_IsEmpty()
{
    if(KeyQueue_Size == 0) return true;
    return false;
}
bool KeyQueue_IsFull()
{
    //if (Head == Tail) return truel
    if(KeyQueue_Size ==9) return true;
    return false;
}
void KeyQueue_Push(char key)
{
    Head->key=key;
    Head = Head->next;
    KeyQueue_Size ++;
}
char KeyQueue_Pop()
{
    char key;
    key = Tail->key;
    Tail = Tail->next;
    KeyQueue_Size --;
    return key;
}
char ReadKeyPad()
{
    int     i;
    char    key;
    uint8_t col;

    for (i=0; i<4; i++)
    {
        key = 0;
        ROW_Write(1<<i);
        col=COL_Read();
        //LCD_Position(1,0);
        //LCD_PrintNumber(key);

        if (col & 0x01) key=KeyPad[i][0];
        if (col & 0x02) key=KeyPad[i][1];
        if (col & 0x04) key=KeyPad[i][2];
        if (col & 0x08) key=KeyPad[i][3];
        if (key != 0) break;
    }

    return key;
}

A: Some problems in your code:

*

*As pointed before, delay = 10; is not well placed

*key variable of main function is set only at the beginning of for loop.

So a corrected code could be:
for(;;)
{
    key = ReadKeyPad();
    LCD_Position(1,8);
    LCD_PutChar(key);

    if (key !=0)
    {
        if (!KeyQueue_IsFull())
            KeyQueue_Push(key);
    }
    //task for poping key
    delay --;
    if(delay <= 0 && !KeyQueue_IsEmpty())
    {
        /* don't forget to store what have been poped from fifo */
        key = KeyQueue_Pop();

        switch (key)
        {
            case '1':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 1");
                delay = 10;
            break;
            case '2':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 2");
                delay = 10;
            break;
            /*
             .
             .
             .
             */
            case '0':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 0");
                delay = 10;
            break;
        }

        CyDelayUs(100);
    }
}

Maybe you can write it shorter:
for(;;)
{
    key = ReadKeyPad();
    LCD_Position(1,8);
    LCD_PutChar(key);

    if (key !=0)
    {
        if (!KeyQueue_IsFull())
            KeyQueue_Push(key);
    }
    //task for poping key
    delay --;
    if(delay <= 0 && !KeyQueue_IsEmpty())
    {
        /* don't forget to store what have been poped from fifo */
        key = KeyQueue_Pop();

        /* print what have been pressed */
        LCD_Position(0,1);
        LCD_PrintString("You pressed ");
        LCD_Position(0,12);
        LCD_PutChar(key);
        delay = 10;

        CyDelayUs(100);
    }
}


text:
Q: Convert "Never fully converted" provinces I'm playing Turkey and I'm trying to convert all my provinces into Sunni. However, I have some Dhimmi/zealots provinces that say that they "never will be Sunni".

My question is: is it possible to convert them at all? I don't care if I should just kill every zealot in my province, provoke them on revolt and them kill all or whatever. But I don't see any possibility including cruel ones that could accomplish that.
P.S. Of course, I don't mention cheating like installing mods or something, it's about hardcore play - no saves, no mods, vanilla game with DLC.

Thanks to @Nicolas , I found the right button, here is a screenshot to complete an answer:

A: For provinces controlled by the Dhimmi, simply remove the Dhimmi estate from the province. This will anger the Dhimmi and create revolt-risk in the province, but that'll go down eventually.
Zeal is even easier: just wait. Religious Zeal is a province modifier that occurs when a province has recently been converted, and goes away after 30 years.
Edit: Screenshot grabbed from Google. I haven't played in a while, but when I last played the building interface looked like this.

If you click on the icon square (next to where it says nobility, in this case), you can change which estate controls the province. It can be accessed by clicking the build tab hanging off of the right side of the province interface, seen below:


text:
Q: async http request handling I'm trying to handle an HTTP request in Go asynchronously this way:

*

*I pass a handler function to the HTTP server

*In the handler I store the HttpRequest / HttpResponse objects in a slice or a map

*When returning from the handler function - the response is NOT returned to the client, but the connection remains open

*When "some" async input received from another source, I take the relevant HttpRequest / HttpResponse objects from memory, write the response and close the connection.

What I aim for is very similar to Jetty-Continuation in Java.
How can I implement such a behaviour in GoLang?

A: You do not need this behavior in Go.
Java HTTP servers use threads and if the servlet waits for something it effectively blocks the current thread. Threads are heavy and thread pools are limited.
In Go the HTTP server implementation uses goroutines and if they are waiting they will not block operating system thread. Goroutines are lightweight and scheduled effectively by Go runtime. By effectively scheduling I mean switching when goroutine makes a system call or waits on channel.
Simply speaking, do not try to copy the workaround from Java servlets as the workaround is not needed in Go.
Let's consider a Java servlet, servlets share operating system threads
class Slow extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        Thread.sleep(1000);
        // stops the thread for a second
        // operating system puts a thread aside and reuses processor
        // it is out of Java control
        // when all pooled HTTP server threads are sleeping no request is served
    }

}

and Go HTTP handler, each handler is run in a seperate goroutine
func fast(w http.ResponseWriter, r *http.Request) {
    time.Sleep(10000 * time.Second)
    // Go scheduler puts the goroutine aside
    // and reuses OS thread for handling another request
    // when one second passes the goroutine is scheduled again
    // and finishes serving request
}

In Go you get what you want by default.


text: Q: CycleGAN produce only black images I have implement a CycleGAN from a tutorial. After one or two epoch it only produce fully BLACK images. No changes happen. Here is my code in GitHub .    I have not understand what is the reason. Please anyone give me any idea.


text:
Q: Android sdk will not install - crashes when checking for jdk I have downloaded the java jdk, and the android sdk installer, but when I run the android sdk installer, it works fine until the screen where it checks for the java jdk.
It starts to not respond, then after about 15 seconds, a crash message pops up.
Any help with this issue?

A: The issue for me was that I did not have the 32-bit version of the JDK installed. I only had the 64-bit version.

A: it may be a bit late, no solution on the internet worked for me and finally out of desperation I deleted the registery key:
HKEY_LOCAL_MACHINE\Software\JavaSoft (not in Wow6432Node)
And it worked! I hope I just saved someone from looking for a solution for two hours like I did.

A: This answer might come a little late, but before installing the Android SDK I had about 6 versions of Java installed. Simply uninstalling every version and then installing the latest JDK for 32 or 64 bit will fix this crash.


text:
Q: How to enable secure context in react-native-webview? I use the react native webview component to load up my log in screen on the Mobile application. With the latest Safari on iOS update in iOS 15, there is a need to make the webview load in a secure context. I use https://<hostname> to load the webview.
But when I try to use window.crypto.subtle.generateKey function, the method throws an exception saying undefined is not an object (evaluating 'a.subtle()[f]')
Is there some way I can load the webview in a secure context other than just having a https session?
Link from Apple team: https://trac.webkit.org/changeset/279628/webkit
Any help appreciated. Thanks.

A: I had the same problem.
I fixed it by importing react-native-webview-crypto into my monorepo and patching it locally like this:
+++ b/packages/react-native-webview-crypto/index.js
@@ -1,6 +1,7 @@
 const React = require("react");
 const { StyleSheet, View, Platform } = require("react-native");
 const { WebView } = require("react-native-webview");
+const { MainBundlePath } = require("react-native-fs")
 const { MainWorker, webViewWorkerString } = require("webview-crypto");

 const styles = StyleSheet.create({
@@ -137,7 +138,7 @@ class PolyfillCrypto extends React.Component {
     const code = `((function () {${webViewWorkerString};${internalLibrary}})())`;
     const source = Platform.select({
       android: { source: { uri } },
-      ios: undefined,
+      ios: { source: { uri: `file://${MainBundlePath}/blank.html` }},
     });

Additionally I've added blank.html file with content:
<html />

to my Resources in Xcode.
So basically after this change it's doing same thing for Ios as it used to do for Android.


text:
Q: how to convert different levels in one row I have a set of data like below:
BETA_LACT   R   I   S
-   23  25  91
-   30  0   109
-   0   0   136
+   73  0   0
+   14  0   59
+   0   0   49

I want to convert the data to the format below:
R_- I_- S_- R_+ I_+ S_+
23  25  91  73  0   0
30  0   109 14  0   59
0   0   136 0   0   49

I tried spread() but failed, could anybody help me?

A: I suspect your problem using spread and gather is that there is nothing your sample data to suggest which rows should be collapsed. As a human, I can observe that you wish to combine rows 1 and 4, 2 and 5, etc. However, there are no other columns or "keys" persay in your dataset to indicate this.
One solution would be to add an index column as I show in the second example below using group_by and mutate. The following reprex (reproducible example) shows both a non-working example analogous to your case and a working example.

library(tidyr)
library(dplyr)

example_data <- data.frame(
  categ = rep(1:3, 3),
  x = 1:9,
  y = 11:19,
  z = 21:29
)

# won't work
example_data %>%
  gather(var, value, -categ) %>%
  unite(new_col_name, var, categ) %>%
  spread(new_col_name, value)
#> Error: Duplicate identifiers for rows (1, 4, 7), (2, 5, 8), (3, 6, 9), (10, 13, 16), (11, 14, 17), (12, 15, 18), (19, 22, 25), (20, 23, 26), (21, 24, 27)

# will work
example_data %>%
  group_by(categ) %>%
  mutate(id = row_number()) %>%
  gather(var, value, -categ, -id) %>%
  unite(new_col_name, var, categ) %>%
  spread(new_col_name, value)
#> # A tibble: 3 x 10
#>      id   x_1   x_2   x_3   y_1   y_2   y_3   z_1   z_2   z_3
#> * <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1     1     1     2     3    11    12    13    21    22    23
#> 2     2     4     5     6    14    15    16    24    25    26
#> 3     3     7     8     9    17    18    19    27    28    29

(As a sidenote, please check out the reprex package! This helps you make a "reproducible example" and ask better questions which will facilitate better community support. Notice how easy it is to copy the above code and run it locally.)


text:
Q: Ошибка в программе угадай число я решил написать программу "угадай число" на Python. Вот код:
from tkinter import *
from tkinter import messagebox

import random
num = random.randint(1,100)
def guess(entry):
    while True:
        guess = entry.get()
        i = int(guess)
        if i == num:
            messagebox.showinfo("Ваш ответ", "Правильно!")
            break
        elif i > num:
            messagebox.showinfo("Ваш ответ", "Загаданное число меньше")
        elif i < num:
            messagebox.showinfo("Ваш ответ", "Загаданное число больше")
tk = Tk()
tk.title("Угадай число")
text = Label(tk,text="Введите число от 1 до 100")
text.pack()
num1 = IntVar()
entry = Entry(tk,width=50,textvariable=num1)
entry.pack()
btn = Button(tk,text="Отправить",command=guess)
btn.pack()
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas = Canvas(tk,width=400,height=300,bd=0,highlightthickness=0)
canvas.pack()

Но выдаёт ошибку:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: guess() missing 1 required positional argument: 'entry'

Я перевёл ошибку, но не понимаю как это исправить.

A: Немного поправил код. Вроде теперь как-то работает. Убрал цикл внутри guess(). Он там не нужен, т.к. делает бесконечный цикл на первом вводе. Плюс убрал в guess() переменную entry.
from tkinter import *
from tkinter import messagebox

import random
num = random.randint(1,100)
def guess():
    #while True:
    val = entry.get()
    i = int(val)
    if i == num:
        messagebox.showinfo("Ваш ответ", "Правильно!")
    elif i > num:
        messagebox.showinfo("Ваш ответ", "Загаданное число меньше")
    elif i < num:
        messagebox.showinfo("Ваш ответ", "Загаданное число больше")
tk = Tk()
tk.title("Угадай число")
text = Label(tk,text="Введите число от 1 до 100")
text.pack()
num1 = IntVar()
entry = Entry(tk,width=50,textvariable=num1)
entry.pack()
btn = Button(tk,text="Отправить",command=guess)
btn.pack()
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas = Canvas(tk,width=400,height=300,bd=0,highlightthickness=0)
canvas.pack()
tk.mainloop()

A: Я решил это так:
from tkinter import *
from tkinter import messagebox
import random
num = random.randint(1,100)
def guess():
while True:
    guess1 = num1.get()
    i = int(guess1)
    if i == num:
        messagebox.showinfo("Ваш ответ", "Правильно!")
        break
    elif i > num:
        messagebox.showinfo("Ваш ответ", "Загаданное число меньше")
        break
    elif i < num:
        messagebox.showinfo("Ваш ответ", "Загаданное число больше")
        break
tk = Tk()
tk.title("Угадай число")
text = Label(tk,text="Введите число от 1 до 100")
text.pack()

num1 = IntVar()
entry = Entry(tk,width=50,textvariable=num1)
entry.pack()

btn = Button(tk,text="Отправить",command=guess)
btn.pack()

tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas = Canvas(tk,width=400,height=300,bd=0,highlightthickness=0)
canvas.pack()


text:
Q: Restriction of dual basis to subspaces. Let V be a finite dimensional vector space and f_1,..,f_m be a linearly indepedent in V*. Prove that the following two statements are equivalent.
(i)f_1,..,f_m is a basis of V*.
(ii)for every subspace W of V, the restrictions of f_1,..,f_m to W spans W*
Here is what I have so far.
(i)=>(ii). We want to show that for a $T\in W^*$, $T=c_1*f_1+...+c_m*f_m$. Let $w\in W\subseteq V$. Let $\{v_1,..,v_m\}$ be a basis of V. Since w is also in V, we can write $w=a_1*v_1+...+a_m*v_m$ for some scalars $a_i$.
LHS:$T(w)=a_1*T(v_1)+...+a_m*T(v_m)$
RHS: $(c_1*f_1+...+c_m*f_m)(w)=c_1*f_1(w)+...+c_m*f_m(w)= c_1*a_1+...+c_m*a_m.$
Therefore if we let $T(v_i)=c_i$, then LHS=RHS which implies f_1,..,f_m spans W*.
I don't know how to do (ii)=>(i)
Thanks

A: Part 2.  To show: If V is a vector space of dimension m and  {$f_1, f_2, ... f_m$} = S  span $W^*$ for every subspace W of V, then S is a basis of $V^*$.
If dim(V) = m then dim($V^*$) = m also.
Let $W_1$ be a subspace of V with dimension m - 1, By hypothesis S spans $W_1^*$  So there must be m-1 independent elements S, call them $S_1$ = {$f_1, f_2, ...  f_{m-1}$} that form a basis for $W_1^*$.
There are m distinct subspaces $W_i$ of V with dimension m - 1, and for each of these S spans $W_i^*$.  However each $W_i$ is different and therefore each $W_i^*$ is different -- that is, no two of them can have the same basis. (This is because $W_i^{**} = W_i$.) So in each case we must pick a different set of m-1 elements of S to form a basis for $W_i^*$.
Let U be a subspace of dimension 1 such that $W \bigcap U$ = 0.  Then some element g of S must be the basis for $U^*$.  There must be at least one of the  $W_i^*$, call it W whose basis does not include g. We have W $\bigcup$ U = V so that $V^*$ =$(W \bigcup U)^*$ = $W^* \bigcup U^*$.  So the basis for $V^*$ is the union of the basis for W and g; and that is S.


text:
Q: Expand and Collapse events in SlickGrid How can I register to onCollapse and onExpand events on SlickGrid with DataView?
I need to track the status of the groups -- which are expanded and which are collapsed.

A: In short: you can't do that. There are no such events in the SlickGrid object and neither in DataView.

In long:

*

*First method:
The grid has an onClick method, which you could subscribe to. However subscribing this event only works for cell or row clicks, even works on the group row but not when you click expand or collapse. This event doesn't get propagated to the - or the + span elements that you can click on the group rows.

*Second method
The DataView has an on onRowsChanged event, which you could subscribe to as well. For example you can try doing it from your JS debugger console as: dataView.onRowsChanged.subscribe(function(e, args) {console.log(args.rows);});
Using this event could seem that we are one step closer, since the expand/collapse button click raises it. However the args parameter that we are receiving in our anonymous function contains only information about the rows needed to be updated on the grids canvas.

*Last chance (a.k.a. don't try these at home or the hackish methods)
I have tried all the possible ways to get around this, with no success. I will list these below just as reference (as of SlickGrid v2.2).

*

*$('.slick-group').click(function(){console.log()});

*$('.slick-group-toggle').click(function(){console.log()});
The attempts listed above only works for the first expand or collapse, since after the action, they are getting detached and attached to the DOM and the grid canvas if they fit (based on the DataView.onRowsChanged events args parameter which I have mentioned in point 2. above).

A: For those who are still looking for a solution, here is how I implemented it.
I had to hide some content in the group row when expanded, so I needed to have a collapsed/expanded class directly on the group row.
For this, I used dataView.getItemMetadata :
var getRowMetadata = function(old_metadata_provider) {
    return function (row) {
        var item = this.getItem(row),
            ret = old_metadata_provider(row);

        //Handle group rows
        if (item.__group) {
            //adding a class
            ret.cssClasses += ' ' + (item.collapsed === 1 ? 'collapsed' : 'expanded');
            //or trigger a custom event....
        }
        //"Normal rows"
        else if (item) {
            ret = ret || {};
            ...
        }
        return ret;
    };
};

....

dataview = new Slick.Data.DataView({
    groupItemMetadataProvider: groupItemMetadataProvider,
    inlineFilters: true
});
dataview.getItemMetadata = getRowMetadata(dataview.getItemMetadata);

A: I know this is really old but just thought I would share my solution. It is possible to access the click event for expanding or collapsing groups!
My solution was quite straight forward. You need to override handleGridClickEvent set within GroupItemMetadataProvider.
So to do this.. right after you register the groupItemMetadataProvider plugin, you call destroy() to unsubscribe the default handleGridClickEvent like so..
this.grid.registerPlugin(groupItemMetadataProvider);

// unsubscribes the default click event handler for grouped rows so we can provide our own which will save the state of the expanders
groupItemMetadataProvider.destroy();

You can then simply copy the function from within GroupItemMetadataProvider and add in any extra functionality you wish..
// On expander click event. This is attached to the grid.onClick but checks for the expander css class
// The function has been taken from slick.groupitemmetadataprovider.js (handleGridClick) and modified to save the expander states
// to local storage.
function onExpanderClick(e, args) {
    ...
}

In your function.. to ensure the expander element has been clicked you can look at the css class of the event
$(e.target).hasClass('slick-group-toggle')

you can see the state of the expander using item.collapsed and add whatever functionality you want depending on the state of the expanders.
Finally subscribe your new function as one of the grids onClick events like so..
grid.onClick.subscribe(onExpanderClick);


text:
Q: docker-compose.yml in Google Cloud Run I have a large understanding problem when it comes to docker-compose, Dockerfile and how GCP's service Cloud Run works. This makes me unable to advance in a project I have and I am litteraly out of things to try.
I have a docker-compose.yml file with the following content:
version: '2'

services:

    # The Application
    app:
        container_name: laravel_app
        build:
            context: ./
            dockerfile: docker/app.dockerfile
        volumes:
            - ./storage:/var/www/storage

    # The Web Server
    web:
        container_name: nginx_server
        build:
            context: ./
            dockerfile: docker/web.dockerfile
        volumes:
        - ./storage/logs/:/var/log/nginx
        ports:
        - 8080:80

As you can see, it is pretty simple, two services one for the app with php and one for the server. Both have their own dockerfiles and the build is correct. Locally everything works, no issue there.
I would now like to deploy those services in a Cloud Run service on GCP. After digging I saw that it is probably only possible to deploy a service with a single Dockerfile. Is there no way to deploy docker-compose.yml containers to Cloud Run? Should I use another service?

A: The immediate answer is: no it won't work as-is! You have to update your packaging.

*

*Firstly, Cloud Run doesn't allow you to mount volume. You need to have a stateless container. Build your container with these file inside and don't load an external volume

*Secondly, to let build a Frontend-backend architecture, I don't recommend to host the static part on Cloud Run. It's better (cheaper, faster) to store your static files on Cloud Storage (frontend) and to let the dynamic processing (backend) on Cloud Run. Then, put in front a HTTPS Global Loadbalancer, with CDN option activated. Configure 2 backend, one with a Cloud Storage backend for the front, the second a serverless NEG for Cloud Run.
yes, it's a lot of rework... Or you can use a traditional IaaS for this, with a VM but you lose all the benefit of the scalability and the serverless features.


text:
Q: Drawing a map on a jframe I currently have a player rectangle that moves if an arrowkey gets pressed by the user. My next goal is to paint a map: 1 = walls(black rectangle), 0 = nothing(white rectangle). How do i implement that? The method for drawing the map is the drawmap2d method. This is my current code:
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;

public class Raycast_World_2 extends JFrame implements ActionListener, KeyListener
{
    public int px,py;
    int velx = 0, vely = 0;
    Graphics f;
    int mapX=8,mapY=8,mapS=64;
    int map[]=
    {
    1,1,1,1,1,1,1,1,
    1,0,1,0,0,0,0,1,
    1,0,0,0,0,0,0,1,
    1,0,1,0,0,0,0,1,
    1,0,0,0,0,0,0,1,
    1,0,1,0,0,0,0,1,
    1,0,0,0,0,0,0,1,
    1,1,1,1,1,1,1,1,
    };

    public Raycast_World_2()
    {
       px = 100;
        py = 100;
        setSize(1024,512);
        setVisible(true);
        setDefaultCloseOperation(3);
        addKeyListener(this);
         setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        setTitle("Raycast_World-Try4_Version 3.0");
        JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenuItem menuItemExit = new JMenuItem("Exit");
menuFile.add(menuItemExit);

menuBar.add(menuFile);

// adds menu bar to the frame
setJMenuBar(menuBar);
getContentPane().setBackground(Color.gray);
    }
    public void actionPerformed(ActionEvent e){

        repaint();

}
    public void paint(java.awt.Graphics g) {
  super.paint(g);
  g.setColor(Color.yellow);

  g.fillRect(px,py,6,6);
  g.dispose();
  drawMap2D(g);
  repaint();
}
public void drawMap2D(java.awt.Graphics g){
    int x,y,xo,yo;
    Color currentcolor;
    for(y=0;y<mapY;y++){
      for(x=0;x<mapX;x++){
        xo = x*mapS;
        yo= y*mapS;
          if(map[y*mapX+x]==1){
            super.paint(g);
            currentcolor = Color.gray;
            g.setColor(currentcolor);
            g.fillRect(x,y,xo,yo);
            System.out.println("program tries to paint me");
        }else{
            super.paint(g);
            currentcolor = Color.white;
            g.setColor(currentcolor);
            g.fillRect(x,y,xo,yo);
            System.out.println("program tries to paint me");
        }

    }

}
}


text:
Q: Продублировать содержимое тега в самого себя пытаюсь продублировать содержимое тега title_box в самого себя, но не выходит.

Test 1

Test 2

    $('.title_box').load(function() {
          var title =  $(this).text();
          $(this).append(""+title+"");
        });

На выходе должно получиться:

Test 1Test 1

Test 2Test 2

Буду благодарен за подсказки.

A: У Вас почти всё правильно и всё работает:

$('.title_box').each(function() {
  var title = $(this).text();
  $(this).append("" + title + "");
});

Test 1

Test 2


text:
Q: DataTables warning: table id=coinsTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7 i am new to all these and i am overwhelmed. i am using a script and i get this error DataTables warning: table id=coinsTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7. Here is my code please help me. I have tried replicating the steps on similar thread but it didnt work.
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/scroller/1.4.2/js/dataTables.scroller.min.js"></script>

@endpush
@push('js')
<script src="{{asset('/assets/admin/FileSaver.min.js')}}"></script>
<script src="{{asset('/assets/admin/sweetalert2.all.js')}}"></script>
<script src="{{asset('/assets/admin/jquery.blockUI.min.js')}}"></script>
<script src="{{asset('/assets/admin/init.js')}}"></script>
@endpush

@push('js')
<script>
$(document).ready(function(e) {
    window.txTable = $('#coinsTable').dataTable({
        "order": [[ 5, 'asc' ]],
        "language": {
            "sDecimal":        ",",
            "sEmptyTable":     "{!! trans("admin.sEmptyTable")  !!}",
            "sInfo":           "{!! trans("admin.sInfo")  !!}",
            "sInfoEmpty":      "{!! trans("admin.sInfoEmpty")  !!}",
            "sInfoFiltered":   "{!! trans("admin.sInfoFiltered")  !!}",
            "sInfoPostFix":    "",
            "sInfoThousands":  ".",
            "sLengthMenu":     "{!! trans("admin.sLengthMenu")  !!}",
            "sLoadingRecords": "{!! trans("admin.sLoadingRecords")  !!}",
            "sProcessing":     "{!! trans("admin.sProcessing")  !!}",
            "sSearch":         "{!! trans("admin.sSearch")  !!}",
            "sZeroRecords":    "{!! trans("admin.sZeroRecords")  !!}",
            "oPaginate": {
                "sFirst":    "{!! trans("admin.sFirst")  !!}",
                "sLast":     "{!! trans("admin.sLast")  !!}",
                "sNext":     "{!! trans("admin.sNext")  !!}",
                "sPrevious": "{!! trans("admin.sPrevious")  !!}"
            },
            "oAria": {
                "sSortAscending":  "{!! trans("admin.sSortAscending")  !!}",
                "sSortDescending": "{!! trans("admin.sSortDescending")  !!}"
            }
        },
        processing: true,
        serverSide: true,
        "autoWidth": true,
        "ajax": {
            "url": "{{$table}}",
            "type": "POST",
            'headers': { 'X-CSRF-TOKEN': '{{ csrf_token() }}'}
        },
        order: [[ 4, "desc" ]] ,
        scrollY: 400,
        scroller: {
            loadingIndicator: true
        },
        "drawCallback": function( ) {
            $('[data-toggle="tooltip"]').tooltip();
        },
        type:'POST',
        columns: [

            {data: 'logo', name: 'logo', orderable:false},
            {data: 'name', name: 'name', orderable: true},
            {data: 'price', name: 'price', orderable: true},
            {data: 'change_pct', name: 'change_pct', orderable: true},
            {data: 'volume', name: 'volume'},
            {data: 'market_cap', name: 'market_cap'},
            {data: 'supply', name: 'supply'}

        ]
    });
});
</script>
@endpush```


text:
Q: Implementing Procedure in SQL Server I have received the following assignment:

*

*Create a procedure setAccount with the parameters @AccountNumber, @CompanyName, @BankName in SQL Server

*Check in the procedure if AccountNumber, CompanyName or BankName already exist. If one of them exists, the procedure should return number 0. If none of them exists the procedure should insert the data in the corresponding tables. Please note the role of the table Object
An additional important information is that a Counterparty can be both a Bank and a Company.
The database (.bak file) can be downloaded using this LINK.
The datamodel (generated with Mgmt Studio) is displayed here:

I noticed that (apart from the Account table) the tables are so defined that primary keys are not generated automatically. Please confirm this separately.
This is how I've done the procedure (RETURN commands are not returning 0 or 1 as output...):
ALTER PROC setAccount
(
 @Kontonummer AS [varchar](255) = NULL
,@Firmenname AS [varchar](1000)
,@Bankname AS [varchar](255)
)
AS
BEGIN
    -- SET NOCOUNT ON

    DECLARE @FlagKontonummer AS SMALLINT
    DECLARE @FlagFirmenname AS SMALLINT
    DECLARE @FlagBankname AS SMALLINT

    SET @FlagKontonummer = (SELECT COUNT(*)
                            FROM [dbo].[Bank]
                            WHERE Bankname LIKE '%' + LTRIM(RTRIM(@Kontonummer)) + '%')
    SET @FlagFirmenname = (SELECT COUNT(*)
                           FROM [dbo].[Bank]
                           WHERE Bankname LIKE '%' + LTRIM(RTRIM(@Firmenname)) + '%')
    SET @FlagBankname = (SELECT COUNT(*)
                         FROM [dbo].[Bank]
                         WHERE Bankname LIKE '%' + LTRIM(RTRIM(@Bankname)) + '%')

    IF @FlagKontonummer > 0 OR @FlagFirmenname > 0 OR @FlagBankname > 0
        RETURN 0

    IF (@FlagKontonummer = 0 AND @FlagFirmenname = 0 AND @FlagBankname = 0)
    BEGIN
        DECLARE @max_ob_ID AS INT
        DECLARE @p_company_id AS VARCHAR (MAX)

        SELECT @max_ob_ID = MAX(ObjectID) FROM [dbo].[Object]

        INSERT INTO [dbo].[Object] ([ObjectID]) VALUES (@max_ob_ID + 1)

        INSERT INTO [dbo].[Bank] (BankID, Bankname)
        VALUES (@max_ob_ID + 1, LTRIM(RTRIM(@Bankname)))

        SELECT @max_ob_ID = MAX(ObjectID) FROM [dbo].[Object]

        INSERT INTO [dbo].[Object] ([ObjectID]) VALUES (@max_ob_ID + 1)

        INSERT INTO [dbo].[Company] (CompanyID, Companyname)
        VALUES (@max_ob_ID + 1, LTRIM(RTRIM(@Firmenname)) )

        SELECT @p_company_id = CompanyID
        FROM [dbo].[Company]
        WHERE Companyname = LTRIM(RTRIM(@Firmenname))

        INSERT INTO [dbo].[Account] ([AccountNumber], [CompanyID], [CounterpartyID])
        VALUES (@Kontonummer, @p_company_id, 10  -- ??? **COUNTERPARTY** - which one ??? ---
        )

        RETURN 1
    END
END

The MAIN QUESTION is: based on the given information is it possible to determine the correct Counterparty? From my point of view this information is missing, and in order to complete the task an additional information has to be provided.
Is that correct, or am I missing something?
Secondary question is regarding the procedure itself - would you write it in this matter, or is there a more elegant solution than mine?


text:
Q: Removing specified word in repeater I'm trying to remove a specified word/line from a string in a repeater and cut the length of the string
  public static string CutTextLength(string text)
    {
        if (text.Length > 400)
        {
            text = text.Substring(0, 400) + "...";
            Regex.Replace(text, "
", "");
        }
        return text;
    }

<%#CutTextLength(Eval("Text").ToString()) %>

When running this code i'm only reducing the length of the string but not removing all the <"br /"> tags in the string.
Can anyone help me with my problem?

A: You should do:
text = Regex.Replace(text, "<""br /"">", "");

because Replace doesn't alter text but returns a new string with the replacements.
Edit
On close reading your question I discovered you want to remove <"br /">. The above, updated statement should do the job.

A: Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.
You can try this for string:
text = text.Replace("
", "");

If you want to use regex. This should work

    static void Main(string[] args)
    {
        string text = @"This text with
,
 ";

        text = Regex.Replace(text, @"
", "A");

        Console.WriteLine(text);
    }


text:
Q: Angular 7 deployment on azure server I am a newbie to microsoft azure server ,I've created a basic app in angular 7 with nodeJS as backend language ,Now i want to deploy that app but i can't setup angular7 enivronment.
 i've tried to install angular cli via bash but its not working for me ,my npm version is 5.6.0 and nodejs version on azure cloud is 8.9.4
I get the following error


text:
Q: What's the meaning of 'has been on it' in this joke? In the BGT show, a boy, Ned Woodman does a joke as performance. During his performance, he said

Why are people so excited talking dog on Britain's Got Talent.
Amanda Holden has been on it for years.

And they show audiences' happy face of laughing. But I don't know why it's so funny.
What's the meaning of 'has been on it' here?

This is the youtube link of the performance: https://www.youtube.com/watch?v=0qxIyOFkJeY

I listened to the joke in the wrong way and I fixed the content with the help of the comment below. ('spin on it' -> 'has been on it')

A: Calling an ugly women 'a dog' is an outdated chauvinistic slur. This boy is alluding to this concept. So, the boy is puzzled as to why people are suddenly excited about seeing a talking dog on the talent show when there has been a talking dog on the show for many years in the person of Amanda Holden (hah hah!). He is suggesting that she is a dog and talks. Hence, why is just another talking dog seen as an exciting novelty? I read this as an ironic gag with no malice intended and, thankfully, there are still a few moderate thinkers who would refrain from taking to Twitter to demand he be 'burned at the stake', as they understand it is being said in jest by a child. The fact that he directed it at Amanda Holden would confirm that because clearly she is not 'a dog'.


text:
Q: How do I prevent this overflow error with multiple columns and listviews? I am creating a message page, where an admin can send messages to the users on the app.
I use a Container, with a Column with a Row and an AnimatedContainer as children, the AnimatedContainer also holds a Column with two Listviews and a TextField.
The Row holds an Icons.add button, whenever the button is pressed, _isExpanded =! _isExpanded. When _isExpanded, the AnimatedContainer height is set to 400, when !_isExpanded, the height is 0. My weakness in flutter is working with spacing, boundries etc. Whenever I expand my AnimatedContainer, I get a bottomOverflow error, which isn't surprising because my Column inside the Animated container (and it's children) have a fixed width. I tried wrapping a lot of widgets with Expanded, but I can't seem to find the right combination. The error keeps appearing. Anyone who is able to help me resolve this?
Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      color: Colors.grey[300]),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('Ontvangers',
                                style: TextStyle(
                                    fontFamily: 'Lato',
                                    fontSize: 16,
                                    fontWeight: FontWeight.w700)),
                            IconButton(
                              icon: Icon(Icons.add),
                              onPressed: () {
                                setState(() {
                                  _isExpanded = !_isExpanded;
                                });
                              },
                            )
                          ],
                        ),
                        AnimatedContainer(
                          duration: Duration(milliseconds: 300),
                          curve: Curves.fastOutSlowIn,
                          height: _isExpanded ? 400 : 0,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              TextField(
                                decoration: InputDecoration(
                                    prefixIcon: Icon(Icons.search),
                                    hintText: 'Zoeken'),
                                controller: _searchController,
                              ),
                              AnimatedContainer(
                                duration: Duration(milliseconds: 300),
                                curve: Curves.fastOutSlowIn,
                                height: selectedUsers.isNotEmpty ? 50 : 0,
                                child: ListView.builder(
                                    scrollDirection: Axis.horizontal,
                                    itemCount: selectedUsers.length,
                                    itemBuilder: (ctx, index) {
                                      return Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          InputChip(
                                              labelStyle: TextStyle(
                                                  color: Colors.black),
                                              label: Text(filteredUsers[index]
                                                      ['firstName'] +
                                                  ' ' +
                                                  filteredUsers[index]
                                                      ['lastName'])),
                                          SizedBox(
                                            width: 5,
                                          )
                                        ],
                                      );
                                    }),
                              ),
                              ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: filteredUsers.length,
                                  itemBuilder: (ctx, index) {
                                    return Column(
                                      children: [
                                        ListTile(
                                            tileColor: Colors.white,
                                            title: Text(filteredUsers[index]
                                                    ['firstName'] +
                                                ' ' +
                                                filteredUsers[index]
                                                    ['lastName']),
                                            subtitle: Text(
                                                filteredUsers[index]['email']),
                                            trailing: IconButton(
                                              icon: selectedUsers.contains(
                                                      filteredUsers[index]
                                                          ['uid'])
                                                  ? Icon(
                                                      Icons.check_box_rounded)
                                                  : Icon(Icons
                                                      .check_box_outline_blank_rounded),
                                              onPressed: () {
                                                if (selectedUsers.contains(
                                                    filteredUsers[index]
                                                        ['uid'])) {
                                                  selectedUsers.remove(
                                                      filteredUsers[index]
                                                          ['uid']);
                                                  setState(() {});
                                                } else {
                                                  selectedUsers.add(
                                                    filteredUsers[index]['uid'],
                                                  );
                                                  setState(() {});
                                                }
                                              },
                                            )),
                                        SizedBox(
                                          height: 8,
                                        )
                                      ],
                                    );
                                  }),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                )

A: Try wrapping your main widget or scaffold inside of a SafeArea. This may take care of your issue.


text:
Q: Problems running scala/play project with Docker I have a multi project SBT build. One of the sub-projects is a Play project. Normally, I'd run ./activator "project website" run to run the Play project. I'm trying to setup a docker development environment, but having trouble getting a proper CMD in my Dockerfile. I'm trying to use docker compose as well. My Dockerfile looks like:
FROM java:latest
ADD . /code
WORKDIR /code
CMD ["./activator", "\"project website\"", "run"]

I escaped the quotes in "project website". When I run docker-compose up to start this up, my project dependencies download, but then it fails with:
wb1_1 | [warn] there were 1 feature warning(s); re-run with -feature for details
wb1_1 | [warn] two warnings found
wb1_1 | release stage is set to: stage
wb1_1 | [info] Set current project to root (in build file:/code/)
wb1_1 | [error] Expected letter
wb1_1 | [error] Expected symbol
wb1_1 | [error] Expected '!'
wb1_1 | [error] Expected '+'
wb1_1 | [error] Expected '++'
wb1_1 | [error] Expected 'debug'
wb1_1 | [error] Expected 'info'
wb1_1 | [error] Expected 'warn'
wb1_1 | [error] Expected 'error'
wb1_1 | [error] Expected ';'
wb1_1 | [error] Expected end of input.
wb1_1 | [error] Expected '--'
wb1_1 | [error] Expected 'show'
wb1_1 | [error] Expected 'all'
wb1_1 | [error] Expected '*'
wb1_1 | [error] Expected '{'
wb1_1 | [error] Expected project ID
wb1_1 | [error] Expected configuration
wb1_1 | [error] Expected key
wb1_1 | [error] Expected '-'
wb1_1 | [error] "project website"
wb1_1 | [error] ^
services_wb1_1 exited with code 1
Gracefully stopping... (press Ctrl+C again to force)

Any ideas on how I can get this to run inside my container?

A: As per our comment thread, you can use CMD ["./activator", "website/run"]


text:
Q: adding legend to a tikz graph I'm creating a picture through tikz package. It shows a eight spoke wagon wheel at two different frames. How can I add the legend __ Frame 1 and ....Frame 2?
When I try to use \addlegendentry it gives me an error. Thanks in advance
 \documentclass[10pt,a4paper]{report}
 \usepackage{tikz}

 \begin{document}
   \begin{tikzpicture}[scale=3]
   \draw (0,0) circle (1cm);

   \draw (0:1cm) -- (180:1cm);
   \draw (45:1cm) -- (225:1cm);
   \draw (90:1cm) -- (270:1cm);
   \draw (135:1cm) -- (315:1cm);

   \draw[dotted] (7.5:1cm) -- (187.5:1cm);
   \draw[dotted] (52.5:1cm) -- (232.5:1cm);
   \draw[dotted] (97.5:1cm) -- (277.5:1cm);
   \draw[dotted] (142.5:1cm) -- (322.5:1cm);
   \end{tikzpicture}
 \end{document}

A: Like this?

your question is not very clear, so this can  be only starting point... MWE, which gives above image is:
\documentclass[10pt,a4paper]{report}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
    \begin{tikzpicture}[scale=3]
\node (n1) [circle,draw,minimum size=6cm] {};% node size can not be scaled
\node (n2) [draw,right=of n1,align=left] {- - - frame 1 \dots\\
                                          -----frame 2 \dots};
\draw   (  0:1) -- (180:1)
        ( 45:1) -- (225:1)
        ( 90:1) -- (270:1)
        (135:1) -- (315:1);
\draw[dotted]
        (  7.5:1) -- (187.5:1)
        ( 52.5:1) -- (232.5:1)
        ( 97.5:1) -- (277.5:1)
        (142.5:1) -- (322.5:1);
    \end{tikzpicture}
\end{document}


text:
Q: Pip - show versions of package Before the pip resolver was changed recently, I could easily do pip install foo== to find out what versions of a package were available:
% pip install hydra-core== --use-deprecated=legacy-resolver
Looking in indexes: https://pypi.org/simple
ERROR: Could not find a version that satisfies the requirement
hydra-core== (from versions: 0.1.4, 0.1.5rc1, 0.1.5, 0.9.0, 0.10.0,
0.11.0rc1, 0.11.0, 0.11.1rc1, 0.11.1, 0.11.2rc1, 0.11.2, 0.11.3, 1.0.0rc1,
1.0.0rc2, 1.0.0rc3, 1.0.0rc4, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5,
1.0.6, 1.1.0.dev1, 1.1.0.dev2, 1.1.0.dev3, 1.1.0.dev4)
ERROR: No matching distribution found for hydra-core==

Now that doesn't work anymore:
% pip install hydra-core==
Looking in indexes: https://pypi.org/simple
ERROR: Could not find a version that satisfies the requirement hydra-core==
ERROR: No matching distribution found for hydra-core==

Is there some other quick way to do this?  Note that I'm not just finding packages from pypi.org, I have private package registries too.

A: If you are using pip version 21.0 > x > 20.3 you can still use the same approach with a flag to explicitly use the discarded resolver:
pip3 install --use-deprecated=legacy-resolver hydra-core==

as explained in the announcement on python.org this flag was removed in January 2021. Now you can
pip install yolk3k

and then
yolk -V hydra-core

from my own experience, this will not always give the full list of available versions for any package. Otherwise see this old post, which was recently updated 3 days ago.


text:
Q: Custom backButtonIcon for NavigatorIOS This question is related to
https://github.com/facebook/react-native/issues/1383
Is there anyway to have a custom back button icon / title with NavigatorIOS?
backButtonIcon, backButtonTitle is not working as expected. The left arrow is always visible. New routes with custom backButtonIcon or backButtonTitle doesnt show

this.props.navigator.push({
    title: 'Next',
    component: Next,
    backButtonIcon: require('./../img/Back.png')
})

A: Use LeftButtonIcon instead of backButtonIcon like this;
this.props.navigator.push({
    title: '详情',
    component: PageList,
    leftButtonIcon: {uri: 'nav-back'},
    onLeftButtonPress: () => {
      ViewController.toggleTabBar(true);
      this.props.navigator.pop();
    },
    passProps: {
      data: data
    }
  });

The letButtonIcon comes from Native App.

A: You can easily achieve this using the Navigator component. Navigator is the JS implementation of a navigator. You can customize every aspect of it and you can use it in both iOS and Android. Further more, NavigatorIos is not maintained as much as Navigator. More info here: https://facebook.github.io/react-native/docs/navigator-comparison.html#content
And here:
https://facebook.github.io/react-native/docs/navigator.html#content


text:
Q: Scroll bar not showing up in android app I am using Titanium for creating my Android app. I have a one big form in my window. But the scrollbar is not showing up there. I think its not set by default in Titanium. So I just want to know is there any way for the scrollbar to show up.

A: I think what you are looking for is showVerticalScrollIndicator or showHorizontalScrollIndicator so setting the one you want to true will make the scroll bar show up.


text:
Q: How do you correctly say large numbers I saw a post on The daily What which links to a video where a person counts from 1 to 100,000.
Is he saying a large portion of the numbers wrong?
Back in high school my algebra teacher was extremely picky.  If we were going to say the number 135, we would say one hundred thirty-five.  If a person said one hundred and thirty-five my teacher would interpret that to mean 100.35.  Was my algebra teacher wrong, or did Jon just waste over 80 hours counting to 100,000 incorrectly.
I tried searching the web, but searching for 'numbers and'  doesn't work very well.  Can you point me to a reference or style guide that describes how to properly say large numbers?

A: American math text books and math manuals (e.g.: Math At Hand published by Great Source Publications) tell students that they don't say 'and' as they are speaking a number.
From page 5 of that text:
How would you read 905,346,521?
Say: nine hundred five million, three hundred forty-six thousand, five hundred twenty-one.
That is an American text.
As a British person, I find this cumbersome and I am sorry, but very American.
I now live in Canada and a teacher told me recently that 120 must be pronounced 'one hundred twenty', because if children say 'one hundred and twenty' then it means one hundred POINT 20.
Of course I said that it does not. In fact, either with the 'and' or without is acceptable, but 'and' does not mean 'point'. The teacher tried to tell me that it did.
This is worrying for what is going to go down the line in our kids' education and declining numeracy abilities. Additionally, we don't say 'twenty' after the decimal point, we say 'point two zero', or better yet, 'point two'. You can put as many zeroes as you like after a decimal digit with a value and it doesn't change its value. 0.1 is the same as 0.1000000. So don't bother with the extra zeroes.
American math manuals and teachers seem to want to express the decimal fraction in terms of relating it to the place value chart, so a decimal part is named so many tenths or hundredths or thousandths or ten thousandths or hundred thousandths or millionths. Really? It is essential to understand the place value chart, but if you express a decimal number as a fraction you are going to get a bunch of kids stopping in their tracks in confusion. I looked on the web this morning and there are some people actually saying that 1.2000 is 'one and two thousandths'. Really? Why not bung in another few zeroes and decide to call it 2 millionths instead? I kid you not. People, if you're going to teach it, you'd better understand it.
I believe it is acceptable to choose to say 'and' or not in your expression of numbers - either is fine but as a British person I always say 'and' when speaking a number such as 1,256. However a decimal point must ALWAYS be clearly stated as either 'point' or you could say 'decimal'. Anything else will cause confusion. Following a decimal point, each digit is to be read individually: 1.234 is said aloud as 'one point two three four'.
It leaves no room for ambiguity or mistake. Bottom line.
If a student is given a mixed number or mixed fraction (same thing, slightly different name) such as 57 20/100 (fifty seven and twenty hundredths) then you say it as a fraction, using 'and', as I just wrote it in words.
However, when you transform that fraction into a decimal number kids should first reduce it (so they can comprehend it better) and  twenty hundredths is actually the same as two tenths, so the number becomes 57.2
Knowing the place value, you know that the first column after the decimal point is tenths, the second column is hundredths the third column is thousandths. If you have two hundredths, the two belongs in the hundredths column (col. 2), but two tenths, the 2 belongs in the first column.
There is lots of room for confusion if you don't know what you are doing, and trying to tell kids that 'and' means 'decimal point' is one big fat way of adding further to the confusion they are going to have. Teachers: please don't do that.

A: Here are a couple more charts. Firstly, to show even Americans still use and more often than not...

And secondly, to show that Brits remain impervious to such pedantry...

Personally I think it's potty to rant about one or the other being more "correct", and it's positively disturbing to see people thinking this leaves scope for confusion between 120 and 100.20. I don't know who thought up dropping the "and" (though Noah Webster has "form" on such issues), but I'm sure they'd be aghast to find it's apparently led to more misunderstandings, not less.
TL;DR: Go with the usage you were taught, but please don't assume others are wrong.
On behalf of the Brits and Walt Disney, I must just say I never heard even an American refer to One Hundred One Dalmatians.

A: Depends on your background but, in Greek speak (at least), the word "and" is used to describe decimal places.  So one hundred "and" thirty five means 100.35, unlike one hundred thirty five, which means 135.  In English speak, however, the word "and" is not used to describe decimal places.  The word "point" is used instead.  Thus, one hundred "and" thirty five becomes 135, while one hundred "point" thirty five is 100.35.

A: "One hundred and thirty five" should definitely be interpreted as 135, not 100.35. "One hundred thirty five" is more acceptable in the U.S., especially in technical settings, although the former is also frequently used. Leaving out the "and" has the advantage of being less ambiguous, in the sense that "one hundred and thirty five" could mean "135" or "100, 35".

A: "One hundred and thirty-five" is perfectly correct, although the "and" tends to be removed in American English. It makes sense mathematically, since "and" is synonymous with "plus" — two apples and three apples makes five apples. One hundred, and thirty-five, makes 135.
The "and" is particularly useful when articulating a series of numbers. "One hundred one, one hundred two" could easily be misheard as "one hundred, one, one hundred, two" whereas using "one hundred and one, one hundred and two" removes that ambiguity.
Ultimately though it depends on location and culture. In the UK the "and" is always used; in the US there are a mixture of usages.
Looking at this ngram, it seems that skipping the "and" has only gained popularity over the last hundred years or so but using the "and" is still far more prevalent:

A: *

*If you accept Wikipedia http://en.wikipedia.org/wiki/101_(number) is pronounced "one hundred and one", "a hundred and one", "one hundred one", "a hundred one", or "one oh one".

*WebMath and Wolfram both writes "one hundred one"

*WebMath says 100.01 is one hundred and one hundredth

A: Your algebra teacher, if s/he ever in fact claimed that, is wrong. While it's common [at least for math teachers] to say that "and" must not be used except to separate the integer part from the fraction/decimal part, the usage is "One hundred and thirty-five hundredths" for 100.35, and the "hundredths" is not optional. This rule makes "One hundred and thirty-five [stop]" meaningless; it does not assign it a meaning of "100.35".

A: I've never heard the digits following the decimal point to be pronounced like the questioner describes. It's always "something-point-three-five". The digits to the right of the decimal point are named individually. I've worked a lot with accountants and statisticians.

A: Although it depends a little on you background / culture / origin etc. According to Standard English , your teacher was right.
Although calling 135 :

One hundred and thirty five

is very widely done, it is incorrect. Whereas saying

One hundred thirty five

is obscure and causes confusions, it is grammatically correct. (Though I do feel sorry for the guy who counted from 1 to 100,000.)
[Although I am not sure whether One hundred _and_ thirty five should be interpreted as 100.35]
There are many style guides that explain . Here are some links:
1-How to write numbers with words.
2-Ten rules for writing numbers with numerals.
3-Number to Word converter.
4-Ten Rules for writing numbers
5-Writing Numbers (another converter)

A: Saying and in a number is a huge pet peeve of mine. I despise it. Lazy and incorrect.  One hundred and one dalmations. Not one hundred and one dalmations. It's sloppy to add an "and" in there. Takes more time it's the matgh equivalent to "um". Slang.

A: I'm a first grade teacher and I teach my students to leave out the 'and' because I am a former bookkeeper and when working with money one hundred and thirty five is one hundred dollars and thirty-five cents. Please teach it the correct way !!

A: I was taught (and it seems logical to me) that 100.35 is read " one-hundred point three five,"
135 is read "one-hundred thirty-five" and to say "one-hundred and thirty-five" should be left for instances where you are speaking of two distinct numbers: 100, and 35

A: In American English, 135 is pronounced one-hundred thirty-five. 100.35 would be pronounced one-hundred and 35 hundredths.


text:
Q: How to format a USB or external drive in 13.04? I am using Kubuntu 13.04. How to format a USB or external drive?

A: Use gparted, like in this how-to. But don't use FAT32, or you will have a 4 GByte file size limit. Use NTFS instead.


text:
Q: Converting a Visual Basic function to PHP I have a Visual Basic function and I am not that familiar with VB. I need to convert it to PHP and have made a start. There are a couple of functions I'm not sure how to replicate and am looking for some help with this and to see if I have got the nesting right etc. In the following code, there is the vb function and then my attempt at te php version. it is not complete and in the php version I have commented out the vb parts I am not sure about. Can anyone help put me on the right lines?
Public Function gfnCrypt(ByVal Expression As String, ByVal Password As String) As String
  'RC4 Encryption
  Dim rb(0 To 255) As Integer, X As Long, Y As Long, Z As Long, Key() As Byte, ByteArray() As Byte, temp As Byte
  On Error Resume Next
  If Len(Password) = 0 Then
    Exit Function
  End If
  If Len(Expression) = 0 Then
    Exit Function
  End If
  If Len(Password) > 256 Then
    Key() = StrConv(Left$(Password, 256), vbFromUnicode)
  Else
    Key() = StrConv(Password, vbFromUnicode)
  End If
  For X = 0 To 255
    rb(X) = X
  Next X
  X = 0
  Y = 0
  Z = 0
  For X = 0 To 255
    Y = (Y + rb(X) + Key(X Mod Len(Password))) Mod 256
    temp = rb(X)
    rb(X) = rb(Y)
    rb(Y) = temp
  Next X
  X = 0
  Y = 0
  Z = 0
  ByteArray() = StrConv(Expression, vbFromUnicode)
  For X = 0 To Len(Expression)
    Y = (Y + 1) Mod 256
    Z = (Z + rb(Y)) Mod 256
    temp = rb(Y)
    rb(Y) = rb(Z)
    rb(Z) = temp
    ByteArray(X) = ByteArray(X) Xor (rb((rb(Y) + rb(Z)) Mod 256))
  Next X
  gfnCrypt = StrConv(ByteArray, vbUnicode)
End Function

And in PHP:
function gfnCrypt($mywebpassword, $mywebkey) {
  //'RC4 Encryption
  //Dim rb(0 To 255) As Integer, X As Long, Y As Long, Z As Long, Key() As Byte, ByteArray() As Byte, temp As Byte
  if(strlen($mywebpassword) == 0){
    return false;
  }
  if(strlen($mywebkey) == 0){
    return false;
  }
  if(strlen($mywebpassword) > 256){
    //Key() = StrConv(Left$(Password, 256), vbFromUnicode)
  }else{
    //Key() = StrConv(Password, vbFromUnicode)
  }
  $rb=array();
  for($x=0;$x=255;$x++){
    $rb['x'] = $x;
    for($x=0;$x=255;$x++){
     $y = ($y + $rb['x'];// + Key(X Mod Len(Password))) Mod 256
     $temp = $rb['x'];
     $rb['x'] = $rb[$y];
     $rb[$y] = $temp;
     //ByteArray() = StrConv(Expression, vbFromUnicode)
      for($x=0;$x=strlen($mywebpassword), $x++){
       $y = ($y + 1);// Mod 256
       $z = ($z + $rb[$y]);// Mod 256
       $temp = $rb[$y];
       $rb[$y] = $rb[$z];
       $rb[$z] = $temp;
       //ByteArray(X) = ByteArray(X) Xor (rb((rb(Y) + rb(Z)) Mod 256))
      }
    }
  }
  //gfnCrypt = StrConv(ByteArray, vbUnicode)
  return $gfnCrypt;
}

A: *

*The arithmetic modulo can be used in php using % operator.

$modulus = $a % $b

*

*I think you will get errors with your 3 embedded for (x…) loops by the way.

*To access an element of the array (the $ith for instance) don't use $array['i'] but $array[$i].

*The StrConv must be a ut8_encode and the left stuff can be done with substr($string, 0, 255).
References: utf8_encode substr

A: If you are trying to do RC4 encryption in PHP then you may wan't to take a look at the project at this link http://code.google.com/p/rc4crypt/

A: I really hope you have some unit tests to test that:
function gfnCrypt($mywebpassword, $mywebkey) {
  //'RC4 Encryption
  //Dim rb(0 To 255) As Integer, X As Long, Y As Long, Z As Long, Key() As Byte, ByteArray() As Byte, temp As Byte
  rb = array();
  Key = array();
  ByteArray = array();
  if(strlen($mywebpassword) == 0){
    return false;
  }
  if(strlen($mywebkey) == 0){
    return false;
  }
  if(strlen($mywebpassword) > 256){
    //Key() = StrConv(Left$(Password, 256), vbFromUnicode)
    Key[] = ut8_encodesubstr(Password, 0, 256));
  }else{
    //Key() = StrConv(Password, vbFromUnicode)
    Key[] = ut8_encode(Password);
  }
  $rb=array();
  for($x=0;$x=255;$x++){
    $rb['x'] = $x;
    for($x=0;$x=255;$x++){
     $y = ($y + $rb['x'] + Key(X % strlen(Password))) % 256;
     $temp = $rb['x'];
     $rb['x'] = $rb[$y];
     $rb[$y] = $temp;
     //ByteArray() = StrConv(Expression, vbFromUnicode)
     ByteArray[] = ut8_encode(Expression);
      for($x=0;$x=strlen($mywebpassword), $x++){
       $y = ($y + 1);// Mod 256
       $z = ($z + $rb[$y]);// Mod 256
       $temp = $rb[$y];
       $rb[$y] = $rb[$z];
       $rb[$z] = $temp;
       //ByteArray(X) = ByteArray(X) Xor (rb((rb(Y) + rb(Z)) Mod 256))
       ByteArray[X] = (ByteArray[X] ^= (rb[(rb[Y] + rb[Z]] % 256)]);
      }
    }
  }
  //gfnCrypt = StrConv(ByteArray, vbUnicode)
  gfnCrypt = ut8_encode(ByteArray);
  return $gfnCrypt;
}

I finished the code you started, but it seems really wrong (for example, why nest 3 for loops, using the same variable ?). It doesn't even seem to match the initial VB code...


text:
Q: Deviance Statistic in HLM analysis I am analyzing a multilevel model using the software HLM. I am trying to find out more about the Deviance statistic that I increasingly see being reported as a measure of the explanatory value/effect size of a model. In general, I know that HLM output reports this statistic and that the smaller it is the better. However:

*

*How does one use/interpret this statistic for a given analysis?

*How does one know if the deviance one obtains is at an acceptable level?

A: The deviance is calculated as
Deviance = -2 * LogLikelihood

For a given analysis, you can't interpret the deviance, and you can't say if it is at an acceptable level. You can use the deviance to compare two models that are nested. If you add parameters to a model, the difference in the deviance is chi-square distributed, with df equal to the number of parameters that you added to the model. It allows you to test whether the change in deviance is statistically significant. (Just as you can use the change in R^2 when you add predictors to a regression model to see if the improvement in fit is statistically significant.)


text:
Q: The script has an unsupported MIME type ('text/html') for firebase messaging service integration in vue js Thank you in advance,
                    I want to enable the push notification service of a firebase in my Vue js App. But while adding the below code, I am getting an error.
main.js (the file is on root)
const messaging = firebase.messaging();
  Notification.requestPermission().then((permission) => {
          if (permission === 'granted') {
              messaging.getToken().then((currentToken) => {
                if (currentToken) {
                    sendTokenToServer(currentToken);
                    updateUIForPushEnabled(currentToken);
                    alert('Token Available')
                } else {
                    updateUIForPushPermissionRequired();
                    setTokenSentToServer(false);
                    alert('Token Not Available')
                }
              }).catch((err) => {

              })
          } else {

          }
        });

firebase-messaging-sw.js (the file is on root)
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');

firebase.initializeApp({
   'messagingSenderId': '<message-sending id>'
});
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/itwonders-web-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

But I am getting below error
The script has an unsupported MIME type ('text/html')

A: @Onyoursix, Try to place firebase-messaging-sw.js into the public folder like {project_root}\public\firebase-messaging-sw.js and try with the below code and remove everything relevant to firebase push notifications code
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');

var config = {
    apiKey: "{YOUR_APIKEY}",
    authDomain: "{YOUR_AUTH_DOMAIN}",
    databaseURL: "{YOUR_DATABASE_UR}",
    projectId: "{YOUR_PROJECT_ID}",
    storageBucket: "{YOUR_STORAGE_BUCKET}",
    messagingSenderId: "{YOUR_MESSAGING_SENDER_ID}",
    appId: "{YOUR_APP_ID}"
      }
firebase.initializeApp(config)
const messaging = firebase.messaging();


text:
Q: Como adicionar um valor ao DBF Para fazer a leitura do arquivo .DBF trabalho da seguinte maneira:
Uso um TADOConnection, sendo a ConnectionString para:
Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=C:\_workspace\projects\DBFEditor\temp

Para ler o arquivo DBF uso um TADOQuery definindo a propriedade SQL para a consulta:
Select * from <arquivodbf>

Sendo assim tenho essas colunas no meu arquivo dbf.
INDICE  NOME    COR ESTILO  ESCALA
100     SAOJOAO      18      0,00

Eu preciso trocar o nome da coluna INDICE PARA ID, para isso estou fazendo da seguinte maneira:
  while not ADOQuery1.Eof do
    begin
      Adoquery1.Edit;
      ADOQuery1.FieldByName('NOME').TEXT:= 'ID';
      Adoquery1.Post;
      ADOQuery1.Next;
    end;

porem eu recebo o seguinte resultado, ao abrir meu excel:
INDICE  NOME    COR ESTILO  ESCALA
 ID     SAOJOAO      18      0,00

como eu espero o resultado:
 ID        NOME    COR ESTILO  ESCALA
 100     SAOJOAO        18      0,00

A: Fiz um exemplo de como poderia fazer, segue abaixo:

Declare no uses Data.DB, Datasnap.DBClient

var
  oCDSDados: TClientDataSet;
  iPos: Integer;
begin
  oCDSDados := TClientDataSet.Create(nil);
try
  oCDSDados.FieldDefs.Add('ID',ftInteger);
  oCDSDados.FieldDefs.Add('NOME',ftString,50);
  oCDSDados.FieldDefs.Add('COR_ESTILO',ftInteger);
  oCDSDados.FieldDefs.Add('ESCALA',ftFloat);
  oCDSDados.CreateDataSet;

  ADOQuery1.First;
  while not (ADOQuery1.Eof) do
  begin
    oCDSDados.Append;
    oCDSDados.FieldByName('ID').AsInteger         := ADOQuery1.FieldByName('INDICE').AsInteger;
    oCDSDados.FieldByName('NOME').AsString        := ADOQuery1.FieldByName('NOME').AsString;
    oCDSDados.FieldByName('COR_ESTILO').AsInteger := ADOQuery1.FieldByName('COR_ESTILO').AsInteger;
    oCDSDados.FieldByName('ESCALA').AsFloat       := ADOQuery1.FieldByName('ESCALA').AsFloat;
    oCDSDados.Post;
    ADOQuery1.Next;
  end;

  //Primeira linha para incluir os fields no Excel.
  for iPos := 0 to oCDSDados.FieldDefs.Count-1 do
  begin
    // para pegar os fields do ClientDataSet
    oCDSDados.FieldDefs[iPos].Name;
  end;

  oCDSDados.First;
  while not (oCDSDados.Eof) do
  begin
    //
    // ESTRUTA PARA MONTAR O DADOS NO EXCEL
    //

   oCDSDados.Next;
 end;
finally
  if (oCDSDados.Active) then
    oCDSDados.Close;
  FreeAndNil(oCDSDados);
end;
end;

Espero ter ajudado. Abraços!


text:
Q: Opening pdf files through MS-Word I am trying to open a pdf file through MS Word, perform certain action such as evaluating calculations, printing the files, etc. and then proceed with closing the file. The error message I received is "Microsoft Excel is waiting for another application to complete an OLE action."
I have previously tried hyperlinkfollow and Shell MyPath & " " & MyFile, vbNormalFocus method, it doesn't work. I am still at the starting phase of opening the pdf files, please advice. Thanks!
Sub Extract_PDF_Data()

Dim mainData As String
Dim strFile As String
Dim Oldname As String
Dim Newname As String
Dim Folderpath As String

Dim s As String
Dim t As Excel.Range
Dim wd As New Word.Application
Dim mydoc As Word.Document

Folderpath = InputBox("Folder path: ")
Folderpath = Folderpath & "\"
strFile = Dir(Folderpath & "", vbNormal)

Do While Len(strFile) > 0
Oldname = Folderpath & strFile
Set wd = CreateObject("Word.Application")
Set mydoc = Word.Documents.Open(Filename:=Oldname, Format:="PDF Files",
ConfirmConversions:=False)

mainData = mydoc.Content.Text
mydoc.Close False
wd.Quit

strFile = Dir
Loop

End Sub

A: Don't us the New keyword in the line that declares the object variable. This will "block" the object variable - it causes the error when the code laters tries to instantiate it. This method can work in VB.NET but not in VBA.
Do it more like this:
Dim wd As Word.Application
Set wd = New Word.Application. 'Or use CreateObject

A: I think a combination of those three sources will lead to the answer:
How to open a pdf with Excel?
How to extract data from pdf using VBA?
How to open and print a pdf using VBA?

I think it will be something like this:
Sub Extract_PDF_Data()

Dim mainData As String
Dim strFile As String
Dim Oldname As String
Dim Newname As String
Dim Folderpath As String
Dim s As String
Dim t As Excel.Range
Dim Appshell As Variant
Dim ap As String
Dim Browsedir As Variant
Dim f As Variant
Dim KeyWord As String

' This is a suggestion, I use it because it is more convenient than copy-pasting folder paths
Dim FSO As Object
Set FSO = CreateObject("Scripting.Filesystemobject")

 ' Get Folder over user input
Set Appshell = CreateObject("Shell.Application")
Set Browsedir = Appshell.BrowseForFolder(0, "Select a Folder", &H1000, "E:\Xample\Path")

' check if not cancalled
If Not Browsedir Is Nothing Then
      Folderpath = Browsedir.items().Item().Path
Else
    GoTo Quit
End If

KeyWord = "The_Materialist_Example"

' go through all files in the folder
For Each f In FSO.GetFolder(Folderpath).Files
    ' if file is a pdf , open, check for keyword, decide if should be printed
    If LCase(Right(f.Name, 3)) = "pdf" Then

        ' Here the methods suggest different answers.
        ' You can either use FollowHyperLink or use the Adobe Library to OPEN PDF

        ' I would write a function that checks the active pdf for the keyword : IsKeyFound
        Debug.Print Folderpath & "\" & f.Name

        Call PrintPDF(Folderpath & "\" & f.Name)
        If IsKeyFound(f, KeyWord) Then
            f.Print
        End If
    End If
Next f

Quit:
End Sub

Private Sub PrintPDF(strPDFFileName As String)
  Dim sAdobeReader As String 'This is the full path to the Adobe Reader or Acrobat application on your computer
  Dim RetVal As Variant
  sAdobeReader = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
  'Debug.Print sAdobeReader & "/P" & Chr(34) & strPDFFileName & Chr(34)
  RetVal = Shell(sAdobeReader & " /P " & Chr(34) & strPDFFileName & Chr(34), 0)
End Sub

Private Function IsKeyFound(PDF As Variant, KeyWord As String) As Boolean
   'Decide if file needs to be printed, insert your criteria and search algorithm here
End Function

I have not been able to figure out how to extract the keywords, you could however use a user input as a first approach and later move on to a automated scan of the pdf.
I hope this gets you further on the way to the solution.


text:
Q: How can I access record or frecord varibale in function result so that i can use it to function submit? I have tried to make the record variable global and after that, I am trying to use it in submit function but it's giving an error 'record is not defined'. Can anyone help me to understand the situation?
Below I have two functions (result and submit), and the record variable is basically have some value in result which I want to access in submit. Can anyone help?
    def submit(): ## this function will use to add stock.
        for i in f_record:                           (SUBMIT FUNCTION )
            for j in i:
                if(j==name1.get()):
                    p=int(i[3]) * quantity1
        price=p

    def result(): # This function will use to see if the stock is added or not. Also to see the present stock                                              (RESULT FUNCTION)
        stock=sqlite3.connect('Super Store Stock')
        c=stock.cursor()
        c.execute('SELECT * FROM y')   ##this will use to select all elements from table we have created
        global record
        record=c.fetchall()
        stock.commit()
        stock.close()
        return


text:
Q: Enable Touch Screen on Lenovo X1 Carbon Touch There are quite a few guides on how to enable touch screens, but none with credentials or specifically to a ThinkPad device like the one I have.  Does anyone know how to enable it or know where I can find a good source?  Thanks!
Note:  I am on a Lenovo ThinkPad X1 Carbon Touch running Ubuntu 12.04LTS.  It uses eGalax capacitive.


text:
Q: Load file from classpath in wildfly +java I have a simple jsp application.
I am trying to load an xml file which it there in src/xml folder. I am using below code but getting FileNotFound exception. Please let me know how to resolve this issue?
Public static void load() {
Document doc = parseDoc(Thread.currentThread().getContextClassLoader().getResource("/xml/test.xml").getFile())
}

This is throwing FileNotFound exception as the path is showing as /D:/Wildfly/bin/content/aap.war/web-inf/classes/xml/test.xml
Tried few different ways but didnt work. Please help me

A: Generel notes:
Please write public and not Public. "src" is not a good folder to load something. "src" normally contains your source code (aka *.java files) - which is nothing you have access to after the files are compiled and put into your server.
What I would suggest is, that you put your XML file into a jar file. So zip your xml folder and rename it to e.g. "xml.jar". I assume there is one folder xml/test.xml. This jar file you add to your classpath as part of your .ear or .war file. After you deploy this you can access it with:
Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/text.xml");
Also don't directly read it but check for null:
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/text.xml);
if (stream == null) {
  throw new IllegalStateException("Resource 'xml/text.xml' not found on classpath");
}
//continue


text:
Q: Adding XMP copyright Notice tag in DOCINFO PS to PDF I am done with these tags.These are converted into XMP of pdf correctly except copyright tag
/Author string
/CreationDate string
/Creator string
/Producer string
/Title string
/Subject string
/Keywords string
/ModDate string
/DOCINFO pdfmark

But my problem is how to add copyright tag in it. I tried "rights" and "Copyright" like this in PS.
/rights (Kings Man)
and
/copyright (Kings Man)

All other tag are showing Good in XMP Meta Data when Postscript Convert to PDF by Adobe Distiller But i am failing to introduce the copyright tag in it.

A: The DOCINFO pdfmark doesn't support either a Copyright or rights key, so you can't add either to the document information using it (only certain keys are permitted).
Ordinarily, at least, XMP metadata doesn't contain a copyright notice either. Now you can add keys to the PDF info dictionary and clearly you can add to the XML, but these would then be non-standard. I am not surprised that the pdfmark operator doesn't support adding non-standard keys.
Essentially, you can't do that, or at least not by using pdfmark.


text:
Q: Disappearing Background Image Style Attribute With Certain URLs I'm not certain if this is specific to React or the build chain inside SPFx, but I'm having issues setting a background image on a div dynamically. I receive the URL from an API call to https://tenant.sharepoint.com/_vti_bin/homeapi.ashx/sites/followed?mostRecentFirst=true&start=0&count=100&fillSiteData=true to retrieve followed sites and use the below code to generate a simple site card with the site logo and title.
const Site = (props: SpSite) => {
  const {Title, Url, BannerImageUrl, Acronym, BannerColor} = props;
  const hasLogo = BannerImageUrl && BannerImageUrl.length > 0;
  const logoUrl = hasLogo ? encodeURI(BannerImageUrl) : null;
  const logoStyle: React.CSSProperties = hasLogo ? {backgroundImage: `url('${logoUrl}')`} : {backgroundColor: BannerColor};
  const siteLogo =
{!hasLogo && Acronym}
;

  return (

{siteLogo}

{Title}

  );
};

When the URL is in the format https://tenant.sharepoint.com/SiteImages/image.jpg (Normal Site) everything works as expected and the background image is set properly on the generated HTML. When the URL has the format of https://tenant.sharepoint.com/_api/GroupService/GetGroupImage?id='RandomGUID' (O365 Group Site) the attribute
style="background-image: url('https://SomeImageUrl')" doesn't get created on the resulting div. I can't figure out if this is being stripped out somewhere in the build chain or if React isn't handling it properly. I can browse directly to the GUID based image URL and it renders just fine.

A: Firstly - The endpoint that you are using is unsupported and undocumented. So, someday that endpoint might abruptly stop working :)
Secondly - I investigated this issue. The issue happens only for "Modern" sites like modern communication and team sites. This made it easier for me to figure out a fix.
Each of these "modern" sites have a fixed site logo url. But the one that is available via your endpoint make another REST call to download an image (with what i guess could be some access token)  and then load it (i.e - when this  /_api/GroupService/GetGroupImage?id='RandomGUID' endpoint is hit, another REST call is made to download an image). So, sometimes this causes issue with the rendering of that image inside a webpart.
The fix - The logo for Modern sites resides in the Site Assets library. Its called __siteIcon__.jpg.  Now, when you hit your endpoint and after you get the results, you need to check if the BannerImageUrl contains /_api/GroupService/... string, if yes, then replace it with SiteAssets/__siteIcon__.jpg.
Sample code in js:
var imageUrl = "https://tenant.sharepoint.com/sites/test/_api/GroupService/GetGroupImage?id='RandomGUID'";

if(imageUrl.indexOf("/_api/GroupService/GetGroupImage")>-1){
    var firstSection = imageUrl.split("/_api")[0];

    //render logoUrl in your UI
    var BannerImageUrl = firstSection + "/SiteAssets/__siteIcon__.jpg";
}