text:
Q: How to use if else statement in a dataframe when comparing dates? I have a dataframe D and I would want to calculate a daily return of "Close" only if they share the same month. So for example there would be 0 for 1995-08-01
 Date         Close   Month
1 1995-07-27 163.32 1995-07
2 1995-07-28 161.36 1995-07
3 1995-07-30 162.91 1995-07
4 1995-08-01 162.95 1995-08
5 1995-08-02 162.69 1995-08

I am trying to use an if-else statement and looping to apply it on other dataframes.
D1 <- D[-1,]
for (i in c("Close"))
{ TT <- dim(D)[1]
  if (D[1:(TT-1),"Month"] == D[2:TT,"Month"]) {
  D1[,i] = round((100*(log(D[2:TT,i]/D[1:(TT-1),i]))), digits = 4)
  }
  else {
  D1[i] = 0 }
 }

I get these results but in the forth row it should be 0.0000 because the forth row is a from different month than the the third row. Moreover, I get this warning message : "Warning message: In if (D[1:(TT - 1), "Month"] == D[2:TT, "Month"]) { : the condition has length > 1 and only the first element will be used". Can you please help me out? Thank you.
 Date         Close   Month
1 1995-07-27 0.5903 1995-07
2 1995-07-28 1.4577 1995-07
3 1995-07-30 0.9139 1995-07
4 1995-08-01 0.0006 1995-08
5 1995-08-02 0.0255 1995-08

A: Next time you should REALLY provide a reproducible example here I did it for you. My solution uses diff and ifelse as requested.
month <- c(1,1:5,5:6)
data <- (1:8)*(1:8)
df <- data.frame(cbind(month, data))

diffs <- sapply(df, diff)
diffs <- data.frame(rbind(NA, diffs))
df$result <- ifelse(diffs$month==0, diffs$data, 0)
df
month data result
1     1    1     NA
2     1    4      3
3     2    9      0
4     3   16      0
5     4   25      0
6     5   36      0
7     5   49     13
8     6   64      0

A: if() expects a single value (usually TRUE or FALSE, but can also be 0 or 1, and it can handle other single values, e.g., it treats positive values like ones).  You are feeding in a vector of values.  The warning message is telling you that it is ignoring all the other values of the vector except the first, which is usually a strong indication that your code is not doing what you intend it to do.
Here's one do-it-yourself approach with no loops (I'm sure some time-series package has a function to calculate returns):
# create your example dataset
D <- data.frame(
    Date = (as.Date("1995-07-27") + 0:6)[-c(3,5)],
    Close = 162 + c(1.32, -.64, .91, .95, .69)
)

# get lagged values as new columns
D$Close_lag <- dplyr::lag(D$Close)
D$Date_lag <- dplyr::lag(D$Date)

# calculate all returns
D$return <- D$Close / D$Close_lag - 1

# identify month switches
D$new_month <- lubridate::month(D$Date) != lubridate::month(D$Date_lag)

# replace returns with zeros when month switches
D[!is.na(D$return) & D$new_month==TRUE, "return"] <- 0

# print results
D


text:
Q: MYSQL and PHP checking if IP address is already used in order to only allow viewing page once The coupon should only show up for IPs that haven't already viewed that type. If they do, it should echo the error page.  It is make to only allow a user to view the page once.
The IP is making it to the database, but the PHP is not working correctly to display the error page when the IP is found in the database under that type.
URL: http://muhs.trinix.co/coupon?type=czo0OiJNZW93Ijs=
<?PHP
if(empty($_GET['type'])){die();}
mysql_connect("localhost", "muhs_cp", "********************");
mysql_select_db("muhs_cp");
$type = mysql_real_escape_string(unserialize(base64_decode($_GET['type'])));
$randid = rand(1, 9999999999);
$ip = $_SERVER['REMOTE_ADDR'];

$resultz = mysql_query("SELECT ip FROM coupons WHERE type = '$type' AND ip = '$ip'        LIMIT 1");

if(mysql_fetch_array($resultz) !== false){
mysql_query("INSERT INTO `coupons` (`id`, `type`, `ip`) VALUES ('$randid', '$type', '$ip')");

$result = mysql_query("SELECT * FROM coupons WHERE type = '".mysql_real_escape_string($type)."'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$expired = $row['expired'];
$notes = $row['notes'];
$cookie = $row['cookie'];
mysql_query("UPDATE `totals` SET `number` = `number` + 1 WHERE `type` = '".mysql_real_escape_string($type)."'");
}
else{
echo "

<title>Your Coupon</title>
<link href='css/screen.css' rel='stylesheet' type='text/css' />

Whoops! Looks like this coupon has already been used.

You are unable to make a coupon more than once.

"; die();};
?>

UPDATE: I had an extra ! in the if statement.  Also I was able to change the code so that it only allows users to see the page once.

A: It is in this line:
if(mysql_fetch_array($resultz) !== false){ ...

If it is not supposed to return something then you should say != NULL. The way you have it will always be !== false so it will never show the page which is part of the else statement because it will never get that far.
For example,
If you want to do A only if B is in state C which for us is not having the IP in the database.

A: I would rewrite that part:
$ip = $_SERVER['REMOTE_ADDR'];

//if you don't want every type to be usable just once, add ip here
$resultz = mysql_query("SELECT ip FROM coupons WHERE type = '$type' AND ip = '$ip' LIMIT 1");

//better to work with num_rows here
if(mysql_num_rows($resultz)>0){
mysql_query("INSERT INTO `coupons` (`id`, `type`, `ip`) VALUES ('$randid', '$type', '$ip')");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding admob to Android app before or after putting it on android market? Do i need to put android app to market first before adding admob or some other display ads on the mobile app? As when i was signing up for admob it asks for android url. I am new to this can anyone explain in detail. How i can do this?

A: When they ask for a URL, they are just looking for a fake, but descriptive URL for your application.  For example, if your application is called "Test1234" and you have www.test1234.com, they suggest you make the URL for your Android application something like:
http://android.test1234.com
Basically it's just a way to distinguish between your applications.


text:
Q: Set Email Subject and Body From API Looking at the Marketing Cloud API (specifically the REST Reference), I can't seem to find anything that allows you to set the subject and body of an email. Is there some work around or way to do this?
I saw that there is the SimpleEmail Action in the Actions Developer Guide, is there something similar that I missed?

A: This is fairly well documented in the SFMC Content Builder API documentation as @EazyE has stated in comments.
Here is a quick sample of the payload for the REST call to build an asset:
{
  "name": "NTO Welcome Series Email",
  "channels": {
    "email": true,
    "web": false
  },
  "views": {
    "html": {
      "content": "<!DOCTYPE html>This is a simple message."
    },
    "text": {},
    "subjectline": {},
    "preheader": {}
  },
  "assetType": {
    "name": "templatebasedemail",
    "id": 207
   }
}

as well as some other examples in the documentation.
You would just change "subjectline": {} with your text, etc.
You can also check out my answer here for similar information.


text:
Q: Drools make conflict with spring-security-oauth2-provider I tried to add drools plugin:
https://grails.org/plugin/drools
to my webapp in grails, by just adding it in BuildConfig.groovy:
plugins {
    // plugins for the build system only
    build ":tomcat:7.0.55"

    // plugins for the compile step
    compile ":scaffolding:2.1.2"
    compile ':cache:1.1.8'
    compile "org.grails.plugins:mail:1.0.7"
    compile ":rest-client-builder:2.0.3"
    compile ":spring-security-core:2.0-RC3"
    compile ":spring-security-oauth2-provider:1.0.5.2"
    compile ":browser-detection:0.4.3"
    compile ":asset-pipeline:2.1.5"
    compile ":remote-pagination:0.4.8"
    compile ":drools:1.1.0"

    // plugins needed at runtime but not for compilation
    runtime ":hibernate4:4.3.6.1" // or ":hibernate:3.6.10.18"
    runtime ":database-migration:1.4.0"
    runtime ":jquery:1.11.1"
    runtime ':twitter-bootstrap:3.3.1'
}

, but I've received an error:
Configuring Spring Security OAuth2 provider ...
... done configuring Spring Security OAuth2 provider Running Common
Auth Plugin... | Error 2015-05-25 13:25:09,499 [localhost-startStop-1]
ERROR context.GrailsContextLoaderListener  - Error initializing the
application: Error creating bean with name 'oauth2ProviderFilter':
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class
[org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter]:
Constructor threw exception; nested exception is
java.lang.NoClassDefFoundError:
com/sun/xml/bind/v2/model/annotation/AnnotationReader Message: Error
creating bean with name 'oauth2ProviderFilter': Instantiation of bean
failed; nested exception is
org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class
[org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter]:
Constructor threw exception; nested exception is
java.lang.NoClassDefFoundError:
com/sun/xml/bind/v2/model/annotation/AnnotationReader
    Line | Method
->>  262 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker ^
745 | run       in java.lang.Thread Caused by
BeanInstantiationException: Could not instantiate bean class
[org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter]:
Constructor threw exception; nested exception is
java.lang.NoClassDefFoundError:
com/sun/xml/bind/v2/model/annotation/AnnotationReader
->>  262 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker ^
745 | run       in java.lang.Thread Caused by NoClassDefFoundError:
com/sun/xml/bind/v2/model/annotation/AnnotationReader
->>  800 | defineClass in java.lang.ClassLoader
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |    142 | defineClass in java.security.SecureClassLoader |    449 | defineClass in java.net.URLClassLoader |     71 | access$100 in
'' |    361 | run . . . in java.net.URLClassLoader$1 |    355 | run
in     '' |    354 | findClass in java.net.URLClassLoader |    425 |
loadClass in java.lang.ClassLoader |   2615 |
privateGetDeclaredMethods in java.lang.Class |   2856 | getMethod0 in
'' |   1668 | getMethod in     '' |    243 | newInstance in
javax.xml.bind.ContextFinder |    235 | newInstance in     '' |    432
| find      in     '' |    637 | newInstance in
javax.xml.bind.JAXBContext |    584 | newInstance in     '' |    262 |
run . . . in java.util.concurrent.FutureTask |   1145 | runWorker in
java.util.concurrent.ThreadPoolExecutor |    615 | run . . . in
java.util.concurrent.ThreadPoolExecutor$Worker ^    745 | run       in
java.lang.Thread Caused by ClassNotFoundException:
com.sun.xml.bind.v2.model.annotation.AnnotationReader
->>  366 | run       in java.net.URLClassLoader$1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |    355 | run       in     '' |    354 | findClass in java.net.URLClassLoader |    425 | loadClass in java.lang.ClassLoader
|    800 | defineClass in     '' |    142 | defineClass in
java.security.SecureClassLoader |    449 | defineClass in
java.net.URLClassLoader |     71 | access$100 in     '' |    361 | run
. . . in java.net.URLClassLoader$1 |    355 | run       in     '' |
354 | findClass in java.net.URLClassLoader |    425 | loadClass in
java.lang.ClassLoader |   2615 | privateGetDeclaredMethods in
java.lang.Class |   2856 | getMethod0 in     '' |   1668 | getMethod
in     '' |    243 | newInstance in javax.xml.bind.ContextFinder |
235 | newInstance in     '' |    432 | find      in     '' |    637 |
newInstance in javax.xml.bind.JAXBContext |    584 | newInstance in
'' |    262 | run . . . in java.util.concurrent.FutureTask |   1145 |
runWorker in java.util.concurrent.ThreadPoolExecutor |    615 | run .
. . in java.util.concurrent.ThreadPoolExecutor$Worker ^    745 | run
in java.lang.Thread Error | Forked Grails VM exited with error

It seems there is a conflict between Drools and spring-security-oauth2-provider.

A: ok, I resolved this issue by adding:
compile ":cxf:2.1.1"

to BuildConfig plugins.
you can find more details by Ken in his comment: https://github.com/kensiprell/grails-drools/issues/8#issuecomment-105252639


text:
Q: Servlet is not invoking when called from jsp I am unable to invoke my servlet please help me out. Below is my code.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form action= "/RoleCommand.do" method = "post">
name:<input type ="text" name = "name"/>

id:<input type = "text" name= "id"/>

<input type = "submit">
</form>

Servlet code

public class RoleCommand extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RoleCommand() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter p = response.getWriter();
        p.println("hi");
        response.sendRedirect("ValidServlet");
String name = request.getParameter("name");
String id = request.getParameter("id");
}
}

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Form</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>Controller</display-name>
    <servlet-name>Controller</servlet-name>
    <servlet-class>com.controller.Controller</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Controller</servlet-name>
    <url-pattern>/Controller</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>DatabaseCon</display-name>
    <servlet-name>DatabaseCon</servlet-name>
    <servlet-class>com.database.DatabaseCon</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DatabaseCon</servlet-name>
    <url-pattern>/DatabaseCon</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>Transaction</display-name>
    <servlet-name>Transaction</servlet-name>
    <servlet-class>com.database.Transaction</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Transaction</servlet-name>
    <url-pattern>/Transaction</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RoleCommand</display-name>
    <servlet-name>RoleCommand</servlet-name>
    <servlet-class>com.command.RoleCommand</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RoleCommand</servlet-name>
    <url-pattern>/RoleCommand</url-pattern>
  </servlet-mapping>
</web-app>

As per the above code it should print on to the console once executed. But when i am clicking on submit button it's throwing an exception resource not found.
Please help me .

A: Remove .do from action and action class should be like following  action= "/RoleCommand"

A: you have wrong mapping of the servlet.
in web.xml
  <servlet>
    <description></description>
    <display-name>RoleCommand</display-name>
    <servlet-name>RoleCommand</servlet-name>
    <servlet-class>com.command.RoleCommand</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RoleCommand</servlet-name>
    <url-pattern>/RoleCommand</url-pattern>
  </servlet-mapping>

change url-pattern to *.do or /RoleCommand.do.
or you can change your form action
<form action= "/RoleCommand.do" method = "post">

to
<form action= "/RoleCommand" method = "post">

Note: both form action and url-pattern must match in order to invoke a servlet from jsp.

A: Change the form as follows, that may help you
<form action="http://localhost:8080/packagename/serveltclassname" >


text:
Q: Multiple client tables or large overall table I've recently taken over a project linking to a large MySQL DB that was originally designed many years ago and need some help.
Currently the DB has 5 tables per client that store their users information, transaction history, logs etc. However we currently have ~900 clients that have applied to use our services, with an average of 5 new clients applying weekly. So the DB has grown to nearly 5000 tables and ever increasing. Many of our clients do not end up using our services so their tables are all empty but still in the DB.
The original DB designer says it was created this way so if a table was ever compromised it would not reveal information on any other client.
As I'm redesigning the project in PHP I'm thinking of redesigning the DB to have an overall user, transaction history, log etc tables using the clients unique id to reference them.
Would this approach be correct or should the DB stay as is?
Could you see any possible security / performance concerns
Thanks for all your help

A: You should redesign the system to have just five tables, with a separate column identifying which client the row pertains to.  SQL handles large tables well, so you shouldn't have to worry about performance.  In fact, having many, many tables can be a hinderance to performance in many cases.
This has many advantages.  You will be able to optimize the table structures for all clients at once.  No more trying to add an index to 300 tables to meet some performance objective.  Managing the database, managing the tables, backing things up -- all of these should be easier with a single table.
You may find that the database even gets smaller in size.  This is because, on average, each of those thousands of tables has a half-paged filled at the end.  This will go from thousands of half-pages to just one.
The one downside is security.  It is easier to put security on tables than one rows in tables.  If this is a concern, you may need to think about these requirements.

A: This may just be a matter of taste, but I would find it far more natural - and thus maintainable - to store this information in as few tables as possible. Also most if not all database ORMs will be expecting a structure like this, and there is no reason to reinvent that wheel.
From the perspective of security, it sounds like this project could be described as a web app. Obviously I don't know the realities of the business logic you're dealing with, but it seems like regardless of the table permissions all access to the database would be via the code base, in which case the app itself needs full permissions for all tables - nullifying any advantage of keeping the tables separated.
If there is a compelling reason for the security measures - say, different services that feed data into the DB independently of the web app, I would still explore ways to handle that authentication at the application layer instead of at the database layer. It will be much easier to handle your security rules in that way. Instead of having rules set in 5000+ different places, a single security rule of 'only let a user view a row of data if their user id equals the user_id column" is far simpler, easier to understand, and therefore far more maintainable (and possibly more secure).
Different people approach databases in different ways. I am a web developer, so I view databases as the place to store my data and nothing more, as it's always a dedicated and generally single-purpose DB installation, and I handle all other logic at the application level. There are people who view databases as the application itself, who make far more extensive use of built-in security features for their massive, distributed, multi-user systems - but I honestly don't know enough about those scenarios to comment on exactly where that line should be drawn.


text:
Q: Memory error в Numpy при попытке реализовать "One-Hot-Encoding" import numpy as np
import codecs

fileObj = codecs.open("fragments.txt", "r", "utf_8_sig")
text = fileObj.read()
fileObj.close()

strings = text.split('\n')

char_dictionary = np.load('bag_of_characters.npy').item()
START_SYM = 165
END_SYM = 166
UNK = 167
SPACE_SYM = 168
CHARACTER_SYM = 169
train_size = len(strings)
dict_len = len(char_dictionary) + 5

MAX_LENGTH = 130

def char_to_code(char):
    if char in char_dictionary.keys():
        return char_dictionary[char]
    else:
        return UNK

data = np.zeros(shape=(train_size, MAX_LENGTH, dict_len),dtype='float32')
for i in range(train_size):
    for pos, char in enumerate(strings[i]):
            data[i, pos, char_to_code(char)] = 1

Пытаюсь преобразовать стоки в numpy массив с помощью one-hot-encoding на character уровне. В массиве 1.6кк строк при попытке преобразовать более +-200к строк выдает memory error.У меня вопрос в том, это физический предел моего ПК(8 гб) или можно как то обойти эту ошибку?
Спасибо.

A: Зачем изобретать колесо? Воспользуйтесь sklearn.feature_extraction.text.CountVectorizer:
Пример:
from sklearn.feature_extraction.text import CountVectorizer
from nltk import sent_tokenize

text = """Пытаюсь преобразовать стоки в numpy массив с помощью one-hot-encoding на character уровне. В массиве 1.6кк строк при попытке преобразовать более +-200к строк выдает memory error. У меня вопрос в том, это физический предел моего ПК(8 гб) или можно как то обойти эту ошибку? Спасибо."""

sents = sent_tokenize(text)

vect = CountVectorizer()
X_vect = vect.fit_transform(sents)

Результат:
In [6]: X_vect.A
Out[6]:
array([[0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
       [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 2, 1, 1, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64)

In [7]: vect.get_feature_names()
Out[7]:
['200к',
 '6кк',
 'character',
 'encoding',
 'error',
 'hot',
 'memory',
 'numpy',
 'one',
 'более',
 'вопрос',
 'выдает',
 'гб',
 'или',
 'как',
 'массив',
 'массиве',
 'меня',
 'моего',
 'можно',
 'на',
 'обойти',
 'ошибку',
 'пк',
 'помощью',
 'попытке',
 'предел',
 'преобразовать',
 'при',
 'пытаюсь',
 'спасибо',
 'стоки',
 'строк',
 'то',
 'том',
 'уровне',
 'физический',
 'это',
 'эту']

PS CountVectorizer по умолчанию возвращает разреженную матрицу в качестве результата - обычно она занимает на несколько порядков меньше памяти по сравнению с обычными Numpy NDArray.
In [9]: X_vect
Out[9]:
<3x39 sparse matrix of type '<class 'numpy.int64'>'
        with 40 stored elements in Compressed Sparse Row format>

In [10]: type(X_vect)
Out[10]: scipy.sparse.csr.csr_matrix

UPDATE:  One-hot-encoding на уровне единичных символов:
In [22]: vect = CountVectorizer(token_pattern=r'(?u)[\w\d]{1}')

In [23]: X_vect = vect.fit_transform(sents)

In [24]: ''.join(vect.get_feature_names())
Out[24]: '01268acdeghimnoprtuyабвгдежзийклмнопрстуфчшщыьэюя'

In [25]: X_vect
Out[25]:
<3x49 sparse matrix of type '<class 'numpy.int64'>'
        with 77 stored elements in Compressed Sparse Row format>


text:
Q: A multi user react app not updating state in all tabs when a new user joins(opens a new tab) I have a multi user socket.io React app, where I'm storing the user info in an array on server side. The app does not show all the users logged in all tabs i.e. the array doesn't update in all tabs when a new user logs in/joins.
Server side:
let onlineUsers = [];

const addNewUser = (username, socketId) => {
  !onlineUsers.some((user) => user.username === username) &&
  onlineUsers.push({ username, socketId });
};

const removeUser = (socketId) => {
  onlineUsers = onlineUsers.filter((user) => user.socketId !== socketId);
};

io.on('connection', socket => {

  socket.on("newUser", (username) => {
      addNewUser(username, socket.id);
      socket.emit("onlineUsers", onlineUsers);
      socket.emit('yourID', socket.id);
      console.log(onlineUsers);
   });

  socket.on('disconnect', () => {
    removeUser(socket.id);
  });

}

Client Side:
const [allusers, setAllusers] = useState([]);

useEffect(() => {
  socket.current.emit('newUser', user);

  socket.current.on("onlineUsers", onlineUsers => {
     setAllusers(onlineUsers);
  })

  socket.current.on("yourID", (id) => {
    setYourID(id);
  })
}, []);

 return (
  <Row>
    {allusers.map(key => {

      if (key.socketId === yourID) {
        return null
      }

      return (
        <button
          key={key.socketId}
          className='knock-btn'
          onClick={() => callPeer(key.socketId)}
        >
         {key.username}
        </button>
      );
    })}
 </Row>

A: Solved it!! It was a socket issue rather than react. was emitting only 1 socket from server once updated.
so instead of 'socket.emit' used 'io.sockets.emit' and that resolved the issue


text:
Q: DeepZoom for WPF add items to map I'm trying to figure out how I can place UIElements (Buttons, Rectangles) on a floorplan which is hosted in a zoomableCanvas as a MultiScaleImage.
The placed UIElements will change their backcolor and other properties dynamically.
Does anyone has an idea how to achieve this?
best regards


text:
Q: Word VBA Script: adding images to a word document in all sub folders I am trying to create a VBA script that will do the following:

*

*Enter a subfolder  (name of folder: 101)

*Open the word document

*Add image to the document were I have placed the "bookmarks" (images are in the same folder)

*Save the document

*Close the document

*Re-enter the next subfolder (name of folder: 102) and re-doing the process until all folder are done

Folder structure as follows:
Root folder: My Pictures

----
Subfolder: 101
----
File: test_document.docx
File: test_document – Copy.docx
File: test_document - Copy - Copy.docx
File: 6_Month_Assessment.jpg
File: portfolio.jpg
File: slide_deck.jpg

----
Subfolder:**102
----
File: test_document.docx
File: 6_Month_Assessment.jpg
File: portfolio.jpg
File: slide_deck.jpg

Etc. (up to 201 Subfolder)

Please see bellow some code I have found on this site (URL: VBA Macro replace text in Word file in all sub folders ) and have tried to modify the code to meet my needs when compiling the code nothing happens. Please note I am a novice when come to VBA Scripting.
   Sub DoLangesNow()
Dim file
Dim path As String
Dim strFolder As String
Dim strSubFolder As String
Dim strFile As String
Dim colSubFolders As New Collection
Dim varItem As Variant

     strFolder = "C:\My Pictures\"

     ' Loop through the subfolders and fill Collection object
     strSubFolder = Dir(strFolder & "*", vbDirectory)
     Do While Not strSubFolder = ""
         Select Case strSubFolder
             Case ".", ".."
                 ' Current folder or parent folder - ignore
             Case Else
                 ' Add to collection
                 colSubFolders.Add Item:=strSubFolder, Key:=strSubFolder
         End Select
         ' On to the next one
         strSubFolder = Dir
     Loop
     ' Loop through the collection
     For Each varItem In colSubFolders
         ' Loop through word docs in subfolder
         'YOU MUST EDIT THIS if you want to change the files extension
        strFile = Dir(strFolder & varItem & "\" & "*.docx")
         Do While strFile <> ""
         Set file = Documents.Open(FileName:=strFolder & _
                 varItem & "\" & strFile)

  ActiveDocument.Bookmarks("TEST").Range.InlineShapes.AddPicture FileName:=ThisDocument.path & "\Thrombolysis.jpg"
  ActiveDocument.Bookmarks("TEST2").Range.InlineShapes.AddPicture FileName:=ThisDocument.path & "\slide_deck.jpg"

' Saves the file
ActiveDocument.Save
ActiveDocument.Close
' set file to next in Dir
strFile = Dir
         Loop
     Next varItem
 End Sub

Update issue (16/09/14 : 17:59) I have started to receive saying the following: "Run-time error '5152"

A: I have fixed the issue by change the following lines of code:
Original code line:
ActiveDocument.Bookmarks("TEST").Range.InlineShapes.AddPicture FileName:=ThisDocument.path & "\images\Thrombolysis.jpg" ActiveDocument.Bookmarks("TEST2").Range.InlineShapes.AddPicture FileName:=ThisDocument.path & "\images\slide_deck.jpg"

New code:
ActiveDocument.Bookmarks("TEST").Range.InlineShapes.AddPicture FileName:=ActiveDocument.path & "\Thrombolysis.jpg" ActiveDocument.Bookmarks("TEST2").Range.InlineShapes.AddPicture FileName:=ActiveDocument.path & "\slide_deck.jpg"


text:
Q: for loop variable changing faster than changing css in setInterval I wrote this function to show flashing lights for a Simon game that I'm making. The flashing part is working, but I'm trying to play a sound every time move.color.backgroundColor === colors[0], which is the highlighted color. The array is being looped over too fast for me to do this and I've been getting several different errors trying to solve this different ways, including all the sounds going off before the flashing has finished because the for loop variable finished looping faster than the variables showed flashing and then breaking the flashing function, even though its supposed to go at 1 second per loop. Here is the code -
game.computerMoves = {green, blue, blue, red, red, yellow};

const colors = [
 new Map([[green, "lime"], [yellow, "#FF6"], [blue, "dodgerblue"], [red,               "salmon"]]),
 new Map([[green, "green"], [yellow, "#CC0"], [red, "red"], [blue, "blue"]])
];

const sounds = {
 green : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
 blue : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"),
 yellow : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
 red : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3")
};

game.computerMoves = {green, yellow, yellow, blue, red, red};

const colorFlashPeriod = 1000; // in ms

function showMoves() {
 let moveCounter = 0;
 const timeoutCount = game.computerMoves.length * 2;
 (function nextColor() {
   //this variable was finished looping before the backgroundColor finished flashing and it incremented faster than 1 second per loop. The flashing was shown at the correct times though, but I can't use this to set keys to add sounds
    let move = game.computerMoves[moveCounter >> 1];
    let c = game.computerMoves[moveCounter]
    console.log(c.id);
    move.style.backgroundColor = colors[(moveCounter++) & 1].get(move);
    if (moveCounter < timeoutCount) { setTimeout(nextColor, colorFlashPeriod) }
 })();
}

I also rewrote the showMoves function to flash lights into a working version here
function showMoves() {
  let i = 0;

const start = setInterval(function() {
  if (i >= game.computerMoves.length) {
      clearInterval(start);
      return;
  }

  const move = game.computerMoves[i];
  setLight(move, true);
  setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments

  i++;
 }, 2000);
}

function setLight(color, isOn) {
  if(isOn){
sounds[color.id].play();
 }
   color.style.backgroundColor = isOn ? colors[0].get(color) : colors[1].get(color);
}

This version of is working how I want it to and playing the sounds at the right flashing times, but I'm not sure if its better designed than the showMoves function above it that I can't figure out how to get the sound to work on. I would appreciate any help with this.
Here is the full code, but you have to activate the functions in the console to see the problem. randomMoves(num) to set the random array for showMoves() to see the flashing lights where I'm having my problem.:

const simonHTML = {
    power : document.querySelector('.powerButton'),
    strictButton : document.getElementById('strict'),
    startButton : document.getElementById('start'),
    displayScore : document.getElementById('score'),
    colors : document.getElementsByClassName('color')
  }

  const game = {
    on : false,
    start : false,
    strict : false,
    score : 0,
    computerMoves : [],
    playerMoves : [],
    colors : [greenBox = document.getElementById('green'),
    blueBox = document.getElementById('blue'),
    yellowBox = document.getElementById('yellow'),
    redBox = document.getElementById('red')]
  }

  //move the purple div back and forth
  function turnOn () {
      if(!game.on){
        simonHTML.power.classList.add('moveRight');
        simonHTML.power.classList.remove('moveLeft')
        game.on = true;
        simonHTML.displayScore.textContent = game.score.toString();
    }
    else if(game.on){
        simonHTML.power.classList.remove('moveRight');
        simonHTML.power.classList.add('moveLeft');
        game.on = false;
        simonHTML.displayScore.textContent = '-';
    }
  }

  function randomMoves (num) {
    for(let i = 0; i < num; i++){
      let moves = game.colors[Math.floor(Math.random() * game.colors.length)]
      game.computerMoves.push(moves);
    }
    return game.computerMoves;
  }

  function resetMoves () {
    game.computerMoves = [];
  }

const colors = [
  new Map([[green, "lime"], [yellow, "#FF6"], [blue, "dodgerblue"], [red, "salmon"]]),
  new Map([[green, "green"], [yellow, "#CC0"], [red, "red"], [blue, "blue"]])
];

const sounds = {
  green : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
  blue : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"),
  yellow : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
  red : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3")
};

const colorFlashPeriod = 1000; // in ms

function showMoves() {
    let moveCounter = 0;
    const timeoutCount = game.computerMoves.length * 2;
    (function nextColor() {
        let move = game.computerMoves[moveCounter >> 1];
        let c = game.computerMoves[moveCounter]
        console.log(c.id);
        move.style.backgroundColor = colors[(moveCounter++) & 1].get(move);
        if (moveCounter < timeoutCount) { setTimeout(nextColor, colorFlashPeriod) }
    })();
}

function playerMoveDown(e){
  e.target.style.backgroundColor = colors[0].get(e.target);
  let color = e.target.id;
  sounds[color].play();
  return game.playerMoves.push(e.target);
}

function playerMoveUp(e){
  e.target.style.backgroundColor = colors[1].get(e.target);
}

for (let i = 0; i < simonHTML.colors.length; i++){
  simonHTML.colors[i].addEventListener('mousedown', playerMoveDown);
  simonHTML.colors[i].addEventListener('mouseup', playerMoveUp);
}

simonHTML.power.addEventListener('click', turnOn);
*{
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    margin: 0;
 padding: 0;
}

.flex-row{
    width:100%;
  height:100%;
  display:flex;
  flex-direction:row;
}

 .center-options{
    align-self:center;
    display:flex;
    flex-direction:column;
    align-items:center;
}

body{
    background-color: gray;
}

.centered {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.outer{
    height: 30em;
    width:30em;
    background-color:rgba(21, 56, 41, 1);
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    border-radius: 50%;
    border-style: solid;
    border-width: 10px;
    box-shadow: 0px 0px 12px #222;
}

/*=============Color buttons=================*/

.color{
    flex-grow:1;
    flex-shrink: 1;
    flex-basis: 50%;
    position: relative;
    cursor:pointer;
}

#green{
    background-color:green;
    border-bottom-left-radius: 100%;
    border-top: 10px solid;
    border-right:5px solid
}

#blue{
    background-color:blue;
    border-top-left-radius: 100%;
    border-right:5px solid
}

#yellow{
    background-color:rgb(204,204,0);
    border-bottom-right-radius: 100%;
    border-top: 10px solid;
    border-left:5px solid;
}

#red{
    background-color:red;
    border-top-right-radius: 100%;
    border-left: 5px solid;
}

/*=============Controller=================*/

#controller{
    z-index: 1;
    height:14em;
    width:14em;
    border-radius:100%;
    background-color:gray;
    border: 10px solid;
    display:flex;
    align-items:center;
    flex-direction:column;
}

#controller h3{
    margin-top:1em;
    align-self: center;
    font-size: 30px;
}

.options{
  margin-top: .5em;
  justify-content:space-evenly;
}

.on-circle{
  width: 20px;
  height: 20px;
  background-color:red;
  border: 3px solid black;
  border-radius:100%;
  box-shadow: 0px 2px 3px #222;
  cursor: pointer;
}

/*===============off-on================*/

#onOff{
  height:100%;
  width:100%;
  justify-content:space-evenly;
}

#onOff h4:nth-of-type(1) {
  margin-top:5px;
  margin-left:20px;
}

#onOff h4:nth-of-type(2) {
  margin-top:5px;
  margin-right:20px;
}

#onOff > div {
  height:2em;
  border-radius:10%;
  width:4em;
  background-color:#404040;
}

#onOff > div > div {
  height:100%;
  width:35%;
  background-color:purple;
  margin-left:1px;
  border-radius:10%;
  border:3px solid black;
  cursor: pointer;
}

.moveRight{
    transition: all .2s linear;
    transform: translateX(2.5em);
}

.moveLeft{
    transition: all .2s linear;
    transform: translateX(0);
}
<!DOCTYPE html>

        <meta charset='utf-8'>
        <title>Simon Game</title>
        <link rel='stylesheet' href='./main.css'>

Simon

Score

-

Start

Strict

Off

On


text:
Q: how to check validation mongodb id with php i get mongodb id of query string. how to check validation this id? i want if mongodb id not valid redirect to another url
get query string:
    if(count($_GET)>0 && $_GET['uid']){

            //get id from string query
            $query = array("_id" => new MongoId($_GET

['uid']));
        $user = DB::findone('users',$query);

    }else{
        //redirect if not exist query string
        header('location:'.ADMIN_URL.'/items/forbidden.php');
    }

plz help...
thanks

A: In new PHP Mongo library https://github.com/mongodb/mongo-php-library the best way to check validity of a string is:
(thanks to Yii2 code https://github.com/yiisoft/yii2-mongodb/tree/master/src/validators)
   function isValid($value)
    {
        if ($value instanceof \MongoDB\BSON\ObjectID) {
            return true;
        }
        try {
            new \MongoDB\BSON\ObjectID($value);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

A: Since ext-mongo version 1.5 you can check it
if(isset($_GET['uid']) && MongoId::isValid ($_GET['uid'])) {
 // Your code here
}

php.net mongoid.isvalid


text:
Q: Package inputenc Error Unicode \u8 not set up for use with Latex only on OSX I'm running my CV, which is compiled by calling pdflatex then biber then pdflatex twice. I have a .bib file generated in Mendeley which biber is reading.
When I run this script on my Mac laptop, I get the Unicode \u8 not set for use with Latex error that has been referenced in many questions on this site. However, when I run the same exact code on my Linux Mint machine, I don't get any errors and everything compiles cleanly.
I hypothesize that it might have something to do with the version of biber that I am using (1.8 on my Linux machine, 2.1 on the Mac) but am at a bit of a loss on this one.
Please note: original version contained an additional question regarding the numbering, but I will move that to a new question. I made the edit so that someone browsing this question in the future is not confused.
MWE as follows (only works as two separate files):
MyPapers.bib
@unpublished{exampletwo,
author = {Last-name, Firstname and lname, En\'{e}as},
booktitle = {In Review},
title = {{Pick a Title}}
}
@inproceedings{exampleone,
author = {Jones, Jim and Example, Jos\'{e}},
booktitle = {Sustentabilidade H{\'{\i}}drica}},
year = {2014}
}

main.tex
\documentclass[11pt,letterpaper,roman]{moderncv}

% moderncv themes
\moderncvstyle{classic}
\moderncvcolor{blue}

\usepackage[utf8]{inputenc}% character

\usepackage{csquotes}

%---------------------Bibliography and BiBLaTeX--------------------
% Use BibLaTeX
\usepackage[backend=biber,
    sorting=ynt]{biblatex}

\DeclareFieldFormat{labelnumber}{\mkbibdesc{#1}}

\makeatletter

% Print labelnumber as actual number, plus item total, minus one
\newrobustcmd{\mkbibdesc}[1]{%
  \number\numexpr\csuse{bbx@itemtotal}+1-#1\relax}

% Initialize category counters
\def\bbx@initcategory#1{\csnumgdef{bbx@count@#1}{0}}
\forlistloop{\bbx@initcategory}{\blx@categories}

% Increment category counters
\def\bbx@countcategory#1{%
  \ifentrytype{#1}
    {\csnumgdef{bbx@count@#1}{\csuse{bbx@count@#1}+1}%
     \addtocategory{#1}{\thefield{entrykey}}%
     \listbreak}
    {}}
\AtDataInput{\forlistloop{\bbx@countcategory}{\blx@categories}}

% Modify \bibbycategory to set item total
\patchcmd{\blx@bibcategory}
  {\blx@key@heading{#1}}
  {\blx@key@heading{#1}%
   \csnumdef{blx@labelnumber@\the\c@refsection}{0}%
   \csnumgdef{bbx@itemtotal}{\csuse{bbx@count@#1}}}
  {}{}

\makeatother
\DeclareBibliographyCategory{unpublished}
\DeclareBibliographyCategory{inproceedings}

\defbibheading{bibliography}{\section*{Publications and  Presentations}}
\defbibheading{unpublished}{\subsection*{Articles In Review}}
\defbibheading{inproceedings}{\subsection*{Conference Papers}}

\addbibresource{MyPapers.bib}

%------------------------ personal data -------------------------------------
\name{Firstname}{Name}

\begin{document}
\makecvtitle

% Publications
\nocite{*} % count all pubs as cited
\printbibheading
\bibbycategory

\end{document}

A: During the processing and sorting biber converts a number commands for accented chars to "glyph + combining accent", in you case "i + COMBINING GRAVE ACCENT (U+0300)".
pdflatex can't handle such "combining accents" and so you get an utf8-inputenc error. Unlike most other inputenc errors you can't correct it, you could only suppress the accent completly.
xelatex and lualatex can't handle them if the font hasn't the accent.
You can avoid the problem -- as cfr already wrote -- by using the correct glyph (Hídrica) in the input in the bib.
You can also avoid it by using biber --output-safechars. biber will then try to write such chars as macros to the bbl. You can also write your own recodedata and load it with biber --recodedata=myrecode.xml. With such a file you have full control about the output.

A: Using the unicode characters rather than LaTeX macros is more reliable in my experience. For example, the following compiles without error:
\begin{filecontents}{\jobname.bib}
@unpublished{exampletwo,
author = {Last-name, Firstname and lname, En\'{e}as},
booktitle = {In Review},
title = {{Pick a Title}}
}
@inproceedings{exampleone,
author = {Jones, Jim and Example, Jos\'{e}},
booktitle = {Sustentabilidade Hídrica}},
year = {2014}
}
\end{filecontents}
\documentclass[11pt,letterpaper,roman]{moderncv}

% moderncv themes
\moderncvstyle{classic}
\moderncvcolor{blue}

\usepackage[utf8]{inputenc}% character

\usepackage{csquotes}

%---------------------Bibliography and BiBLaTeX--------------------
% Use BibLaTeX
\usepackage[backend=biber,
    sorting=ynt]{biblatex}

\DeclareFieldFormat{labelnumber}{\mkbibdesc{#1}}

\makeatletter

% Print labelnumber as actual number, plus item total, minus one
\newrobustcmd{\mkbibdesc}[1]{%
  \number\numexpr\csuse{bbx@itemtotal}+1-#1\relax}

% Initialize category counters
\def\bbx@initcategory#1{\csnumgdef{bbx@count@#1}{0}}
\forlistloop{\bbx@initcategory}{\blx@categories}

% Increment category counters
\def\bbx@countcategory#1{%
  \ifentrytype{#1}
    {\csnumgdef{bbx@count@#1}{\csuse{bbx@count@#1}+1}%
     \addtocategory{#1}{\thefield{entrykey}}%
     \listbreak}
    {}}
\AtDataInput{\forlistloop{\bbx@countcategory}{\blx@categories}}

% Modify \bibbycategory to set item total
\patchcmd{\blx@bibcategory}
  {\blx@key@heading{#1}}
  {\blx@key@heading{#1}%
   \csnumdef{blx@labelnumber@\the\c@refsection}{0}%
   \csnumgdef{bbx@itemtotal}{\csuse{bbx@count@#1}}}
  {}{}

\makeatother
\DeclareBibliographyCategory{unpublished}
\DeclareBibliographyCategory{inproceedings}

\defbibheading{bibliography}{\section*{Publications and  Presentations}}
\defbibheading{unpublished}{\subsection*{Articles In Review}}
\defbibheading{inproceedings}{\subsection*{Conference Papers}}

\addbibresource{\jobname.bib}

%------------------------ personal data -------------------------------------
\name{Firstname}{Name}

\begin{document}
\makecvtitle

% Publications
\nocite{*} % count all pubs as cited
\printbibheading
\bibbycategory

\end{document}

and produces the expected output:

Don't ask me why it is fine with the e and not the i. I have no idea ;).


text:
Q: How to show a component n times in React Native I have a flatlist that shows some firebase docs, every doc contains a name and a value, I need to show that name n times, where n=value.
<FlatList
               data = {WorkoutList}
               keyExtractor={(item) => item.id}
               renderItem={({item}) =>
                        <View>
                          <Text large light>{item.name}</Text>
                          <Text large light>{item.value} x</Text>
                        </View> }
/>

This will show
Paul
3
Mark
2
Luke
1

I want to use the value informations to show this
Paul
Paul
Paul
Mark
Mark
Luke

How can I show the 'item.name' text for 'item.value' times?

A: Create another list and loop trough your initial one. Add to the list your data n according to the value. Use then the new list instead of your inital one.

const list=[]

WorkoutList.map(i=>{

  const {id, name, value}=i

  for (let i = 0; i <= value; i++) {
    list.push({name, value:i,id:`${id}_${i}`})
  }

  return i
})

<FlatList
               data = {list}
               keyExtractor={(item) => item.id}
               renderItem={({item}) =>
                        <View>
                          <Text large light>{item.name}</Text>
                          <Text large light>{item.value} x</Text>
                        </View> }
/>


text:
Q: Current change through Series resistors My question surrounds a simple scenario.
I have a 12V DC power source connected to 2.2kΩ/10kΩ/22kΩ resistors in series.
For an assignment, I have theoretically calculated Voltage drops across all resistors, as well as respective current draw for each resistor.  I am aware that the current entering a resistor should be the same as coming out.
I have simulated the circuit in Circuit Wizard (Uni assigned software package), and found that after each resistor the current drops fractionally.
For example - The Total Circuit resistance is detailed as 350.97microA.
Then:
Through 2.2kΩ - drops to 350.92MicroA
Through 10kΩ - drops to 350.88MicroA
Through 22kΩ - drops to 350.86MicroA
Obviously - the difference between my calculated values and the simulated values is only around 0.02%.. However I wouldnt expect the current to change.
When I increase voltage on the power supply - to signifcantly larger values (50V+) - current measurements remain as expected.
Am I right in presuming that this is due to the impedance thats been calibrated into this digital Ammeter?
Im drawing conclusions and this is the only thing I can think of.

A: If the discrepancy was caused by some high resistance to ground that the simulator adds to aid convergence or because of the ammeter burden resistance then the same errors (as a percentage of the current) should occur even at higher voltages. Since the discrepancy did not occur at higher voltages I am suspecting some kind of numerical problem in the simulation calculations, perhaps as simple as roundoff error for very small values of current.


text:
Q: Unit test: Program ended with exit code: 82 App consist from modules My app consists from modules(frameworks) and i use pods for add third party framework. In pod file i add dependency for some lib only for target  that will be use this framework. Example:  i have "Acount.framework" and it use lib for keychain access and other modules dont know about it.  So in pod file i write
def userAccount_pods
    project '../UserAccount/UserAccount.xcodeproj'
    workspace '../UserAccount/UserAccount.workspace'

    pod 'Valet'
end
target 'UserAccount' do
    userAccount_pods
end
target 'UserAccountTests' do
    userAccount_pods
end

Also i have other framework  -"Logic.framework" and it use acount framework(in the his build setting i add  binary link)  and all working perfect. But i have some trouble with unit tests.
My tests for "logic framework" use "user account" (inside methods)
and i have log:
The bundle "logicTest" couldn't be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle.
Library not loaded: @rpath/Valet.framework/Valet
Referenced from: Acount
Program ended with exit code: 82

I know that for fix it i can add pod "Valet" in target - logicTest  but i  find it strange.
Please help me find elegant solution
Thanks averyone in advance


text:
Q: Kadmin can not create principle but kadmin.local can I am enabling security mode on Cloudera 5 beta. with cloudera manager and after performing 8th step of security enabling document from here cloudera manager should fire Generate Credential command but it is not.
so what i am doing is to run the Generate Credential manually but it is giving me error inlogs ie.
KADMIN='kadmin -k -t /etc/cloudera-scm-server/cmf.keytab -p cloudera-scm/admin@IMP.CO.IN -r IMP.CO.IN'
+ kadmin -k -t /etc/cloudera-scm-server/cmf.keytab -p cloudera-scm/admin@IMP.CO.IN -r IMP.CO.IN -q 'addprinc -randkey hue/cdh4hdm@IMP.CO.IN'
WARNING: no policy specified for hue/cdh4hdm@IMP.CO.IN; defaulting to no policy
add_principal: Operation requires ``add'' privilege while creating "hue/cdh4hdm@IMP.CO.IN".
+ kadmin -k -t /etc/cloudera-scm-server/cmf.keytab -p cloudera-scm/admin@IMP.CO.IN -r IMP.CO.IN -q 'xst -k /tmp/cmf4198733808580266866.keytab hue/cdh4hdm@IMP.CO.IN'
kadmin: Operation requires ``change-password'' privilege while changing hue/cdh4hdm@IMP.CO.IN's key
+ chmod 600 /tmp/cmf4198733808580266866.keytab
chmod: cannot access `/tmp/cmf4198733808580266866.keytab': No such file or directory

it seems that kadmin can not create principle.
my question is how can i give kadmin add principle privilege or how can i run this command using kadmin.local?
is there any way so i can get out of from this problem...

A: Some configuration are needed for providing a user principal to create any principle by using kadmin.
One has to edit kadm5.acl file and add below entry in kadm5.acl file:
*/admin@EXAMPLE.COM

Here * represents the wildcard, So the user principal who matches the string as provided in kadm5.acl will be able to create any principal for example:
root/admin@EXAMPLE.COM

After changing configuration one need to restart the Kerberos for taking the changes in effect. For more details refer this

A: I had the same problem and got solved by starting the kadmind service.


text:
Q: Quick Way to Bluk Copy Azure Blobs I have about 40,000 blobs in azure storage, they have been given the wrong file extension. They have been uploaded with the filename <name>.png and I need to correct the name to <name>.jpg. In the 1st instance I'd like simply copy the originals into the same blob store but with a new file name.
azcopy would normally be my go to for this kind of thing, but it doesn't seem to have the options I need.
How can I bulk copy and rename files in an azure blob store?

A: Azure Blob Storage doesn't support renaming directly. However, you can work it around by copying the blob to a new blob with modified name (by StartCopy method), and removing the original blob (by Delete method). The copy procedure can be pretty fast if the source and destination is under the same storage account since it's actually a shallow copy.


text:
Q: How can I build sums of values from DataTables in vb.net? I'm using VB.Net to retrieve data from a database, do some calculations, and then show this data in a datagridview. I already imported the data from the database into a DataTable in my software. So far so good.
Now I want to add up values from columns where another column in the same row has a specific text.
Here's an example. I have data (in the DataTable) in the following form:
Date         //   type       //   value
10/09/2020   //   value80    //   92
10/09/2020   //   value71    //   5
10/09/2020   //   value63    //   2
10/07/2020   //   value80    //   85
10/07/2020   //   value71    //   10
10/07/2020   //   value63    //   1

I want to build the sum of the 3 type values, where "value80", "value71" and "value63" are from the same date. The new variable value_sum should be calculated such that for 10/09/2020:
value_sum = value80 + value71 + value63 = 92 + 5 + 2 = 99

and for 10/7/2020:
value_sum = value80 + value71 + value63 = 85+ 10 + 1 = 96

How can I calculate the new values in order to save them in another DataTable?

A: In the Linq query we Group By the date field and select the date and the sum. See https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/queries/group-by-clause There is a .CopyToDataTable method (https://learn.microsoft.com/en-us/dotnet/api/system.data.datatableextensions.copytodatatable?view=netcore-3.1) but I don't know if or how it works with anonymous types. It is easy enough to just loop through the query result and  add the rows to the new DataTable.
Private Sub OPCode()
    'Create original DataTable with your sample data
    Dim dt As New DataTable
    dt.Columns.Add("ValueDate", GetType(Date))
    dt.Columns.Add("Type", GetType(String))
    dt.Columns.Add("Value", GetType(Integer))
    With dt.Rows
        .Add(#10/09/2020#, "value80", 92)
        .Add(#10/08/2020#, "value71", 5)
        .Add(#10/09/2020#, "value85", 2)
        .Add(#10/07/2020#, "value80", 85)
        .Add(#10/07/2020#, "value71", 10)
        .Add(#10/07/2020#, "value63", 1)
    End With
    'Select the date groups and sum by group
    Dim TotalsByDate = From row In dt.AsEnumerable
                       Group By DateValue = row.Field(Of Date)("ValueDate")
                           Into Dates = Group, Sum(row.Field(Of Integer)("Value"))
                       Select DateValue, Sum
    'Prepare a new DataTable
    Dim dt2 As New DataTable
    dt2.Columns.Add("DateGroup", GetType(Date))
    dt2.Columns.Add("DateSum", GetType(Integer))
    'Fill the new DataTable
    For Each item In TotalsByDate
        dt2.Rows.Add(item.DateValue, item.Sum)
    Next
    'Display results
    DataGridView1.DataSource = dt2
End Sub


text:
Q: packrat restore when switching between git branches with different packages I'm making large changes to an R project on a different git branch which includes changes to packrat packages and versions. When I switch back to the original master branch after making those changes, I need to run packrat::restore() to get back to the original project state because I am only tracking the packrat.lock file. Then, if I switch back to the development branch I have to run packrat::restore() again to pick up where I left off with the new changes.
Do I have this correct? Can you suggest a better workflow that eliminates the need to run packrat::restore() which can take a lot of time?
This also makes it difficult to schedule jobs to run automatically from the master branch. I have to make sure to switch to the master branch and run packrat::restore() before scripts are scheduled to run, and I can't work on the development branch while the background jobs are running.


text:
Q: Can't add event to Week View using Date from API Response My API puts in MongoDB a BsonDateTime. I receive two Dates from this API called startDate and endDate but I can't add an event to Week View with it. When I convert startDate to String, it writes Mon May 14 08:00:00 GMT+01:00 2018.
This is the content in Postman:
[
{
    "Id": "5b51ab5ad09030396092b0cd",
    "userId": "5b56f3c714e86f36e0433359",
    "company": "Empresa 2",
    "year": "2015",
    "month": "May",
    "day": "15",
    "weekDay": "Tuesday",
    "shift": "Morning",
    "weekDayId": "2",
    "shiftId": "1",
    "hours": "8",
    "startDate": "2018-05-14T07:00:00Z",
    "endDate": "2018-05-14T16:00:00Z"
}
]

And this is my code in Android Studio:
 public void updateEvents() {
    weekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
        @Override
        public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {

            Thread.currentThread().interrupt();

            APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
            Call<Schedule[]> call = apiInterface.getScheduleByUserID("5b56f3c714e86f36e0433359");
            call.enqueue(new Callback<Schedule[]>() {
                @Override
                public void onResponse(Call<Schedule[]> call, final Response<Schedule[]> response) {

                    start = response.body()[0].getStartDate();
                    end = response.body()[0].getStartDate();
                    Toast.makeText(DiaHorarioActivity.this, start.toString(), Toast.LENGTH_SHORT).show();
                    Toast.makeText(DiaHorarioActivity.this, end.toString(), Toast.LENGTH_SHORT).show();

                   Calendar startTime = new GregorianCalendar();
                    startTime.setTime(start);
                    Calendar endTime = (Calendar) startTime.clone();
                    endTime.setTime(end);
                    WeekViewEvent event = new WeekViewEvent(1, "test", startTime, endTime);
                    event.setColor(getResources().getColor(R.color.cardRejeitar));
                    events.add(event);

                }

                @Override
                public void onFailure(Call<Schedule[]> call, Throwable t) {
                    Toast.makeText(DiaHorarioActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            });

           Thread.currentThread().run();

            return events;
        }
    });
}

The event doesn't appear anywhere. Please help.


text:
Q: How to make a new window the size of the selected image I am currently attempting to make a brand new window that is at minimum the size of the selected image. In addition, I  am attempting to zoom in/out of the image, and scroll up/down and side to side.
This is how I created my form.
Form form = new Form();
form.Text = "Image Viewer";
PictureBox pictureBox = new PictureBox();
pictureBox.Image = imageClicked;
pictureBox.Dock = DockStyle.Fill;
form.Controls.Add(pictureBox);
form.ShowDialog();

A: You could do:
        Form form = new Form();
        form.Text = "Image Viewer";
        form.AutoSize = true;
        form.AutoSizeMode = AutoSizeMode.GrowAndShrink;

        PictureBox pictureBox = new PictureBox();
        pictureBox.Image = imageClicked;
        pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
        pictureBox.Location = new Point(0, 0);

        form.Controls.Add(pictureBox);
        form.ShowDialog();

A: I would guess you could use the imageClicked size
        Form form = new Form();
        form.Size = img.Size;
        form.Text = "Image Viewer";
        PictureBox pictureBox = new PictureBox();
        pictureBox.Image = img;
        pictureBox.Dock = DockStyle.Fill;
        form.Controls.Add(pictureBox);
        form.ShowDialog();


text:
Q: All convolution powers exist in $\ell^2$. Does the convolution theorem still hold? What I have here is a sequence $c\in\ell^2(\mathbb Z^2)$ for which each convolution power $c*\ldots*c$ exists and is contained in $\ell^2(\mathbb Z^2)$, too. It is clear from $c\in\ell^2(\mathbb Z^2)$ that $c^{[2]} = c*c$ is contained in $\ell^\infty(\mathbb Z^2)$, but I actually know that $c^{[2]}\in\ell^2(\mathbb Z^2)$. Same for $c^{[3]} = (c*c)*c$ and so on...
Clearly the class of these sequences $c$ contains $\ell^1(\mathbb Z^2)$. But is it larger? In addition, I know that there exists some $n$ such that $c^{[n]}$ is a basis vector $e_m$.
What I would like to have is that $\widehat{c^{[n]}} = \hat c^n$ (convolution theorem), where $\hat d$ is the DTFT of $d\in\ell^2(\mathbb Z^2)$, i.e.,
$$
\hat d(x) = \sum_{k\in\mathbb Z^2}d_ke^{-2\pi i\langle k,x\rangle},
$$
and that $\hat c$ is continuous (which both would be true if $c\in\ell^1(\mathbb Z^2)$).
Any idea anyone?


text:
Q: How do I delete Internet Explorer and Microsoft Edge? How do I delete Internet Explorer and Microsoft Edge? When I go to settings, I didn't see any apps. I looked at where it says systems and there were none there either. Nothing was there that looked like this:
enter image description here

A: These utilities can never be fully deleted, only disabled, as they use Windows
components. Microsoft will soon replace Edge by a Chromium version, so perhaps
it is not worth disabling.
Disable Microsoft Edge

*

*Go to C:\Windows\SystemApps

*Locate the Microsoft Edge folder. Mine is Microsoft.MicrosoftEdge_8wekyb3d8bbwe

*Save the name of the folder, as you will need it to re-enable the app

*Rename the folder

*Click Continue if asked.

To re-enable Edge, give the folder its original name back.
Disable Internet Explorer 11

*

*Go to Control Panel > Programs > Programs and Features

*Click Turn Windows features on or off

*Clear the checkbox next to "Internet Explorer 11"

*Click Yes and OK and reboot.


text:
Q: Activar función, removerla y volverla a activar Hice un scroll infinito (no tengo problema con eso, todo funciona bien) pero tengo una función llamada addCardFilter(), esta sirve para agregar productos al carrito de compras (tampoco tengo problema con eso, funciona perfectamente). Mi problema es que cuando voy haciendo scroll la función se llama varias veces, y cuando agrego un producto al carrito esta se agrega dependiendo de la paginación del scroll, es decir, si hice scroll y llamé dos veces a la petición Ajax, el producto se agrega dos veces.
Lo que quiero es que la función solo se llame una vez; ya lo hice sacando la función addCardFilter() fuera, pero si lo hago de esa manera, cuando hago scroll ya no se agrega al carrito porque tengo que llamar la función addCardFilter() cada vez que haga la petición Ajax.
Lo que quisiera es saber si existe una manera de llamar la función addCardFilter(), hacer el scroll, hacer la petición ajax, después quitarla y llamarla otra vez, pero que se ejecute solo una vez al ir haciendo scroll.
let pagina = 0;
let ultimoProducto;
cargarProductos(pagina);

let observador = new IntersectionObserver((entradas, observador) => {
  entradas.forEach(entrada => {
    if (entrada.isIntersecting) {
      pagina++;
      cargarProductos(pagina);
    }
  })
}, {
  rootMargin: '0px  0px 200px 0px',
  threshold: 1.0
})

  var totalRecord = pagina;
  var totalData = $("#totalRecords").val();
  $.ajax({
    type: 'POST',
    url: base_url + '/Tienda/fil',
    dataType: "json",
    data: { totalRecord: totalRecord },
    success: function (data) {
      $("#results").append(data.products);
      if (totalRecord <= totalData) {
        if (ultimoProducto) {
          observador.unobserve(ultimoProducto);
        }
        let productosEnPantalla = document.querySelectorAll('.contenedor .producto');
        ultimoProducto = productosEnPantalla[productosEnPantalla.length - 1];
        observador.observe(ultimoProducto);
        addCartFilter();
      }
      totalRecord++;
    }
  });
}```


text:
Q: How to use application.yml file from my sub modules? Hi I am working on a spring boot application which contains multiple apps and multiple modules.
Folder structure is like this
project
       - apps
         - app1
         - app2
       - modules
         - module1
         - module2

each modules have their own resource application-module{number}.yml file.
Now I am using these module1 and module2 in my app1 which is a spring boot application.
app1 have application.yml file which contains this
spring:
    profiles:
      include: >
          module1,
          module2

I also added EnableConfigurationProperties({Module1Config.class, Module2Config.class}) after @SpringBootApplication in my application file of app1. Still configuration are not getting picked up.
If I am putting those modules config in app1 llike
app1
   - resources
        - application.yml
        - application-module1.yml
        - application-module2.yml

then it is working. But I want to use those from my modules only.. How can I do that???

A: Oh I did it somehow...
I added one application.yml file in module1 resource folder with content
spring:
    profiles:
       include: >
          module1

similarly in module2
spring:
     profiles:
         include: >
            module2

It's working now... thanks to me... :)


text:
Q: regex.test() function not giving proper result I think I can explain my doubt by showing the code instead of exlpaining it::
HTML:
<!DOCTYPE html>

        <title>Building Web Page for Client</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="css.css">

        <form>
            Enter the banner Message:
            <input type="text" name="userMessage" id="message" maxlength="32">

            Enter the Zip Code:
            <input type="text" name="userZip" id="zipcode" maxlength="5">

        </form>

Javascript::
//Code block for element declarers for special function checkers
var inputList = document.getElementsByTagName('input');
var zipField = document.getElementById('zipcode');
var regexForZip = /^\d{5}$/;
zipField.onblur = zipChecker;

function zipChecker(){
    if(checker1 && checker2){
        if(!(regexForZip.test(zipField)))
            inputList[1].nextElementSibling.textContent = 'You can only enter numbers';
        else
            inputList[1].nextElementSibling.textContent = '';
    }
}

Now, the HTML is pretty simple , and the javascript even simpler. Now, can you look at the checker1 and checker2 booleans? Both of those are true(Sorry about not including them in this code, the code is a bit large).
I defined a regular expression which will ONLY contain 5 digits, nothing else. Now what I do is I try to take the second input element, and whatever the user enters, I check that for only 5 digits. By the code, if the input doesn't match the regular expression, the next  tag will have a text prompting the user, otherwise, it will be empty.
NOTE: For this case, the input will be 5 characters long.
Now here is the problem: No matter what I give as the input, the page prompts me to only enter numbers, which doesn't makes sense. Suppose, I enter 11111. It tells me what it should have told me if I entered any other character than a number.
What's the problem in this?

A: You are running your RegExp against a DOM Element
if (!regexForZip.test(zipField))

What you might want to test for is the value of the element, which is a string:
if (!regexForZip.test(zipField.value))


text:
Q: Does HTML conform to the XML specification? HTML and XML are syntactically very similar, so what I want to know is if valid HTML code will always conform to the XML specification.

A: No, it won't.
HTML 2 through 4.x were SGML applications, not XML applications. (HTML+ might also have been an SGML application, it isn't clear from a brief skim of the specification)
HTML 5 has its own parse rules.
(XHTML and the XML serialisation of HTML 5 will be XML though)

A:
Does HTML conform to the XML specification?

No, it does not. HTML supports:

*

*unclosed tags (e.g.  instead of )

*wrongly nested tags (e.g. bla instead of bla)

*unquoted attributes (e.g. ...)

*contents that is not propery encoded (e.g. this & that instead of this & that)

*tags that explicitly must contain unencoded content (i.e.


text:
Q: Do we need to define Option(Maybe) in TypeScript? In the context of Functional Programming, I want to have the capabilities of Option or Maybe from Scala, Haskell in TypeScript.
I can simply define Option below with TS compiler option strictNullChecks turned on:
type Option<A> = A | null

While in Haskell, PureScript, ... it is defined like
type Option<A> = Some<A> | None
type Maybe<A> = Just<A> | Nothing

In order to benefit from the concept, Do I have to wrap my value in Some or Just and define a separate Symbol for null, or is what I typed above is enough?

A: I would define it as
type Option<T> = {value: T} | null;

This way it does not become ambiguous when null is a possible value of type T (as pointed out in the comments) and you can use it as follows:
if (myValueOfOptionType) {
  console.log(myValueOfOptionType.value);
}

A: I try to answer my question with my findings.
If our initial type already has null value in it, we would have a problem. Take a look at the different paths to return values in the function below. Imagine Integer is a set of all Integer values. Then look into where I used null and just(null):
function divide2IfEven(x: Integer): Option<Integer | null> {
  if (x % 2 === 0) {
    if (x === 0)
      return null
    else
      return just(2 / x)
  } else {
    return just(null)
  }
}

Here I am distinguishing between the result of calculation and error. I'm considering divide by zero an illegal operation, but output for odd numbers to be absence of an answer, but not an error.
This is why it is a better to wrap the value in an object like in Some or Just.


text:
Q: Server Ram Full when I Call PHP Api from mobile For a android app I create apis to get data from server. But server ram become full when I run my app. I follow this steps...
connection:
include("connection.php");
$mysqli->query("SET NAMES 'utf8'");

Query:
$sql1="SELECT ...";
$result1 = $mysqli->query($sql1);

Close Connection:
$mysqli->close();

One example of my queries:
 $sql1="SELECT user_id FROM user_table WHERE email like '$email'";
 $result1 = $mysqli->query($sql1);
 if ($result1->num_rows > 0) {
    // output data of each row
   while($row = $result1->fetch_assoc()) {
     $user_id=$row["user_id"];
   }
}

Normally I select 20 to 50 rows from 100 to 200 rows.
Is there any problem of my code that can be responsible for ram overflow.
Thanks.


text:
Q: Unable to run UDF on hive server I'm running hive in thrift server mode. I have a UDF in a jar file that I'm trying to use by running
add jar <path to jar>
create temporary function func_name as 'com.test.udf.UDF_CLASS'

However, when I run the create temporary function command I get an error

Query returned non-zero code: 9, cause: FAILED: Execution Error,
  return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask

I've checked that the name & path of the jar and that the user running the hive server has all the correct permissions to access the jar. What is weird is if I run hive in CLI mode and run the exact same commands, then everything works. Any ideas on why hive CLI may be behaving differently from the hive thrift server?

A: Fixed the problem using the following steps:
1) Place each UDF jar in /usr/lib/hive/auxlib
2) Specify the path to each jar in hive-site.xml for the hive.aux.jars.path property (ex: file:///usr/lib/hive/auxlib/jar1.jar,file:///usr/lib/hive/auxlib/jar2.jar)
3) Create a script to make a thrift request to the hive server to run create temporary function func_name as 'com.test.udf.ClassName' for each UDF after the hive server is started
Edit: For Hive 0.9 no matter what I did, Hiveserver couldn't find jars in the auxlib directory. To get this to work on Hiveserver 0.9 I had to just dump the jar in the directory specified by Hive's classpath.

A: After playing with this for awhile I got it to work by putting the .class file into a directory structure that matches it's package, and adding it to the .jar from there. For reference I've included the whole process, including compiling and inserting into hive.

*

*I used the UDF example here

*Compile it: javac -classpath $CLASSPATH Lower.java. Note: the CLASSPATH was defined like this: CLASSPATH=$(ls $HIVE_HOME/lib/hive-serde-*.jar):$(ls $HIVE_HOME/lib/hive-exec-*.jar):$(ls $HADOOP_HOME/hadoop-core-*.jar), as described here.

*Copy the .class file to a folder com/example/hive/udf/

*Added it to a jar with this command: jar -cf lower.jar com/example/hive/udf/Lower.class

*Verify that the package looks right: jar -tf lower.jar. You should see a line like this: com/example/hive/udf/Lower.class.

*Import the jar into hive. add jar lower.jar; create temporary function my_lower as 'com.example.hive.udf.Lower';

A: You can also do by passing the --auxpath option to the hive command
hive --auxpath /path-to-/hive-examples.jar
or
by setting the HIVE_AUX_JARS_PATH environmental varialble.


text:
Q: Optimize counting in an array I think my code could be done better ...
What I want:
array a = ([1,2,3],[4,5,6],[7,8,9])
array b = ([2,3,4],[2,2,2])

Euclidean distance from  a[0] to b[0] and b[1] and then the minimum of that and so on with the other values...
Result should be something like that
result = ([1,2])

I think the way I did it is a little bit complicated:
result = [0]*len(b)
for i in a:
    c = 0
    minimum = euclid(a[0],b[0])
    place = 0
    for j in b:
        c=c+1
    if (minimum > euclid(i,j)):
          minimum = euclid(i,j)
          place = c
    result[place-1] = result[place-1]+1

ok well i try to explain it better. I have got two array A and B Array A have got 3 Values (Value <=> [1,2,3]) Now i want to calculate the euclidean distance of All Values of A with all values of B and Count how often B[0] or B[1] was the minimum.
so i start the code manual:
At first i calculate a[0] with b[0] and found out that thats the minimum because there is no minimum at the moment. At next i calculate a[0] with b[1] and found out that euclidean(a[0],b[1]) < euchlidean(a[0],b[0]) so i set the array wich is at the moment at c([0,0]) to c([0,1]). Next i calculate the euclidean distance a[1] to b[0] and b[1] and found out that b[0] ist the minimum of this two values so i set c to c([1,1])...

A: I believe what you are saying is that you have two lists of points - a & b. For each point in a, increment a counter for whichever point in b is the closest (minimum euclidean distance). Is that correct?
Here's how I would achieve that:
results = [0] * len(b)
for p_a in a:
    dists = [euclid(p_a, p_b) for p_b in b]
    min_index = dists.index(min(dists))
    results[min_index] += 1


text:
Q: Extjs Using actioncolumn to make radiocolumn not working I try to make a radio column using actioncolumn in http://jsfiddle.net/WAZah/
here is my items in actioncolum
             items: [{
                 icon:'',
                 //renderer: function (val, metadata, record) {
                 getClass: function(value,metadata,record){
                     //alert(record.get('check'));
                     var knowledge = record.get('check');
                     if (knowledge == 1 ){
                        return 'radio-col-on';
                         //metadata.css = 'radio-col-on'
                     } else {
                         return 'radio-col-off';
                         //metadata.css = 'radio-col-off'
                     }
                 }
             }]

and my css
.x-action-col-cell img.radio-col-on {
    background-image: url('http://compare-gap-insurance.co.uk/wp-content/uploads/2012/10/Vista_radio-button_general1.jpg') !important;
}
.x-action-col-cell img.radio-col-off {
    background-image: url('http://www.uams.edu/safety/images/Radio-button.jpg') !important;
}

How can i make that work thanks.

A: You're returning a css class name which gets applied to the image, but you have no image (or at least not one that's rendered large enough to see).  If you add an icon image such as a transparent spacer gif of the same size as your radio button image, this should work.
I suggest that you might want to use the suggestion from @Reimius though.  You could actually create a real radio button in the cell if you use a regular column and a renderer.
At any rate, here's code that seems to work for your example:
items: [{
    icon:'/url/path/to/a/transparent/spacer.gif',
    getClass: function(value,metadata,record){
        var knowledge = record.get('check');
        if (knowledge == 1 ){
            return 'radio-col-on';
        } else {
            return 'radio-col-off';
        }
    }
}]

And a fiddle that updates your example to use this technique with a (admittedly incorrectly sized) spacer gif: http://jsfiddle.net/cfarmerga/WAZah/3/


text:
Q: Show that a bounded, monotone increasing sequence is a Cauchy sequence Please check my proof
Suppose that sequence is bounded then it exist $a_{n}< M$
Since it is monotone increase sequence and bouned, then limit exist
By defination if limit of sequence it will exist $|a_{n}-L|<\epsilon $
that it shows it cauchy sequence.

A: What is the definition of Cauchy Sequence you are using? You are using two theorems here, first that every bounded monotone sequence has a limit, and second that every convergent sequence is Cauchy - that seems heavy duty to me.
Using the fact that every set of real numbers which is bounded above has a least upper bound, we can choose $M$ as the least upper bound of the sequence.
Since $M$ is the least upper bound we know that $M-\epsilon$ is not an upper bound, so there is an $N$ with $M-\epsilon \lt a_N \le M$. Now suppose that $m\gt n\gt N$. The sequence is monotone increasing, so $a_m\ge a_n\ge a_N$ (not assuming strictly increasing). We therefore have $$M-\epsilon \lt a_N\le a_n\le a_m \le M$$ from which it follows that $0\le a_m-a_n \lt \epsilon$. So we can demonstrate that the Cauchy condition holds.
It is, of course, equally easy to prove that the limit is $M$, but this is not what is asked. My instinct is that you are intended to show that you know what the Cauchy condition is, and show explicitly that it holds.


text:
Q: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. How to fix the error? I was trying to install auto-py-to-exe.
And I'm getting the error:
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output

I used both pip install auto-py-to-exe
and python -m pip install auto-py-exe

A: The user @hoefling answered my question here and there are no more errors. You need to install gevent. In cmd (I advise running as administrator) type pip install gevent and then type pip install auto-py-to-exe. gevent PYPI webpage.


text:
Q: ComboBox e SQLReader Eu tenho um ComboBox com uma lista de items que contém nomes que são gerados a partir do meu banco de dados(eu puxo o nome da coluna cerveja que estão alocadas na tabela):
private void Form1_Load(object sender, EventArgs e)
{
   try
   {
   conexao.Open();
   SqlCommand cmdd = new SqlCommand("select Cerveja from Cervejas where Cerveja ='" + comboBox1.SelectedItem + "'", conexao);
   SqlDataReader DR;
   DR = cmdd.ExecuteReader();
   if (DR.HasRows)
   {
     while (DR.Read())
     {
        comboBox1.Items.Add(DR.GetString(0));
     }
   }
   else
   {
        MessageBox.Show("Não tem cervejas no nosso banco de dados!");
   }

A partir desse código eu consigo obter o nome da coluna "Cervejas" no combobox ao iniciar o programa. O que eu preciso fazer agora, é quando o usuário selecionar um item no combobox, o mesmo faz uma comparação com o nome do item do combobox e as cervejas no banco de dados, puxando a row da cerveja certa, eu estava tentando assim, porém não consigo:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        try
        {
            conexao.Open();
            SqlCommand cmd = new SqlCommand("select * from Cervejas where Cerveja ='" + comboBox1.SelectedItem + "'", conexao);
            SqlDataReader DR;
            DR = cmd.ExecuteReader();
            if (DR.Read())
            {
                if (comboBox1.SelectedItem == DR.GetValue(1))
                {
                    MessageBox.Show("teste");
                }
                else MessageBox.Show("teste2");
            }
        }
        catch (Exception ex)
        {
            conexao.Close();
            MessageBox.Show("Erro de conexão Modbus: \n\n" + ex.Message);
        }

No caso, nesta parte:
if (comboBox1.SelectedItem == DR.GetValue(1))
{
   MessageBox.Show("teste");
}

Eu faço esta comparação, se o item selecionado corresponder a alguma cerveja no banco de dados deveria imprimir a palavra 'teste', porém isso não acontece.

A: A verificação com o if era desnecessária, uma vez que eu uso a cláusula WHERE no cmd.
Apenas editei:
SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
     Messagebox.Show = DR.GetValue(0).ToString(); // teste
}


text:
Q: file uploaded via php: no such file or directory i'm working on a website wherein the users can upload images (uses php 4.3.11). the files are uploaded with no problem as i can see them in the upload directory and i don't get any error message, but when i try to access the uploaded files via ftp, i get an error: no such file or directory. sometimes, i am able to access the file sometimes i get this error. what could be the problem here?
[update]
thanks for the help guys. i'm not familiar with the ftp daemon stuff. but i do access my files via ftp using FireFTP. the files are there but when try to download them or change the file properties, i get the said error. i also tried uploading a file in the folder through ftp and i was able to download it with no problem.
here is some of the code i'm working on, its kind of roundabout but i'll see on how to improve it.
my working directory is something like this www.domain.com/register/
and the upload directory is here www.domain.com/register/uploads/
users are required to register and upon sign-up, a folder is created for them in the uploads directory. i couldn't find a way to create a folder without having to be in the uploads folder itself so i redirect to a create-user-folder.php file in the uploads dir.
the file just contained this code:

    $user_foldername = rawurldecode($_GET['name']);
    mkdir($user_foldername);
    header("Location: ../form.php");     // redirect back to the page

i checked and the created folder's permission is set to 775.
and here's part of the code i use in uploading ( /register/function/function.php ):

    $path = "../uploads/$user_foldername/";
    for($j = 0; $j < $num_of_uploads; $j++){
        if(is_uploaded_file($_FILES[$file]['tmp_name'][$j])){
            $filename = $_FILES[$file]['name'][$j];
            copy($_FILES[$file]['tmp_name'][$j],$path.$filename);
        }
    }

i checked using FireFTP and the files are in the /uploads/user_foldername/ directory and its permission is set to 664. the strange thing is that when i try to download the files, at times there would be no problem at all but there are times when the error will appear.
[another update]
i added chmod() after the copy() function,

    $filename = $_FILES[$file]['name'][$j];
    copy($_FILES[$file]['tmp_name'][$j],$path.$filename);
    chmod($path.$filename, 0755);

but i still get the error.
another thing is that when i access /register/uploads/user_foldername/ through the url, i can see all of the uploaded files and view them, but how is it that i can't access them via ftp?
thanks again!

A: This is either a permission issue, or a configuration error. Here are things you should try:
What are the permission of the uploaded files? Does the FTP user has access to these files? Have you tried logging in as the user the FTP daemon would use and see if you could read the file that way?
Do you really see the correct directory? Have you verified by putting a file in that directory yourself and downloading it? Have you used the ftp command ls to verify the presence of the folder/folders/files?

A: You might need to chmod the folder the files are in, or in some cases the files themselves.
try chmoding them to 775
You can chmod files and folders through PHP it's self, with the chmod function. Or, you could use a FTP program such as filezilla.

A: Also check to make sure the intermediate directories are also permissioned as 755, as all the directories in the path need to be executable to be traversed.

A: i just figured out the problem. it was all because of the file name having accented characters in it, which explains why i do not always get the error message :|
<sigh> i should have seen this earlier, but anyway i hope this helps in case someone ran into the same problem.
thanks again! i really appreciate it :)


text:
Q: JavaScript (JS) function array equality works as pointer? How to just use the variables? I was creating a code where I need to use some variables from a global scope, when I made my local = global, I've noticed the changes I've made in the local scope were being modified into the global scope.
This is an example of what I am talking about
global = [];
load_global();
use_global();

function load_global() {
  for (i = 0; i < 10; i++) {
    global.push(i);
  }
}

function use_global() {
  local = [];
  local = global;
  for (i = 0; i < 5; i++) {
    global.push("x");
  }
  console.log(local);
}

JSbin Example
Is there a way to use the values of a global array, but without changing it?

A: You can try copying the global array
local = global.slice()

btw you might wanna use var keyword to make that array local. Without it the "local" array will be accessible from outside of the function

A: You need to clone the array into a local variable. You can do that with slice or concat for example.
To add clone to javascript arrays, you can use
Array.prototype.clone = function() {
    return this.slice(0);
};

And then
var localArray = globalArray.clone();

Also check this SO question here Javascript fastest way to duplicate an Array - slice vs for loop

A: Besides old school Array#slice, you can use the ES6 method Array.from, which is designed for such scenarios:
var local = Array.from(global)

This method can be used on array-like objects or any iterable values, which don't have a slice method. You may say Array.prototype.slice.call(). Oops you are right, but isn't that annoying?
Besides, you can pass a mapping function to it as well. For example:
Array.from('asdf', c => c.toUpperCase())  // ["A", "S", "D", "F"]

Comparing to ES5 style, you can see how neat ES6 is:
Array.prototype.slice.call('asdf').map(function(c){return c.toUpperCase()})

Read MDN doc for more.
On the other hand, the method is not widely supported at the moment, you need babel or a polyfill. But ES6 is the future, eventually it'll be fully supported by all major browsers.

A: In Javascript, as in many other languages, you only handle references of objects. This also means that the object "inside" your array could also need to be copied. The answers based on the use of Array.slice() are excellent but it doesn't make a deep copy of the items in the array (meaning the Object element in the array are also copied so changing the state of a local object doesnt affect your global object).
One very simple (but maybe not very efficient) solution could be to serialize and deserialize your array. Ex:
var newObj = JSON.parse(JSON.stringify(obj));

Note that using JSON doesn't allow you to handle an functions. Here was an answer using this technique.
EDIT
To allow deep copy, you can also iterate the properties of the object as DMaster suggested but you should use some kine of recursion. I have taken this example from this answer in SO.
function clone(destination, source) {
    for (var property in source) {
        if (typeof source[property] === "object" && source[property] !== null && destination[property]) {
            clone(destination[property], source[property]);
        } else {
            destination[property] = source[property];
        }
    }
}


text:
Q: Exception with $this->headLink()->appendStylesheet('/path/xyz.css'); in Pimcore 5 I just created my view.html.php script in Pimcore 5.
Unfortunately, it is not possible to integrate the CSS data. The manual with <link rel="stylesheet" type="text/css" href="../static... is ok.
For example, I used:
$this->headLink()->appendStylesheet('/static/bootstrap/css/bootstrap.css');

The file bootstrap.css exists.
Exception:

Attempted to call an undefined method named "headLink" of class "Symfony\Component\Debug\DebugClassLoader".

Screenshot:

Can anyone help? Does anyone know next?

A: Where are you using this? Based on your screenshot you are trying to call this inside pimcore/lib/Pimcore/Templating/Helper/Headlink.php which is wrong.
You should use it within view.html.php or layout.html


text:
Q: IE7 - Floated layout divs stacking on top of each other with negative opposite margin I am trying to use Zen Grids to avoid spending hours fighting with my layouts as I have been. The main advantage that I wanted from it besides simplicity was avoiding the compounding sub-pixel rounding issues in most browsers (provided via floats and negative margins to position the elements rather than relying on the previous columns).
However, in IE7 I cannot get the layout to behave. I have IE7 legacy support on and the boxsizing.htc working correctly. The test page I made consists of a header, two side bars, a content area, and a footer. When positioning the elements using floats and negative margins as Zen Grids does, I end up with all of the elements stacking in the same physical space, as you can see below. Using Zen Grids results in the exact same behavior. This only happens with IE7 (I am not concerned with IE6).
I have tried setting haslayout on different elements with no success and I cannot find an example of the same issue to save my life.
Layout collapse screenshot.
I set up a jsfiddle example here:
jsfiddle
Here is the html:
<!doctype html>

    <link rel="stylesheet" href="css/style.css">
    <meta charset="UTF-8">
    <title></title>

Header

Sidebar 1

Page Content

Sidebar 2

Footer

And the CSS:
.container {
    position: relative; /* Checked to see if haslayout was the issue */
    zoom: 1;
    width: 1000px;
    background: silver;
}
.header {
    float: left;
    margin-left: 0;
    margin-right: -100%;
    width: 100%;
    height: 60px; /* For visibility */
    background: green;
}
.sideOne {
    float: left;
    clear: left;
    margin-left: 0;
    margin-right: -25%;
    width: 25%;
    height: 40px; /* For visibility */
    background: purple;
}
.content {
    float: left;
    margin-left: 25%;
    margin-right: -75%;
    width: 50%;
    height: 40px; /* For visibility */
    background: orange;
}


text:
Q: Auto redirect to https using IIS Url Rewrite Moduleexcept one route I want all incoming http requests for my ASP.NET site to be redirected to https requests except the following route which I want to be served using http:
http://example.com/asdf
where 'asdf' can be replaced with any combination of alphanumeric characters
I am using IIS Url Rewrite module.


text:
Q: How to exclude duplicate values / NULL values SQL I hope that someone from you will be able to help me as I got stuck with a (silly) condition logic.
I am joining 2 temp tables.
The target is to see the Jobs, Tracking numbers, etc. (all actions) in one row always for one Consignee (Consignee Ref). In other words, to show all actions/data per Consignee Ref.
The issue I got is duplacated values. The problem is that the Original Job (620X) field can have assigned Tracking_1 but it can be also null. Also the Second Job (629X) filed can have but do not need to have assigned the Tracking number/value. It can be also the case that both Tracking_1 and Tracking are NULL for one Consignee Ref.
When I would exclude Jobs where Tracking_1 or Tracking is NULL, then I will loose the Jobs that have no Tracking Numbers at all. So I used the code below, but then I am getting duplicates.
SELECT * FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
ORDER BY [Original Job (620X)] asc

How can I make it that I will get rid of the unnecessary duplicates (an example marked in red)?
And at the same time not to loose  those jobs that have no Tracking Numbers?
I hope it makes sense.
Thank you very much in advance for any advise!
This is the entire code:
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp;

SELECT distinct
cne.[Consignee Ref],
s.[Trial AWB] as [Original Job (620X)],
rl.[CarrierReference] as [Tracking_1],
CAST(st.[Sched Collection date] as date) AS [Collection Date],
CAST(st.[Act Del Date] as date) AS [Delivery Date],
s.[Clientaccountcode] as [Account Code]

into #Temp
FROM MKN_Reporting.dbo.shipment AS s WITH (NOLOCK)
LEFT JOIN MKN_Reporting.dbo.[Lookup Month By JN Tb] AS b WITH (NOLOCK) ON s.[id] = b.[JobId]
LEFT JOIN MKN_Reporting.dbo.[Lookup Branch currency Tb] AS c WITH (NOLOCK) ON b.BranchPrefix = c.[Branch Prefix]
LEFT JOIN MKN_Reporting.dbo.[Lookup Client group Tb] AS g WITH (NOLOCK) ON s.[Clientaccountcode] = g.[Customer A/c]
LEFT JOIN MKN_Reporting.dbo.[Chargeto] AS cg WITH (NOLOCK) ON s.[id] = cg.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Shipper] AS sh WITH (NOLOCK) ON s.[id] = sh.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Cnee] AS cne WITH (NOLOCK) ON s.[id] = cne.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS r WITH (NOLOCK) ON sh.[Shipper Country code] = r.[Country Code]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS reg WITH (NOLOCK) ON cne.[Consignee Country code] = reg.[Country Code]
INNER JOIN MKN_Reporting.dbo.[Status] st ON COALESCE(s.ParentId, s.id) = st.Jobid
LEFT JOIN [CARRIERS_CHARGES] AS cc ON s.id = cc.JobId
LEFT JOIN [RouteLegs] as rl on cc.RouteLegId = rl.id

WHERE [Clientaccountcode] in ('US429', 'MI1091')
--AND rl.[CarrierReference] is not null

-------------------------------------------
IF OBJECT_ID('tempdb..#Temp2') IS NOT NULL
    DROP TABLE #Temp2;

SELECT distinct
cne.[Consignee Ref],
s.[Study Number] as [Study_],
s.[Site Number] as [Site No_],
s.[Trial AWB] as [Second (629X)],
rl.[CarrierReference] as [Tracking],
CAST(st.[Sched Collection date] as date) AS [Collection Date],
CAST(st.[Act Del Date] as date) AS [Delivery Date],
s.[Clientaccountcode] as [Account Code]

into #Temp2
FROM MKN_Reporting.dbo.shipment AS s WITH (NOLOCK)
LEFT JOIN MKN_Reporting.dbo.[Lookup Month By JN Tb] AS b WITH (NOLOCK) ON s.[id] = b.[JobId]
LEFT JOIN MKN_Reporting.dbo.[Lookup Branch currency Tb] AS c WITH (NOLOCK) ON b.BranchPrefix = c.[Branch Prefix]
LEFT JOIN MKN_Reporting.dbo.[Lookup Client group Tb] AS g WITH (NOLOCK) ON s.[Clientaccountcode] = g.[Customer A/c]
LEFT JOIN MKN_Reporting.dbo.[Chargeto] AS cg WITH (NOLOCK) ON s.[id] = cg.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Shipper] AS sh WITH (NOLOCK) ON s.[id] = sh.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Cnee] AS cne WITH (NOLOCK) ON s.[id] = cne.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS r WITH (NOLOCK) ON sh.[Shipper Country code] = r.[Country Code]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS reg WITH (NOLOCK) ON cne.[Consignee Country code] = reg.[Country Code]
INNER JOIN MKN_Reporting.dbo.[Status] st ON COALESCE(s.ParentId, s.id) = st.Jobid
LEFT JOIN [CARRIERS_CHARGES] AS cc ON s.id = cc.JobId
left JOIN [RouteLegs] as rl on cc.RouteLegId = rl.id
WHERE [Clientaccountcode] in ('US1598')
--AND rl.[CarrierReference] is not null

---------------------------------------------
SELECT * FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
ORDER BY [Original Job (620X)] asc

A: I guess OP is looking for some kind of field aggregation for T2.
With SQL Server 2017+, like in PostgreSQL,  you can now use STRING_AGG (same syntax than the Oracle LISTAGG.. "Why did they not use the same keyword...").
STRING_AGG will ignore null values from T2 and requires grouping if not alone. You have to add the other T1 and T2 required fields if any, but take care for T2 that it can imply duplicates and may need aggregation too...
Here is an example with your provided TSQL :
SELECT t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1],
       STRING_AGG(t2.[Tracking],',') WITHIN GROUP (ORDER BY t2.[Tracking] ASC) Tracking_T2
  FROM #Temp t1
       INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
 WHERE t1.[Tracking_1] is not null
 GROUP BY t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1]
 ORDER BY t1.[Original Job (620X)] asc

EDIT: For previous SQL Server release (before 2017), you can achieve string aggregation with XML query :
EDIT2: Adding EXISTS clause to convey the INNER JOIN from the initial query.
SELECT t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1],
       STUFF((SELECT ', ' + t2.[Tracking]
                         FROM #Temp2 t2
                        WHERE t1.[Consignee Ref] = t2.[Consignee Ref]
                        ORDER BY t2.[Tracking]
                          FOR XML PATH('')), 1, 1, N'') Tracking_T2
  FROM #Temp t1
 WHERE t1.[Tracking_1] is not null
   AND EXISTS (SELECT DISTINCT 1 FROM #Temp2 t2 WHERE t2.[Consignee Ref] = t1.[Consignee Ref])
 GROUP BY t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1]
 ORDER BY t1.[Original Job (620X)] asc


text:
Q: Nyquist plot for quasi polynomials I want to analyze the quasi polynomial given as p(x)=x+exp(-x) using its Nyquist plot. I want the Nyquist plot of p(iw)/(iw+1). How to do this in Matlab? Please help.

A: One of the main reasons people spend thousands of dollars on Matlab is their extensive documentation and help functionality. You should use that.
Typing in
doc nyquist

will take you to the help explorer with this page.
What you probably want to supply it with a model; you can do that by evaluating your exp-function for a range of points, and then using frd to convert these discrete measurement points to a system nyquist can work with. No magic, and everything linked from the nyquist help page :)