text:
Q: Regex in if condition of karate framework Is it possible to use a regex in karate if condition as below
eval if ( xx!="#regex [0-9]{7}") karate.log("success")

I wanted to execute a if statement, regex evaluation is passed . Above code doesn't evaluate as regex . It simply prints the log

A: You can use karate.match():
* def test = '123'
* if (karate.match(test, '#regex [0-9]+').pass) karate.log('pass')

Please refer to the docs: https://github.com/intuit/karate#karate-match


text:
Q: What are proper typings for a function that takes a function as its argument and returns a function that has the same typings as the input function? I'm writing a function that takes a function as an argument and then will return a modified version of the same function that was taken as the input. (Note that the function gets changed to a promise).
const addLoggerToFunc = (plainFunc) => {
return async (...args) => {
   await doSomeAsyncStuff()
   console.log(`function ${input.name} has been called`);
   plainFunc(...args)
  }
}

I want to make sure that typings are not lost once a function has been passed to the addLoggerToFunc function.
const foo = async (baz: string, bar: number) => {
// ... Do something
}

export const fooWithLogger = addLoggerToFunc(foo)

// I expect fooWithLogger to have the same typings as foo

What I tried:
const addLoggerToFunc = <T, G>(plainFunc: (...args: T[]) => Promise<G>): ((...args: T[]) => Promise<G>) => {
  return async (...args: T[]) => {
    console.log(`function ${plainFunc.name} has been called`);
    return plainFunc(...args);
  };
};

However now fooWithLogger has a type of
const fooWithLogger: (...args: (string | number)[]) => Promise<void>
instead of
const fooWithLogger = (baz: string, bar: number) => Promise<void>

A: const addLoggerToFunc = <T extends any[], G>(plainFunc: (...args: T) => Promise<G>): ((...args: T) => Promise<G>) => {
  return async (...args: T) => {
    console.log(`function ${plainFunc.name} has been called`);
    return plainFunc(...args);
  };
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't understand why $ doesn't match on this list I've always struggled with getting regex to work. Better put, why is is my regex pattern not successfully matching a string. Usually I'm using regex in bash scripts, find and send commands.
As I understood it, $ at the end of a regex pattern will match lines that end with the pattern.Can anyone explain why this isn't matching correctly.
Regex Pattern
\.\/.*\.moved$

./Library.moved*
./.cpan/build/ExtUtils-MakeMaker-6.96-u4aD1K/t/ZPfMx0qYVS

However using a ^ works producing a match.
Regex Pattern
^\.\/.*\.moved

./Library.moved
./.cpan/build/ExtUtils-MakeMaker-6.96-u4aD1K/t/ZPfMx0qYVS


text:
Q: C# is it possible to change priority of acquiring a lock? If there are multiple threads all waiting on the same lock is it possible to have the Main thread have higher priority in acquiring the lock. Meaning that if worker threads go to the lock statement before the main thread, the main thread would acquire the lock before the other threads that were already waiting on it.

A: No, the lock statement maps to System.Threading.Monitor.Enter() (MSDN) and there is no overload that accepts a priority parameter.
The closest thing I can think of is a ReaderWriterLock(Slim) but I would seriously reconsider the design that leads to this request. There probably are better ways to achieve what you need.

A: Through a native lock statement, no.  Through your own custom locking mechanism, sure, if you're willing to spend the time and effort to develop it.
Here's my draft a a solution.  It may or may not work, and may not be super efficient, but it's at least a starting place:
public class Lock
{
    bool locked = false;

    private object key = new object();
    SortedDictionary<int, Queue<ManualResetEvent>> notifiers =
        new SortedDictionary<int, Queue<ManualResetEvent>>();

    ManualResetEvent specialNotifier = null;

    public void Lock()
    {
        lock (key)
        {
            if (locked)
            {
                ManualResetEvent notifier = new ManualResetEvent(false);

                int priority = getPriorityForThread();

                Queue<ManualResetEvent> queue = notifiers[priority];
                if (queue == null)
                {
                    queue = new Queue<ManualResetEvent>();
                    notifiers[priority] = queue;
                }

                queue.Enqueue(notifier);

                notifier.WaitOne();
            }
            else
            {
                locked = true;
            }
        }
    }

    private static int getPriorityForThread()
    {
        return 0;
    }

    public void Release()
    {
        lock (key)
        {
            foreach (var queue in notifiers.Values)
            {
                if (queue.Any())
                {
                    var notifier = queue.Dequeue();
                    notifier.Set();
                    return;
                }
            }
            locked = false;
        }
    }
}

A: Here is another solution. I has a lot of lines, but it is pretty simple. The function DoSomethingSingle will be called only one thread at a time, and those with the highPriority flag will get preference.
    static int numWaiting = 0;
    static object single = new object();

    ResultType DoSomething(string[] argList, bool highPriority = false)
    {
        try
        {
            if (highPriority)
            {
                Interlocked.Increment(ref numWaiting);
            }

            for (;;)
            {
                lock (single)
                {
                    if (highPriority || numWaiting == 0)
                    {
                        return DoSomethingSingle(argList);
                    }
                }
                // Sleep gives other threads a chance to enter the lock
                Thread.Sleep(0);
            }
        }
        finally
        {
            if (highPriority)
            {
                Interlocked.Decrement(ref numWaiting);
            }
        }
    }

This allows two priority levels. Guaranteed that a low priority thread will gain access to the resource only if there are no high priority threads waiting for it.
edit: change to interlock incr/dec


text:
Q: Woo commerce rest api get all product for customer I am trying to get all product using bearer token(using JWT Plugin).
Using admin token fetching the all products but when using customer token not fetching the product data.
call: /wp-json/wc/v3/products

response:
{
    "code": "woocommerce_rest_cannot_view",
    "message": "Sorry, you cannot list resources.",
    "data": {
        "status": 403
    }
}

img:
click here to see image

A: Just use https instead of http in your weblink

A: 403 means you do not have permission to access the resource. I installed a role and permission manager plugin and gave "READ PRIVATE PRODUCTS" permission to "customer" role.

A: Try this:
wc-api/v3/products.

change wp-json/wc to wc-api.


text:
Q: Civilization 6 saved game location? Where are saved game files stored in the Mac version of Civilization 6?

A: I'm assuming you bought the game through Steam? If you bought the game from the Mac App Store then the saved game files are located in ~/Library/Containers/com.aspyr.civ6.appstore/Data/Library/Application Support/Sid Meier's Civilization VI/Saves/
and the benchmark result files are located in /Users/albertfilice/Library/Containers/com.aspyr.civ6.appstore/Data/Library/Application Support/Sid Meier's Civilization VI/Logs/
(I would have added this as a comment but I don't have enough reputation).

A: Figured it out. Not exactly user friendly...
Saves are located in ~/Library/Application Support/Sid Meier's Civilization VI/Saves
Open with Terminal
Open Terminal and type open ~/Library/Application\ Support/Sid\ Meier\'s\ Civilization\ VI/Saves
Open with Finder
Open Finder and press Cmd+Shift+G, paste ~/Library/Application Support/Sid Meier's Civilization VI/Saves and hit Go


text:
Q: Can loaders be used without content provider or combination is must?
*

*Can loaders be used without content provider or combination is must?

*Is it best practice to use content provider only when it is intended
to use by other applications or for only local use also content
provider is recommended?

*If data updated in SQLite, Will loader deliver updated data, if not used with content provider?
I have tried to find convincing answers to above questions, but could not find it. Please help.

A: *

*A Loader is a way to load information for your activity/fragment without performing the computation on the UI thread. It can be used with a Content provider or you can use a subclass of Loader/AsyncTaskLoader to access data of your own choosing. You can find more info on how and when to use a Loader here.

*It is best practice to use a content provider to access data when a content provider is available. They are maintained by the system and are a good way to ensure the consistency of the data provided. You can create your own content provider to provide data from one application to another. More information can be found here.

*You can create a loader for an sqlite database by follwing the info in this guide at section 7 here.


text:
Q: Why doesn't Gnome 3.4.1 installed from PPA on 12.04 load? i've just installed gnome 3.4.1 on my ubuntu 12.04, but when I log on to it, as GNOME, the only thing showning is the background image. No icons, bottom panel, or launcher. Nothing at all.
I've read that it's necessary to start with Gnome, rather than Gnome Classic, to install shell extensions such as the frippery applications menu.
 I hope that I can make myself understood, english is not my first language and i'm new at this.

A: Do you have a top task bar gnome 3 is very diffrent to gnome 2
also can you activate the app switcher by pushing your mouse to the top left corner of the desplay try it and let me know


text:
Q: Не распознается смартфон на Ubuntu 14.04 Помогите исправить проблему при подключении физического устройства на Ubuntu 14.04! Сделал все настройки но студия не распознает смартфон (android 4.2)
Ранее возникала такая проблема, но старыми методами не решилось!
Использовал данную инструкцию.

A: Мне всегда помогает выбор подключения - Камера (PTP). Его можно выбрать в верхней сдвигающейся шторке.


text:
Q: Pymongo Cursor Memory Issue When I got records from MongoDB with Python(pymongo), I think that the cursor of pymongo pull all queried documents at once.
This is serious problem to me because if the document is very large size(include many rows and columns), when do find operation, docker image is killed by OOM.
I tried to set batch size of cursor but still it seems to get queried documents at once and return batch to me iterate.
The dataset is CSV format file with 3 million rows and 50 columns.
When load this file with pandas.read_csv(), Memory Profiler shows that 1.2 GB of RAM used at CSV reader.
But when pull this dataset from MongoDB with pymongo, the profiler shows that 30GB of RAM used at the cursor.
How do I solve this memory issue?


text:
Q: How to encrypt/decrypt a password using StandardPBEStringEncryptor? I am trying to encrypt/decrypt password in my application using StandardPBEStringEncryptor. However I think the code I am using is resulting in a memory leak. Am I using this correctly?
public static String getPassword(String seed, String encryptedPwd) {
  StandardPBEStringEncryptor pes = new StandardPBEStringEncryptor();
  pes.setProvider(new BouncyCastleProvider());
  pes.setPassword(seed);
  String originalPwd = pes.decrypt(encryptedPwd);
  return originalPwd;

}
public static String getDecryptedString( String encryptedPwd) {
   return MyClass.getPassword( 'mypassword', encryptedPwd);
}

I use the getDecryptedString() method everywhere in the application for decryption of passwords.
Does having 2 static methods like above cause a memory leak?


text:
Q: Pass data and functions to child components , not rendering I have an issue while passing data from parent component to child AccountsDropDown. As per the below code i could pass the depositAcct param to the child , but not the selected value and the onValueChnage methods .
So as per the current code these are the 2 issues am facing

*

*The selected value is not rendering

*OnValueChange event is not working , its not set the parent state.

This is my Parent component
import React, { Component } from "react";
const transferType = ["Transfer", "Pay Loan"];

export default class a2aTransfer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            mode: "start",
            selectedTransferType: transferType[0],
            fromAcct: "",
            toAcct: "",
            amt: "",
            memo: ""
        };
    }

    componentDidMount() {
        this.setState({ fromAcct: this.context.depositAcct[0].desc });
        this.setState({ toAcct: this.context.loanAcct[0].desc });
    }
    render() {
        TransferForm = () => {
            return (
                <Container>
                    <Content>
                        <Form>

                            <View style={styles.item}>
                                <Text note>From Account</Text>

                                <AccountsDropDown
                                    selectedValue={this.state.fromAcct}
                                    depositAcct={this.context.depositAcct}
                                    navigation={this.props.navigation}
                                    onValueChange={itemValue => this.setState({ fromAcct: itemValue })}
                                />
                            </View>

                        </Form>
                    </Content>
                </Container>
            );
        };

        if (this.state.mode == "start") {
            return <TransferForm />;
        }
        return <TransferConfirm />;
    }
}
a2aTransfer.contextType = MyContext;

This is my child component
  import React, { Component } from "react";
import { Picker, Icon } from "native-base";
import { Dimensions, Platform } from "react-native";
export default class accountsDropDown extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Picker
                selectedValue={this.props.selectedValue}
                mode="dropdown"
                iosHeader="Choose To Account"
                style={{ width: Platform.OS === "ios" ? undefined : Dimensions.get("window").width }}
                iosIcon={<Icon name="arrow-down" />}
                onValueChange={() => this.props.onValueChange}
            >
                {typeof this.props.depositAcct != "undefined" &&
                    this.props.depositAcct.map((acct, idx) => {
                        return <Picker.Item key={idx} label={acct.desc} value={acct.masked} />;
                    })}

            </Picker>
        );
    }
}

A: onValueChange is a function so you need to call it in the child component with the value:
    <Picker
        selectedValue={this.props.selectedValue}
        mode="dropdown"
        iosHeader="Choose To Account"
        style={{ width: Platform.OS === "ios" ? undefined : Dimensions.get("window").width }}
        iosIcon={<Icon name="arrow-down" />}
        onValueChange={(value) => this.props.onValueChange(value)}

If you don't need to transform value then just pass the function directly:
onValueChange={this.props.onValueChange}

A: You have written ok code, just check that are you getting data from context.
console your selectedValue in render method and check that data getting from context or not
render() {
    console.log(this.props.selectedValue);
    return (
        <Picker
            selectedValue={this.props.selectedValue}
            mode="dropdown"
            iosHeader="Choose To Account"
            style={{ width: Platform.OS === "ios" ? undefined : Dimensions.get("window").width }}
            iosIcon={<Icon name="arrow-down" />}
            onValueChange={() => this.props.onValueChange}
        >
            {typeof this.props.depositAcct != "undefined" &&
                this.props.depositAcct.map((acct, idx) => {
                    return <Picker.Item key={idx} label={acct.desc} value={acct.masked} />;
                })}

        </Picker>
    );
}


text:
Q: O que exatamente é necessário para publicar no Google plus com suas APIs Minha pergunta é sobre o Google + Domains API:
A partir desta resposta é dito: "Atualmente, não há API pública para publicar no Google+".
Então, procure outras perguntas e respostas, vejo a possibilidade de POST com Google + Domains API através da conta de domínio do Google.
Então, novamente, surgiram muitas dúvidas:
1- Qual é a conta do Google Domain e como definir isso para o propósito de postar no Google Plus (Perfil / Página ou Comunidades)?
Eu aprendo sobre OAuth2 e git google respositore php class library.
Em alguns testes (do localhost), obtive autorização e acessoToken, mas sempre com erros como esse no final: Credenciais proibidas ou inválidas.
Nas minhas pesquisas, o erro é porque não uso Google Domain Acccount.
Então eu não vejo em todos os resultados do Google a maneira de fazer isso de ponta a ponta, de criar o Google Account Domain para POST no Google Plus.
Eu não estou pedindo um tutorial completo, apenas o caminho para um eu faço isso.
Após 5 dias consecutivos, aqui está a minha última tentativa (ou não, quem sabe), mas estou cansado e não consigo ver a luz no final do túnel.
Todas as dicas são bem-vindas.


text:
Q: Undecorated Microsoft Symbol: SomeClass::`vftable'{for `Foo::Bar'} I'm using UnDecorateSymbolNameW from dbghelp to un-decorate Microsoft symbol names. When undecorating with UNDNAME_COMPLETE, the symbol name can sometimes have, what I understand to be, some compiler appended information to it. For example a vftable symbol can sometimes have a curly bracket block containing a for keyword followed by a class/interface name, e.g.

SomeClass::'vftable'{for 'Foo::Bar'}

Can anybody inform me as to what the "{for 'Foo::Bar'}" portion of the name means?
Additionally does anybody know of some documentation about this so I can read up as I can't find anything.
Thanks very much!

A: Your class SomeClass uses multiple inheritance, and it has multiple base classes with virtual methods. Therefore, SomeClass needs multiple vtables (one for each base class with virtual methods). The {for 'Foo::Bar'} tells you which vtable you have. In this case, it is the vtable for the Foo::Bar base class.
(This should have been self-evident from the name.)


text:
Q: Find all $f:(0, \infty) \to R$, that for each $x \in (0, \infty)$ satisfies $ax^2f(\frac{1}{x}) + f(x) = \frac{x}{x + 1}$, where $|a| \ne 1$.
Find all $f:(0, \infty) \to R$, that for each $x \in (0, \infty)$ satisfies $ax^2f(\frac{1}{x}) + f(x) = \frac{x}{x + 1}$, where $|a| \ne 1$.

What I've tried so far is using $x = 1$, and from there $f(1) = \frac{1}{2a + 2}$, but that hasn't led me anywhere.
Is there some general approach to these kinds of problems, or is it more or less up to experimentation?
I guess my main concern is knowing when I've found all of them.


text:
Q: If I need a data structure with random access, is Vector my only good choice? And if there are other good choices, why isn't there a typeclass yet that has all the common traits of random access? Then Vector and other random access data structures would have instances of that typeclass.

A: No, Vector is not your only "good" choice, depending on what you mean by "good".  For example, Array is a similar data structure with a slightly more cumbersome API, but it also allows a richer set of choices for the indexing set and differs in implementation details in ways that might be helpful in some cases (e.g., an Array of Bools is a bitmap, while a Vector of Bools uses one byte per element).
Also, if there is much adding and removing of elements on the ends, then the Seq type from Data.Sequence might be a good choice (though its random access performance varies from O(1) at the ends to O(log n) in the middle, roughly speaking).
It's hard to say definitely why there is no standard library typeclass for a random access API, but note that Haskell typically does not have data structure API typeclasses of this level of specificity in the standard library.  There are no standard typeclasses for the base Map and Set data structures APIs either, for example, even though these would also apply to the various hash-based maps and sets that are available.
The standard library typeclasses that are available are typically higher-level abstractions, like Foldable and Traversable.
However, the lens package provides a collection of indexed typeclass abstractions, so for example there are Ixed instances for Vector, Array, and Seq such that:
v ^? ix 2

gets you Just the element with index 2, if v is any one of the above types (or a list or a host of other indexable collections).  The possible downside of using these typeclasses is that you kind of have to buy into the whole lens ecosystem and its syntactic approach to use them effectively.
As an alternative, for a particular application, it's often a reasonable approach to write application-specific typeclasses that encapsulate the operations performed on key data structures and then implement the data structures as instances of those typeclasses.  This can realize many of the benefits of the generic typeclasses you're imagining, but can be more flexible than pre-fabricated typeclasses and instances without being that much more work to implement.


text:
Q: How to convert FileInfo into FileInfo[] I have been working on a program that requires a different approach to finish a job using try and catch nested within another try/catch.
For this purpose I have had to create a set of files as strings and then converted them to FileInfo.
IEnumerable<string> paths = null;
foreach (String fil in paths)
    FileInfo h = new FileInfo(fil);

So That wasn't so difficult, I require FileInfo to be in the form of a FileInfo[] array to continue the program however.
System.IO.FileInfo[] files = null;

Simply put, what is the best method to convert one type to the other, either directly from the string of from the converted FileInfo into a FileInfo array (FileInfo[])?

A: Yeah or create a single-item array:
FileInfo[] files = new FileInfo[] { info };

A: Why not directly?
paths.Select(p => new FileInfo(p)).ToArray();

A: Use:
var result = paths.Select(p => new FileInfo(p)).ToArray();

A: You could just use Linq select to create your FileInfo[]
 IEnumerable<string> paths = null; // assuming you are going to fill this with filenames
 FileInfo[] fileInfos = paths.Select(p => new FileInfo(p)).ToArray();


text:
Q: How to add 'not empty' constraint on a field in table in MySQL database? I'm using MySQL database server**(Server version: 5.5.40-0ubuntu0.14.04.1-log - (Ubuntu))**.
There in one table titled 'users' in a database. In the table 'users' there is one column titled 'full_name'.
Following are the constraints on it
Name : full_name
Type : `varchar(255)`
Collation : `latin1_swedish_ci`
Attributes :
Null : No
Default : None
Extra :

The issue I'm facing with this column('full_name') is some where from PHP code empty value gets inserted in this column though I've added a NOT NULL constraint.
I want to avoid doing that thing from anywhere. That is empty/blank/white space characters/NULL should not get insert into this column. I want to do it from the database table itself rather than making modifications in PHP code.
Can someone please help me in preventing insertion of such values in this column?
One more thing is there are few records present in this table that contains NULL value in the field 'full_name'. I think those values have been present before I added the NOT NULL constraint to the column 'full_name'. My another doubt is are these NULL values affecting the column?

A: You can add a check constraint like this :
full_name VARCHAR(45) CHECK (full_name <> '')

UPDATE:
As @vhu pointed out :

CHECK() is parsed but ignored as part of the CREATE statement.

So you have to add a TRIGGER before an INSERT for your users table.
This TRIGGER will be called before the INSERT and he will check if the value to set to a is empty. If it's true, a will be set to NULL:
CREATE TRIGGER `test_BINS` BEFORE INSERT ON `test` FOR EACH ROW
IF new.`a` = '' THEN SET new.`a` = NULL; END IF; END;

test is the name of the table, test_BIN is the name of the TRIGGER and a is the name of one column of the table test.
Note : This code has been generated by MySQL Workbench.


text:
Q: JavaScript Responsive Menu I have this navigation menu as in the image here.
Below is my JS that I currently have to make it responsive so that it opens up on clicking it but it is not working:

function showMenu(event) {

  event.preventDefault();

  let element = document.getElementById('header');

  if (element.classList.contains('active')) {
    element.className = "";
  } else {
    element.className = "active";
  }
}
header {
  padding: 0 !important;
  background: #fff;
}

header.active {
  box-shadow: 0 1px 5px 1px rgba(0, 0, 0, 0.2);
}

header.fixed {
  padding: 0 0;
}

header button {
  position: absolute;
  top: 12px;
  right: 25px;
  display: block;
  width: 30px;
  height: 40px;
  padding-top: 6px;
  border: none;
  background: #fff;
}

header button span {
  position: relative;
  top: 0;
  display: block;
  width: 100%;
  height: 2.5px;
  margin-bottom: 5px;
  transition: all .2s ease;
  border-radius: 15px;
  background: #0d2366;
}

header button span:nth-child(2) {
  right: 0;
  width: 80%;
  opacity: 1;
}

header button span:nth-child(3) {
  width: 60%;
}

header.active button span:nth-child(1) {
  top: 8px;
  left: -4px;
  -ms-transform: rotate(38deg);
  transform: rotateZ(38deg);
}

header.active button span:nth-child(2) {
  right: -100%;
  opacity: 0;
}

header.active button span:nth-child(3) {
  top: -6px;
  left: -4px;
  width: 100px;
  -ms-transform: rotate(-38deg);
  transform: rotateZ(-38deg);
}

header ul.menu-left {
  display: none;
}

header img {
  margin-left: 25px !important;
}

header.active ul.menu-left {
  display: block;
  float: none;
  clear: both;
}

header.active ul.menu-left li {
  display: block !important;
  padding: 10px 20px;
}

header ul.menu-right {
  display: none;
}

    <button id="submenu">

            </button>

Home

About

Services

Pricing

Contact

Get Started

The active class here represents the responsive menu icon.
Any help is highly appreciated.
Thanks!

A: By using the addEventListener you can watch the click event. After clicking the button, the third line below will toggle between adding and removing the class 'active' on the id="header"
document.getElementById("submenu").addEventListener("click", function(event) {
  event.preventDefault();
  document.getElementById("header").classList.toggle("active");
});


text:
Q: Linux always mount USB device at same point? I have a character USB card reader device and I want it always mount at the same location. Currently its located here:
ls -sla /dev/bus/usb/003/007
0 crw-rw-r-- 1 eveusb root 189, 262 Th10 29 14:56 /dev/bus/usb/003/007
And because I am planning to access from Kubenetes service I need for that mount point to stay the same on all the nodes that have a card reader. So I would like to predesignate the mount point if possible. Can this be done?

A: You can use udev, little examples are below
$ udevinfo -a -p /sys/block/sdc/ | grep model
    ATTRS{model}=="Ext HDD XXX    "

Now, that we have model attribute, we can add it to /etc/udev/rules.d/custom.rules by following line
SUBSYSTEM=="scsi", ATTRS{model}=="Ext HDD XX    ", SYMLINK+="<name of device file to be mounted in>"

$ /etc/init.d/udev restart


text:
Q: Test database connection in php without username & password There are some nice php database connection tests around, but they all seem to require a username & password. How would one confirm (using php and presumably mysqli) that a database server is up and would accept connections should one be attempted with a correct username & password, but report some details on the failure if the server was down or timed out or what not.

A: I would use the code 1045 to see if you can connect. This error code indicates that the credentials are incorrect. If the server responds with that code then it means it is reachable.
<?php

$reachable = false;

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $mysqli = new mysqli('localhost', 'some invalid user', 'wrong password');
} catch (mysqli_sql_exception $e) {
    if (1045 === $e->getCode()) {
        $reachable = true;
    }
}

var_dump($reachable);
?>


text:
Q: Integer square root in java I am writing a program to get the integer square root of a number.
My Code:
import java.util.Scanner;
public class IntRoot{
    public static void main(String[] args){
    int num;
    System.out.print("Enter a non-negative integer: ");
    Scanner sc = new Scanner(System.in);
    num = sc.nextInt();
    int i;
    int y=1;
    for (i=1; num>=i+(i+2); i +=2){
        ++y;
    }
    System.out.print(y);
    }
}

The program should add odd positive integers one at a time (1+3+5+7+...) until the next sum is less than or equal to num, then count the number of odd numbers used to give the integer square root (and print that number).
eg. integer square root of 12 would be 3, since 1+3+5 = 9, and there are 3 odd numbers in the sum
Currently my program doesn't print the correct number. "i" should start at 1 and increase by 2 each time. This for loop would repeat until the next sum of "i"'s would be greater than "num", and "y" would grow by 1 each time to give the number of times "i" has grown. So if input is 7, "i" should stop when y=2, similarly, if input is 4, i should stop when y=2, and if input is 49, i should stop when y=7.
Is there something wrong with my code? or my logic?

A: tl;dr - skip to the bottom. Use a do/while loop.

How do we get to using a do/while loop? I suggest splitting the "break" condition from your loop. Right now it's more complicated to understand what is happening (which is probably why you are confused).
Something like:
int curSum = 0;
for (i=1; i<num; i +=2){
    if (curSum + i >= num) {
        break;
    }
    ++y;
    curSum +=i;
}

Is much more clear. It's easier to read and understand what is actually happening in your loop logic.
You can read through the for loop and nearly exactly, in English, read

*

*"iterate i, by multiples of 2 (starting at 1, so all odd numbers). Count the number of times you can sum these  until the current sum plus the next value is greater than the input number."

Along this line, I would suggest a bit better variable names:
import java.util.Scanner;
public class IntRoot{
    public static void main(String[] args){
        int num;
        System.out.print("Enter a non-negative integer: ");
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();
        int i;
        int iterations=1;
        int curSum = 0;
        for (i=1; i<num; i +=2){
            if (curSum + i >= num) {
                break;
            }
            iterations++;
            curSum +=i;
        }

        System.out.print(iterations);
    }
}

Last, the question is... given your conditions, are you really "iterate over every number up to your input number?" to which the answer is, "no, you want to iterate until a condition is met."
There are better loop structures for this,  such as a do-while loop:
import java.util.Scanner;
public class IntRoot{
    public static void main(String[] args){
        int num;
        System.out.print("Enter a non-negative integer: ");
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();
        int i=1;
        int iterations=1;
        int curSum = 0;
        do {
            i+=2;
            iterations++;
            curSum +=i;
        } while (curSum + i < num);

        System.out.print(iterations);
    }
}

A: Your for loop is just counting:
for (i=1; num>=i+(i+2); i +=2){
    …
}

Iterates with i having the values of 1, 3, 5, 7, 9, …
If you want to have the values 1, 1+3, 1+3+5, 1+3+5+7, … in your loop you have to do something like this:
sum = 1;
for (i = 1; num >= sum; i += 2) {
    sum += i;
    …
}

A: You've got a few things wrong but here's something that works
int currSum = 0;
int oddCount = 0;
for(int i = 1; currSum + i <= num; i+=2) {
   currSum += i;
   oddCount++;
}

Basically this does the check that currSum = 1+3+5....+i < num and if your current sum is not greater than num, then you are adding the next odd integer to your current sum, incrementing number of odd numbers seen, and checking again.

A: I got this to work:
int value = 4;
int count = 0;
int i = 0;
for (; count < value; i++) {
    count += i * 2 + 1; // i*2+1 == 1, 3, 5, 7, ...
}

if (count != value) i--;
System.out.printf("The Square Root of %d is %d.\n", value, i);

Substitute any value in for value. It does exactly what you're trying to do.
EDIT: Sorry, wrote the code in C++. Fixed for Java.

A: You might find this easier with a while loop that you break out of. I won't say you can't make it work with a for but I think the condition to quit is inside the loop, for cleaner code:
while(true)
{
  i += 2;
  s += i;
  if(s + i > num)
     break;
  ++y;
}

A: I changed the default value of y to 0, as on my test it was allways giving one more.
int num;
System.out.print("Enter a non-negative integer: ");
num = 12;
int i;
int y=0;
for (i=1; num>=i+(i+2); i +=2){

System.out.print("Iteration " +i+"|");
    ++y;
}
System.out.print(y);
}

I added a couple of s.out.
the out was this. so seem the y=0 gave the valid value.

Enter a non-negative integer: Iteration 1|Iteration 3|Iteration 5|3

A: public class App
{
    public static void main(String args[])
    {

        Scanner sc=new Scanner(System.in);
        System.out.println("enter the value :");
        int num=sc.nextInt();

        int a =num/10;//32
        num=num%10;//1
        int b=a/10;//3
        int c=a%10;
        int total=c+b+num;
        System.out.println("The sum of digit is:" +total);

    }
}


text:
Q: How to pass the seahorses in candy box 2 I've been going in the ocean for a while, but now I've gotten to these seahorses. They shoot the magic, and I can dodge those, but I can never actually reach the seahorses themselves to kill them. How do I pass these creatures?

A: or if you just want to be simple, you can just use a fire ball and kill them off one by one

A: You have to use weapons with good range like the Monkey Wizard Staff or the Octopus King's Crown with Jaspers (the best I think)


text:
Q: Best method of particle simulation in Objective-C I'm about to create a particle simulator in Objective-C on the Mac, using Core Graphics for rendering. I've calculated that Core Graphics is capable of rendering about 1.8*10^6 1x1 colored pixels per second to a view using CGContextFillRect, which works out to about 250,000 1x1 particles per frame being rendered to the screen, for the FPS to remain at 60.
A limit of 250,000 particles isn't that great - I'd like that number to be much higher. What is the most efficient way to render this many 1x1 coloured pixels to a view?
Is there a way to better utilise the GPU?
This is the code I have been using:
- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor (ctx, 1, 0, 0, 1);
    CFTimeInterval t1 = CFAbsoluteTimeGetCurrent();
    CGRect point = CGRectMake(10.0f, 10.0f, 1.0f, 1.0f);

    for (int i = 0; i < 20000000; i++) {
        CGContextFillRect (ctx, point);
    }

    NSLog(@"%.10f", CFAbsoluteTimeGetCurrent() - t1);
}


text:
Q: Swift - Error calling a function from another function While following Apple's book "The Swift Programming Language"
I ran across an issue while working on the "EXPERIMENT - Write a function that calculates the average of its arguments." from the first chapter.
To determine the average of a set of numbers, I want to reuse my sum of numbers [setOf(numbers: Int...)] function and divide by the count of numbers [numbers.count].  I am receiving the Error:
Could not find an overload for '__conversions' that accepts the supplied arguments

when I try to call sumOf(numbers) from my averageOf(numbers) function.
What should I change to call my sumOf(numbers) function correctly, from my averageOf(numbers) function?
func sumOf(numbers: Int...) -> Int {
    var sum = 0 //0
    for number in numbers {
        sum += number
    }
    return sum  //651
}
sumOf(42, 597, 12)  //651

func averageOf(numbers: Int...) -> Int {
    var sum = sumOf(numbers) //Issue in this line
    return  sum / numbers.count
}
averageOf(42, 597, 12)

Paste the code above into a new Xcode 6 playground to recreate.
Error Screenshot (I need 10 reputation points before I can post the image.)

A: You're passing a different type as the function expects. Apparently Int... is not the same as Int[].
You could create an override that accepts Int[] and returns the sum.


text:
Q: Run-Time Error '-2147417848 (80010108)' when using ComboBox events I am trying to create a Userform that has several ComboBoxes to aid the user in selecting data from large lists. I added an event so that after the user has selected a valid Customer in the Company ComboBox, the Division ComboBox is automatically given Focus and has the Dropdown opened.
This would be perfect if it didn't also cause the error:
Run-Time Error '-2147417848 (80010108)'
Automation error
The object invoked as disconnected from its clients.

I know exactly which line is causing the error, because I removed basically every other line and the error appears when I try to add this line: Me.Division.DropDown (Division is the name of my 2nd ComboBox)
Here is the offending Event Script
Private Sub Company_Change()
    Me.Division.Clear
    Me.Division.Enabled = False

    If ValueExistsInList(Me.Company.List, Me.Company.Value) Then
        Me.Division.Enabled = True
        Me.Division.List = Array("A","B","C")
        Me.Division.SetFocus
        Me.Division.DropDown
    End If

End Sub

ValueExistsInList returns a Boolean, which is True when the user has entered a valid selection into the Company ComboBox. Then I insert the list of divisions for that selected company into Division.List. Then I try to do SetFocus and DropDown. The error doesn't happen on that line though, it actually waits until I get to End Sub and then the error appears. But if I remove the DropDown line, the error disappears.
Does anyone know how I can avoid this error while still being able to use DropDown?

I was able to create a reproducible example in a new workbook:
Step 1. Create a macro in a worksheet code module:
Sub Example()
    UserForm1.Show
End Sub

Step 2. Create a userform with 2 comboboxes, ComboBoxA and ComboBoxB
Step 3. Put this code module in the userform
Private Sub ComboBoxA_Change()
    Me.ComboBoxB.Enabled = False

    If ComboBoxA.Value = "A" Or ComboBoxA.Value = "B" Or ComboBoxA.Value = "C" Then
        Me.ComboBoxB.Enabled = True
        Me.ComboBoxB.Clear
        Me.ComboBoxB.Value = ""
        Me.ComboBoxB.List = Array("1" & ComboBoxA.Value, "2" & ComboBoxA.Value)
        Me.ComboBoxB.SetFocus
        Me.ComboBoxB.DropDown
    End If
End Sub

Private Sub UserForm_Initialize()
    Me.ComboBoxB.Enabled = False
    Me.ComboBoxA.List = Array("A", "B", "C")
    Me.ComboBoxA.SetFocus
End Sub

Step 4. Run the worksheet macro to open the userform.
Step 5. Select any option in ComboBoxA.
The error should appear.


text:
Q: When is 0.99999… ≠ 1? There are many ways to see that $0.999\ldots=1$ over the Reals (or over $\Bbb Q$ or $\Bbb C$ for that matter) like "Is it true that 0.99999…=1?", and the reasoning is easy enough:
If $x=0.\bar9$ then $10x=9.\bar{9}$ and consequenty, $9x=9.0$.
Some time ago I watched a math video which explained that the equality is not true everywhere, without mentioning what would break down, and no specific example was given, but what can go wrong, what are explicit examples?
What comes to mind are fields like the $p$-adics, the Superreals and Hyperreals. While I can follow their basic definitions or popular introductions, I have absolutely no intuition, let alone knowledge, what makes them different or not.
To make sense of $$s_n:=9\sum_{k=1}^n 10^{-k}$$
it's enough to have the arithmetic of a field.  To make sense of
$$0.\bar 9 := \lim_{n\to\infty} s_n$$
dunno what's needed here.  A metric perhaps like $\operatorname{abs}:x\mapsto |x|$.  The sequence should converge and the concept of convergence should make sense of course, and the limit should be $1$. Topologically closed is maybe too strong, but if the field is also a complete metric space that should suffice?
What I don't know is whether the above structures match (except for $\bar{\Bbb Q}_p$, which is however becond by comprehension / intuition).
And suppose the series $s_n$ from above converges to an element $0.\bar 9$ of the domain.  Does this imply that $0.\bar 9 -1$ is an infinitesimal?
Maybe someone can iterate on these structures or on other domains that are worth talking about.  And is it a requirement that $10^{-n}\to0$? Or may it be the case that $10^{-n}$ need not to become arbitrarily small and $0.\bar9$ still makes sense? What about Duals and split-complex?

Note: My questions are not about uniqueness of representation.

A: I think this might help answer some of the spirit of the question, I try to give some of the reasoning in the p-adic cases which ends up having the sequence not converge in two different "flavors". I think learning more about the definition of a limit and Cauchy sequences might help you here.
Ostrowski's theorem says that every absolute value we can put on the rationals is either the real, a p-adic, or trivial absolute value. This is not entirely comprehensive, but a good start for seeing where your sequence can be seen to be valid. From here we can build up the real or any of the p-adic fields by completion with respect to this absolute value.
Specifically in the p-adic cases, we define the p-adic absolute value on rational numbers by pulling out the largest power of the prime. More precisely for $a,b, n \in \mathbb{Z}$ with $a,b$ not divisible by a prime number $p$, we can represent any rational number $x=p^n\frac{a}{b}$ and define its p-adic absolute value to be:
$$\left|p^n\frac{a}{b}\right|_p = \frac{1}{p^n}$$
Here if we take $.999...$ as a limit of the sequence $\frac{9}{10}, \frac{9}{10}+\frac{9}{100}, \frac{9}{10}+\frac{9}{100}+\frac{9}{1000}, ... $ we end up in either one of two situations.
In the 2-adics or the 5-adics, the sequence can't converge because we are adding on larger and larger terms to our sequence since their absolute values diverge as $n \to \infty$: $\left|\frac{9}{10^n}\right|_2 = 2^n$ and $\left|\frac{9}{10^n}\right|_5 = 5^n$
In the other p-adic fields we have that it doesn't converge because the sequence of terms never decays to $0$ but is still bounded above and infinitely "oscillates" around, very similar to Grandi's series. To directly see this, we can simplify the geometric series of partial sums to $9\frac{(10^{-1})^n-1}{10^{-1}-1}$ and focus on the nonconstant term for which infinitely many values, $(10^{-1})^n-1 \not \equiv 0 \mod p$.


text:
Q: What is the difference between Django and Django CMS? I am new to Django, so can someone please tell me the exact difference between Django and Django CMS.
I have to design a complete website for educational purpose, should I use Django CMS or without it also i can do my job.

A: Django is a web framework which can sometimes be used to make a CMS, but it is not, by itself, a full CMS.
That in itself indicates that the difference between the two is quite huge:
Django
If you are running a new Django website the first time, you will get only a "It worked" and nothing else, no action possible.

From this point, you need to create new applications, write some Python code, create HTML templates, define URL patterns, set up a database... A lot of programmer tasks.
The Django default project can be compared to the It works! of Apache or nginx: nothing can be done with the website yet; you need to invent everything.
With Django, the development is way easier than starting from scratch, however, as it has a lot of features like authentication, administration or ORM are already present, allowing you to focus not on "table stakes" that every site must support but instead on the features that make your project different from any other.
Django CMS

*

*If you are running a new Django CMS project for the first time, you will get a more friendly page, which will invite you to connect to the admin and start customize you website, from you browser.

From this point, everything has already been installed and you can start to create a static website (almost) without touching a text editor and Python code. You can create pages, organise the layout and page categories from the CMS' admin, install some plugins made by the community to extend features, etc.
Django CMS is useful if you want a static website (portfolio, small company website, ...) of an e-commerce solution
What should I do?

*

*If your website is only a few pages without user interaction, you can use Django CMS. It will be way easier for you to get running and for you to maintain going forward.

*If you want to have one specific feature which requires some Python development, you can develop a Django CMS plugin and integrate it.

*If you really need a complete set of features & interactivity with user, you will need create a Django project from scratch.

A: Django is a framework that helps you to develop a cms.
django-cms is already a developed cms to publish a website.


text:
Q: Why should we avoid the future API when using gRPC with Python? In the official documentation, it is suggested that:

Using the future API in the sync stack results in the creation of an extra thread. Avoid the future API if possible.

Why is that?
Another question is, in the source code of grpc python, they also use the future API, so am I confusing these two futures?

def create_server(thread_pool: futures.ThreadPoolExecutor, ...)


text:
Q: PNP water level detector circuit I'm trying to build a simple water level detector using BC557 PNP transistor (there's already a similar question here but doesn't solve my problem...)
Circuit 1 below is what I'm thinking to build based on the standard biasing of PNP circuits (Circuit 2) as there's only 1 power source available. However, without a power source to reverse bias Emitter, I'm not able to have a Collector current. I think I'm doing something wrong here as it should work based on this for example. I can simulate an emitter current in Circuit 1 but no matter what resistors I use on the Emitter end (using 20k and 200k here) I cannot get a Collector current. Any idea what I'm doing wrong? This is my simulation.

A: Problem: Learning curve error with Falstad drawing.
You had Red Dot below LED indicating it was not a junction (disconnected) So shink line and add another wire as in my comment link fixed.
But you had 12V with a pretty big LED current which only uses a couple volts which is very inefficient. So I assumed 20mA here.
Also remember to reduce hFE to 10% of maximum when using a switch.


text:
Q: Kali vmware live vs graphic install I was following Kali VM installations and trying to create a Kali virtual machine with VMWare. So far, Everything is ok. And I can do everything in the Live without installation when the VM start up. So I want to know in what case we need install the Kali?

A: You'd want to do an install if you want to make sure your VM stays up to date, or if you want to install any tools that aren't on the ISO. For me, I write a lot of scripts, and prefer a full linux box, or VM so i can make sure the plethora of scripts i end up writing stay permanent.
There are advantages to not installing too, like the fact that if you hork something up, a fresh instance is a reboot away.


text:
Q: PHP Check if 2 variables are the same, like a test I need help to check if variables (from a database) are the same, like a test.
First I was using just "==", but I saw this: http://php.net/manual/en/language.operators.comparison.php , and now I'm using "===". But it still doesn't work.
My code:
    $uids = array();
    $trues = array();
    while ($row = mysqli_fetch_assoc($result)) {
      array_push($uids, $row['UID']);
    } while ($row1 = mysqli_fetch_assoc($result1)) {
      array_push($uids, $row1['UID']);
    } while ($row2 = mysqli_fetch_assoc($result2)) {
      array_push($uids, $row2['UID']);
    }
    for ($i = 0; $i < count($uids); $i++) {
      $r = 0;
      if ($row['question1'] === $row['uAnswer1']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question2'] === $row['uAnswer2']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question3'] === $row['uAnswer3']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question4'] === $row['uAnswer4']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question5'] === $row['uAnswer5']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question6'] === $row['uAnswer6']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question7'] === $row['uAnswer7']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question8'] === $row['uAnswer8']) {
        $r++;
      } else {
        $r = $r;
      } if ($row['question9'] === $row['uAnswer9']) {
        $r++;
      } else {
          $r = $r;
      } if ($row['question10'] === $row['uAnswer10']) {
        $r++;
      } else {
        $r = $r;
      }
      array_push($trues, $r);
      echo $uids[$i] . " [" . $r . "]<br>";
    }
    print_r($trues);
  }

What the result is: https://hastebin.com/uxitoyoyib.php
So it actually says everything is right, but I know that it isn't. Can you help me with this?
Thanks!

A: use
  if ($row['question4'] == $row['uAnswer4']) {
        //do something
        }

and try to print your 2 variable.

A: Compare variables like
if ( strtolower(trim($row['question5'])) === strtolower(trim($row['uAnswer5'])) )

Remove spaces if added with strings, convert the string in lowercase to the exact match of both strings.

A: You can use the strcmp() or strcasecmp() functions or the === operator.


text:
Q: Range query on partial composite columns I can't figure out how to make all the range queries i need using Astyanax.
I've tried what's explained here but it does not seem to work.
FYI I'm coming from the Hector world where i got this all working nicely and for reasons i won't explain, we decided to switch to Astyanax.
I have a column family described as follow. Note the "ReversedType" that allows us to have the latest TimeUUID first. It shouldn't impact the rest, at leat it never did with Hector:
ColumnFamily: mycf
      Key Validation Class: org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.UTF8Type)
      Default column value validator: org.apache.cassandra.db.marshal.UTF8Type
      Columns sorted by: org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.TimeUUIDType))

And here's it's definition as an Astyanax CF:
public static final CF = new ColumnFamily<Rowkey, Column>(
    NAME,
    new AnnotatedCompositeSerializer<Rowkey>(Rowkey.class),
    new AnnotatedCompositeSerializer<Column>(Column.class),
    StringSerializer.get()
);

public static class Column {
    @Component(ordinal = 0)
    public String    colname        = null;
    @Component(ordinal = 1)
    public UUID        timeUUID    = null;
}

public static class Rowkey {
    @Component(ordinal = 0)
    public String    aid;
    @Component(ordinal = 1)
    public String    cid;
}

I use to be able to do a query using partial composites as described here. What i really need is to be able to do the following range queries:
# Range 1
# Should get the 10 first elements of the rowkey
colstart: null
colend: null
limit: 10

# Range 2
# Should get the 10 first elements of the rowkey
# that has as first part of the composite the string "mycol"
colstart: Column("mycol", null)
colend: Column("mycol", null)
limit: 10

# Range 3
# Should get the 10 first elements of the rowkey
# that has as first part of the composite the string "mycol"
# and with a timeuuid created with a timstamp between 'timestampStart' and 'timestampEnd'
colstart: Column("mycol", TimeUUID(timestampStart))
colend: Column("mycol", TimeUUID(timestampEnd))
limit: 10

# Range 4, not actually a range
# Should get the 1 column composed of "mycol" and existingTimeUUID
colstart: Column("mycol", existingTimeUUID)
colend: Column("mycol", existingTimeUUID)
limit: 10

Here's the 3 ways i've tried:
# Code 1
keyspace.prepareQuery(columnFamily)
    .getKey(rowkey)
    .withColumnRange(columnStart, columnEnd, false, 10)
    .execute()
    .getResult();

# Code 2
RangeBuilder rangeBuilder = new RangeBuilder()
    .setStart(columnStart, CF.getColumnSerializer())
    .setEnd(columnEnd, CF.getColumnSerializer())
    .setReversed(false)
    .setLimit(10);
keyspace.prepareQuery(columnFamily)
    .getKey(rowkey)
    .withColumnRange(rangeBuilder.build())
    .execute()
    .getResult();

# Code 3
CompositeRangeBuilder rangeBuilder = ((AnnotatedCompositeSerializer<Column>) colSerializer)
    .buildRange()
    .withPrefix(columnStart.colname)
    .greaterThanEquals(columnStart.timeUUID)
    .lessThanEquals(columnEnd.timeUUID)
    .limit(10);
keyspace.prepareQuery(columnFamily)
    .getKey(rowkey)
    .withColumnRange(rangeBuilder.build())
    .execute()
    .getResult();

Based on my Hector background, the composite i give (Annotated Classes) miss the EQUALITY parameter.
Code 3 wouldn't do exactly what i need as the prefix applies to both start and end and those may be different if i wanted, for intance, to range query from (col1, timUUID1) to (col2, TimeUUID2).
I managed to make Range 4 work with all three codes easely.
I managed to make Range 1 work with all three codes by doing so:

*

*In Code 1 i gave null as param for start and end

*In Code 2 i avoided calling setStart and setEnd

*In Code 3 i avoided calling withPrefix or any equality methode.

I managed to make Range 2 work only with Code 3:

*

*I provided either greaterThanEquals(columnStart.colname) or lessThanEquals(columnStart.colname) and no other equality/prefix method

I did not manage to make Range 3 at all.
Clearely, i would like to use only Code 1 as I actually don't know the column family i will be querying. Here i'm just using an example with a composite column but it may not be composite or have more than 2 fields.
In hector it's really as easy as this and i would like some equivalent:
MultigetSliceQuery<K, C, V> q = HFactory.createMultigetSliceQuery(connection.getKeyspace(), this.getRowKeySerializer(), this.getColumnNameSerializer(), this.getColumnValueSerializer());
q.setColumnFamily(this.getCfName());
q.setKeys(keys)
q.setRange(colStart, colEnd, reversed, count);
q.execute();

With colStart and colEnd beeing of any type and if composite, allowing partial composites with an Equality defined on each component.
Thanks for your help.

A: I wasn't able to do all i wanted using the above methods but i found a 4th one that even though it doesn't please me, works.
I'm using the ByteBuffer version of withColumnRange in Code 1. The start and end buffer are built using the actual Composite class as follows:
public static <T> ByteBuffer toRangeStart(List<Object> list, boolean reversed) {
    return toRangeValue(list, reversed ? ComponentEquality.GREATER_THAN_EQUAL : ComponentEquality.EQUAL);
}

public static <T> ByteBuffer toRangeEnd(List<Object> list, boolean reversed) {
    return toRangeValue(list, reversed ? ComponentEquality.EQUAL : ComponentEquality.GREATER_THAN_EQUAL);
}

public static <T> ByteBuffer toRangeValue(List<Object> list, ComponentEquality eq) {
    // We use a real composite as we didn't find any other way to build those ranges
    Composite c = new Composite();

    int i;
    for (i = 0; i < list.size() - 1; i++) {
        c.addComponent(list.get(i), SerializerTypeInferer.getSerializer(list.get(i)), ComponentEquality.EQUAL);
    }
    c.addComponent(list.get(i), SerializerTypeInferer.getSerializer(list.get(i)), eq);

    return c.serialize();
}


text:
Q: Why InternetExplorer 11 doesn't fire events in inactive tab? I have a problem with IE11: I open new window in js and bind to it an event in old window. But it isn't work when old window is inactive. When I fast switch tabs -it work and also it work when I use window.blur to remove focus from new tab.
There is my code:
var win = window.open(url);
//win.blur(); trash solution
this.bindLoadEvent(win, function() {
     element.invoke();
});

bindLoadEvent: function (win, handler) {
     if (win.addEventListener) {
            win.addEventListener('load', handler, true);
     } else {
            win.attachEvent('onload', handler);
     }
}

It's seems like IE doesn't fire events in inactive tabs.
P.S. Also I tested it in Firefox and Chrome - it's work great.

A: Load event may occur before you attach handler.
Try to check whether window already loaded before you attach event handler:
bindLoadEvent = function (win, handler) {
    if (win.document.readyState === "complete") {
      setTimeout(handler, 0);
    } else if (win.addEventListener) {
      win.addEventListener('load', handler, true);
    } else {
      win.attachEvent('onload', handler);
    }
  };

For more information check How to detect if document has loaded (IE 7/Firefox 3) and Detecting the onload event of a window opened with window.open questions.


text:
Q: ansible-playbook: Unable to find subdir in expected paths with fileglob I try to copy files from roles/common/files with fileglob, but ansible-playbook searchs them in roles/common/tasks/files
Using Roles documentation says:

Any copy, script, template or include tasks (in the role) can
  reference files in roles/x/{files,templates,tasks}/ (dir depends on
  task) without having to path them relatively or absolutely.

Playbook:
# ./ansible/roles/common/tasks/main.yml
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
  - name: setup bashrc
    import_tasks: bashrc.yml

Task:
# ./ansible/roles/common/tasks/bashrc.yml
- name: try to find bashrc libs in roles/common/files/bashrc
  copy:
    src: "{{ item }}"
    dest: /tmp
  with_fileglob:
    - bashrc/*.lib.sh
# Causes the same error:
#   loop: "{{ lookup('fileglob', 'bashrc/*', wantlist=True) }}"

Files tree:
.
├── ansible
│   └── roles
│       └── common
│           ├── files
│           │   └── bashrc
│           │       ├── shell-aliases.lib.sh
│           │       ├── shell-functions.lib.sh
│           │       └── shell-settings.lib.sh
│           └── tasks
│               ├── bashrc.yml
│               ├── main.retry
│               └── main.yml

Run playbook:
$ ansible-playbook -vvvvv ./ansible/roles/common/tasks/main.yml
...
TASK [try to find bashrc libs in roles/common/files/bashrc] *******...
task path: /home/<user>/git/homedirsync/ansible/roles/common/tasks/bashrc.yml:1
looking for "bashrc" at "/home/<user>/git/homedirsync/ansible/roles/common/tasks/files/bashrc"
looking for "bashrc" at "/home/<user>/git/homedirsync/ansible/roles/common/tasks/bashrc"
looking for "bashrc" at "/home/<user>/git/homedirsync/ansible/roles/common/tasks/files/bashrc"
looking for "bashrc" at "/home/<user>/git/homedirsync/ansible/roles/common/tasks/bashrc"
 [WARNING]: Unable to find 'bashrc' in expected paths
...

Ansible version:
ansible 2.6.1
  config file = /home/<user>/.ansible.cfg
  configured module search path = [u'/var/ansible/library']
  ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.6 (default, Nov 13 2018, 12:45:42) [GCC 4.8.4]

I saw a lot of examples where it works and issues where it doesn't, but I can't localize the root of problem in my case. Community, please help.

A:
Q: "Unable to find subdir in expected paths with fileglob"

A: Quoting from fileglob's NOTES

"Matching is against local system files on the Ansible controller. "

Role's feature "Any copy, script, template or include tasks can reference files in roles/x/{files,templates,tasks} ..." does not apply to fileglob.
Instead, it's possible to use special variables. For example
with_fileglob:
  - '{{ role_path }}/files/bashrc/*.lib.sh'


text:
Q: Dictionary or fixed-size list for efficient MongoDB storage I've read how BSON works as opposed to JSON, but I still couldn't come to a conclusion which of the following is stored more efficiently in MongoDB:
Ex1:
[
    { "f1": "smth", "f2": 0.8, "f3": [[1,2],[3,4]], "f4": 0 },
    { "f1": "smth", "f2": 0.8, "f3": [[1,2],[3,4]], "f4": 0 },
    { "f1": "smth", "f2": 0.8, "f3": [[1,2],[3,4]], "f4": 0 }
]

Ex2:
[
    ["smth", "smth", "smth"],
    [0.8,0.8,0.8],
    [[[1,2],[3,4]],[[1,2],[3,4]],[[1,2],[3,4]]],
    [0,0,0]
]

Regardless of the duplicate values of course, I fear that because of the repetitive dictionary keys (i.e., "f1", "f2", "f3", "f4"), Ex2 would take less storage space, especially when the number of documents in the DB is in millions. I do consider of course that in Ex2, each array at a different index has a meaning that is not directly declared (as in Ex1 - "f1"...).

A: First, your application needs to work. It doesn't matter how fast it is if it doesn't provide useful functionality. Assuming you are implementing a real project, these usually not just have non-trivial requirements, but also the requirements change over time. Optimizing your data model (which is quite difficult to change regardless of the database used) at the expense of making your application totally inflexible is generally going to end with the failure of the project.
You can shorten field names if you want. Mongoid for example provides this functionality out of the box.
"Fixed-size list" is not a meaningful term with respect to MongoDB. All arrays can be of any size and the size is encoded in the array. MongoDB isn't implemented like a relational database with fixed row size if you use certain types.
As prasad said, your second option is probably going to become unusable in a hurry once you start trying to query it in any meaningful way, but, if you use MongoDB as a write-only data store and your schema is going to be fixed for the life of the project, sure, your data will take up less space on disk and will be faster to insert if you omit field names and use arrays.
On the other hand, if you want an inexpensive bulk data store that is still queryable, try https://docs.mongodb.com/datalake/.


text:
Q: Kendo UI Model validation only working on local environment I am using Kendo UI with ASP.NET MVC 3. We have one page where we use the MVC wrapper for a Kendo grid, bound to model classes annotated with validation requirements.
Everything works fine when deployed locally, but when deployed on our test server the validation doesn't work. After closer inspection I saw that the resulting javascript produced by the Kendo MVC wrapper for the column definitions has different values for the "editor" field for each column.
The value of the "editor" field when run on our test server is missing the data-val attributes for the input element.
What causes could there be for this difference in output? We have double checked and it is the same source being used for both deployments. Also everything else works normally on the test environment.
This is the value for the "editor" field on one of the columns when deployed locally:
"editor":"\u003cinput class=\"text-box single-line\" data-val=\"true\" data-val-regex=\"Invalid Platform Name!\" data-val-regex-pattern=\"^[a-z A-Z]+$\" data-val-required=\"The PlatformName field is required.\" id=\"PlatformName\" name=\"PlatformName\" type=\"text\" value=\"\" /\u003e\u003cspan class=\"field-validation-valid\" data-valmsg-for=\"PlatformName\" data-valmsg-replace=\"true\"\u003e\u003c/span\u003e"

And this is what is generated for the same column on the test server:
"editor":"\u003cinput class=\"text-box single-line\" id=\"PlatformName\" name=\"PlatformName\" type=\"text\" value=\"\" /\u003e\u003cspan class=\"field-validation-valid\" id=\"PlatformName_validationMessage\"\u003e\u003c/span\u003e"

Model:
public class PlatformModel
{
    public int Id { get; set; }
    [Required]
    [RegularExpression(@"^[a-z A-Z]+$", ErrorMessage = "Invalid Platform Name!")]
    [CustomValidation(typeof(ApproverGroupValidator), "IsEntryNull")]
    public string PlatformName { get; set; }
    [Required]
    public string AclGroup { get; set; }
    [Editable(false)]
    public bool IsDefault { get; set; }
}

MVC Wrapper:
@(Html.Kendo().Grid<PlatformModel>().Name("ManagePlatformGrid")
            .Columns(columns =>
            {
                columns.Bound(c => c.Id).Hidden();
                columns.Template(@).ClientTemplate("# if(!IsDefault) { #
X
# } #")
                    .Width(30)
                    .HeaderHtmlAttributes(new { style = "border-left-width:0px;border-right-width:0px;" })
                    .HtmlAttributes(new { style = "border-left-width:0px;" });
                columns.Bound(c => c.PlatformName).Title("Platform Name")
                    .HeaderHtmlAttributes(new { style = "border-left-width:0px;" })
                    .HtmlAttributes(new { style = "border-left-width:0px;text-align:right;" })
                    .Width(160);
                columns.Bound(c => c.AclGroup).Title("ACL Group");
            })
            .Sortable()
            .Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Bottom))
            .Events(events => events.DataBound("PlatformBound"))
            .DataSource(dataSource => dataSource
                .Ajax()
                .Batch(true)
                    .Read(read => read.Action("GetPlatform", "ApproverGroupTeam"))
                    .Model(model => model.Id(c => c.Id))
                    .Create(create => create.Action("CreatePlatform", "ApproverGroupTeam"))
                    .Update(update => update.Action("UpdatePlatform", "ApproverGroupTeam"))
                    .Destroy(create => create.Action("DeletePlatform", "ApproverGroupTeam"))
                    .Events(events => events.Error("PlatformHaveErrors"))
            )
        )

A: The problem was that we were using Web.config transforms and were missing the two lines:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

in our Web.TEST.config file, so even though they were present in the main Web.config file the appSettings section was being replaced by the section which was missing these settings in our test environment.


text:
Q: Row Number doesn't match with Line count in unix. How is it possible? I have a large csv file 'test.csv' whose line count is:
$ wc -l test.csv
2154868

Whereas if I count the first column in that file which is a date column, its count is:
$ cat test.csv | grep -w "2021-06-04" | wc -l
2154855

The datecode field is never empty due to query and is same throughout. So how can the line counts be so different?
Sample File data:
DATECODE|SKUCODE|SUPPLIERCODE|SUP_NAME|PRIMARY_SUPPLIER_IND|IS_VPN|IS_DIFFCODE|IS_DIFF_DIFFCODE|IS02_DIFF03_DIFFCODE|IS_DIFF04_DIFFCODE
2021-06-04|106|02971|AAAAA, INC.|Y|58730|2X (2X)|20MM (20MM)|SILVER (SILVER)|GLOSS (GLOSS)
2021-06-04|119|02080|BBBB|Y|CI400||||
2021-06-04|1194|02080|BBBB|Y|AT419||||

A: Run grep -vw "2021-06-04" test.csv to see the lines that are being filtered out.


text:
Q: Multi-Dimensional Arrays Julia I am new to using Julia and have little experience with the language. I am trying to understand how multi-dimensional arrays work in it and how to access the array at the different dimensions. The documentation confuses me, so maybe someone here can explain it better.
I created an array (m = Array{Int64}(6,3)) and am trying to access the different parts of that array. Clearly I am understanding it wrong so any help in general about Arrays/Multi-Dimensional Arrays would help.
Thanks
Edit I am trying to read a file in that has the contents
58 129 10
58 129 7
25 56 10
24 125 25
24 125 15
13 41 10
0

The purpose of the project is to take these fractions (58/129) and round the fractions using farey sequence. The last number in the row is what both numbers need to be below. Currently, I am not looking for help on how to do the problem, just how to create a multidimensional array with all the numbers except the last row (0). My trouble is how to put the numbers into the array after I have created it.
So I want m[0][0] = 58, so on. I'm not sure how syntax works for this and the manual is confusing. Hopefully this is enough information.

A: Julia's arrays are not lists-of-lists or arrays of pointers.  They are a single container, with elements arranged in a rectangular shape. As such, you do not access successive dimensions with repeated indexing calls like m[j][i] — instead you use one indexing call with multiple indices: m[i, j].
If you trim off that last 0 in your file, you can just use the built-in readdlm to load that file into a matrix.  I've copied those first six rows into my clipboard to make it a bit easier to follow here:
julia> str = clipboard()
"58 129 10\n58 129 7\n25 56 10\n24 125 25\n24 125 15\n13 41 10"

julia> readdlm(IOBuffer(str), Int) # or readdlm("path/to/trimmed/file", Int)
6×3 Array{Int64,2}:
 58  129  10
 58  129   7
 25   56  10
 24  125  25
 24  125  15
 13   41  10

That's not very helpful in teaching you how Julia's arrays work, though. Constructing an array like m = Array{Int64}(6,3) creates an uninitialized matrix with 18 elements arranged in 6 rows and 3 columns.  It's a bit easier to see how things work if we fill it with a sensible pattern:
julia> m .= [10,20,30,40,50,60] .+ [1 2 3]
6×3 Array{Int64,2}:
 11  12  13
 21  22  23
 31  32  33
 41  42  43
 51  52  53
 61  62  63

This has set up the values of the array to have the row number in their tens place and the column number in the ones place. Accessing m[r,c] returns the value in m at row r and column c.
julia> m[2,3] # second row, third column
23

Now, r and c don't have to be integers — they can also be vectors of integers to select multiple rows or columns:
julia> m[[2,3,4],[1,2]] # Selects rows 2, 3, and 4 across columns 1 and 2
3×2 Array{Int64,2}:
 21  22
 31  32
 41  42

Of course ranges like 2:4 are just vectors themselves, so you can more easily and efficiently write that example as m[2:4, 1:2].  A : by itself is a shorthand for a vector of all the indices within the dimension it indexes into:
julia> m[1, :] # the first row of all columns
3-element Array{Int64,1}:
 11
 12
 13

julia> m[:, 1] # all rows of the first column
6-element Array{Int64,1}:
 11
 21
 31
 41
 51
 61

Finally, note that Julia's Array is column-major and arranged contiguously in memory. This means that if you just use one index, like m[2], you're just going to walk down that first column.  As a special extension, we support what's commonly referred to as "linear indexing", where we allow that single index to span into the higher dimensions.  So m[7] accesses the 7th contiguous element, wrapping around into the first row of the second column:
julia> m[5],m[6],m[7],m[8]
(51, 61, 12, 22)


text:
Q: Disable Hyper-V Server 2016 auto updates I ran into a strange issue last week.
I have a bunch of Hyper-V 2016 Servers joined to a freshly created Active Directory domain (no GPO is currently configured).
There is one server who's rebooting at random moments, making the VMs running on it unavailable. It's not a critical server, so there's no cluster to back up.
I was wondering why, in the sconfig.cmd tool, the "Windows Update Settings" is set to "Personalised", and why I cannot change it to manual or "Download Only"?
Is there any way to change this? It's annoying to see this server rebooting during production hours and not be able to change the setting.

A: The requirement to make configuration changes using the "sconfig" tool is to use a user which be member of the Administrators group. Once into the toot you can follow these steps to apply the change:

*

*Type "5" and hit Enter.

*Then type "A" (Automatic), "D" (DownloadOnly), or "M" (Manual) then hit Enter.

*An Update Settings window will pop up to confirm the setting was changed, click OK.

The tool does not provide an update value of "Personalised", so check that your server is not receiving a customized configuration from other source like domain or local GPOs.
About the reboot events, check it they coincide with update events to be sure this is the root cause for them. Normally updates should be programmed during not office hours.
Check into the server logs to other possible causes for this reboot events, maybe a hardware fault, memory fault, etc.


text:
Q: Handling multiple errors in go I'm new to go and finding the error handling to be extremely verbose.  I've read the reasoning for it and mostly agree, but there are a few places where it seems like there's more code to handle errors than actually do the work.  Here is a (contrived) example, where I pipe "Hello world!" into cat and read and print the output.  Basically every line has three more to handle the error, and I'm not really even handling anything.
package main

import "fmt"
import "io"
import "io/ioutil"
import "os/exec"

func main() {
    cmd := exec.Command("cat", "-")
    stdin, err := cmd.StdinPipe()
    if err != nil {
        return
    }
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return
    }
    err = cmd.Start()
    if err != nil {
        return
    }
    _, err = io.WriteString(stdin, "Hello world!")
    if err != nil {
        return
    }
    err = stdin.Close();
    if err != nil {
        return
    }
    output, err := ioutil.ReadAll(stdout)
    if err != nil {
        return
    }
    fmt.Println(string(output))
    return
}

Is there an idiomatic, clean way to handle this?  I just feel like I'm missing something.

A: Clearly, we must handle any errors; we can't just ignore them.
For example, trying to make the example less artificial,
package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "os"
    "os/exec"
)

func piping(input string) (string, error) {
    cmd := exec.Command("cat", "-")
    stdin, err := cmd.StdinPipe()
    if err != nil {
        return "", err
    }
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return "", err
    }
    err = cmd.Start()
    if err != nil {
        return "", err
    }
    _, err = io.WriteString(stdin, input)
    if err != nil {
        return "", err
    }
    err = stdin.Close()
    if err != nil {
        return "", err
    }
    all, err := ioutil.ReadAll(stdout)
    output := string(all)
    if err != nil {
        return output, err
    }
    return output, nil
}

func main() {
    in := "Hello world!"
    fmt.Println(in)
    out, err := piping(in)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(out)
}

Output:
Hello world!
Hello world!

Error Handling and Go
In Go, error handling is important. The language's design and
  conventions encourage you to explicitly check for errors where they
  occur (as distinct from the convention in other languages of throwing
  exceptions and sometimes catching them). In some cases this makes Go
  code verbose.

A: For idiomatic, refer to peterSO's answer which begins to touch on the subject of returning errors, and this can be taken further by wrapping errors with some extra bit of information related to the context of the call within your application.
There may be cases where iterative runs over an operation might warrant something more generalized with some unusually creative examples in the following link, but as I commented on that question, it was a bad code example to examine: Go — handling multiple errors elegantly?
Regardless, looking solely at the example you have, this is nothing more than a one-off in main, so treat it like such if you're just looking to mess around as one might do in an interactive python console.
package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "os/exec"
)

func main() {
    cmd := exec.Command("cat", "-")
    stdin, _ := cmd.StdinPipe()
    stdout, _ := cmd.StdoutPipe()

    cmd.Start()
    io.WriteString(stdin, "Hello world!")

    stdin.Close();
    output, _ := ioutil.ReadAll(stdout)

    fmt.Println(string(output))
}

A: I just wrote a few hundreds lines in Go, so I'm not titled to indicate any idiomatic way.
However, in case of repetitive call-and-check-error steps , I find that the code is a bit easier to write and to read as well  if I  revert the logic : instead of checking the condition for exiting (err != nil ), I check the condition for continuing ( err == nil ), like shown below.
This can be done, if you have an unique way to handle the error, no matter which error is, like returning to the caller or printing/logging it.
The drawback to this approach is that you can't implicitly declare the variables with :=, because they would have the scope of the if block in which they are assigned.
func main() {
    var output []byte
    var stdin io.WriteCloser
    var stdout io.Reader

    cmd := exec.Command("cat", "-")

    stdin, err := cmd.StdinPipe()

    if err == nil {
      stdout, err = cmd.StdoutPipe()
    }

    if err == nil {
      err = cmd.Start()
    }

    if err == nil {
      _, err = io.WriteString(stdin, "Hello world!")
    }

    if err == nil {
    output, err = ioutil.ReadAll(stdout)
    }

    if err == nil {
     err = stdin.Close();
    }

    if err == nil {
            fmt.Println(string(output))
    } else {
         fmt.Println(string(err.Error())) // Error handling goes here
    }

    return
}

A: In a situation like this, I usually just flatten it out a bit.
func myFunc() (err error) {
    cmd := exec.Command("cat", "-")

    stdin,  err := cmd.StdinPipe();                  if err != nil { return }
    stdout, err := cmd.StdoutPipe();                 if err != nil { return }

       err  = cmd.Start();                           if err != nil { return }
    _, err  = io.WriteString(stdin, "Hello world!"); if err != nil { return }
       err  = stdin.Close();                         if err != nil { return }
    o, err := ioutil.ReadAll(stdout);                if err != nil { return }

    fmt.Println(string(o))
    return
}

Still ugly, but at least it's less vertical, and we get some alignment.
I can't say this adheres to any sort of convention, but it's a whole lot easier to read IMO.


text:
Q: Relationship between getWidth() method in Display class and XML layout in Android According to the Android documentation for screen support, they have described as follow,

*

*xlarge screens are at least 960dp x 720dp

*large screens are at least 640dp x 480dp

*normal screens are at least 470dp x 320dp

*small screens are at least 426dp x 320dp
I have a code snippet as follows;
Display display = getWindowManager().getDefaultDisplay();
int displayWidth = display.getWidth();

I need to get an idea for the value range for XML layouts which is related to displayWidth out-put.
As an example, I want an answer like;
if 0 < displayWidth < 320 are small screens
Above phrase may wrong, I just saw an example.
Further, we can have directories like layout, layout-small, layout-large, layout-xlarge and layout-xlarge-land under res directory. So what is the displayWidth applicable for those layouts.
As an example just like above;
if 0 < displayWidth < 320 for layout-small
Thank you.

A:   try {
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        if (display.getHeight() == 480 && display.getWidth() == 320) {

                  //Medium Screens
            i = 1;
            return i;
        } else if (display.getHeight() == 320 && display.getWidth() == 240) {
                 //Small Screens
            i = 1;
            return i;
        } else if (display.getHeight() == 800 && display.getWidth() == 480) {
                //Large Screens
            i = 1;
            return i;
        } else if (display.getHeight() == 1280 && display.getWidth() == 800) {

               //X-large Screens
           i = 2;
            return i;
        }

    } catch (Exception e) {
        i = 0;
    }
    return i;

A: I think' it's better to calculate diagonal length of the screen as below.
DisplayMetrics  displayMetrics = getResources().getDisplayMetrics();
    double screen_phys_width  = (double)displayMetrics.widthPixels / displayMetrics.xdpi;
    double screen_phys_height = (double)displayMetrics.heightPixels / displayMetrics.ydpi;
    screen_diagonal = Math.sqrt(screen_phys_width * screen_phys_width + screen_phys_height * screen_phys_height);

A: If your goal is to know which layout from the layouts in the layout-small or layout-large, etc will be used, you can use this trick.
You can have a view with a gone visibility and add a tag to this view indicating which kind of layout it is.
At run time, you can retrive this view and test its tag. This way you will know which layout is been used.
The android documentation gives you the information that for such and such screen dimension the corresponding type of the layout will be used. Now it is your design decision to write different layouts for different screen sizes.


text:
Q: How to Skip preview page (step 4 ) and redirect the user to Thank you page(Step 5) in Django-Oscar I have been working on django-oscar, where i am integrating stripe prebuilt checkout page, i want to be able to achieve any one of this 2 scenarios,
Scenario 1:
How to skip step 4(Preview) and redirect the user to the step 5(Thank you) without clicking on the "Place order" button on Preview page ?
i.e on clicking on the "pay" button in stripe checkout page, i want to be able to call "submit" method of PaymentDetailsView.
the rest functionality should work as it is.
Scenario 2:
How to make the preview page first and then the payment page after preview ?
Please If you can just give me an overview of what methods i need to overwrite to achieve any one of this 2 scenarios, that would be helpful for me.
Let me know if you need more explanation or you want to see what i have done yet ?

A: First and foremost, the steps are found in templates/oscar/checkout/nav.html, you open that nav.html and then you can edit it by removing the step that you want to skip.


text:
Q: Rails # within HTML href comments out the line In my controller I am setting a variable equal to an HTML string in order to account for a base case. However, # comments out the rest of the line. How can I escape this?
@chart_data = "
If you login to your social media apps, this section will display social analytics.
"

Note: this is not an .html.erb file it is .rb

A: @chart_data = <<-HTML.strip!

If you login to your social media apps, this section will display social analytics.

HTML

Or
@chart_data = %Q{

If you login to your social media apps, this section will display social analytics.

}.strip!

Or
@chart_data = "
If you login to your social media apps, this section will display social analytics.
"

Pay attention to the \

A: Try following code:
@chart_data = "
If you login to your social media apps, this section will display social analytics.
"


text:
Q: Vue select load optionsafter click How i can load data after click on vue-select, if i do this it's load aftet two click
 <v2-select style="width:150px;max-width: 150px"
                   @click="loadFormats"
                   :searchable="false"
                   :clearable="false
 "
                   :options="formats"
                   v-model="localSelectedFormat.value"
                   label="nameFormat"
        >

        </v2-select>
loadFormats(){
     this.getFormats().then(res => {
 this.formats = res.data;
...
})

A: you can remove the click event and call the loadFormats function in the mounted lifecycle hook function.
code below:
     <v2-select style="width:150px;max-width: 150px"
                       :searchable="false"
                       :clearable="false"
                       :options="formats"
                       v-model="localSelectedFormat.value"
                       label="nameFormat"
            >

      </v2-select>

     mounted(){
       this.loadFormats()
     }

    ```


text:
Q: How can I create an abstraction of the map function working on single values? I try to create a class to abstract the map function of Arrays to works transparently on single values.
export class Container<T> {
  value: T;

  constructor(value: T) {
    this.value = value;
  }

  map<U>(f: (x: T extends Array<infer R> ? R : T) => U): Container<T extends Array<any> ? Array<U> : U> {
    if (Array.isArray(this.value)) {
      const mapped = this.value.map(f);
      return new Container(mapped); // <-- Error A here
    }

    return new Container<U>(f(this.value /* <-- Error B here */)); // <-- Error C here
  }

  unwrap(): T {
    return this.value;
  }
}

//Sample usage
const sayHello = (name: string) => `Hello ${name}`;
const shout = (str: string) => str.toUpperCase();

const a = new Container("Toto").map(sayHello).map(shout).unwrap() // HELLO TOTO
const b = new Container(["Harry", "Ron", "Hermione"]).map(sayHello).map(shout).unwrap() // ["HELLO HARRY", "HELLO RON", "HELLO HERMIONE"]

But typescript complains, and i don't understand why the type doesn't match
// Error A
Type 'Container<U[]>' is not assignable to type 'Container<T extends any[] ? U[] : U>'.
  Type 'U[]' is not assignable to type 'T extends any[] ? U[] : U'.ts(2322)

// Error B
Argument of type 'T' is not assignable to parameter of type 'T extends (infer R)[] ? R : T'

// Error C
Type 'Container<U>' is not assignable to type 'Container<T extends any[] ? U[] : U>'.
  Type 'U' is not assignable to type 'T extends any[] ? U[] : U'

I now I can "fix" it with any but look for a cleaner solution

A: Here's a solution which is kind of clunky but works: let T be the individual element type (instead of either the element type or an array type), then have a second type parameter for whether or not value is an array. You still need a type assertion in the unwrap method.
I also had to replace the constructor with a static factory method with two overloads, so that the second type parameter can be provided correctly.
export class Container<T, IsArray extends boolean> {
  value: T | T[];

  static of<T>(value: T[]): Container<T, true>;
  static of<T>(value: T): Container<T, false>;
  static of(value: unknown) {
    return new Container(value);
  }
  private constructor(value: T | T[]) {
    this.value = value;
  }

  map<U>(f: (x: T) => U): Container<U, IsArray> {
    if (Array.isArray(this.value)) {
      const mapped = this.value.map(f);
      return new Container(mapped);
    }

    return new Container<U, IsArray>(f(this.value));
  }

  unwrap(): IsArray extends true ? T[] : T {
    return this.value as IsArray extends true ? T[] : T;
  }
}

Playground Link
That said, it would be much simpler if you just used plain arrays. You can wrap a single value in an array like [value] instead of Container.of(value) and there is no more overhead than wrapping it in a Container instance; and then there is no overhead needed when your value is an array. Compare:
const a = ["Toto"].map(sayHello).map(shout)[0];
const b = ["Harry", "Ron", "Hermione"].map(sayHello).map(shout);


text:
Q: Collada model faces not displaying correctly in three.js After importing a collada model into three.js, some of the model's faces are only visible from the inside of the model and not from the outside.
How can I fix the problem with the faces in question?
Is it possible to have the model's faces visible from both sides?

A: The reason it doesn't work properly is because your file has this double_sided flag set:
<effect id="material_3_4_0-effect" name="material_3_4_0-effect">
   <profile_COMMON>
      ...
      <extra>
         <technique profile="GOOGLEEARTH">
            <double_sided>1</double_sided>
         </technique>
      </extra>
   </profile_COMMON>
</effect>

The three.js ColladaLoader doesn't look for this flag and set doubleSided on the material like it should. I've filed a bug for the issue.

A: To fix the faces being oriented incorrectly, load the model into a 3D modeling program like Blender and flip the normals of the faces that aren't displaying correctly.
Three.js meshes have a doublesided property you can set which will usually allow you to display the model with the faces visible from both sides.
Here's a short example of how to load a collada mesh and enable double-sided rendering.
var loader = new THREE.ColladaLoader();
loader.load('path/to/mesh.dae', loadModel);

function loadModel(geom) {
    var mesh = new THREE.Mesh(geom, new THREE.MeshBasicMaterial());
    mesh.doublesided = true;
    scene.add(mesh);
}

And a live example: http://jsfiddle.net/r7Yq2/


text:
Q: How to design libraries written in ANSI C? I want to develop a library with ANSI C.
I have a string struct:
struct libme_string
{
  char* buffer;
  int length;
};

I want to write a function, libme_create_string(), that creates and initializes a string (like constructors in C++).
Which of these methods is better for designing libme_create_string()?

Method #1
Allocate memory for string object in libme_create_string() and return it:
struct libme_string* libme_create_string(int length)
{
  // Check arguments...

  // Allocate memory for object.
  struct libme_string* str = malloc(sizeof(struct libme_string));

  // Handle memory allocation errors...

  str->buffer = malloc(length);
  str->length = length;

  // Handle memory allocation errors...

  return str;
}

void libme_delete_string(struct libme_string* str)
{
    // Check arguments...

    free(str->buffer);
    free(str);
}

Use
struct libme_string* str;
str = libme_create_string(1024);

// ...

libme_delete_string(str);
str = NULL;

Method #2
Do not allocate memory for string object in libme_create_string() function, accept it as an argument:
struct void libme_create_string(libme_string* str, int length)
{
  // Check arguments...

  // Just allocate memory for members.
  str->buffer = malloc(length);
  str->length = length;

  // Handle memory allocation errors...
}

void libme_delete_string(struct libme_string* str)
{
  // Check arguments...

  free(str->buffer);
}

Use
struct libme_string str; // << different, not a pointer!
libme_create_string(&str, 1024);

// ...

libme_delete_string(&str);

Notes

*

*string just a sample.

*Method #2 is faster, isn't it?

Lastly, are there any good design guidelines for designing libraries written in C?

A: Personally, I would view the second version as less intuitive and more error prone.
If you're trying your hardest to encapsulate instantiation (which you should be doing anyway), then the first really is the only way to go — one step, done. The second version means that in order to have a fully initialized variable, you need to not only instantiate it, but you need to call a helper function on it immediately. That extra step is a bug waiting to happen.

A: Personally I prefer the first method. Agreed: it's a bit C++ like, but ...
thing_t *thing_new(...);
void thing_delete(thing_t *ptr);

I do think that all "size" or "count" members should be unsigned, preferably size_t.
Also: you last snippet tries to free() an automatic variable. That is a good reason not to use it.
EDIT:
There is (at least) a third way: return the entire object as a value. I don't particularly like the method, but it at least avoids the double allocation. It goes like this:
typedef struct {
  StrLen length;
  StrType type;      /* type is not stored in the brainfile
                     **but recomputed on   loading */
  char *word;
} STRING;

STATIC STRING new_string(char *str, size_t len)
{
STRING this;

if (str) {
     if (!len) len = strlen(str);
     if (len) { this.word = malloc(len); memcpy(this.word, str, len); }
     else { this.word = malloc(1); memset(this.word, 0, 1); }
     this.length = len;
     this.type = word_classify(this);
     }
else        {
     this.word = NULL;
     this.length = 0;
     this.type = 0;
     }
return this;
}

Typical usage goes like this:
if (*np == WORD_NIL) {
  STRING this;
  *np = dict->size++;
  this = new_string(word.word, word.length);
  dict->entry[*np].string = this;
  dict->entry[*np].hash = hash_word(this);
  }

(code inherited from megahal, reused in wakkerbot)
As I said, I don't like this method, but the struct assignment definitely has its advantages.

A: Why not factor the process into two functions, so you can use whichever you need:
struct libme_string * create_string();
void destroy_string(struct libme_string *);

struct libme_string * init_string(struct libme_string * str, unsigned int length);
struct limbe_string * deinit_string(struct libme_string * str);

Usage #1, all dynamic allocations:
struct libme_string * str = init_string(create_string(), 10);
destroy_string(deinit_string(str));

Usage #2, automatic outer struct:
struct libme_string str;
init_string(&str);
deinit_string(&str);

Make sure that the init functions return the pointer, so that you can compose the calls like I did.
If deinit() also sets the pointer to zero, then you could make destroy() call deinit() if the pointer is non-zero, though that breaks the symmetry a bit.


text:
Q: Dbplyr count unique (n_distinct) with case_when or if_else I want to create a new column counting unique dates (dplyr::n_distinct) with dplyr::case_when function using a dplyr::tbl df object.
I tried the following code:
df %>%
group_by(id) %>%
mutate(
    last_date = max(date),
    distinct_date_2020 = case_when(
            date >= "2020-01-01" & date <= "2020-12-31" ~ n_distinct(date[!type == "Online"]),
            TRUE ~ as.integer(0))
) %>%
ungroup()

The mutate of distinct_date_2020 does not work. I receive the following error message:

[Microsoft][ODBC SQL Server Driver][SQL Server]Use of DISTINCT is not allowed with the OVER clause.

If I run without the distinct_date_2020, it works:
df %>%
group_by(id) %>%
mutate(
    last_date = max(date)
) %>%
ungroup()

I also tried these variants, without success:
distinct_date_2020 = n_distinct(date[date >= "2020-01-01" & date <= "2020-12-31" & !type == "Online"])

and
distinct_date_2020 = ifelse(date >= "2020-01-01" & date <= "2020-12-31", n_distinct(date[!type == "Online"]), NA)

If I run these after collect(), it works. But I want to send this as a SQL command to the server.
DBI::dbGetInfo:

$dbms.name [1] "Microsoft SQL Server"
$db.version [1] "11.00.6523"

Anyone know how to solve this? Thanks!

A: I finally got it working. I first grouped by id, extracted the last date and then grouped by year (using DATEADD and DATEDIFF, avoiding the lubridate package because of its lack of compatibility with the dbplyr package). Summarizing and putting the condition [type != "Online"] between brackets also worked. I got the desired results with the code below:
df %>%
    group_by(id) %>%
        mutate(
            last_date_temp = max(date)
        ) %>%
    group_by(year = DATEADD(sql("year"), DATEDIFF(sql("year"), 0, date), 0), id) %>%
    summarize(
        last_date = max(last_date_temp, na.rm = TRUE),
        distinct_date = n_distinct(date[type != "Online"]),
    ) %>%
    ungroup() %>%
    select(id, year, everything()) %>%
    arrange(id, year) %>%
    collect()

A: The issue is neither with case_when nor with n_distinct but with square brackets applied to date.
Within R, date[!type == "Online"] selects a subset of all rows in the column. SQL queries (mostly) work row-by-row, hence requiring the input to n_distinct to be a filtering of the date column based on the type column will not produce valid SQL.
One way to test this is with the show_query command:
df %>%
group_by(id) %>%
mutate(
    last_date = max(date),
    distinct_date_2020 = case_when(
            date >= "2020-01-01" & date <= "2020-12-31" ~ n_distinct(date[!type == "Online"]),
            TRUE ~ as.integer(0))
) %>%
ungroup() %>%
show_query()

Unless this produces valid SQL code then your query is guaranteed to error.
The solution is to do this filtering separately:
dist_dates = df %>%
    group_by(id) %>%
    filter(type != "Online",
           date >= "2020-01-01",
           date <= "2020-12-31") %>%
    mutate(distinct_date_2020 = n_distinct(date)) %>%
    ungroup()

max_dates = df %>%
    group_by(id) %>%
    mutate(last_date = max(date))
    ungroup()

output = max_dates %>%
    left_join(dist_dates, by = "id") %>%
    select(id, last_date, distinct_date_2020)

I have made the two summaries separately, so that the filter does not apply to last_date.
I have removed the case_when as in your example it only serves as a filter. But if you want to do it this way try:
dist_dates = df %>%
    group_by(id) %>%
    filter(type != "Online") %>%
    mutate(
        distinct_date_2020 = case_when(
            date >= "2020-01-01" & date <= "2020-12-31" ~ n_distinct(date),
            TRUE ~ as.integer(0))
    ) %>%
    ungroup()


text:
Q: Unable to create a textclip in moviepy (imagemagick succesfully installed?) - got Utf8 Error i got this error when using moviepy with "TextClip": 'utf8' codec can't decode byte 0x84 in position 5: invalid start byte
Imagemagick and wand are (proper?) installed.
Does anybody knows a possible solution?

A: Apparently moviePy expects non unicode strings (file moviepy/video/VideoClip.py, line 1095). the workaround for this would be to decode your unicode strings before passing them to the TextClip:
if isinstance(mytext, unicode):
    mytext = mytext.encode('latin1')

EDIT
MoviePy expects UTF8 strings (non unicode), so the above becomes
if isinstance(mytext, unicode):
    mytext_str = mytext.encode('utf8')


text:
Q: Concatenation doesn't work in phpmyadmin XAMPP I tried to use "||" for concatenation:
The query I used:
"SELECT id, name, age, age||id FROM myTable;"

This is the output:

Can anyone tell me why the output is not 201 (in first column) and 162(in second column)?? Also it gives similar outputs when I use two attributes that are of varchar datatype and the above two attributes are of int datatype.

A: There is no such concatenation in mySQL. This is Oracle SQL dialect. You have to use the CONCAT function in mysql
SELECT id, name, age, CONCAT(age,id) FROM myTable

A: Can anyone tell me why the output is not 201
its because, in mysql, you need to enable PIPES_AS_CONCAT. in order to work with ||

If the PIPES_AS_CONCAT SQL mode is enabled, || signifies the
SQL-standard string concatenation operator (like CONCAT()).

You can set it using phpmyadmin->variables->searchFor SQL_MODE

Refer mysql doc
But i would suggest you to use
CONCAT(columnName1, columnName2, ...)

A: visit the Mysql Documentations :
on this link you will find a list of String Functions and Operators
but you not use|| to concatenate caratcters or strings but do this :

*

*SELECT id, name, age, concat(age,id) FROM myTable; or

*SELECT id, name, age, concat_ws(' ',age,id) FROM myTable; if you want to space the age with id like this for example 23 1. 23 for age and 1 for id.