text:
Q: I can't get JUnit working on easy Java example I can't get this JUnit test working on this easy Java example I am working on. It works inside Eclipse but not from the command line... mvn test
Here is my test code:
import junit.framework.Assert;
import org.junit.Test;
import org.runnablejar.TestJAR.App;

public class TestApp {
    @Test
    public void testPrintHelloWorld() {

        Assert.assertEquals(App.getHelloWorld(), "Hello Worl");

    }
}

Here is my test output:
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building TestJAR
[INFO]    task-segment: [test]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/jsmith/workspace-sts-3.0.0.RELEASE/TestJAR/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources {execution: default-testResources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/jsmith/workspace-sts-3.0.0.RELEASE/TestJAR/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 2 source files to /home/jsmith/workspace-sts-3.0.0.RELEASE/TestJAR/target/test-classes
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
/home/jsmith/workspace-sts-3.0.0.RELEASE/TestJAR/src/test/java/TestApp.java:[7,2] annotations are not supported in -source 1.3
(use -source 5 or higher to enable annotations)
    @Test

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Mon Sep 17 20:36:52 EDT 2012
[INFO] Final Memory: 10M/98M
[INFO] ------------------------------------------------------------------------

A: You need to configure the maven-compiler-plugin to use 1.5 or 1.6.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>


text:
Q: pandas - how to get last n groups of a groupby object and combine them as a dataframe How to get last 'n' groups after df.groupby() and combine them as a dataframe.
data = pd.read_sql_query(sql=sqlstr, con=sql_conn, index_col='SampleTime')
grouped = data.groupby(data.index.date,sort=False)

After doing grouped.ngroups i am getting total number of groups 277. I want to combine last 12 groups and generate a dataframe.

A: Assuming you know the order of grouped
grouped = zip(*df.groupby(data.index.date,sort=False))
pd.concat(list(grouped)[1][-12:])

A: Pandas GroupBy objects are iterables. To extract the last n elements of an iterable, there's generally no need to create a list from the iterable and slice the last n elements. This will be memory-expensive.
Instead, you can use either itertools.islice (as suggested by @mtraceur) or collections.deque. Both work in O(n) time.
itertools.islice
Unlike a generator, a Pandas GroupBy object is an iterable which can be reused. Therefore, you can calculate the number of groups via len(g) for a GroupBy object g and then slice g via islice. Or, perhaps  more idiomatic, you can use GroupBy.ngroups. Then use pd.concat to concatenate an iterable of dataframes:
from operator import itemgetter

g = data.groupby(data.index.date, sort=False)
res = pd.concat(islice(map(itemgetter(1), g), max(0, g.ngroups-12), None))

collections.deque
Alternatively, you can use collections.deque and specify maxlen, then concatenate as before.
from collections import deque

grouped = data.groupby(data.index.date, sort=False)
res = pd.concat(deque(map(itemgetter(1), grouped), maxlen=12))

As described in the collections docs:

Once a bounded length deque is full, when new items are added, a
  corresponding number of items are discarded from the opposite end....
  They are also useful for tracking transactions and other pools of data
  where only the most recent activity is of interest.

A: use pd.concat on lists comprehension and groupby.get_group
pd.concat([grouped.get_group(x) for x in list(grouped.groups.keys())[-12:]])

A: You could pass a list comprehension to pd.concat():
import pandas as pd

df = pd.DataFrame([
['A',1,2],
['A',7,6],
['B',1,3],
['B',9,9],
['C',1,8],
['A',4,3],
['C',7,6],
['D',4,2]],
columns=['Var','Val1','Val2'])

last_n = 2
grouped = df.groupby('Var')

pd.concat([grouped.get_group(group) for i, group in enumerate(grouped.groups) if i>=len(grouped)-last_n])

Yields:
  Var  Val1  Val2
4   C     1     8
6   C     7     6
7   D     4     2

A: Get last n keys and filter dataframe with those keys
n = 12
grouped = data.groupby(data.index.date)
keys = list(grouped.groups.keys())
last_n_groups = data.loc[data[data.index.date].isin(keys[-n:])]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Отладка Ajax в Django Пытаюсь выполнить код на сервере через django, но не знаю как отловить ошибку, так как не могу понять, выполняется ли код на сервере и передаются ли туда хоть какие то данные:
views.py
def create_strike_view(request):
    message = "jjjj"
    return HttpResponse(message)

account_deatails.html
{% extends 'base.html' %}
{% block content %}

        {% if account.image %}

        {% else %}

        {% endif %}
            <form method='post' id='test'>
              <input type="hidden" value="video34"/>
              <input type='submit' value='Test button'/>

Initial text

            </form>

{% endblock content %}

urls.py
<код выше>
path('ajax/',create_strike_view,name = "post_strike"),
<код ниже>

Как понять выполняется ли код?
Как в последствии его отлаживать?

A: Постараюсь ответить, т.к. сейчас очень часто сталкиваюсь с этим.
1е. как написано в комментарии, необходимо открыть панель разработчика F12 и во вкладке Network найти ваш post-запрос он идет с типом xhr, далее во вкладке Headers внизу вы увидите отправленные данные, в вашем случае ключ 'video'. Там же в Network есть вкладка Responce в которой в случае успеха вы должны увидеть предполагаемое "jjjj". Убедитесь в правильности написания запроса, начните с передачи текстовых данных. загрузка файлов, таких как видео происходит иначе.
2е. Добавьте в ajax обработку ошибки error: это добавит вам информативности. Н-р:
success : ... ,
error: function (xhr, status, error) {
    console.log(xhr.responceText);
    #или
    console.log(status, error);
}

3е. Не знаю как у вас (возможно данная ошибка была проигнорирована, странно, что вы с ней не столкнулись), но в джанго есть обязательное условие для форм - это защита от подмены вводимых данных, для этого в данном фреймворке используется csrf token. возможно он стоит вашем основном файле html, т.к. ваш пример html кода взят из расширения шаблона ({% extends...). вот мой пример его использования для ajax-запросов:
views.py
from django.views.decorators.csrf import csrf_protect

@csrf_protect #я использую декоратор на той вьюхе которая требует защиты
def create_strike_view(request):
    message = "jjjj"
    return HttpResponse(message)

account_deatails.html


text:
Q: Excel generate and send email using phpexcel library in Codeigniter I have tried to report generated in excel format and send email using PHPExcel library. I need to some html align in excel file, so i have download my output as html in my local folder. But i unable to convert html file to excel file, when we tried below code, generated excel file shows only html filename not html table content.
 $this->data['report1']=$this->report_m->get_report();
 $this->data['report_details']=$this->report_m->get_report_details();

 $this->load->library('PHPExcel/iofactory');
 $html=$this->load->view('viewfilename',$data,TRUE);

 $tmpfile = time().'.html';
 file_put_contents($tmpfile, $html);
 //by using above code html file created successfully

 //method 1 for reading html
 $reader = new PHPExcel_Reader_HTML;
 $content = $reader->load($tmpfile);

 $objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
 $objWriter->save('excelfile.xlsx');

 //method 2 for reading html
 $objPHPExcel = new PHPExcel();
 $excelHTMLReader = IOFactory::createReader('HTML');
 $excelHTMLReader->loadIntoExisting($tmpfile, $objPHPExcel);
 $objPHPExcel->getActiveSheet()->setTitle('report');

 $writer = IOFactory::createWriter($objPHPExcel, 'Excel2007');
 $writer->save("nameoffiledrrr.xls");

 unlink($tmpfile);

A: Answer :
$html=$this->load->view('sendmail_template',$data,TRUE);

include("simple_html_dom.php");
$rowRecords = str_get_html($html);

//echo $html;
$filename="Report-".$dtimeFile.".xls";
$path='./reports/';
$csv_handler = fopen ($path.$filename,'w');
fwrite ($csv_handler,$rowRecords);
fclose ($csv_handler);

$msg='Report';

$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));

$file_path=base_url('reports/'.$filename);

$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxxxxxxxxx@gmail.com',
'smtp_pass' => 'xxxxxxxxxx',
'mailtype'  => 'html',
'charset'   => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$email = $result->to_addr;

$info = "info@xxxx.xx";
$infoname = "info";
$message = "PFA Report";
$this->email->set_mailtype("html");
$this->email->from($info, $infoname);
$this->email->to($email);

$subject = 'Report';
$this->email->subject($subject);
$this->email->message($message);
$this->email->attach($file_path);

 $r = $this->email->send();
    if (!$r) {
    echo "Failed to send email:" . $this->email->print_debugger(array("header"));
} else {
     echo "Mail Sent";
}


text:
Q: Как прописать зависимость vaadin компонентов в build.gradle Здравствуйте! С Gradle я не особо хорошо знаком, поэтому не знаю прописать зависимость vaadin компонентов. Я думаю, должно было получиться что-то вроде такого
compile("com.vaadin:ui");

Уверен что нужно указать версию vaadin, но не знаю как.
Вообще я хочу ипортировать com.vaadin.ui.TreeTable
Что я делаю правильно а что нет?


text:
Q: retrieving a "non-key" value using prepared statement (insert statement) in java I am well aware of the fact that one can retrieve Auto-generated keys using the prepared Statement with the following syntax:
ps = connect.prepareStatement(SQL-insert-Statement , Statement.RETURN_GENERATED_KEYS);

But , is it possible to retrieve a non-key value with this insert statement. (IT is Auto generated and auto-incremented but not a Primary key in the database table).
Thanks.


text:
Q: How do you anticipate breaking changes in iOS and Android updates? An application I'm working on was broken by an iOS non-retrocompatible update. It had a big impact on our client's business before we could fix it.
So I'm trying to find a way to anticipate breaking changes in iOS and Android updates.
I've already found:

*

*Apple technical publications: https://developer.apple.com/library/content/navigation/

*Android behavior changes:
https://developer.android.com/preview/behavior-changes.html
But it's a lot of reading and I want to make sure every developer in my company knows everything there is to know about breaking changes and that they learn about it as soon as the information is available.

*

*How do you do this kind of technical watch ?

*How do you go straight to the useful information ?

*Do you know any website or newsletter that might help ?

Thank you a lot for your help.

A: A couple tips for Android development:

*

*Monitor and address deprecation warnings in your build.  This is generally a good practice, but especially important on Android.  Deprecated methods are an indication that an API will be retired in a future version of the platform. Often this could be an indication that you will soon have to re-write a component in your application.

*Make use of the Android support library. This will allow you to implement functionality requiring newer API levels on devices that are not yet at that level. This allows you to code to newer APIs thus helping to future-proof you app.

This is a far-from-complete list.  For a much more in-depth overview of this topic see: https://developer.android.com/training/basics/supporting-devices/platforms.html

A: Update-breaking changes in iOS are rare. That having been said, a few observations:

*

*When there are breaking changes, it's usually in stuff about which Apple has given us ample warning. E.g.,

*

*Apple has started to enforce long-standing counsel about making writing thread-safe code, making sure that certain tasks must happen on the main thread, etc.

*Likewise, the shift from 32-bit to 64-bit code base was something that Apple warned us about years in advance.

*When Apple says something is "best practice", it's sometimes because they know that failure to do so can result in breaking changes at some future date (usually years down the line). E.g. Apple has advised autosizing masks well before new screen sizes came along. They were advising autolayout and size categories well before split screen multi-tasking was released. Etc.
If they say something is "best practice", they're often trying to help you future-proof your product.

*Where possible, stay in the highest possible abstraction in your code. The lower level you implemented your code, the more likely it is to not gracefully handle changes you didn't anticipate. The higher-level the API is, the more likely Apple has taken care of ensuring a graceful transition.

*Avoid relying upon undocumented behavior. And definitely avoid anything in direct contravention to the existing docs. (I know it sounds crazy, but there are all sorts of situations where documentation warns you about not doing something even though you might discover empirically that you can get around it.)
Bottom line, if you've empirically discovered some cute technique that isn't documented anywhere, that can easily break. If it's not formally outlined in the documentation, the more likely the behavior is to result in breaking changes.

*Watching the "What's New in ..." WWDC videos is a great way to not only discover what's new in every release, but there's often parenthetical remarks about "if you used to do x, consider doing y." Heed those warnings.
I think the WWDC videos are must watch for everyone (esp the high-level "What's New" videos), but if that's too much for your team, divide them up among the team and then reconvene the group and have each person give a 5 minute précis on what's critical.

*Every time there is a new release, you should review the release notes, e.g. these should redirect you to the latest docs:

*

*iOS: http://developer.apple.com/go/?id=ios-sdk-release-notes.

*Xcode: http://developer.apple.com/go/?id=xcode-release-notes.
The signal-to-noise ratio in these docs can be a bit low, but generally important stuff is covered in here.

*Listen to the compiler:

*

*If API has been deprecated, the compiler will warn you. Deprecated API is at risk of being formally removed in future release. If you need deprecated API to support devices running older OS versions, then add run-time version checks, using the API most appropriate for that OS version.

*Be wary about disabling compiler warnings. It's quite easy to disregard compiler warnings, or worse, silencing them. If there are any warnings that have been silenced, not only turn them back on, but treat them as errors.


text:
Q: Facebook and Medium Content Placeholder Style Recently I've noticed that Facebook and Medium are using a lazy loading style. However, there're none of the jQuery or any other library I've found yet to achieve the same style.
Does anyone know how to achieve that or any familiar jQuery library that can do the same?
Here's the screenshot which I'm referring to:

A: I've just found one at Codepen:

 @-webkit-keyframes placeHolderShimmer {
   0% {
     background-position: -468px 0
   }
   100% {
     background-position: 468px 0
   }
 }

 @keyframes placeHolderShimmer {
   0% {
     background-position: -468px 0
   }
   100% {
     background-position: 468px 0
   }
 }

 .timeline-wrapper {
   background-color: #e9eaed;
   color: #141823;
   padding: 20px;
   border: 1px solid #ccc;
 }

 .timeline-item {
   background: #fff;
   border: 1px solid;
   border-color: #e5e6e9 #dfe0e4 #d0d1d5;
   border-radius: 3px;
   padding: 12px;
   margin: 0 auto;
   max-width: 472px;
   min-height: 200px;
 }

 .animated-background {
   -webkit-animation-duration: 1s;
   animation-duration: 1s;
   -webkit-animation-fill-mode: forwards;
   animation-fill-mode: forwards;
   -webkit-animation-iteration-count: infinite;
   animation-iteration-count: infinite;
   -webkit-animation-name: placeHolderShimmer;
   animation-name: placeHolderShimmer;
   -webkit-animation-timing-function: linear;
   animation-timing-function: linear;
   background: #f6f7f8;
   background: #eeeeee;
   background: -webkit-gradient(linear, left top, right top, color-stop(8%, #eeeeee), color-stop(18%, #dddddd), color-stop(33%, #eeeeee));
   background: -webkit-linear-gradient(left, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
   background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
   -webkit-background-size: 800px 104px;
   background-size: 800px 104px;
   height: 96px;
   position: relative;
 }

 .background-masker {
   background: #fff;
   position: absolute;
   -webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
   box-sizing: border-box;
 }

 .outlined .background-masker {
   border: 1px solid #ddd;
 }

 .outlined:hover .background-masker {
   border: none;
 }

 .outlined:hover .background-masker:hover {
   border: 1px solid #ccc;
   z-index: 1;
 }

 .background-masker.header-top,
 .background-masker.header-bottom,
 .background-masker.subheader-bottom {
   top: 0;
   left: 40px;
   right: 0;
   height: 10px;
 }

 .background-masker.header-left,
 .background-masker.subheader-left,
 .background-masker.header-right,
 .background-masker.subheader-right {
   top: 10px;
   left: 40px;
   height: 8px;
   width: 10px;
 }

 .background-masker.header-bottom {
   top: 18px;
   height: 6px;
 }

 .background-masker.subheader-left,
 .background-masker.subheader-right {
   top: 24px;
   height: 6px;
 }

 .background-masker.header-right,
 .background-masker.subheader-right {
   width: auto;
   left: 300px;
   right: 0;
 }

 .background-masker.subheader-right {
   left: 230px;
 }

 .background-masker.subheader-bottom {
   top: 30px;
   height: 10px;
 }

 .background-masker.content-top,
 .background-masker.content-second-line,
 .background-masker.content-third-line,
 .background-masker.content-second-end,
 .background-masker.content-third-end,
 .background-masker.content-first-end {
   top: 40px;
   left: 0;
   right: 0;
   height: 6px;
 }

 .background-masker.content-top {
   height: 20px;
 }

 .background-masker.content-first-end,
 .background-masker.content-second-end,
 .background-masker.content-third-end {
   width: auto;
   left: 380px;
   right: 0;
   top: 60px;
   height: 8px;
 }

 .background-masker.content-second-line {
   top: 68px;
 }

 .background-masker.content-second-end {
   left: 420px;
   top: 74px;
 }

 .background-masker.content-third-line {
   top: 82px;
 }

 .background-masker.content-third-end {
   left: 300px;
   top: 88px;
 }


text:
Q: Dynamic Navigation with responsive design and pure css I built a few websites with responsive navigation already. There are many solutions for responsive designs of website navigation if you have  a static navigation.
However, for my current project I am building an user-individual dynamic navigation, so the number of navigation element as well as their contents are subject to change and are user individual. Therefore I tried different things with flexbox and floating layouts already but did not find a solution meeting my needs.
Do you have an idea how to fix the problem showed in the picture attached?

I also attached some sample code.

<!DOCTYPE html>

Title Zone

Navigation Elem 1

Navigation Element 2

Navigation 3

Element 4

Element 5

Navigation 6

Element n

A: you need use media query to set what will appear in each screen size.
In the HTML file you will define all cases including a div tag "more" with yheir li tag
but when the screen size if less than a certain number this div will recive display: none
for example:

element 1

element 2

element 3

element 4

more...

element 3

element 4

and with media query you can hide or show something based in the width screen like this:
@media only screen and (max-width: 400px) {
  .disabledOnMobile {
    display: none;
  }
}

hiding all tag with disabledOnMobile class (element 3 and 4 showing their only with "more")
@media only screen and (min-width: 400px) {
  .activeOnMobile {
    display: none;
  }
}

Here we hide the activeOnMobile when the screen is bigger than 400px showing only element 3 and 4 that is outside activeOnMobile class
in your case you need add the hover on "more" and set anothers settings, it's only a example, you can also add a breakpoin in any screen size. To becobe it's easier you can use some library like bootstrap.
You can lear more about media query here


text:
Q: For $N$ particles acting under gravity, how long until they settle into a virial equilibrium? As the title says, if I have a system of particles interacting only due to gravity, over what timescale do we expect them to fall into a virial equilibrium?
By virial equilibrium I mean a system that satisfies the virial theorem:
$$ 2K + W =0 $$
where $K$ and $W$ are the kinetic and potential energy of the system, respectively.

A: According to this lecture from the University of Edinburgh, numerical simulations of N-body systems suggest a half-mass relaxation time:
$$
t_\text{rh} = 0.138\frac{N^{1/2}r_\text{h}^{3/2}}{m^{1/2}G^{1/2}\ln(\gamma N)}
$$
where $r_\text{h}$ is the radius that initially contains half the mass of the system, $G$ is the gravitational constant, $m$ is the average particle mass, $N$ is the number of particles, and $\gamma$ is a constant, approximately 0.11 for a system containing equal masses.
Since the half-mass radius is a good approximation to the virial radius, this is a good approximation (at least a lower bound) to the virial equilibrium timescale.
There is also a version that depends on velocity dispersion $v$ and density $\rho$:
$$
t_\text{r} = 0.065\frac{v^3}{\rho m G^2\ln(\gamma N)}
$$


text:
Q: how to convert python list[a,b,c,d] to [a:b, c:d] format How do I convert a python list to the [a:b, c:d] format?
This format is used in cropping of images in python-opencv.
Suppose that I have cropping dimensions of an image in a list cropDim but don't know how to make it into opencv acceptable format as image[a:b, c:d].
import cv2
def crop(cropDim):
    bimage = cv2.imread("nor.jpg")
    cropped = bimage[a:b, c:d]
    cv2.imwrite('nor-crop.jpg', cropped)

A: First of all let's get the terminology straight - that's not a Python list, it's an array with two dimensions. You're trying to do a slice on it.
cropped = bimage[cropDim[0]:cropDim[1], cropDim[2]:cropDim[3]]

A: k so lets play the guessing game with good assumption :)
as per the heading it says how to convert python list[a,b,c,d] to [a:b, c:d] format:
so we will assume cropDim = [a,b,c,d] and output required is [a:b,c:d]
cropDim = [a,b,c,d]
templist1 = []
templist2 = []
for i,item in enumerate(cropDim):
    if i % 2 ==0:
        templist1.append(item)
    else:
        templist2.append(item)
result = map(':'.join,zip(templist1,templist2))
print result #behold the power of assumption


text:
Q: Complex Integration Over Square Integrate the following counterclockwise over $C$: $$\int_C\frac{5z^3+5 \sin(z)}{(z-2i)^3} dz,$$ where $C$ is the boundary of the square with vertices  $\pm 3, \pm3i$.
I imagine $4$ integrals need to be summed?
How do you calculate the boundaries and then set up the integrals?

A: If you know residue theorem, you should use it. Otherwise, you're going to have a very bad time.

A: Hint: If you have studied Cauchy's integral formula

$$ f^{(n)}(a) = \frac{n!}{2\pi i} \oint_\gamma \frac{f(z)}{(z-a)^{n+1}}\, dz, $$

then you can use it.


text:
Q: Displaying mean +/- st. error or confidence interval on bar charts When I look at scientific papers, bar charts I usually come to see are shown with mean +/- sem (standard error of the mean).
As stated here,

When standard error (SE) bars do not overlap, you cannot be sure that
  the difference between two means is statistically significant

and

If 95% CI error bars do not overlap, you can be sure the difference is
  statistically significant (P < 0.05).

Even if the reverse is not true, why don't we always use the confidence interval instead of the sem in bar charts, since it seems more informative ?

A: SE and CI give us different - albeit related - information about the data. SE tells us about the variability of the mean values, e.g. if we were to repeat the study. CI tells us about the accuracy of our estimates. They are related because SE is used to calculate the CIs.
The why for using one or the other thus comes down to what the author wants to convey. If you are reporting the results of a statistical test elsewhere in your report/publication, using CIs might be considered extraneous as you already have a measure of statistical significance in the P value from the test.
While SE may have become de rigueur, this excellent paper shows clearly some of the many pitfalls related to just sticking with SE by default. Bottom line: think about what story your data are telling, and use appropriate figures to represent this story accurately.


text:
Q: C# code to Python with COM interface - casting issue I have trouble to convert comtype in the needed objects. I get a working C# sample and must convert it into python Code. I use ComTypes for that.
The detailed Problem:
The Object Hirachy is the following(from the CANoe documentation):
System
  +Namespaces:Namespaces (collection)
Namespaces
  +Count
  +Item:Namespace
Namespace
  +Name
  +Variables
  +Namespaces:Namespaces

Python code:
App = CreateObject('CANoe.Application')
mNamespaces = App.System.Namespaces #oNamespaces = POINTER(INamespaces2)
mNamespace = mNamespaces.Item(3) #mNamespace = POINTER(INamespace), I have the Right object with a wrong interface. mNamespace had the right namespace object (_Statistics)
mStatisticsNamespaces = ? #here

C# excample Code to Transfer:
mSystem = (CANoe.System)mApplication.System;
mNamespaces = (CANoe.Namespaces)mSystem.Namespaces;
mNamespace = (CANoe.Namespace)mNamespaces["_Statistics"];
mStatisticsNamespaces = (CANoe.Namespaces)mNamespace.Namespaces;
mNamespaceCAN1 = (CANoe.Namespace)mStatisticsNamespaces["CAN1"];
mVariables = (CANoe.Variables)mNamespaceCAN1.Variables;
mVariable = (CANoe.Variable)mVariables["Busload"];

The mNamespace object contains now the Methods
mNamespace
    +Name
    +Variables
VisualStudio Variable view of mNamespace
VisualStudio Variable view of mNamespaces
It seams I must convert the mNamespace object like the C# sample. But I don't have an Idea how I can make it.
I had in Python no includes like c++/C# so I can't write like the C# sample.
Had anyone an Idee how to manage this?
Thanks


text:
Q: How to change value if multiple duplicate rows more then 3 in Oracle SQL I am trying to select if A.POLICY_NO or A.POLICY_TITLE values duplicate rows more than 3, want to change C.SMALL_CATEGORY_TITLE values to "Z" and also want to cahge B.SMALL_CATEGORY_SID values to null.
I used 3 tables that YIP.YOUTH_POLICY as A, YIP.YOUTH_POLICY_AREA as B and YIP.YOUTH_SMALL_CATEGORY as C. the PK and FK is POLICY_NO.
ForExample if the table

A.POLICY_NO
B.SMALL_CATEGORY_SID
C.SMALL_CATEGORY_TITLE
A.POLICY_TITLE

1
80
A
VALUE1

1
90
B
VALUE1

1
95
C
VALUE1

2
80
A
VALUE2

2
90
B
VALUE2

2
95
C
VALUE2

3
80
A
VALUE3

3
90
B
VALUE3

4
80
A
VALUE4

I wnat to select like

A.POLICY_NO
B.SMALL_CATEGORY_SID
C.SMALL_CATEGORY_TITLE
A.POLICY_TITLE

1
NULL
Z
VALUE1

2
NULL
Z
VALUE2

3
80
A
VALUE3

3
90
B
VALUE3

4
80
A
VALUE4

this is the query select except when duplicate values more then 3,
SELECT
 A.POLICY_NO
 , B.SMALL_CATEGORY_SID
 , C.SMALL_CATEGORY_TITLE
 , A.POLICY_TITLE
 , COUNT(*) OVER() AS TOTAL_COUNT
FROM
 YIP.YOUTH_POLICY A
 LEFT JOIN
 YIP.YOUTH_POLICY_AREA B
 ON A.POLICY_NO = B.POLICY_NO
 LEFT JOIN
 YIP.YOUTH_SMALL_CATEGORY C
 ON B.SMALL_CATEGORY_SID = C.SMALL_CATEGORY_SID
 WHERE A.POLICY_NO IN (SELECT
                        F.POLICY_NO
                        FROM YIP.YOUTH_POLICY F
                        LEFT JOIN
                         YIP.YOUTH_POLICY_AREA G
                         ON F.POLICY_NO = G.POLICY_NO
                         LEFT JOIN
                         YIP.YOUTH_SMALL_CATEGORY H
                         ON G.SMALL_CATEGORY_SID = H.SMALL_CATEGORY_SID
                        GROUP BY F.POLICY_NO
                        HAVING COUNT(*) < 3)
ORDER BY A.POLICY_NO;

and I was tried to change C.SMALL_CATEGORY_TITLE values when POLICY_NO values duplicated more then 3
SELECT
 A.POLICY_NO
 --, B.SMALL_CATEGORY_SID
 , SUM(CASE WHEN C.SMALL_CATEGORY_TITLE IN (SELECT
                                        F.POLICY_NO
                                        FROM YIP.YOUTH_POLICY F
                                        LEFT JOIN
                                         YIP.YOUTH_POLICY_AREA G
                                         ON F.POLICY_NO = G.POLICY_NO
                                         LEFT JOIN
                                         YIP.YOUTH_SMALL_CATEGORY H
                                         ON G.SMALL_CATEGORY_SID = H.SMALL_CATEGORY_SID
                                        GROUP BY F.POLICY_NO
                                        HAVING COUNT(*) > 2) THEN 1 ELSE NULL END) AS 'Z'
 , A.POLICY_TITLE
 , COUNT(*) OVER() AS TOTAL_COUNT
FROM
 YIP.YOUTH_POLICY A
 LEFT JOIN
 YIP.YOUTH_POLICY_AREA B
 ON A.POLICY_NO = B.POLICY_NO
 LEFT JOIN
 YIP.YOUTH_SMALL_CATEGORY C
 ON B.SMALL_CATEGORY_SID = C.SMALL_CATEGORY_SID
ORDER BY A.POLICY_NO;

I got SQL Error [42000]: JDBC-8006:Missing FROM keyword.   ¶at line 17, column 59 of null:¶           HAVING COUNT(*) > 2) THEN 1 ELSE NULL END) AS 'Z'¶
Is there any way to fix it? I was thinking more then 5 hours but i could't fix it

A: The trick is to use the windowing function COUNT(*) OVER to get a count over the entire rowset in order to later make decisions about each individual row. You can finally collapse it down with DISTINCT or GROUP BY.
SELECT DISTINCT
       policy_no,
       CASE WHEN (policy_count >= 3 OR policy_title_count>= 3) THEN NULL
            ELSE small_category_sid
       END AS small_category_sid,
       CASE WHEN (policy_count >= 3 OR policy_title_count>= 3) THEN 'Z'
            ELSE small_category_title
       END AS small_category_title,
       policy_title
  FROM (SELECT x.*,
               COUNT(*) OVER (PARTITION BY policy_no) policy_count,
               COUNT(*) OVER (PARTITION BY policy_title) policy_title_count
          FROM yip.youth_policy x)


text:
Q: MVC post not getting the updated value of a mvc textbox, when we change the content of a txtbox via jquery in client side which is copied from a pup We have a MVC textbox(orignal textbox) in our form that expects time formatted string(eg:10:30), and we have provided a normal button next to it that opens a pop-up and user can see another textbox inside that which can be used for entering time in decimal format(eg:10.5)
then the pop-up shows the converted decimal to time format ie; 10:30. If user clicks OK then we takes the accepted value from the popup to orignal text box in the form.
The above user actions are done via jquery, we shows up jquery poupup and normal html input text box and takes the value back to original ASP.net MVC text box control.
All is fine, even jquery works fine. we have even checked the value of the original text box in javascript from DOM in Developer tool, But the value property of the original text is still the old value what we received when we opened our form - but when we checked the value using javascript in developer tool watch- its our new value.
Looks like our update in the value on the textbox is not posting to server.
Do anyone have any idea to make this working?


text:
Q: Swift: Get multiple array values like "x" For example, I have an array like var myArray = ['player_static.png', 'player_run0.png', 'player_run1.png', 'player_run2.png', 'player_jump0.png', 'player_jump1.png']
Is there any simple way to get only the "player_runX.png" images?

A: You can use filter to get all elements that hasPrefix("player_run"):
let myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]

let playerRuns = myArray.filter{$0.hasPrefix("player_run")}
print(playerRuns)  //["player_run0.png", "player_run1.png", "player_run2.png"]

A: One way to do this would be to iterate over the array and retrieve the elements that match the pattern. A very quick sample would be something like this:
var myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]

func getSubArray(array:[String],prefix:String) -> [String]
{
    var newArray = [String]()
    for img in array
    {
        if img.substringToIndex(img.startIndex.advancedBy(prefix.characters.count)) == prefix
        {
            newArray.append(img)
        }
    }
    return newArray
}

var test = getSubArray(myArray, prefix: "player_run")


text:
Q: ProFTPD options: how to debug Within a Red Hat Enterprise Linux Server release 7.6 (Maipo) I would like to use the module mod_ban in order to set a ClientConnectRate event.
The service is started as: systemctl start proftpd
Service is configured as below:
[root@lclftpcrb001blq ~]# cat /usr/lib/systemd/system/proftpd.service
[Unit]
Description = ProFTPD FTP Server
After = network.target nss-lookup.target local-fs.target remote-fs.target

[Service]
Type = forking
PIDFile = /run/proftpd/proftpd.pid
Environment = PROFTPD_OPTIONS=
EnvironmentFile = -/etc/sysconfig/proftpd
ExecStart = /usr/sbin/proftpd $PROFTPD_OPTIONS
ExecReload = /bin/kill -HUP $MAINPID

[Install]
WantedBy = multi-user.target

So, other than configuring this code in /etc/proftpd.conf:
<IfDefine DYNAMIC_BAN_LISTS>
  BanEngine     on
  BanLog        /var/log/proftpd/ban.log
  BanTable      /var/run/proftpd/ban.tab
  BanOnEvent  ClientConnectRate   10/00:10:00 00:15:00 "Stop connecting frequently"
  BanMessage                    "Host %a has been banned"
  BanControlsACLs               all allow user ftpadm
</IfDefine>

I also have /etc/sysconfig/proftpd:
PROFTPD_OPTIONS="-DDYNAMIC_BAN_LISTS"

Despite the configurations, when I start the service the debug tells me:
proftpd[29035]: <IfDefine>: skipping 'DYNAMIC_BAN_LISTS' section at line 85

From my understanding, the IfDefine block is loaded if DYNAMIC_BAN_LISTS is present in /etc/sysconfig/proftpd.
So the only thing I can think is that for some reason it's not retrieving
the option from /etc/sysconfig/proftpd ...
How can I check this point?
Thanks!


text:
Q: How to show only Standard Format post in my custom taxonomy page -wordpress 3.8.1 Hi I want to show only standard format in my custom taxonomy:
Actually I have many category and format in my project , hence on this page I need only to show standard format and specific  category

<?php
/**
 * Locations taxonomy archive
 */
get_header();
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
?>

<?php echo apply_filters( 'the_title', $term->name ); ?> News

        <?php if ( !empty( $term->description ) ): ?>

            <?php echo esc_html($term->description); ?>

        <?php endif; ?>

        <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>

        <div id="post-<?php the_ID(); ?>" <?php post_class('post clearfix'); ?>>

<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?>

<?php the_time(get_option('date_format')); ?> by <?php the_author_posts_link(); ?>

                    <?php the_content( __('Full story…') ); ?>

        <?php endwhile; ?>

<?php next_posts_link('« Previous Entries') ?>

<?php previous_posts_link('Next Entries »') ?>

        <?php else: ?>

No News in <?php echo apply_filters( 'the_title', $term->name ); ?>

It seems there isn't anything happening in <?php echo apply_filters( 'the_title', $term->name ); ?> right now. Check back later, something is bound to happen soon.

        <?php endif; ?>

        <?php get_sidebar(); ?>

<?php get_footer(); ?>

A: tandard is not actually a post format. When no specific format is set, wordpress will assign Standard to that post. This is what you will see in the back end in post editor. If you need to exclude all other post types and just display something specific that has no post format assigned to it you will use false == has_post_format() For example
 if ( false == has_post_format()) {
    <--show post without a post format-->
   }


text:
Q: Java garbage collection in Queue dequeue() sample code I was going through the code of the implementation of a Queue in a course on algorithms and observed the code for dequeue() which the author used:
private Node first, last;

private class Node {
    String item;
    Node next;
}

public boolean isEmpty() {
    return first == null;
}

// Code segment in doubt
public String dequeue() {
    String item = first.item;
    first = first.next;
    if (isEmpty()) last = null;
    return item;
}

Here, first and last, understandably, point to the first and last elements in the queue respectively. I am a bit skeptical about the code in dequeue() which the author uses. Since, he is simply doing:
first = first.next;

without assigning first.next to null. Will it not leave a dangling reference (or loitering) which will hinder the Garbage Collection mechanism of JVM? I'm a bit confused, shouldn't the code for dequeue() look like this instead? (I know for sure that in C/C++ the code should be like below, but want to know the expected behavior of JAVA in this case)
public String dequeue() {
    Node old;
    old = first;
    first = first.next;
    old.next = null;
    if (isEmpty()) last = null;
    return old.item;
}

I will also appreciate it if someone could point me to a resource which covers this topic in detail with good examples.

A: Setting old.next = null is unnecessary, because old is ready to be garbage-collected (the first = first.next assignment eliminates its last live reference (once dequeue exits)) and so the garbage collector won't trace any of its references.

A: Lets say you have 2 objects in Queue: A and B
first points to A and first.next points to B (in other words A.next == B)
The only reference to A is Queue#first variable. When you do
first = first.next; // first == B

noone references A object anymore, so it is eligible for garbage collection.

A: If your Queue is not implemented as a Doubly Queue ( meaning you can access both .Next and .Prev in your queue), then after setting first to be first.next , there's gonna be no reference or pointer to first and then the garbage collection thread will know that it (first) needs to be Garbage Collected (Associated memory will be released).

A: Only references from live objects matter.  These determine which objects are live.
If an object has a reference to a live object, but it is not referenced this will be collected. (The JVM doesn't use reference counts and there is no need to update this)
Another case which concerns people if if two object reference each other (but nothing else does)  Again this is fine because only objects which can accessed from a root node (e.g a Thread) as retained and everything else is collected.


text:
Q: Multiple DAG runs after one finished successfully One of the Tasks I have in my Airflow DAG is exporting data from BQ to files (I use wildcard * in the URI) and I see that at the end of the specific Task of exporting to files, it starts additional runs of the DAG and fails in the first Task.
It seems that the number of runs depends on the number of files it exports (when I changed the URI to be without wildcard it started a single extra run right after it managed to export).
Why is this happening? What can I do differently to avoid these multiple runs?
That's how it looks in airflow tree:

import datetime
import json
from airflow import utils
from airflow.models import DAG
from airflow.operators.dummy import DummyOperator
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from airflow.operators.python_operator import PythonOperator
from google.cloud import bigquery, pubsub_v1

def publish_message(**context):
    publisher = pubsub_v1.PublisherClient()

    topic_path = publisher.topic_path('a', 'a')

    data_str = json.dumps(context['task_instance'].xcom_pull(task_ids='set_params', key='request_params'))
    data = data_str.encode("utf-8")

    future = publisher.publish(topic_path, data)
    print(future.result())

    print(f"Published messages to {topic_path}.")

def set_params(params, **context):
    query_params = {}
    file_format = 'json'
    compression = 'gzip'
    params_fixed = json.loads(params.replace("\'", "\""))
    for sub in params_fixed['params']:
        if sub["param_name"] == 'file_format':
            file_format = sub["param_value"]
        elif sub["param_name"] == 'compression':
            compression = sub["param_value"]
        else:
            query_params[sub["param_name"]] = sub["param_value"]
    context['task_instance'].xcom_push(key='file_format', value=file_format)
    context['task_instance'].xcom_push(key='compression', value=compression)
    context['task_instance'].xcom_push(key='query_params', value=query_params)
    context['task_instance'].xcom_push(key='request_params', value=params_fixed)

with DAG(dag_id="export_data_to_gcs",
        start_date=datetime.datetime(2021, 1, 1),
        schedule_interval=None) as dag:

    start = DummyOperator(task_id="start")

    my_params = '{{dag_run.conf}}'

    set_params = PythonOperator(
        task_id='set_params',
        provide_context=True,
        python_callable=set_params,
        op_kwargs={'params': my_params},
        dag=dag,
    )

    execute_sql = BigQueryOperator(
        task_id='execute_sql',
        sql='/SQL/sql_query.sql',
        bigquery_conn_id='bigquery_default',
        use_legacy_sql=False,
        dag=dag,
    )

    publish_message = PythonOperator(
        task_id='publish_message',
        provide_context=True,
        python_callable=publish_message,
        dag=dag,
    )

start >> set_params >> execute_sql >> publish_message

A: The problem was solved when I switched to another gcp environment


text:
Q: How to rename many groups of rows in Pandas? I have a list of lists:
result_list = [[10x20], [10x10], [10x5], [10x2], [10x20, [10x10], [10x5] ....[10x2]]
Inside each [ ] there are 10 values. I imported this list of lists to a Pandas Dataframe,I calculated the average and rounded to 2 decimals.
I need to rename the rows. As an image is better to explain, I added 2 pictures.
Dataframe I have:

Dataframe I need:

Now the code:
   df.loc['AWA'] = [[0:4], :]
   df.loc['REM'] = [[4:8], :]
   df.loc['S1'] = [[8:12], :]
   df.loc['S2'] = [[12:16], :]
   df.loc['SWS'] = [[16:20], :]
   df.loc['stades'] = [[20:24], :]

I also thought of "group by". But how can I use it when my rows do not have a name?

A: Assume I have this df
df = pd.DataFrame(np.random.rand(24, 10))
df['Total Acc'] = df.sum(1)
df

Create a new index and assign it
lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'stades']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df.index = pd.MultiIndex.from_product([lvl0, lvl1])
df


text:
Q: Represent levels in a single table or multiple tables If I have a table with multiple optional levels, is it better to have a single table with nullable levels or multiple tables with not nullable levels.
One benefit I could see is the separate tables would permit all keys to be not null which would be better for data integrity.
SINGLE  table
COUNTRY    BUSINESS   EMPLOYEE   VALUE
-----------------------------------------
1          NULL       NULL       ValueA
1          2          NULL       ValueB
1          2          3          ValueC

or

COUNTRY  table
COUNTRY  VALUE
---------------
1        ValueA

BUSINESS table
COUNTRY    BUSINESS   VALUE
------------------------------
1          2          ValueB

EMPLOYEE table
COUNTRY    BUSINESS   EMPLOYEE  VALUE
-----------------------------------------
1          2          3         ValueC

A: This depends on your business requirement.
Benefits of "multiple tables with not nullable levels" are

*

*proper indexes

*proper data selection

*proper data manipulation

*Proper use of Constraints

*In single word, Normalization
You must look for Normalization and your business requirement before proceeding with the design.
Normalization summary - Here
Cheers!!


text:
Q: Cleaner way of using inheritance to separate 'static' code from 'dynamic' code (With static and dynamic I mean the distinction whether code is susceptible to change)
I have a bit of a weird problem I'm currently stuck on. I'm writing an application which involves some complex interactions between components in which it becomes hard to keep track of the code flow. To simplify this, I'm trying to structure the code by creating 'layers', where each layer has increased functionality compared to the layer above it. Each layer is contained in a package. I'm having the following problem:
Consider the following 2 classes and their subclasses with increased functionality:
Class A:
package layer;
class A {
    B b;

    A() {
        b = new B();
    }

    void foo() {
        b.foo();
    }

    /* More A-class methods here */
}

Class B:
package layer;
class B {
    void foo() {
        // Do something
    }

    /* More B-class methods here */
}

Subclass A:
package sublayer;
class ASub extends A {

    ASub() {
        super.b = new BSub(); // This needs a cast to compile
    }
}

Subclass B:
package sublayer;
class BSub extends B {
     @Override
     void foo() {
        // Do something with more functionality
     }
}

In the end I just want to instantiate and modify classes ASub and BSub, being able to use all methods of superclasses A and B without actually needing to modify code in classes A and B itself.
If I call new ASub().foo(), I want the overridden foo() of BSub to execute instead of that of B. Ofcourse I can add a variable BSub bsub in ASub and override A's foo() method to call bsub.foo(), but this doesnt avoid the creation of the object b in the constructor of A, which seems sloppy coding. Any thoughts on this? Any comments are welcome.

A: Using inheritance to promote reusability is a really really bad idea. The inheritance should be always driven by the nature of the objects that you are trying to describe. You need to learn yourself to work with terms and abstractions to ask yourself "What is the nature of what I am trying to describe". My suggestion is to learn a book on Domain Driven Design for example or Code Complete. Also think about polymorphism and design patterns.

A: Your question is a bit controversial.  Object creation and dependency injection is the subject of a lot of discussion and a core focus of various frameworks and design patterns.
But here is, I hope, one simple answer to your question, which isn't a general "what's the best way to create objects in Java?"
In the code below, I move the responsibility of instantiating B to a method (instantiateB()) which is called from the A (superclass) constructor.  So, when you want to subclass A, you override that method instead of overriding the constructor.
package com.matt.tester;

public class SE {

    static class A {
        B b;

        A() {
            instantiateB();
        }

        void instantiateB () {
            this.b = new B();
        }

        void foo() {
            b.foo();
        }

        /* More A-class methods here */
    }

    static class B {
        void foo() {
            System.out.println("Hellow from B.foo()!");
        }

        /* More B-class methods here */
    }
    static class ASub extends A {

        @Override
        void instantiateB() {
            this.b = new BSub();
        }
    }
    static class BSub extends B {
         @Override
         void foo() {
            System.out.println("Hellow from BSub.foo()!");
         }
    }

    public static void main(String[] args) {
        A a = new ASub();
        a.foo();
    }
}


text:
Q: Unhandheld Exception: System.Indexoutofbound exception: Index was outside the bound of array I am trying to write the code for splitting first char from a string like:
Input is = This Is Stackoverflow
Output(which i want)= TIS
But i am getting Unhandheld Exception: System.Indexoutofbound exception: Index was outside the bound of array
//my code is
using System;
public class n2
{

    public static void Main(String[] args)
    {

        String s1;
        Console.WriteLine("Enter the string");
        s1=Console.ReadLine();
        Console.WriteLine(s1);
        char[] charArr=s1.ToCharArray();

        for(int i=0;i<s1.Length;i++)
        {
            Console.WriteLine(charArr[i]);
        }

        Console.WriteLine(s1.Length);
        char[] n1= new char[s1.Length];
        n1[0]=charArr[0];

        for(int j=1;j<s1.Length-1;j++)
        {
                if(charArr[j]==' ')
                {
                for(int k=1;k<10;k++)
                    {
                        n1[k]=charArr[++j];
                    }
                          }
        }

        for(int i=0;i<10;i++)
        {
            Console.Write(n1[i]);
        }

    }
}

I dont know the mistake, please provide suggestions.
Thanks in advance....

A: The problem in your code is in line n1[k]=charArr[++j]; You need to check value of j before charArr[++j] in if clause. Something as follows,
if(j<s1.Length-1)
{
   n1[k]=charArr[j++]; //doing post increment!
}

A: The immediate reason of the error is in the
  n1[k]=charArr[++j];

However, regular expressions and Linq seem to be a better approach here:
  String source = "This Is Stackoverflow";

  // "TIS"
  String result = String.Join("", Regex
    .Matches(source, @"(^| )\w")
    .OfType<Match>()
    .Select(m => m.Value.Trim()));


text:
Q: Apache .htaccess - 301 redirecting home page I'm trying to redirect website A to website B. All of the sub-pages are redirecting as intended, but the home page is not. Here is a snippet of my .htaccess:
# HOMEPAGE  (This one isn't working)
RewriteRule ^/$ http://www.drinkinggamezone.com [L,R=301]

# SUBPAGE (Works)
RewriteRule ^1990s-rock-power-hour/?$ http://drinkinggamezone.com/power-hours/1990s-rock? [L,R=301]

A: You have an unnecessary / in the first part of your rule, it should be :
RewriteRule ^$ http://www.drinkinggamezone.com [L,R=301]

Regarding index.php, just do the same (again, without /, obviously) :
RewriteRule ^index.php$ http://www.drinkinggamezone.com [L,R=301]

A: Try this:
RewriteCond %{HTTP_HOST} ^DomainA.com
RewriteRule ^(.*) http://DomainB.com/$1 [P]

Hope it will work.


text:
Q: How to focus input on a child component from parent? I'm using React.forwardRef to set a ref on my Child component, like so:
const Input = React.forwardRef(
  ({ value, onChange, onKeyPress, placeholder, type, label, ref }) => (

      <input
        ref={ref}
        style={{
          borderRadius: `${scale.s1}rem`,
          border: `1px solid ${color.lightGrey}`,
          padding: `${scale.s3}rem`,
          marginBottom: `${scale.s3}rem`
        }}
        value={value}
        onChange={onChange}
        onKeyPress={onKeyPress}
        placeholder={placeholder ? placeholder : "Type something..."}
        type={type ? type : "text"}
      />

  )
);

In the parent I use const ref = React.createRef() and then call it:
 onClick = () => {
    this.setState({ showOther: true });
    console.log(this.ref, "ref");
    this.ref.focus();
  };

  render() {
    return (

        <button onClick={this.onClick}>Click me</button>
        <Input
          ref={ref}
          value={this.state.value}
          onChange={this.handleChange}
          onKeyPress={this.handleKeyPress}
          placeholder="Type something..."
        />

    );
  }

What I get from the console is this:
Object {current: null}
current: null
"ref"
My questions:

*

*Why is this null?

*How do I focus the input?

Codesandbox

A: Based on your sandbox, You use ref from outside class Component instead this.ref. Just change it from
<Input
  ref={ref}
/>

into this
<Input
  ref={this.ref}
/>

and inside onClick function to be like this
 onClick = () => {
    this.setState({ showOther: true });
    console.log(this.ref, "ref");
    this.ref.current.focus(); // change it
  };

this is the working codesandbox, enjoy!


text:
Q: enum refuses to convert to String A strange thing, I have two enum sets:
public enum ComponentActionTypes {
    Add = 0,
    Move = 1,
    Delete = 2,
    Edit = 3,
    Enable = 4,
    Disable = 5
}
public enum ComponentNames {
    Component = 0,
    Logo = 1,
    Main_menu = 2,
    Search_box = 3,
    Highlighter = 4,
    RSS = 5,
    Twitter = 6,
    YouTube = 7
}

when I try to print the following text,
ActionText =
string.Format("{0}ed a {1}", action.ComponentActionType, action.ComponentName);

will generate:
184ed a Logo instead of Added a Logo
action.ComponentActionType is converted to number (ToString didn't help) and also a
strange number (like 184, not the enum number itself)
Any idea how to solve this?
Update:
namespace BrandToolbar.Common.ActionLog.Model
{
    public class ActionItem
    {
        public Guid UserId { get; set; }
        public Int64 PublicId { get; set; }
        public ComponentActionTypes ComponentActionType { get; set; }
        public DateTime Date { get; set; }
        public ComponentNames ComponentName { get; set; }
        public string UiJsonPreview { get; set; }
    }
}

public static ActionItemUI ConvertModelToUiObj(ActionItem action)
{
    return new ActionItemUI()
    {
        ActionText = string.Format(
            "{0}ed a {1}",
            action.ComponentActionType,
            action.ComponentName
        ).Replace("_", " "),
        TooltipText = string.Format(
            "{0}ed on {1}",
            action.ComponentActionType,
            action.Date.ToString(StringFormatter.DateFormat)
        ),
        ImageUrl = string.Empty,
        ConponentText = string.Empty
    };
}

A: ComponentActionTypes.Add has value == 0. action.ComponentActionType from code sample has value == 184. So far as enum variables allow to store values, which are not in enum definition, you've got such result.
You need to check, why action.ComponentActionType equals to 184.

A: Try
Enum.GetName(typeof(ComponentActionTypes), action.ComponentAction);

Not sure about the "184" through.

A: Can you check how the ComponentActionType field is filled? Enum values can contain other values than listed. For example: this is perfectly valid:
    enum foo {A = 1,B = 2,C = 3};
    var b = (foo)7;

(If it wasn't allowed by default, masking with enums would not be possible). The string representation in this case for b is 7, because it cannot be matched to an item in the enumeration.


text:
Q: How to merge two collections and let result end up in user defined field? Suppose I have two collections: one main collection and one collection containing meta data. The meta data has additional (volatile) data that I don't want to have in my main collection.
What I'd like to do next is to merge this meta data with the main collection. This is possible since they both use the same _id. However I don't want all meta data to end up in the main document, I want to to end up in a field named meta. Like this:
// Main record
{
  _id: 1234,
  varA: "foo",
  varB: "bar"
}

// Meta record
{
  _id: 1234,
  metaA: "cafe",
  metaB: "babe"
}

The merge should end up with
// Merged record
{
  _id: 1234,
  varA: "foo",
  varB: "bar",
  meta:
  {
    metaA: "cafe",
    metaB: "babe"
  }
}

Obviously I could manually iterate through all documents and combine them myself, but that's slow and I'm sure this can be solved using aggregation stages.
I already tried various options of $merge, all to no avail. If anyone has an idea, please let me know.
Thanks!

A:
I already tried various options of $merge, all to no avail. If anyone has an idea, please let me know.

If I'm understanding the situation appropriately, there is no option built into the $merge stage that would achieve your goal directly. Rather, the solution here is going to be in shaping the data via preceding stages in the aggregation prior to the $merge itself.
Specifically, the meta record that you currently have looks like this:
{
  _id: 1234,
  metaA: "cafe",
  metaB: "babe"
}

What you need it to be in order to use $merge directly looks something more like this:
{
  _id: 1234,
  meta: {
    metaA: 'cafe',
    metaB: 'babe'
  }
}

Such a transformation can be achieved with a pipeline such as:
[
  { $addFields: {meta:'$$ROOT'} },
  { $unset:'meta._id' },
  { $project:{_id:1, meta:1} }
]

Putting this altogether and appending the $merge (with default values) yields the change to the document(s) in the main collection as desired:
> db.main.find()
[
  { _id: 1234, varA: 'foo', varB: 'bar' }
]
> db.meta.find()
[
  { _id: 1234, metaA: 'cafe', metaB: 'babe' }
]
> db.meta.aggregate([
  {$addFields:{meta:'$$ROOT'}},
  {$unset:'meta._id'},
  {$project:{_id:1, meta:1}},
  {$merge:{into:'main'}}
])

> db.main.find()
[
  {
    _id: 1234,
    varA: 'foo',
    varB: 'bar',
    meta: { metaA: 'cafe', metaB: 'babe' }
  }
]


text:
Q: Loss in Keras is stable I have the sample with 378 lines and 15 columns. Every line is some values. I need to categorize in 3 classes.
Code:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import numpy
import pandas as pd
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Input
from keras.models import Model
from keras import optimizers
tokenizer = Tokenizer()
def load_data_from_arrays(strings, labels, train_test_split=0.9):
    data_size = len(strings)
    test_size = int(data_size - round(data_size * train_test_split))
    print("Test size: {}".format(test_size))

    print("\nTraining set:")
    x_train = strings[test_size:]
    print("\t - x_train: {}".format(len(x_train)))
    y_train = labels[test_size:]
    print("\t - y_train: {}".format(len(y_train)))

    print("\nTesting set:")
    x_test = strings[:test_size]
    print("\t - x_test: {}".format(len(x_test)))
    y_test = labels[:test_size]
    print("\t - y_test: {}".format(len(y_test)))
    size = data_size - test_size

    return x_train, y_train, x_test, y_test, size, test_size
def create_labels(re_mass, size, num_class):
    train_mass = numpy.zeros([size, num_class])
    for i in range(size):
        for j in range(num_class):
            if j + 1 == re_mass[i]:
                train_mass[i][j] = 1
    return train_mass
hidden_size = 512
sgd = optimizers.SGD(lr=0.001, momentum=0.0, decay=0.0, nesterov=False)
df=pd.read_csv('/home/llirik/PycharmProjects/MegaBastard/Exp.csv',usecols = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14],skiprows = [0],header=None)
d = df.values
l = pd.read_csv('/home/llirik/PycharmProjects/MegaBastard/Pred.csv',usecols = [0] ,header=None)
labels = l.values
data = numpy.float32(d)
labels = numpy.array(l)
X_train, y_train, X_test, y_test, size, test_size = load_data_from_arrays(data, labels, train_test_split=0.5)
print('Размерность X_train:', X_train.shape)
print('Размерность y_train:', y_train.shape)
epochs = 2
num_classes = 3
Y_train = create_labels(y_train, size, num_classes)
Y_test = create_labels(y_test, test_size, num_classes)
print('Размерность Y_train:', Y_train.shape)
inp = Input(shape=(15, ))
hidden_1 = Dense(hidden_size, activation='relu')(inp)
hidden_2 = Dense(hidden_size, activation='relu')(hidden_1)
out = Dense(num_classes, activation='softmax')(hidden_2)

model = Model(inputs=inp, outputs=out)
model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])

print(model.summary())
history = model.fit(X_train, Y_train,
                    batch_size=1,
                    epochs=epochs,
                    verbose=1,
                    validation_split=0.1,
                )
score = model.evaluate(X_test, Y_test,
                       batch_size=1, verbose=1)

print()
print(u'Оценка теста: {}'.format(score[0]))
print(u'Оценка точности модели: {}'.format(score[1]))

I don't know how validation_split works, but I think problem is not here.
Output
Test size: 189

Training set:
     - x_train: 188
     - y_train: 189

Testing set:
     - x_test: 189
     - y_test: 189
Размерность X_train: (188, 15)
Размерность y_train: (189, 1)
Размерность Y_train: (188, 3)
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 15)                0
_________________________________________________________________
dense_1 (Dense)              (None, 512)               8192
_________________________________________________________________
dense_2 (Dense)              (None, 512)               262656
_________________________________________________________________
dense_3 (Dense)              (None, 3)                 1539
=================================================================
Total params: 272,387
Trainable params: 272,387
Non-trainable params: 0
None
Train on 169 samples, validate on 19 samples
Epoch 1/2

  1/169 [..............................] - ETA: 40s - loss: 0.0000e+00 - acc: 0.0000e+00
  7/169 [>.............................] - ETA: 6s - loss: 0.0000e+00 - acc: 0.4286
 14/169 [=>............................] - ETA: 3s - loss: 0.0000e+00 - acc: 0.5714
 21/169 [==>...........................] - ETA: 2s - loss: 0.0000e+00 - acc: 0.4762
 28/169 [===>..........................] - ETA: 2s - loss: 0.0000e+00 - acc: 0.4643
 34/169 [=====>........................] - ETA: 2s - loss: 0.0000e+00 - acc: 0.5294
 41/169 [======>.......................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5122
 48/169 [=======>......................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5417
 55/169 [========>.....................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5273
 62/169 [==========>...................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5161
 69/169 [===========>..................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5072
 76/169 [============>.................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5000
 83/169 [=============>................] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4699
 90/169 [==============>...............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4889
 97/169 [================>.............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4948
104/169 [=================>............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4904
111/169 [==================>...........] - ETA: 0s - loss: 0.0000e+00 - acc: 0.5045
118/169 [===================>..........] - ETA: 0s - loss: 0.0000e+00 - acc: 0.5000
125/169 [=====================>........] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4960
132/169 [======================>.......] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4924
139/169 [=======================>......] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4820
146/169 [========================>.....] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4863
153/169 [==========================>...] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4771
160/169 [===========================>..] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4688
166/169 [============================>.] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4819
169/169 [==============================] - 2s 10ms/step - loss: 0.0000e+00 - acc: 0.4911 - val_loss: 0.0000e+00 - val_acc: 0.3684
Epoch 2/2

  1/169 [..............................] - ETA: 1s - loss: 0.0000e+00 - acc: 1.0000
  8/169 [>.............................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.6250
 15/169 [=>............................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5333
 22/169 [==>...........................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.5455
 29/169 [====>.........................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.4483
 36/169 [=====>........................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.4444
 43/169 [======>.......................] - ETA: 1s - loss: 0.0000e+00 - acc: 0.4419
 50/169 [=======>......................] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4600
 57/169 [=========>....................] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4386
 64/169 [==========>...................] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4219
 71/169 [===========>..................] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4507
 78/169 [============>.................] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4744
 85/169 [==============>...............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4706
 92/169 [===============>..............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4891
 99/169 [================>.............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4848
106/169 [=================>............] - ETA: 0s - loss: 0.0000e+00 - acc: 0.5000
112/169 [==================>...........] - ETA: 0s - loss: 0.0000e+00 - acc: 0.5000
119/169 [====================>.........] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4874
126/169 [=====================>........] - ETA: 0s - loss: 0.0000e+00 - acc: 0.5000
133/169 [======================>.......] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4962
140/169 [=======================>......] - ETA: 0s - loss: 0.0000e+00 - acc: 0.5000
147/169 [=========================>....] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4898
154/169 [==========================>...] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4870
161/169 [===========================>..] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4969
168/169 [============================>.] - ETA: 0s - loss: 0.0000e+00 - acc: 0.4940
169/169 [==============================] - 1s 8ms/step - loss: 0.0000e+00 - acc: 0.4911 - val_loss: 0.0000e+00 - val_acc: 0.3684

  1/189 [..............................] - ETA: 0s
 20/189 [==>...........................] - ETA: 0s
 39/189 [=====>........................] - ETA: 0s
 58/189 [========>.....................] - ETA: 0s
 78/189 [===========>..................] - ETA: 0s
 98/189 [==============>...............] - ETA: 0s
118/189 [=================>............] - ETA: 0s
138/189 [====================>.........] - ETA: 0s
158/189 [========================>.....] - ETA: 0s
178/189 [===========================>..] - ETA: 0s
189/189 [==============================] - 0s 3ms/step

Оценка теста: 10.745396931966146
Оценка точности модели: 0.14285714285714285

Question
For some reason the network is not trained. I think, because the error does not change. Why it does not change? The network seems to be not complicated.

A: It seems like your training loss is zero, so optimizer can't do anything beyond this point. Given that you have so little training data, you might be overfitting and the model fails to generalize to validation.


text:
Q: How to place two forms on the same page? I want to place both register and login form on the same page.
They both starts with:
if (!empty($_POST)) ...

so, I need something like:
if (!empty($_POST_01))...  // regForm
  and
if (!empty($_POST_02))...  //loginForm

Also how to prevent executing first form if the second is busy, and vice versa (user clicks on both)
My idea is to create a simple variable on starting process, for example $x = 1 and at the end of process $x = 0, so:
if ((!empty($_POST_01)) And $x = 0)...

Probably, there is a better way.

A: Well you can have each form go to to a different page. (which is preferable)
Or have a different value for the a certain input and base posts on that:
switch($_POST['submit']) {
    case 'login':
    //...
    break;
    case 'register':
    //...
    break;
}

A: Give the submit buttons for both forms different names and use PHP to check which button has submitted data.
Form one button - btn1
Form two button -btn2
PHP Code:
if($_POST['btn1']){
    //Login
}elseif($_POST['btn2']){
    //Register
}

A: You can use this easiest method.

<form action="validator.php" method="post" id="form1">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="submit" form="form1">
</form>

<form action="validator.php" method="post" id="form2">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="submit" form="form2">
</form>

A: You could make two forms with 2 different actions
<form action="login.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<form action="register.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Register">
</form>

Or do this
<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="login">
    <input type="submit" value="Login">
</form>

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="register">
    <input type="submit" value="Register">
</form>

Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.
Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure

A: Here are two form with two submit button:
<form method="post" action="page.php">
  <input type="submit" name="btnPostMe1" value="Confirm"/>
</form>

<form method="post" action="page.php">
  <input type="submit" name="btnPostMe2" value="Confirm"/>
</form>

And here is your PHP code:
if (isset($_POST['btnPostMe1'])) { //your code 1 }
if (isset($_POST['btnPostMe2'])) { //your code 2 }

A: Hope this will help you. Assumed that login form has: username and password inputs.
if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}


text:
Q: centos7 jps return nothing I am using a centos7 on VMware, somehow today, when I run jps, it return nothing, it used to have at least a jps process.
[xxxxxx]$ jps
[xxxxxx]$

Any suggestions about why this is happening, and how to solve it?


text:
Q: Webpack can't find (font) dependencies NPM/Webpack can't find dependencies with Laravel Mix
These dependencies were not found:

* font-awesome
* ionicons

ERROR in multi lodash jquery bootstrap-sass fastclick jquery-slimscroll admin-lte icheck ionicons font-awesome datatables.net datatables.net-bs
Module not found: Error: Can't resolve 'font-awesome' in 'D:\Laragon'
 @ multi lodash jquery bootstrap-sass fastclick jquery-slimscroll admin-lte icheck ionicons font-awesome datatables.net datatables.net-bs

More clearly. These are installed (can find them in node_modules) and require location is correct. I'm also using more packages, and these problems are related to, coincidentally, the only fonts in my webpack.
They are available in the package.json and package.json.lock.
Installed trying different methods: firstly npm install and --save-dev, also tried yarn install and yarn add.
My webpack.mix.js:
let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.webpackConfig({
    module: {
        loaders: [
            {
                test: /\.js?/,
                exclude: [/node_modules/, /styles/],
                loaders: ['babel'],
                include: path.join(__dirname, 'src')
            },
            {
                test: /\.scss$/,
                loader: 'style!css!resolve-url!sass?sourceMap'
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff'
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file-loader'
            }
        ]
    }
});

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

mix.js('resources/assets/js/auth.js', 'public/js')
   .sass('resources/assets/sass/auth.scss', 'public/css');

mix.js('resources/assets/js/admin-lte.js', 'public/js')
   .sass('resources/assets/sass/admin-lte.scss', 'public/css');

mix.autoload({
    jquery: [ '$', 'jQuery', 'jquery'],
    DataTable: 'datatables.net-bs'
});

mix.extract([
    'lodash', 'jquery', 'bootstrap-sass',
    'fastclick', 'jquery-slimscroll', 'admin-lte',
    'icheck', 'ionicons', 'font-awesome',
    'datatables.net', 'datatables.net-bs'
], 'public/js/vendor.js');

mix.version();

I also tried it without the mix.webpackConfig, adding the config this was a desperate attempt to fix the fonts.
Here is my package.json:
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "admin-lte": "^2.4.2",
        "axios": "^0.17",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1.3",
        "datatables.net": "^1.10.16",
        "fastclick": "^1.0.6",
        "font-awesome": "^4.7.0",
        "icheck": "^1.0.2",
        "ionicons": "^3.0.0",
        "jquery": "^3.3.1",
        "jquery-slimscroll": "^1.3.8",
        "laravel-mix": "^2.0",
        "lodash": "^4.17.4",
        "popper.js": "^1.12",
        "script-loader": "^0.7.2"
    },
    "dependencies": {
        "bootstrap-sass": "^3.3.7",
        "datatables.net-bs": "^1.10.16"
    }
}

And in my .scss:
@import '~font-awesome/scss/font-awesome';

Both on Mac and Windows 10

A: Include Font Awesome into your NPM config
"devDependencies": {
   ......
   ......
    "font-awesome": "^4.7.0"
}

Run npm update
And then your app.scss include this
// Font Awesome
@import "~font-awesome/scss/font-awesome.scss";

Run npm dev or `npm watch

A: Getting rid of font-awesome and ionicons from the extract function solves the problem.


text:
Q: enable/disable form submit button not working I have been working with a form in which I want the submit button to be disabled unless a textarea and a select option is chosen.
The textarea verifications works fine, the problem is with the select.
The thing is that the select takes its value from a Custom drowpdown that pases the value to the select and I think that is the problem, as the script doesn't take it as the select has a value.
The script works if:
a) You first pick a select option and then type in the textarea.
b) You type in the textarea, select an option and then type again in the textarea.
The script for the enable/disable button is this
    $(function () {
        $("#result, #content-text-ta").bind("keyup change",
  function () {
      if ($("#content-text-ta").val() != "" && $("#result").val() != "")
          $(this).closest("form").find(":submit").removeAttr("disabled").removeClass('disabled').addClass('enabled');
      else
          $(this).closest("form").find(":submit").attr("disabled", "disabled").removeClass('enabled').addClass('disabled');
      });
        });

The textarea and dropdown that pases the value to the select (id="catselect")
<textarea title="Post Text" name="content-text-ta" id="content-text-ta"></textarea>

Elige categoria

Citas Famosas1

Frases Bonitas2

                    <fieldset">
                        <select name='categories' id='catselect' class='tdomf_categories' size='1'>
                            <option id="result"></option>
                        </select>
                    </fieldset>

A: Use the following code:
function validateForm() {
    if ($("#content-text-ta").val() !== "" && $("#catselect").val().length > 0) {
        $("form").find("input[type*='submit']").removeAttr("disabled").removeClass('disabled').addClass('enabled');
    } else {
        $("form").find("input[type*='submit']").attr("disabled", "disabled").removeClass('enabled').addClass('disabled');
    }
}
$(function() {
    $("#catselect").html("");
    $(".dropdown dd ul li a").click(function() {
        var text = $(this).html();
        $(".dropdown dt a span").html(text);
        $(".dropdown dd ul").hide();
        $("#catselect").val($("#sample").find("dt a span.value").html());
        validateForm();
    });
    $("#catselect").append($("<option/>", {
        value: "",
        text: $(this).find('span').first().contents().filter(function() {
            return this.nodeType == 3;
        }).text()
    }));
    $(".dropdown dd ul li").each(function() {
        $("#catselect").append($("<option/>", {
            value: $(this).find(".value").text(),
            text: $(this).find('a').first().contents().filter(function() {
                return this.nodeType == 3;
            }).text()
        }));
        $("#catselect, #content-text-ta").bind("keyup change click", validateForm);
    });

Live Demo | Source


text:
Q: jquery mobile refresh header bar I'm using jQuery Mobile to make a mobile version of my website and have a question regarding refreshing cached pages.
I have a header bar and have placed a login button on it.
If the user clicks the button and successfully logs in, I replace the login button (on the server side) with a logout button.
The problem is, if I press the browser back button, the login button is still displayed.
Subsequently loaded (non-cached) pages correctly show the logout button.
I'm presuming this is because when I press back, the page is coming from cache?
Is there a way I can refresh the header bar so it shows the logout button on cached pages too?
I don't think I can just refresh the entire page in question because I don't know which pages the user has visited before they login.

A: There is a number of options:
1) Disable pages cache (browser back & forward buttons):
$.mobile.hashListeningEnabled = false;

2) Create event catches the current page name and than manipulate the header: (something like...):
$("#PageName").live("pagebeforeshow", function (event, data) {

    // get current URL
    var pageName = $(location).attr("href").split("#")[1];

    // manipulate by the page name
    if(pageName == XXX){

       Header....

    }
}


text:
Q: How to copy specific columns in specific order from one sheet to another? I need to copy date and time, code and names from a big data sheet, which contains multiple columns. Row counts may differ.
The sequence of actions should be:

*

*Copy the consecutive Range from A3  which is the first active cell through to the data at column AZ - This is a manual selection.

*Using the VBA linked Command button start the process of copying data in next sheet:
for example

sheet1.column B  = sheet2.column A
sheet2.column B= ""
'empty and data copy is not needed, please just generate the empty row
sheet1.column Y = sheet2.column C

*After the copying process is over, clear all data from sheet1

My core problem is the data count for above rows differs every time. I can't find a correct sequence of commands to get these columns in the order I need from sheet1. To add to that, the formatting breaks and the time values are 'stringified', so it can't be reused.
The generated data needs to be exported to another workbook and the copying process is critically important as I do it repeatedly. Locating and copying each column manually every time.

A: The solution to your problem is of the form f(x) = y where x is the column no. of the source sheet and y is the column number of that very same column on the destination sheet.
f(x) is a simple mapping between a Source column and transformed into a destination column no.
As you still need to define the problem better by including sample data, I'll simply brief you on The 3 steps to resolve your problem.
I hope you know your VBA well enough to encode the steps into the specific VBA code you need to solve this permanently.

*

*Create a sheet as a "ControlPanel" that maps the columns you need.

*Assuming your sheets are named appropriately as per the code below.

*Kindly do apply your VBA skills and discretion to customize the code below as per your needs.
Public Sub Add_Msng_And_Check_Prev_EmpData()
''  Objective : Check missing employees from the incoming data placed in the Destination_Sheet sheet which is the client's format.
''  The _Source_Sheet sheet is our destination where processed data sits,
''  columns from Destination_Sheet are mapped to specific columns of the _Source_Sheet sheet.
''  Copy the missing emp codes to these mapped columns.

'' Support :  myfullnamewithoutspaces@gmail.com
'' Status : Production 14-Dec-2016 10.32 PM
'' Version : 1.0
'' To Do : 10 is the column number on Source_Sheet where the emp code resides
'' Convert this magic number to a generic solution

Dim Src_Sheet, Destination_Sheet As Worksheet
Dim Dest_Sheet_Column_Mapping, Src_Sheet_Column_Location As Range

Set Src_Sheet = Sheets("Source_Sheet")
Set Destination_Sheet = Sheets("Destination_Sheet")

Set Dest_Sheet_Column_Mapping = Sheets("ControlPanel").Range("A2:A60")
Set Src_Sheet_Column_Location = Sheets("ControlPanel").Range("D2:D60")

Dim myMap()  As Integer
Dim myRow As Variant
ReDim myMap(Dest_Sheet_Column_Mapping.Count + 1)

'' Map the source_columns to the destination_columns
For Each myRow In Src_Sheet_Column_Location
'' Index corresponds to Source_Sheet column
'' Value at Index to Destination_Sheet
'' for eg: Destination_Sheet.column = myMap(Src_Sheet.column)
    myMap(myRow) = Dest_Sheet_Column_Mapping.Cells(myRow, 1).Value
Next myRow

Dim Primary_Key_Not_Null As Collection
Set Primary_Key_Not_Null = New Collection
Dim Master, Src_Sheet_Range, Src_Range As Range
Dim MissingEmployeeCode, LookupValue, tempVar, LookupResult  As Variant
Dim LastRow, i, Src_Range_Rows_Count, Src_Sheet_Range_Rows_Count As Integer

'' This is the source of all new entries we need to search for.
Set Src_Sheet_Range = Destination_Sheet.Range(Destination_Sheet.Cells(1, myMap(10)), Destination_Sheet.Cells(Destination_Sheet.Cells(1048576, myMap(10)).End(xlUp).Row, myMap(10)))
Src_Sheet_Range_Rows_Count = Src_Sheet_Range.Rows.Count

'' This is the database of all previous existing entries we need to search against.
Set Src_Range = Src_Sheet.Range(Src_Sheet.Cells(1, 10), Src_Sheet.Cells(Src_Sheet.Cells(1048576, 10).End(xlUp).Row, 10))
Src_Range_Rows_Count = Src_Range.Rows.Count

    For i = 3 To Src_Sheet_Range_Rows_Count
    '' Skip the blank rows and header at rows 0 to 2
        On Error Resume Next
        LookupValue = Destination_Sheet.Cells(i, myMap(10)).Value
            LookupResult = Application.Match(LookupValue, Src_Range, 0)
                If (IsError(LookupResult)) Then
                '' To Do : Check for Duplicates within the previously added values
                '' LookupValue becomes your missing empcode and i is the row number it's located at
                '' The row number i becomes critical when you want to copy the same record that you have just found missing.
                    Primary_Key_Not_Null.Add i '' LookupValue
                    '' LookupValue is the actual missing empcode, however we need the row number for the copy operation later
                End If
    Next i

LastRow = Src_Sheet.Cells(1048576, 10).End(xlUp).Offset(1, 0).Row
Dim FirstRow, LastColumn, j, Src_Range_Columns_Count As Integer
FirstRow = LastRow

''--Phase 3--------------------------------------------------------------------------------------------------
'' Objective : Get and paste data for each missing empcode
With Src_Range
    LastColumn = .Cells(1, 1).End(xlToRight).Column
    LastRow = Primary_Key_Not_Null.Count + FirstRow
    Set Src_Range = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn))
    Src_Range_Columns_Count = Src_Range.Columns.Count
        For i = FirstRow To LastRow ''FirstRow + 3 '' Commented for Debugging
            For j = 1 To Src_Range_Columns_Count '' 59
            ''  The simple logic is Row Numbers and Column numbers obtained from all the above operations
            ''  define the cells in the Src_Sheet sheet that we need this data pasted ito.
            ''  For details please see the code below.
            Src_Sheet.Cells(i, j).Value = Destination_Sheet.Cells(Primary_Key_Not_Null(i - FirstRow + 1), myMap(j)).Value
            Next j
        Next i
End With

''--Phase 4--------------------------------------------------------------------------------------------------
''  Objective : For the previous range in Source_Sheet, check each cell in each column against the mapped columns in the Destination_Sheet.
''  When you find a discrepancy: style it Bad, for the matches: style it Good,
''  for the not found : Style it neutral.
LastRow = FirstRow
FirstRow = 2
Set Src_Range = Src_Sheet.Range(Src_Sheet.Cells(2, 1), Src_Sheet.Cells(LastRow, LastColumn))
Src_Range.Style = "Normal"

Dim FoundRow, FoundColumn As Integer
FoundRow = 0
FoundColumn = 10
Dim LookupRange, LookupDatabase As Range
Set LookupRange = Src_Sheet.Range(Src_Sheet.Cells(1, 10), Src_Sheet.Cells(LastRow, 10))
Set LookupDatabase = Destination_Sheet.Range(Destination_Sheet.Cells(1, myMap(10)), Destination_Sheet.Cells(Src_Sheet_Range_Rows_Count, myMap(10)))

Dim FoundRows As Collection
Set FoundRows = New Collection

'' Locate the row of each employee code on Emp Master, push it into a collection and let the emp code be it's key
Dim LookupRange_Row_Count As Integer
LookupRange_Row_Count = LookupRange.Rows.Count
For i = 2 To LookupRange_Row_Count
On Error Resume Next
    FoundRow = Application.Match(LookupRange.Cells(i, 1).Value, LookupDatabase, 0)
    If (Not IsError(FoundRow)) Then
    '' myRow contains EmpCode which is the key, FoundRow = Where I Found it, becomes the value.
     FoundRows.Add FoundRow, CStr(LookupRange.Cells(i, 1).Value)
    End If
Next i

Dim Src_Sheet_Value, EmpMstrValue, myEmpCodeString As String

For i = FirstRow To LastRow '' 2 to 1029
    For j = 1 To Src_Range_Columns_Count '' 59
    ''  Handle 4 cases.
    ''  1.  Src_Sheet Cell Value Found and matches = Good
    ''  2.  Src_Sheet Cell Value Found and does not match = Bad
    ''  3.  Src_Sheet Cell Value Not Found or not in Scope and hence does not match = Neutral
    ''  4.  Src_Sheet Cell Value is a duplicate of a value which is already checked earlier. = ??
    Src_Sheet_Value = Src_Sheet.Cells(i, j).Value
        myEmpCodeString = CStr(LookupRange.Cells(i, 1).Value)
        myRow = CInt(FoundRows(myEmpCodeString))
    EmpMstrValue = Destination_Sheet.Cells(myRow, myMap(j)).Value

    ''  Implements 1.  Src_Sheet Cell Value Found and matches = Good

    If Src_Sheet_Value = EmpMstrValue Then
        Src_Sheet.Cells(i, j).Style = "Good"
    Else
        Src_Sheet.Cells(i, j).Style = "Bad"
    End If

    Next j
Next i
End Sub

I found myself in the same situation as yourself sometime back. Although the code is conceptually simple, it requires you to thoroughly define your problem in the Source, Destination, Transformation pattern.
Do Feel free to mail me at myfullnamewithoutspaces@gmail.com. I'll assist any way I can.


text:
Q: Bluetooth issue after upgrade to Ubuntu 20.04 I just upgraded my computer form Ubuntu 18.04 to Ubuntu 20.04 using the terminal. Everything went fine (except for some issues with the video card embedded in the motherboard but I was expecting this and I should have fixed it) but now I cannot turn on the bluetooth switch. I have a bluetooth dongle (Qualcomm Atheros Communications AR3011 Bluetooth, according to lsusb) but I did not menage to turn it on. If I run sudo modprobe btusb I get an erro message saying:
modprobe: FATAL: Module btusb not found in directory /lib/modules/5.4.0-1053-gke
I have upgraded (both with update and dist-update) but all package are up to date.
The output of service bluetooth status is:
 bluetooth.service - Bluetooth service
     Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: man:bluetoothd(8)

The output of lsusb is:
Bus 002 Device 002: ID 8087:8002 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:800a Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 002: ID 03f0:5d17 HP, Inc HP LaserJet P2035
Bus 003 Device 005: ID 046d:c077 Logitech, Inc. M105 Optical Mouse
Bus 003 Device 004: ID 1c4f:0002 SiGma Micro Keyboard TRACER Gamma Ivory
Bus 003 Device 003: ID 0cf3:3000 Qualcomm Atheros Communications AR3011 Bluetooth (no firmware)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub


text:
Q: Связывание переменных и оператор IN Доброе время суток, коллеги!
Несомненно, связывание переменных важный момент при написании адекватного приложения, работающего с БД. Но как быть с оператором IN ?
Попробовали передать строку вот так:
select * from table where id in ( :array_id )
:array_id = '10,20,30,40,50'

Естественно array_id воспринимается как строка и нужного эффекта не производит...
Далее пришла в голову идея о использовании
select * from table where
instr( :array_id , ','||id||',') > 0
:array_id = ',10,20,30,40,50,'

Но подсознание подсказывает что это будет не самое лучшее решение с точки зрения быстродействия.
Неужели нет более корректного решения подобной проблемы?
A: варианты решения:

1) из строки "1,2,3" формируем запрос вида:
select 1 as <fieldname> from dual
union
select 2 as <fieldname> from dual
union
select 3 as <fieldname> from dual

который подставляется в изначальный запрос. если не прокатит то придется еще и завернуть в курсор + стоит вынести локигу в отдельную функцию/процедуру
2) используем временную таблицу. если нет таблицы создаем ее:
create tmp_table as (
... вставляем сюда запрос из пункта 1
)

если есть таблица (спец. заготовленная для наших нужд) то все проще (формируем набор insert'ов):
insert into tmp_table values (1);
insert into tmp_table values (2);
insert into tmp_table values (3);

думаю что делать дальше с ними понятно ?

В свое время аналогичную задачу решали таким способом: 2 таблицы tasks, task_args. в первой задаем таск во второй его аргументы. Процедура вытягивала по id задачи значения парметров. напр:
select int_value from task_args where task_id = ? and arg_name = "account_id";

select str_value from task_args where task_id = ? and arg_name = "account_name";

не стоит забывать что любые подобные извращения убивают перфоманс
A: Обсуждение на SO для примера. Краткий ответ: так не получится.
Варианты решения:

*

*генерация текста запроса и параметры в цикле.

*создание временной таблицы и занесение списка в нее, т.е. парсить строку будет субд.

*instr - убивает всю идею индексов и проч.

Самый простой и правильный метод - первый. Какой бы ни был запрос, проще его сформировать и дать базе заниматься тем, что она умеет лучше - выбирать данные, а строки передавать для парсинга - это вариант тупиковый.

A: Проблема не нова. Есть хорошая статья на эту тему.
Помнится, что есть перевод какой-то версии этой статьи.
A: Попробуйте использовать DBMS.SQL


text:
Q: How to extract specific lines from a text file using awk? I have a text file that looks like this.
A   102
B   456
C   678
H    A       B        C      D       E        F      G       H       I       J
    1.18    0.20    0.23    0.05    1.89    0.72    0.11    0.49    0.31    1.45
    3.23    0.06    2.67    1.96    0.76    0.97    0.84    0.77    0.39    1.08

I need to extract all the lines that start with B,H and two  lines after H . How can I do this using awk?
The expected output would be
 B   456
 H    A       B        C      D       E        F      G       H       I       J
    1.18    0.20    0.23    0.05    1.89    0.72    0.11    0.49    0.31    1.45
    3.23    0.06    2.67    1.96    0.76    0.97    0.84    0.77    0.39    1.08

Any suggestions please.

A: awk '/^[BH]/ || /^[[:blank:]]*[[:digit:]]/' inputfile

A: Ignoring the blank line after B in your output (your problem specifications give no indication as to why that blank line is in the output, so I'm assuming it should not be there):
awk '/^H/{t=3} /^B/ || t-- >0' input.file

will print all lines that start with B and each line that starts with H along with the next two lines.

A: bash-3.00$ cat t
A   102
B   456
C   678
H    A       B        C      D       E        F      G       H       I       J
    1.18    0.20    0.23    0.05    1.89    0.72    0.11    0.49    0.31    1.45
    3.23    0.06    2.67    1.96    0.76    0.97    0.84    0.77    0.39    1.08

bash-3.00$ awk '{if(( $1 == "B") || ($1 == "H") || ($0 ~ /^ / )) print;}' t
B   456
H    A       B        C      D       E        F      G       H       I       J
    1.18    0.20    0.23    0.05    1.89    0.72    0.11    0.49    0.31    1.45
    3.23    0.06    2.67    1.96    0.76    0.97    0.84    0.77    0.39    1.08

OR in short
awk '{if($0 ~ /^[BH ]/ ) print;}' t

OR even shorter
awk '/^[BH ]/' t

A: cat filename.txt | awk '/^[B(H(^ .*$){2})].*$/' > output.txt

EDIT: Updated for OP's edit

A: If H and B aren't the only headers that are sent before tabular data and you intend to omit those blocks of data (you don't specify the requirements fully) you have to use a flip-flop to remember if you're currently in a block you want to keep or not:
awk '/^[^ 0-9]/ {inblock=0}; /^[BH]/ {inblock=1}; { if (inblock) print }' d.txt


text:
Q: Can I reuse a calculated field in a SELECT query? Is there a way to reuse a calculated field within a mysql statement. I get the error "unknown column total_sale" for:
SELECT
    s.f1 + s.f2 as total_sale,
    s.f1 / total_sale as f1_percent
FROM sales s

or do I have to repeat the calculation, which would make for a very long SQL statement if I added all the calculations I need.
SELECT
    s.f1 + s.f2 as total_sale,
    s.f1 / (s.f1 + s.f2) as f1_percent
FROM sales s

of course I can do all the calculations in my php program.

A: Yes, you can reuse variables. This is how you do it:
SELECT
    @total_sale := s.f1 + s.f2 as total_sale,
    s.f1 / @total_sale as f1_percent
FROM sales s

Read more about it here: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
[Note: This behavior is undefined. According to the MySQL docs:]

As a general rule, you should never assign a value to a user variable and read the value within the same statement. You might get the results you expect, but this is not guaranteed.

A: You can use a sub-select:
select tbl1.total_sale,
       tbl1.f1/tbl1.total_sale as f1_percent
  from (select s.f1+s.f2 AS total_sale,
               s.f1
          from sales s) as tbl1;

A: The following seems to work well in my testing on MySQL 5.5:
SELECT
    s.f1 + s.f2 as total_sale,
    s.f1 / (SELECT total_sale) as f1_percent
FROM sales s

A: You can use subqueries, like this:
SELECT
    h.total_sale,
    s.f1 / h.total_sale AS f1_percent
FROM sales s,
    (SELECT id, f1 + f2 AS total_sale FROM sales) h
WHERE
    s.id = h.id

Edit:
fixed cartesian product, assuming the primary key is id.
This should be equivalent to OMG Ponies' solution after optimizing, but I think it will become harder to read if you need more subqueries.

A: I had a look at various answers here and did a few experiments.
Specifically I am using MariaDB 10.1.
For a "simple" thing you can do what Robert D suggested in his comment:
SELECT Price_Per_SqFt, (Price_Per_SqFt/2) AS col1, (SELECT col1 + 1) AS col2 FROM Items

If you are using some sort of aggregate function with an inner join you can't use this, but you can combine this approach with the inner join approach as follows (NB VAT = "sales tax"... and NB in financial data currency fields typically have 4 decimal places, I think it's historic...)
SELECT
    invoices.invoiceNo, invoices.clientID, invoices.Date, invoices.Paid,
  invoicesWithSubtotal.Subtotal,
  ROUND( CAST( Subtotal * invoices.VATRate AS DECIMAL( 10, 4 )), 2 ) AS VAT,
  (SELECT VAT + Subtotal) AS Total
FROM invoices
    INNER JOIN
    ( SELECT Sum( invoiceitems.Charge ) AS Subtotal, invoices.InvoiceNo FROM invoices
        INNER JOIN invoiceitems ON invoices.InvoiceNo = invoiceitems.InvoiceNo
            GROUP BY invoices.InvoiceNo ) invoicesWithSubtotal
    ON invoices.InvoiceNo = invoicesWithSubtotal.InvoiceNo

I wanted to use the above to create a View to list invoices with their subtotals, VAT and totals... it turned out that MariaDB (and almost certainly MySQL) don't allow nesting in the FROM clause.  However this is easily solved by making a first View which lists the InvoiceNo and Subtotal, and then making a second View which references the first. Performance-wise I have no idea at all about this sort of double-View arrangement.

A: Only cross-platform supported means is by using a derived table/inline view:
SELECT x.total_sale,
       x.f1 / x.total_sale as f1_percent
  FROM (SELECT s.f1,
               s.f1 + s.f2 as total_sale,
          FROM sales s) x

A: I have been testing the following and it seems to work all the time, maybe there is a reason for this, is it because I have predefined the variable @total_sales as being a value not a string, and have not redefined its type during the select statement ??
If I  do  the following
    set @total_sales = 0;

    SELECT
       @total_sale := s.f1 + s.f2 as total_sale,
      s.f1 / @total_sale as f1_percent
   FROM sales s