text:
Q: How do I replace a specific position (X,Y) in a string with multiple lines? (PHP) I've got a field 30x7 (see below) and I want to replace a specific position.
The position is randomly given and I want to replace the random position (X,Y) with a letter.
I already got the field and the replacement but it's not exactly what I want.
`
 $field=('################################')."\n".str_repeat.('#                              #\n', 7)('################################')."\n"

`
The field will look like this
##############################
#                            #
#                            #
#                            #
#                            #
#                            #
#                            #
#                            #
##############################

and the empty space at the given position should be replaced with a letter.
It's 32x9 with the hashtags so only the empty spaces are the actual field.
I don't know how to exclude the surrounding hashtags from the position and how to calculate the actual position from x and y.
   $position=($position_x)*($position_y);
   $field=substr_replace($field,'O',$position,1);
   echo("$field");

That's what I tried. I know that $position is wrong but I don't know how to fix it.
Is it even possible with the way I created the field or should I try it differently?
Thanks for your help in advance!

A: You need to make sure your $field is correct. Your code has some syntax errors.
The trick is to calculate the coordinates.

*

*increase x + 1 for the left border

*increase y + 1 for the top border

*the cols are + 3, because of left border, right border and the newline

*For the final position multiply the number of rows by number of columns plus x

$placeField = function (string $char, int $x, int $y): string {
    $cols = 30;
    $rows = 7;

    $topBottomFrame = str_repeat('#', $cols + 2) . "\n";
    $centerFrame    = '#' . str_repeat(' ', $cols) . "#\n";
    $field          = $topBottomFrame . str_repeat($centerFrame, $rows) . $topBottomFrame;

    if ($x < 0 || $x >= $cols || $y < 0 || $y >= $rows) {
        return "Invalid coordinates\n";
    }

    $x++;
    $y++;

    return substr_replace($field, $char, $y * ($cols + 3) + $x, 1);
};

echo $placeField("A", 0, 0);
echo $placeField("B", 29, 6);
echo $placeField("C", 15, 3);

Output
################################
#A                             #
#                              #
#                              #
#                              #
#                              #
#                              #
#                              #
################################
################################
#                              #
#                              #
#                              #
#                              #
#                              #
#                              #
#                             B#
################################
################################
#                              #
#                              #
#                              #
#               C              #
#                              #
#                              #
#                              #
################################


text:
Q: Cmake not working after installed from pip After I installed the cmake from pip, I did a symbolic link from where pip has installed the cmake to /usr/bin/cmake, but it seems cmake does not work properly through a symbolic link. Error message:
CMake Error: Could not find CMAKE_ROOT !!!
CMake has most likely not been installed correctly.

Any thoughts on how to make this work without reinstalling by other means?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assign polygon to the nearby points in ArcMap I'm a new user to ArcGIS and I'm trying to match a polygon to a point that's nearby. To be more specific, the blue area are the census tracts that get polluted. The green spots are the factories, the potential sources of the pollution. I would like to take every census tract and match it with the nearby factory (basically assuming the nearby factory is the culprit). If the census tract itself contains one factory, I want them to get matched. If the census tract itself contains more than one factory as in the highlighted area on the image, I'd like this census tract get matched to all the factories within it. If the census tract itself contains no factory, I'd like to match it with the closest factory.
I tried 'Join' from 'Join and relates' and 'Spatial Join' and 'Near' from the toolbox. It looks like 'Spatial Join' does what I want (one to many, closet). But when the census tract has two factories in it, it only gets matched to one of them, not both. I also exported the attribute table of the spatial join and the one to many match is still not there.
I'm not sure what I did wrong or maybe it can be achieved by some other function that I'm aware of. I'm currently working with ArcGIS desktop 10.3


text: Q: Heteroscedasticity due to skewness of predictor(s) I read that in a linear model skewness of one of the independent variables can be the reason for heteroscedasticity in the model but I can't think of (or create) an example where this would be the case, i.e. where $Y = X \beta + u$ with $u \sim N(0, \Sigma)$ but where a Goldfeld-Quandt test would (correctly) detect heteroscedasticity. What would be such an example or is the initial statement incorrect?


text:
Q: Labeling specific features in ArcGIS for Desktop? In ArcGIS 10.3 for Desktop, I work with this point layer and I want to remove all the Sg & Sgs labels from it:

So I can get this result only:

All the labels are in one field named "field_name" (it is a string type field).
I can seperate the data into two fields or export the features with the numbers only.
I prefer to remove it with SQL Expression. I tried this one:
def FindLabel ([field_name]):
  if "Sg" IN [field_name] :
    pass
  return [field_name]

I am getting this error:
Error 0 no line 0.
SyntaxError: invalid syntax (<string>, line 2)

A: Your second line includes the word IN in uppercase and in python it should be lower case in.
Your return line should be inside an else
Possibly better than an in you should just check for the first two characters:
def FindLabel ([field_name]):
    if [field_name][:2] == "Sg" :
        pass
    else:
        return [field_name]

A: If you only want to label the feature with it Object ID (the numbers you posted in the second picture), then you need to open the layer properties, navigate to the display tab and select label all features the same way and use the field Object ID form the drop down. Simple as that.


text:
Q: Reflections in custom java gradle plugin I have a gradle project with multiple modules, each built to it's own .jar file. I want to use reflections in a custom java gradle plugin, to generate a report on annotated classes/methods.
/build.gradle
apply plugin: com.my.plugins.MyPlugin

/buildSrc/build.gradle
repositories {
    mavenCentral()
}

dependencies {
    compile 'org.reflections:reflections:0.9.11'
    compile 'javax.annotation:javax.annotation-api:1.3.2'
}

/buildSrc/src/main/java/com/my/plugins/MyPlugin.java
@NonNullApi
public class MyPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {
        MyTask myTask = project.getTasks().create("mytask", MyTask.class);
        Task javaCompileTask = project.getTasks().getByName("compileJava");
        myTask.dependsOn(javaCompileTask);
    }
}

/buildSrc/src/main/java/com/my/plugins/MyTask.java
public class MyTask extends DefaultTask {

    @TaskAction
    public void perform() throws MalformedURLException, ClassNotFoundException {

        List<URL> listOfURL = new ArrayList<>();
        Set<File> runtimeFiles = getProject().getConfigurations().findByName("runtime").getFiles();
        for (File file : runtimeFiles) {
            // TODO: Exclude files from gradle cache folder
            if (file.getPath().contains("build\\libs")) {
                listOfURL.add(file.toURI().toURL());
            }
        }

        URL[] urls = listOfURL.toArray(new URL[0]);
        System.out.println("\nURLs:");
        for (URL u : urls) {
            System.out.println("  " + u.toString());
        }

        ClassLoader classLoader = new URLClassLoader(urls, null);
        classLoader.loadClass("com.my.services.sample.MyClass");
        System.out.println("\nClassLoader OK!\n");

        Configuration config = new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forClassLoader(classLoader))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.my.services")))
            .addClassLoader(classLoader)
            .setScanners(new SubTypesScanner(),
                    new TypeAnnotationsScanner(),
                    new MethodAnnotationsScanner());

        Reflections reflections = new Reflections(config);

        System.out.println("\nPermitAll Classes\n");
        for (Class c : reflections.getTypesAnnotatedWith(PermitAll.class)) {
            System.out.println(c.getName());
        }

        System.out.println("\nPermitAll Methods\n");
        for (Method m : reflections.getMethodsAnnotatedWith(PermitAll.class)) {
            System.out.println(m.getName());
        }

    }
}

When I run gradlew mytask, I see the list of all my .jar files under build\libs in the list of URLs.
Although the classLoader can successfully load (for example) MyClass, the new Reflections() line generates numerous "could not get type for name" errors, for example:

could not get type for name com.my.services.sample.MyClass from any class loader

Then, the list of PermitAll Classes generates correctly, but the list of PermitAll Methods fails with an exception, for example:

Execution failed for task ':mytask'.
> org/dom4j/DocumentException

I have already used the following as guides but am unable to make any further progress:
https://discuss.gradle.org/t/gradle-plugin-with-reflections/22690
Reflections could not get class type

A: You should use the following to create the classloader
URL[] urls = project.sourceSets.main.runtimeClasspath.files.collect {
    it.toURI().toURL()
} as URL[]
ClassLoader classloader = new URLClassLoader(urls, null)


text:
Q: How to extract only first line that matches each pattern from a file? I have a text file that looks like
Line_A 123
Line_A 456
Line_A 789
Line_B 123
Line_B 456
Line_B 789
Line_C 123
Line_C 456
Line_C 789

And a reference file that looks like this:
 Line_A
 Line_B
 Line_C

I want to extract the first line from the text file that matches each name in the reference file like this:
Line_A 123
Line_B 123
Line_C 123

So far I can only get the first line from the first match with:
grep -A1 -w -f  reference.txt -m 1 file.txt

Maybe I need a for loop? TIA

A: another awk
$ awk 'NR==FNR{a[$1];next} $1 in a{delete a[$1]; print}' reference file

keep the references in a set, when seen in the file print the line and remove reference, so only the first instance will be printed.

A: Yet another awk:
$ awk 'a[$1]++==1' ref file
Line_A 123
Line_B 123
Line_C 123

Read both files in above order, count each string in first column and print when it's seen the second time. This will fail if there are strings in file that are not in reference. In that case use one of the other solutions.

A: You can do it in Awk with a single pass over the files as long as you list the reference file first in the argument list:
awk 'FNR == NR { name[$1] = 0; }
     FNR != NR { for (i in name) if ($0 ~ i && name[i]++ == 0) { print $0; break; } }' \
    reference.txt file.txt

With the sample inputs, this yields the required output.
This is a fairly standard technique in Awk.  You read the first file using the FNR == NR condition (file line number equal to overall line number; only true for lines in the first file) and save appropriate information for later use.  Often, people use a next in the first line; it works.  It means they can avoid
the FNR != NR condition — I like that for symmetry.
When processing the second and subsequent files, check whether each of the names read from the first file matches a line, and the name hasn't been printed before, printing the line if it hasn't been handled.  The break avoids checking other names if the current name matches.
This is the way many people would write the command; it also works.
awk 'FNR == NR { name[$1] = 0; next }
     { for (i in name) if ($0 ~ i && name[i]++ == 0) { print $0; break; } }' \
    reference.txt file.txt

Both versions of the code here look for the name anywhere in the line; if you strictly want to match the $1 of the second (or subsequent) files, you can alter the conditions (indeed, simplify them).  And karakfa shows deleting matches when they're matched (instead of incrementing a counter), which is better for performance as you don't have to continue matching that which is no longer relevant.  However, the code shown here would be simpler to adapt to showing the second, or third, or last entry for a given name (handling second or third involves changing the 0 to 1 or 2; handling 'last' requires more substantial changes).


text:
Q: Construct an arbitrage opportunity in a multi-period model I am currently revising for my exam in Financial Mathematics, and I could not solve this question:
For $T > 1$, consider a $T$-period model with a single risky asset and a bank account which pays zero interest, $r = 0$. The price process of the asset is given by
\begin{align*}
S(0) = 1, \quad S(t) = \begin{cases}
S(t-1) e^{X(t-1)}, & S(t-1) > \varepsilon \\
S(t-1) e^{X(t-1)+2}, & S(t-1) \le \varepsilon
\end{cases},
\quad t = 1, \ldots, T,
\end{align*}
where $\varepsilon \in (0,1)$ and $X = (X(t), t \ge 0)$ is a sequence of iid random variables such that each $X(t)$ takes the value $1$ with probability $1/2$ and $-1$ with probability $1/2$.
Construct an arbitrage opportunity for this model and verify all the conditions which define such an opportunity. Hint: for a complete answer, you will need to state appropriate assumptions on $\varepsilon$ and $T$.
What I have done so far:
We search a self-financing trading strategy $H$ such that $V_0 = 0$, $V_T \ge 0$ and $\mathbb EV_T > 0$. So if
\begin{align*}
0 = V_0 = H_0(1)+H_1(1) \underbrace{S(0)}_{= 1} = H_0(1)+H_1(1),
\end{align*}
we must have
\begin{align}
H_0(1) = -H_1(1).
\end{align}
Next, since $H$ needs to be self-financing and $r = 0$, we obtain
\begin{align}
V_t = V_t^* = V_0^* + G_t^* = V_0 + G_t = 0 + G_t = G_t.
\end{align}
Write
\begin{align*}
S(t) &= S(t-1)e^{X(t-1)} 1_{\{S(t-1) > \varepsilon\}} + S(t-1)e^{X(t-1)+2} 1_{\{S(t-1) \le \varepsilon\}} \\
&= S(t-1)e^{X(t-1)} (1_{\{S(t-1) > \varepsilon\}} + e^2 1_{\{S(t-1) \le \varepsilon\}}).
\end{align*}
We have that
\begin{align*}
V_T &= G_T = \sum_{u = 1}^T H_1(u) \Delta S(u)
= \sum_{u = 1}^T H_1(u) (S(u) - S(u-1)) \\
&= \sum_{u = 1}^T H_1(u) (S(u-1)e^{X(u-1)} (1_{\{S(u-1) > \varepsilon\}} + e^2 1_{\{S(u-1) \le \varepsilon\}}) - S(u-1)) \\
&= \sum_{u = 1}^T H_1(u) S(u-1) (e^{X(u-1)} (1_{\{S(u-1) > \varepsilon\}} + e^2 1_{\{S(u-1) \le \varepsilon\}}) - 1)
\end{align*}
Unfortunately, I don't really know how to go on and to derive some conditions. Please help.


text:
Q: Spotfire: How to calculate a new column based off a column with blanks using another column to help get the correct value to insert Example:
Name|Number|CALC
----|------|----
a   |123   |a
    |123   |a
a   |123   |a
a   |123   |a
b   |321   |b
    |321   |b
    |321   |b

I need to get a calculated column that will find the non-null value in the Name column corresponding to the correct number in the number column so that I can filter by name and get all the data.

A: You just need a Max() and Over statement.
Max([Name]) over ([Number])


text:
Q: LINQ query - Multiple where with multiple sub queries based on int array I have a sql query that performs the type of select I'm after:
select * from Products p where p.ProductId in (
    select distinct ProductId from ProductFacets
    where ProductId in (select ProductId from ProductFacets where FacetTypeId = 1)
    and ProductId in (select ProductId from ProductFacets where FacetTypeId = 4)
)

There can be multiple FacetTypeIds passed into this query.
This query is constructed in a method based on a parameter argument of type int[].
public IEnumerable<Product> GetProductsByFacetTypes(string productTypeSysName, int[] facetTypeIds)

I'm trying to work out how to achieve this in LINQ. So far I've come up with something like this:
var products = from p in sc.Products
where p.ProductType.SysName == productTypeSysName
where p.FacetTypes.Any(x => x.FacetTypeId == 1)
where p.FacetTypes.Any(x => x.FacetTypeId == 4)
select p;

This returns the correct result set.
However I'm not sure how I can build this query using the int[] facetTypeIds parameter.
EDIT:
ProductFacets contains the following data:
ProductId, FacetTypeId
1, 1
1, 2
2, 1
2, 3
3, 4
3, 5
4, 1
4, 2

As an example, I'd like to be able to select only Products which have a FacetTypeId of 1 AND 2.
The result set should contain ProductIds 1 and 4

A: A local collection may be transmitted to the database by calling Contains:
from ft in facetTypes
where facetTypeIds.Contains(ft.FacetTypeId)
select ft;

The local collection is translated into sql parameters.  Sql Server has a limit of ~2100 parameters, so beware.

Products that have any of the facets
from p in sc.Products
where p.ProductType.SysName == productTypeSysName
where
(
  from ft in p.FacetTypes
  where facetTypeIds.Contains(ft.FacetTypeId)
  select ft
).Any()
select p;

Products that have all facets.
int facetCount = facetTypeIds.Count();

from p in sc.Products
where p.ProductType.SysName == productTypeSysName
where
(
  from ft in p.FacetTypes
  where facetTypeIds.Contains(ft.FacetTypeId)
  select ft.FacetTypeId
).Distinct().Count() == facetCount
select p;

A: EDIT:  Sorry I misread the question.  I would suggest you use a PredicateBuilder and build up the Where clause dynamically if you need all of the types to be present.  This would use extension methods directly.
var facetTypeIds = new [] { 1, 4, ... };
var predicate = PredicateBuilder.True<Product>();
foreach (int id in facetTypeIds)
{
    int facetId = id; // avoid capturing loop variable
    predicate = predicate.And( p => p.FacetTypes.Any( x => x.FacetTypeId == facetId );
}

var products = sc.Products
                 .Where( p => p.ProductType.SysName == productTypeSysName )
                 .Where( predicate );

Original (wrong, but left for context):
You want to use Contains.   Note also you can use the logical and to replace multiple Where clauses with a single Where clause.
var facetTypeIds = new [] { 1, 4, ... };

var products = from p in sc.Products
where p.ProductType.SysName == productTypeSysName
      &&  p.FacetTypes.Any( x => facetTypeIds.Contains( x.FacetTypeId ) )
select p;

A: This is based on tvanfosson's code.  I have doubts about the performance of this approach though.
var facetTypeIds = new [] { 1, 4, ... };

var products = from p in sc.Products
where p.ProductType.SysName == productTypeSysName
      && facetTypeIds.All(ft => p.FacetTypes.Any(x => x.FacetTypeId == ft))
select p;


text:
Q: Delete some items while looping a set I want something like:
for node_a in A_nodes:
    a_pos = A.node[node_a]['pos']
    link_len = math.sqrt((a_pos[0]-a_base_pos[0])**2+(b_pos[1]-b_base_pos[1])**2)
    if link_len < th:
        A_nodes.remove(node_a)

How to meet my requirements?

A: You can try like this,
myset = { item for item in myset if item<tr}

Or,
new_set = {}
for item in myset:
   if item < tr:
      new_set.add(item)

myset = new_set

A: You could use set.intersection and range:
>>> tr = 5
>>> myset = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> myset.intersection(range(tr + 1))
{1, 2, 3, 4, 5}
>>> myset & set(range(tr + 1))
{1, 2, 3, 4, 5}
>>>

As you can see, everything greater than tr is removed.

A: The problem you'll have with this is you can't modify a collection in place while you're iterating over it, so you'll need to filter and reassign to my_set instead. There are a number of ways you can do this.
Example 1: Comprehension
my_set = {item for item in myset if item < tr }

Example 2: Filter
def my_filter(item):
    item < tr

my_set = filter(my_filter, my_set)

Example 2a: Filter with lambda
my_set = filter(lambda x: x < tr, my_set)

Example 3: For loop
new_set = {}
for item in my_set:
    if item < tr:
        new_set.add(item)
my_set = new_set

So if we were to apply 2A to your code, roughly because you're not showing a lot of variable definitions:
def calc_len(node):
    #return the length here using your calculation

A_nodes = filter(lambda x: calc_len(x) < th, A_nodes)


text:
Q: show a subset of $\mathbb R^n$ is compact if it is closed and bounded Use the two lemmas to prove that a subset of $\mathbb R^n$ is compact if it is closed and bounded.
Lemma 1: A closed subset of a compact space is compact
Lemma 2: If $X$ and $Y$ are compact then $X\times Y$ is compact.
I had an idea, but that was quickly shown to be wrong by the answers in this thread
https://math.stackexchange.com/questions/1026318/a-closed-and-bounded-subset-of-rn/1026334#1026334
Thanks

A: Your idea from the previous thread was almost correct.
HINT: Show that if $A\subseteq\Bbb R^n$ is closed and bounded, then it is a subset of some product of closed intervals (in fact, you can use the same interval!).


text:
Q: Concat multiple rows based on If/Then to poulate a 5 digit code Hoping someone can help.
I have data as follows in two seperate columns in a table called StudentRace
Student_ID    RaceCD
----------    ------
123456        1
123456        2
589645        4
987654        3
987654        4

I am looking for a way to combine the data for the students by student id to output into 00000 format. example: Student_ID 123456 RACE: 12000; Student_ID 589645 Race: 00040; Student_ID 987654  Race = 00340. I need to have it be a sub query as it is part of a large report that pulls 50+ fields. If anyone is able to help I would greatly appreciate it. I am using Toads Data Point for Oracle to create my query.

A: The result can be achieved with a single group by without any joins.
Setup
CREATE TABLE studentrace
(
    Student_ID,
    RaceCD
)
AS
    SELECT 123456, 1 FROM DUAL
    UNION ALL
    SELECT 123456, 2 FROM DUAL
    UNION ALL
    SELECT 589645, 4 FROM DUAL
    UNION ALL
    SELECT 987654, 3 FROM DUAL
    UNION ALL
    SELECT 987654, 4 FROM DUAL;

Query
  SELECT student_id, LPAD (SUM (racecd * POWER (10, 5 - racecd)), 5, '0') AS race
    FROM studentrace
GROUP BY student_id;

Result
   STUDENT_ID     RACE
_____________ ________
       589645 00040
       987654 00340
       123456 12000

A: You can use a partitioned outer join:
SELECT t.Student_id,
       LISTAGG( COALESCE( t.raceCD, 0 ) ) WITHIN GROUP ( ORDER BY r.race )
         AS RaceCDs
FROM   ( SELECT LEVEL AS race
         FROM   DUAL
         CONNECT BY LEVEL <= 5 ) r
       LEFT OUTER JOIN table_name t
       PARTITION BY ( t.Student_ID )
       ON ( r.race = t.RaceCD )
GROUP BY t.student_id

Which, for your test data:
CREATE TABLE table_name ( Student_ID, RaceCD ) AS
SELECT 123456, 1 FROM DUAL UNION ALL
SELECT 123456, 2 FROM DUAL UNION ALL
SELECT 589645, 4 FROM DUAL UNION ALL
SELECT 987654, 3 FROM DUAL UNION ALL
SELECT 987654, 4 FROM DUAL

Outputs:

STUDENT_ID | RACECDS
---------: | :------
    123456 | 12000
    589645 | 00040
    987654 | 00340

db<>fiddle here


text:
Q: How can I add columns from 2 different files to an output in CSV python my test.csv
1,1,2
2,1,3
3,1,4

my test2.csv
2,3
2,3
2,3

How can i make the output.csv:
1,1,2,2,3
2,1,3,2,3
3,1,4,2,3

so to combine two csv files to one?
Here's my code
import csv, os, sys
with open('test.csv', 'rb') as input, open('output.csv', 'wb') as output, open ('test2.csv', 'rb') as input2:
        reader = csv.reader(input, delimiter = ',')
        reader2 = csv.reader(input2, delimiter = ',')
        writer = csv.writer(output, delimiter = ',')

        all = []
        header = next(reader)
        all.append(header)
        count = 0
        for row,row2 in reader and reader2:
                count += 1
                while count:
                        all.append(row+row2)
                        break
        writer.writerows(all)

Obviously this doesn't work, but does anybody understand what I'm going for?

A: Use zip() to iterate over both readers at once:
reader1 = csv.reader(input, delimiter = ',')
reader2 = csv.reader(input2, delimiter = ',')

for row1, row2 in zip(reader1, reader2):
    writer.writerow(row1 + row2)

Or a shorter version:
writer.writerows(map(list.__add__, row1, row2))

In case the files are huge then using map, zip is not going to be a good idea in Python 2, as they will load all the rows from both files, better go for their iterator versions present in
itertools module: itertools.imap and itertools.izip:
for row,row2 in reader and reader2: is equivalent to iterating over just reader2 because and works like this:
>>> 1 and 2
2
>>> 2 and 3
3
>>> 0 and 2  # returned the first falsy value, but as an iterator is not a falsy value
0            # so it will return `reader2` in your case.

Update:
To update test2.csv in-place you can use the fileinput module, but with this you won't be able to use the csv module.
>>> import fileinput
>>> with open('test.csv') as f:
    for line in fileinput.input('test2.csv', inplace=True):
        print next(f).rstrip() + ',' + line,
...
>>> !cat test2.csv
1,1,2,2,3
2,1,3,2,3
3,1,4,2,3

Using csv module you'll have to read all the lines from test2.csv in memory first and then write the new data into it.
with open('test.csv') as f1, open('test2.csv', 'r+') as f2:
                                   #open in r+ mode
   reader1 = csv.reader(f1)
   rows_f2 = list(csv.reader(f2)) #read all the rows
   f2.truncate(0)                 #truncate the file
   writer = csv.writer(f2)
   writer.writerows(map(list.__add__, reader1, rows_f2))

A: Simply just concatenate line by line with comma...
with open('test.csv', 'rb') as input, open('output.csv', 'wb') as output, open ('test2.csv', 'rb') as input2:
    for row, row2 in zip(input, input2):
        output.write(row.rstrip('\n') + ',' + row2)


text:
Q: youTube data API V3 - search return Error 400 when PublishedAfter is used I am running a search by keyword from a java project, exactly like in the example -
https://developers.google.com/youtube/v3/code_samples/java#search_by_keyword
It works great, but when I add to the example the PublishedAfter option
search.setPublishedAfter(myDateTime);
it returns error 400 message": "Bad Request"
  YouTube.Search.List search = youtube.search().list("id,snippet");

  String apiKey = properties.getProperty("youtube.apikey");
  search.setKey(apiKey);
  search.setQ(queryTerm);
  search.setPublishedAfter(myDateTime) // the code works when removing this line

  search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
  search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

  SearchListResponse searchResponse = search.execute();
  List<SearchResult> searchResultList = searchResponse.getItems();

I want to use the setPublishedAfter option
Please Help
Thanks

A: Youtube api v3 says that "The publishedAfter parameter indicates that the API response should only contain resources created after the specified time. The value is an RFC 3339 formatted date-time value (1970-01-01T00:00:00Z)" Therefore, your problem is most likely to because of your date format. Look at your "myDateTime" object. Mistake should be near to it. Also look at my code :
Calendar cal = Calendar.getInstance();
Date currentDateOfAmerica=cal.getTime();
cal.set(12, cal.get(12)-1);
Date dateOneMinuteBefore=cal.getTime();
DateTime dt1 = new DateTime(dateOneMinuteBefore);
DateTime dt2 = new DateTime(currentDateOfAmerica);

search.setPublishedAfter(dt1);
search.setPublishedBefore(dt2);

This code segment sets searching video which are uploaded between now and one minute ago

A: You are having a problem with fields part. Most likely publishedafter is not described in fields part you suggested.
Just comment out setFields, should work.


text:
Q: HIVE via Python hive_utils/hive_service: logging in as a particular user Currently I can successfully connect and run queries from Python on HIVE using hive_utils doing the following:
import hive_utils

query = """ select * from table
            where partition = x
"""

conn = hive_utils.HiveClient(server=x, port=10000,db='default')

a = conn.execute(query)
a = list(a)

Queries that include conditional statements however (and that work over HUE) such as:
 query = """ select * from table
             where partition = x
             and app_id = y
 """

have returned this error:

HiveServerException:  errorCode=1,  message='Query returned non-zero
  code:1' cause: FAILED: Execution Error return code 1 from
  org.apache.hadoop.hive.ql.exec.MapRedTask SQLState='08S01'

Since i am not sending any kind of user information when i establish a connection, I suspect the error is due to the type of permissions available to whichever user is being set.
How do I identify myself as a particular user?

A: Please refer to the following:
Re: FAILED: Execution Error, return code -101 from org.apache.hadoop.hive.ql.exec.MapRedTask
Most relevant section is:
Go to this link :
http://docs.amazonwebservices.com/ElasticMapReduce/latest/DeveloperGuide/UsingEMR_Hive.html

and add

hadoop-0.20-core.jar
hive/lib/hive-exec-0.7.1.jar
hive/lib/hive-jdbc-0.7.1.jar
hive/lib/hive-metastore-0.7.1.jar
hive/lib/hive-service-0.7.1.jar
hive/lib/libfb303.jar
lib/commons-logging-1.0.4.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar

to the class path of your project , add this jars from the lib of hadoop
and hive, and try the code. and also add the path of hadoop, hive, and
hbase(if your are using) lib folder path to the project class path, like
you have added the jars.


text:
Q: Weird behavior when copying one hash to another I have a class which manages configuration (saved locally as JSON) and I've written a method to copy configuration from one file to another. Both JSON files are loaded as hashes into instance variables (@local and @repository, respectively). I've run into some strange behavior where setting a key on one hash is overwriting the value for the same key in the other hash. I've narrowed my issue down to line 14 of the code snippet below. My puts statement on line 12 shows @repository[brand][:branches][branch] as being a non-empty hash with data, while my puts statement on line 21 shows @repository[brand][:branches][branch] as being an empty hash.
def copy(brand, branch = nil)
    brand = brand.to_sym
    branch =  branch.to_sym

    if branch.nil?
        if @local[:repository].has_key?(brand)
            @local[:repository][brand].deep_merge(@repository[brand])
        else
            @local[:repository][brand] = @repository[brand]
        end
    else
        puts @repository[brand][:branches][branch]
        unless @local[:repository].has_key?(brand)
            @local[:repository][brand] = @repository[brand]
            @local[:repository][brand][:branches] = Hash.new
        end

        unless @local[:repository][brand][:branches].has_key?(branch)
            @local[:repository][brand][:branches][branch] = Hash.new
        end
        puts @repository[brand][:branches][branch]
        @local[:repository][brand][:branches][branch].deep_merge(@repository[brand][:branches][branch])
    end

    self.write(CONFIG_FILE, @local)
end

If I change line 14 to @local[:repository][brand] = Hash.new, the value for that hash on line 21 is no longer empty and is in fact the expected value. One key thing is that the brand key in @local[:repository] doesn't exist yet.
Can anyone shed some light on what's going on here?

A: The culprit lies in this line (which you use twice):
@local[:repository][brand] = @repository[brand]

This does not make a copy of the hash that resides in @repository[brand]. Let's split that up a bit so we can talk about it more clearly:
brand_detail = @repository[brand]
local_repo = @local[:repository]
local_repo[brand] = brand_detail

After the third statement, local_repo[brand] will not contain a copy of the brand_details hash but instead a reference to that hash. So now all of these lines would have the same effect; they would all modify the same hash instance:

*

*brand_detail[:branches] = 3

*local_repo[brand][:branches] = 3

*@repository[brand][:branches] = 3
You should be able to circumvent this by explicitly adding a copy instead of a reference using dup:
@local[:repository][brand] = @repository[brand].dup


text:
Q: How to find object with Missing label? I have a requirement where I need to create a list of all missing labels in any particular object.
For example.
I want to create a new table with a couple of fields and an overridden method. Now, suppose I am setting up the table property label as "Car details" similarly I am creating new fields and setting their label properties as "Car" and "Model" respectively and overriding validateWrite method with the error "Car-model combination not valid". But, I am not creating a label for any one of them. So now I want to write a job which will show that I need to create three missing labels.
I know Best practice check will give me warnings for the above scenario but I need it as a list as I'll use this list to enhance the Label editor.
Thanks in advance.

A: You could loop through the AOT using the TreeNode class and select elements where the label property is blank. Then you can send the information out to the infolog or whatever you wish.
There are numerous code examples out there of how to do that, such as this one looping over forms selecting on the HTMLHelpTopic property.


text:
Q: Basis of a Tensor Product I was wondering if anyone could explain why the following proof of linear independence is not valid.
Choose the identity function, $i: V \times W \to V \times W$. This function is clearly bilinear so by definition of the tensor product it induces a linear function $\bar{i}:V \otimes W \to V \times W$ defined by $\bar{i}(v \otimes w) = (v,w).$ Next we observe that if the bases are given as above, then $\{(v_i,w_j)\}_{i \in I, j \in J}$ forms a basis for $V \times W$.  Now we may use the result that if the image of a set of elements under a linear function is a basis, then those elements are linearly independent, along with $\{v_i \otimes w_j\}_{i \in I, j \in J} \subset V \otimes W$ as the set with the observation that $\bar{i}(v_i \otimes w_j) = (v_i,w_j)$ to conclude that $\{v_i \otimes w_j\}_{i \in I, j \in J}$ is linearly independent.

A: The identity function is not bilinear. $(a+b,c)=(a,c)+(b,0)\neq (a,c)+(b,c)$.


text:
Q: Ошибка, при одновременном запуске php с одинаковыми post данными Помогите, пожалуйста. Никогда с таким не встречался. Проблема в том что с ajax отправляется запрос на сервер, с определенным $_POST['num'], ему по этому номеру выдается товар(ы). Сами они хранятся построчно и распарсить не проблема, но вот с точки зрения защиты произошла трабла - если скрипт одновременно запустить, то он выдаст столько же раз, сколько одновременных запусков. Пробовал в temp таблице создавать временную запись делать, что текущий номер в обработке - бесполезно.
//Проверяем на то, существует ли заказ с номером из POST
for($i=0; $i<sizeof($array['data']); $i++){
        $sum = $array['data'][0]['sum']['amount'];
        $comment = $array['data'][0]['comment'];
        $status = $array['data'][0]['status'];
        if(($order['amount'] == $sum or $sum > $order['amount']) and $order['rand'] == $comment and $status == 'SUCCESS'){
            $size = intval($order['size']);
            $order_number = $order['number'];
            $order_random = $order['rand'];
            $db->Query("SELECT * FROM `product` WHERE `id`='$order_number'");
            $product = $db->FetchArray();
            $output = $product['link'];
            $output_array = explode(PHP_EOL, $output); //Разбиваем строку
            for ($j=0; $j<$size; $j++){
                $data .= $output_array[$j]; // Выводим пользователю товары в N количестве
                unset($output_array[$j]); // Удаляем их из массива
            }
            $input = implode(PHP_EOL, $output_array); // И потом записываем в строку
            $db->Query("UPDATE `product` SET `link`='$input' WHERE `id`='$order_number'");
            $db->Query("DELETE FROM `order` WHERE `rand`='$order_random'"); //Удаляем номер заказа
            $product_name = $product['name'];
            $product_date = time();//date("F j, Y, g:i a");
            $db->Query("INSERT INTO `sold` (`product`, `how`, `date`, `price`, `code`, `extract`) VALUES ('$product_name', '$size', '$product_date', '$sum', '$order_random', '$data')");
            $fail = 1;
            break;
        }
    }


text:
Q: Sessions Django: Daphne + Uwgsi I am currently deploying a django project using channel 2.x with uwgsi for http requests and daphne for background tasks.
Daphne by itself is running correctly as well as uwgsi.
Configuration for both is the following:
location /stream {
    # daphne server running on port 8001 so we set a proxy to that url
    proxy_pass http://0.0.0.0:8001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_redirect   off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
}

# These requests are handled by uwsgi
location / {
    include uwsgi_params;
    uwsgi_pass unix:/run/uwsgi/app/project/socket;

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # Make the following two variables accessible to the application:
    uwsgi_param SSL_CLIENT_VERIFY $ssl_client_verify;
    uwsgi_param SSL_CLIENT_RAW_CERT $ssl_client_raw_cert;
}

All background workers are preceded by /stream. All endpoints are protected. When login in and accessing endpoints such as /api/v1/resource it correctly returns the data but when triggering tasks via /stream I get permission denied (403). Debugging this behavior I have come to the conclusion that sessions are not persisted among Daphne and Uwsgi.
How can I achieve sessions to be shared between them?


text:
Q: Как уменьшить ширину кнопки для Windows Phone 8.1? Мне нужно разместить в своем приложении квадратную кнопку, но уменьшить ширину меньше дефолтной не получается (увеличить можно). Это вообще реально сделать со стандартной Button?

A: Всегда можно полностью переопределить темплейт. Но для начала попробуйте установить свойство MinWidth=0


text:
Q: Cannot set breakpoint at if else statement in Chrome developer tool In the old version of chrome, I can set breakpoint at if else statement to view the value of object in if condition.
But when upgraded chrome to the latest version, I cannot do it now. The breakpoint is auto place inside the if block.
It make difficult to debugging, has to place two breakpoint if I want to debug at if else statement
My source code is not minify or truncate anything else.

A: As for Chrome 67, a workaround is that you need to click on the same line in the name.js file to set a breakpoint. A breakpoint will be added automatically in the corresponding name.ts file. It's kind of awkward, but at least makes you stop at the if statement.


text:
Q: What's the measure of the radius of the circle below? For reference: In the figure, calculate $R$. If : $\overset{\LARGE{\frown}}{AB}= 120°$, $CM = 1$ and $MB = 2$
(Answer: $\frac{3}{4}(\sqrt{3}+1$))
My progress:

Draw OP
Th.Chords:
$CM.MP = BM.AM \implies 1.[(R-1)+(R)] = 2.AM\\
\boxed{2AM = 2R-1}: \boxed{R=AM+ \frac{1}{2}}\\
\triangle AOB (isósceles):$\
Draw $AE$
$\implies$
$\triangle EAB(right):
AE^2+(2+AM)^2 = 4R^2\\
AE^2 +4+4AM + AM^2 = 4R^2\\
AE^2 + 4+8R-4 + R^2 - R+\frac{1}{4} = 4R^2\\
4AE^2+16+32R - 16+4R^2-4R+1 = 16R^2\\
4AE^2+28R-12R^2+1 = 0 \implies\\
AE^2 = 12R^2-28R-1\\$
...?
I have not found another relationship with AM

A: I can't quite follow your work, but you should be able to get a relation with $AM$ and $R$ by using the fact that $OAB$ is a 30-30-120 triangle.
Hint for one possible alternate method:  Drop an altitude from $ON$ to $AB$.  So $N$ is the midpoint of $AB$.  Now focus on the lengths $OM,MN,NB,BO,ON$, writing what you can in terms of the radius $R$.
Let me know if I should elaborate.

A: $\angle AOB = 120^o$
Law of cosines:
$AB^2 = 2R^2 + 2R^2 \cdot \frac 12 = 3R^2 \implies AB = R \sqrt3$
Power point M:
$1 \cdot (2R-1) = 2 \cdot (R \sqrt3 - 2) \iff 2R -1 = 2R\sqrt3 - 4 \iff R = \frac3{2(\sqrt3-1)} = \frac{3(\sqrt3+1)}4$

A:
Extend $\overline{CMO}$ to meet the circle at E and Extend $\overline{AO}$ to meet the circle at $D$. As $\triangle ABD$ is a 30-60-90 triangle $AB=R\sqrt{3}$. Since $BM=2$ and $AM=R\sqrt{3}-2$.
Now, look at $\triangle ACM$ and $\triangle BEM$ they are similar.
$\frac{1}{2}=\frac{R\sqrt{3}-2}{2R-1}$
After solving for R you get,
$R=\frac{3}{2(\sqrt{3}-1)}$
by getting the decimal value for R,
$R=2.04$
The decimal value of the answer you have posted is also 2.04
Then the proof will be true


text:
Q: Which function does Python print use? I've got an object which I print to the terminal, and it looks like this:
>>> print b

"De neergang kan een duikvlucht worden."

So I then wondered from which function this the result is. So I tried the following:
>>> b.__repr__()
'<lxml.etree._XSLTResultTree object at 0x112c6a980>'
>>> b.__str__()
'\xe2\x80\x9eDe neergang kan een duikvlucht worden.\xe2\x80\x9d
'
>>> b.__unicode__()
'u'
\u201eDe neergang kan een duikvlucht worden.\u201d
'

As you can see, neither of these functions displays what the print statement shows. I always thought that print actually shows the result of either __repr__(), __str__() or __unicode__(), but that is clearly not the case.
So what does print actually call?

A: It is easy enough to check this sort of thing:
>>> class C(object):
    def __repr__(self):
        print("repr called")
        return "repr"
    def __str__(self):
        print("str called")
        return "str"
    def __unicode__(self):
        print("unicode called")
        return "unicode"

>>> print C()
str called
str
>>>

In fact what happens internally is that print (as a function that is, I haven't checked the opcode though I think it is the same) calls PyFile_WriteObject with the Py_PRINT_RAW flag.

int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Write
  object obj to file object p. The only supported flag for flags is
  Py_PRINT_RAW; if given, the str() of the object is written instead of
  the repr(). Return 0 on success or -1 on failure; the appropriate
  exception will be set.

A:
object.__str__(self)
Called by str(object) and the built-in functions format() and print() to compute the >'informal' or nicely printable string representation of an object. The return value must >be a string object.

This is from python documentation. So clearly, print function will call defined __str()__, if you define both __str()__ and __repr()__ inside the class. But in the case you just implement __repr()__, then print(object) shall use __repr()__.
Hope this will help.


text: Q: Where is V2 GO sdk for listing, creating, and updating openshift clusters in the GO sdk V2? I have the GO sdk V2 and used ListClusters in eks.  I ran it and it doesn't list any openshift clusters in the aws account in any region.  Where is the GO sdk V2 functions to list, create, delete, and update OpenShift clusters? Thank you!


text:
Q: Question is to find two numbers within 1 to num that multiply to become num t=int(input())
while t > 0:
    num=int(input())
    lst=[]
    n=0
    for i in range(1,math.floor(math.sqrt(num))+1):
        if num%i==0:
            lst.append(i)
    n=len(lst)
    if n == 1:
        print(1,num)
    else:
        print(lst[1],int(num/lst[1]))
    t-=1

Question is to find two numbers within 1 to num that multiply to become num(for prime it is only 1, num and for rest any 2 factors). The time limit exceeded error is the thing that I am seeing now. Can anyone help me in optimizing it?

A: You can optimise the code by changing the limit inside the range to sqrt(num).I hope this solves your problem.
You can try like this:
 import math
 t= int(input())
 while(t>0):
     num = int(input())
     lst = []
     for i in range(1,(math.sqrt(num))+1):
          if(num%i == 0):
              lst.append((i,num/i))
              break
     print(lst[0])
     t= t-1

A: *

*If you just need to find any 2 factors, there is no need to use a list. Just break after the first one found.

*As suggested in the comments, there is no need to iterate until num, as the factors will start to repeat. It is enough to iterate until the square.

*Lastly, you can take advantage of the built-in divmod function to avoid calculating the modulus and then the division.

from math import sqrt

num = int(input())
for n in range(2, int(sqrt(num)) + 1):
    div, mod = divmod(num, n)
    if mod == 0:
        print(n, div)
        break
else:
    print(1, num)

*

*This uses the for/else construct so in case no factors were found, just 1, num will be printed which is always true.


text:
Q: printStars method with recursion Here are my instructions:
Write a recursive method called printStar(int n) which will print the following when n=4:
****
***
**
*
*
**
***
****

This is what I did so far:
public class Stars{
   public static void main (String[] args){
      printStars(4);
   }

   public static void printStars(int count){
      if (count==0){
         System.out.println("");
      }
      else{
         System.out.print("*");
         printStars(count-1);
      }
   }
}

My attempt only prints one line of the given number of stars. I don't know how to print multiple lines with only one call of the method. Any help is appreciated.

A: This one uses tail recursion, is split into helper function, and uses loop only to get the character as required.
public class JavaR {
   public static void main(String[] args) {
        System.out.println(star(4, new StringBuilder()));
   }

  public static StringBuilder star(int times, StringBuilder builder) {
    return getStars(times, builder, times);
  }

  public static StringBuilder getStars(int currentIteration, StringBuilder builder, int times) {
      if (currentIteration < -1 * times) return builder;
      else if (currentIteration != 0) {
        builder.append(getNTimes(Math.abs(currentIteration)));
        return getStars(currentIteration - 1, builder, times);
      } else {
        return getStars(currentIteration - 1, builder, times);
      }
  }

  public static String getNTimes(int count) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < count; i++) {
        builder.append("*");
    }
    return builder.append("\n").toString();
  }
}

A: Your program is incorrect, see the below program and analyze it -
public class Stars{
   public static void main (String[] args){
      printStars(4);
   }

   public static void printStars(int count){
      if (count==0){
        // System.out.println("");
      }
      else{
          int tempCount = count;
          while(tempCount>0){
              System.out.print("*");
              tempCount--;
          }
         System.out.println();

         printStars(count-1);

         while(tempCount<count){
          System.out.print("*");
          tempCount++;
      }
      System.out.println();
      }
   }
}

Explanation - I am using two while loops to print stars, first to print the start in asc order and second to print in reverse order. Using variable tempCount to get the current counter.

A: Try this
public static void printStars(int count){
    if (count == 0){
        return;
    }
    printStarNTimes(count);
    printStars(count-1);
    printStarNTimes(count);
}
private static void printStarNTimes(int n) {
    for (int i = 0; i < n; i++) {
        System.out.print("*");
    }
    System.out.println();
}

Logic is in printing star count times in the current call and when the recursive call returns.

A: The method needs information about the max number of *, as well as direction (is number of * increasing or decreasing)
Since the requested method signature includes only one argument, you have a few alternatives to define the additional needed information:
Use a partially recursive method like in this and this answers, or use a helper method:
public static void printStars(int count){

    printStars(count, count, -1);
}

public static void printStars(int count , int max, int increment){

    for(int i =0; i< count; i++) {
        System.out.print("*");
    }

    count += increment;
    if(count ==0 ) { //lower limit reached
        increment = -increment;
    }else {
        System.out.println("");
    }

    if (count > max){ //upper limit reached
        return;
    }
    printStars(count, max, increment);
}


text:
Q: Store PHP File that Makes Database Calls In or Out of the Root? I have a website that uses Ajax to make PHP calls to a database.  Simple enough.  I'd like to secure my php files from prying eyes.  I've found that I can restrict some access by setting file_uploads=Off, but I'd like to go a bit further.  What is the best practice for securing this file?  I'm guessing something like Appache setting, a command in the PHP file itslef (as above), or perhaps I should just move the file out of the site's root directory, but I'm just not sure.
Many thanks!


text:
Q: Machine not connecting to Github I'm trying to follow along with a tutorial video and I am unable to get past the 1st step of creating the project using react next js. Within Visual Studio Code I enter the following then am giving the response -
after opening vscode and opening a terminal I type
-npx create-next-app -e with-tailwindcss ( then my projects name )

After I press enter, the files start to download, but then I receive an error as stated below
-Downloading files for example with-tailwindcss. This might take a moment.
? Could not download "with-tailwindcss" because of a connectivity issue between your machine and GitHub.
Do you want to use the default template instead? » (Y/n)

I am unable to start the project because I am receiving the error that there is a connectivity issue between my machine and github. I do not understand why because I have never seen this error before prior to using the command npx- create-next-app -e with-tailwindcss
If I type npx create (project name) I do not receive an error and there is no connectivity issue between my machine and github.
Does anyone know how to solve this? I have been browsing everywhere and cannot find the solution. Thank you !


text:
Q: Print LABEL text in multiple lines in Cesium JS API I have a problem printing text in multiple lines using Label in Cesium JavaScript API. text is member of Label class which takes String as input but doesn't really support multiple line labels using '\n' character (typically as in Java string1 + '\n' + string2). Is there any way of printing labels in multiple lines?

A: UPDATE, 2017-Jan-02: Cesium 1.29 was released today with official support for multi-line labels, added in #4306.  The newline '\n' character is now accepted as a line break.

Original answer:
This feature is desired but not yet implemented.  There is some code in issue #2575 that implements this, but is not yet ready to merge into master.  I'll ping the issue and see if there can be any more progress on this.
In the meantime, you can emulate the feature by placing multiple labels with different Y pixel offsets.


text:
Q: Requiring to move to older Crystal reports version to work with reports I am running version 13.0.24  of crystal reports but have to revert to an older version to print out reports. How can I update the compatibility for my app to include newer CR versions.
Also, If we add support for newest version of crystal reports, can the older version still work too so we don't have to update all existing customers installs?
I have identified that from SP21 backward compatibility is broken by googling but not sure of what are available options to achieve this.
Any help is appreciated. Thanks in advance!


text:
Q: Adding Gaussian Noise to unbalanced dataset I have a highly umbalanced dataset, and the models that I used are overfitting. I read somewhere about SMOTE and I wanted to try it. However, the latter needs at least two samples (k_neighbors=1) to perform oversampling. The minority class in my dataset has one sample, thus SMOTE won't work. To oversee this problem I want to replicate (duplicate?) the minority class and add some gaussian noise and then apply SMOTE.
So my questions are:

*

*Is this approach realistic? is it ok to apply it?

*Should I add the Gaussian noise to the features or labels or both (my dataset is already seperated to features and labels)

*How can I choose the best parameters for the gaussian noise (sigma and mu)? should I use the following code for that?

import numpy as np
mu, sigma = 0, 0.1
# creating a noise with the same dimension as the dataset (features, labels, or both) "dim"
noise = np.random.normal(mu, sigma, "dim")
print(noise)

A: Imagine that you are trying to learn a new language from a textbook. Unfortunately you were given only a single page of the textbook. This is not enough to learn much, so to generate more pages you cut the page into tiny pieces, each containing one to few letters, then shuffle them and randomly combine. Would this give you more textbook pages?
If you don't have enough data to oversample it, than the problem is not having unbalanced data, but not having enough data. You cannot gain additional data by oversampling it, or adding noise to it.
Yes, to some extent, you can use things like data augmentation, but those techniques are based on meaningful transformations of the data, rather than adding noise to it. It also won't work if your initial data is not big enough.


text:
Q: How do I position one picture over another? I want to overlay one picture on another, like this:
——————————————————————————
|                        |
|     img1               |
|                        |
|              ————————  |
|              | img2 |  |
|              ————————  |
——————————————————————————

How do I do that with ConTeXt?
I have no clue where to start. It seems that playing with spaces (e.g., \blank) won't help.

A: Loading a huge library such as tikz for such a simple task isn't necessary. You can place your img1 as a background to a frame into which you place your img2. For further adjustments, you can set parameters such as offset or top and bottom (see the documentation). Here's an example:
\startTEXpage

\defineoverlay [mybackground] [{\externalfigure [mill]
  [width=\overlaywidth,height=\overlayheight]}]

\framed [background=mybackground,
     frame=off,
     strut=no,
     width=7cm,
     height=10cm,
     offset=\zeropoint,
     top=\vss,
     bottom=,
     align=flushright]
{\externalfigure [hacker] [height=2cm]}

\stopTEXpage

With the result:

A: As mentioned by JLDiaz, TiKz is compatible with ConTeXt.  Then elaborating from this answer the solution is as simple as :
\usemodule[tikz]
\starttext
  \starttikzpicture
    \node[anchor=south west,inner sep=0] (image) at (0,0) {\externalfigure[fig1][width=10cm]};
    \startscope[x={(image.south east)},y={(image.north west)}]
      \node[anchor=south west,inner sep=0] at (0.7,0.2) {\externalfigure[fig2][width=2cm]};
    \stopscope
  \stoptikzpicture
\stoptext

(\startscope and \endscope lines are not needed if you are at ease with absolute coordinates.)
x={(image.south east)} redefines the x unitary vector as going from (0,0) (bottom left of img1) to (image.south east) (i.e. bottom right of img1).


text:
Q: JSON Object nulo soy un programador inexperto que esta desarrollando en Android utilizando el lenguaje Java. Mi problema es que estoy haciendo una request con la libreria Volley y el servidor responde correctamente pero, al momento de parsear la respuesta recibida de un JSON a un JSON Array en una clase no se llena la información y el arreglo queda como nulo. Aquí un fragmento del código
    private void getDatosVacantes() {
    String url = "http://10.18.232.64/SNE_API/getDatosVacante.php";

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            System.out.println(response);
            JsonArray jsonArray = new JsonParser().parse(response).getAsJsonArray();

            System.out.println("JSON" + jsonArray);
            JSON.DatosVacante[] vacantesDisponibles = new Gson().fromJson(jsonArray, JSON.DatosVacante[].class);

            String nombre = vacantesDisponibles[0].nomEmpresa;
            String oferta = vacantesDisponibles[0].oferta;

            System.out.println("nombre " + nombre);
            System.out.println("oferta " + oferta);
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("Error del servidor/n" + error);
        }
    });
    requestQueue.add(stringRequest);
}

Cabe destacar que se está realizando en un fragmento, de antemano gracias:)
aqui el codigo de error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sne, PID: 17584
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sne/com.example.sne.PantallaPrincipal}: java.lang.NullPointerException: Attempt to read from null array
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2907)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2986)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1641)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6694)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
 Caused by: java.lang.NullPointerException: Attempt to read from null array
    at com.example.sne.fragments.FragmentPrincipal.onCreateView(FragmentPrincipal.java:47)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
    at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
    at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
    at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
    at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1355)
    at android.app.Activity.performStart(Activity.java:7001)

A: el Problema esta en la forma que intentas parsear los datos te paso un ejemplo de como puedes obtener los valores de un JSONArray.
public static void main(String[] args) {

    try {
        String response = "[  \n"
                + "   {  \n"
                + "      \"NombreEmpresa\":\"Pizza Lalin\",\n"
                + "      \"TituloOferta\":\"Busco repartidor de pizzas\"\n"
                + "   },\n"
                + "   {  \n"
                + "      \"NombreEmpresa\":\"Mh Herramientas\",\n"
                + "      \"TituloOferta\":\"Busco operador de herramientas pesadas\"\n"
                + "   },\n"
                + "   {  \n"
                + "      \"NombreEmpresa\":\"Manisher\",\n"
                + "      \"TituloOferta\":\"Solicito ingeniero en metalurgia\\r\\n\"\n"
                + "   }\n"
                + "]";
        System.out.println(response);

        JSONParser jsonParser = new JSONParser();

        JSONArray ArrayItems = (JSONArray) jsonParser.parse(response);
        //Print Cuerpo Array
        System.err.println("ARRAY Print:" + ArrayItems.toJSONString());

        //La Mejor forma es cargando estos Datos en un ArrayList Ejemplo si lo deseas

        ArrayList<vacantesDisponibles> lista=new ArrayList<>();

        //Recorremos el Array

        for (int i = 0; i < ArrayItems.size(); i++) {
            //obtemos los objetos que componen el Array
            JSONObject cuerpo = (JSONObject) ArrayItems.get(i);
            //obtemos los valores.
            String NombreEmpresa=cuerpo.get("NombreEmpresa").toString();
            String TituloOferta=cuerpo.get("TituloOferta").toString();
            vacantesDisponibles objetos=new vacantesDisponibles();
            objetos.setNombreEmpresa(NombreEmpresa);
            objetos.setTituloOferta(TituloOferta);
            //Cargamos el Objecto al ArrayList
            lista.add(objetos);

        }

        ///o bien puedes hacer uso de los valores directamente por el Indice..
        System.err.println("Obteniendo Valores por Indice...");
        JSONObject cuerpo = (JSONObject) ArrayItems.get(0);
        //obtemos los valores.
        String NombreEmpresa=cuerpo.get("NombreEmpresa").toString();
        String TituloOferta=cuerpo.get("TituloOferta").toString();

        System.err.println("NombreEmpresa:"+NombreEmpresa);
        System.err.println("TituloOferta:"+TituloOferta);

    } catch (ParseException ex) {
        Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
    }

}


text:
Q: Align Side Navigation Panel icon in a Custom Toolbar I am using a custom Toolbar for my Android App So that I can style my app title and while doing so I have noticed that the alignment of the title and the side navigation panel icon are not in an order and I am unable to figure out how to resolve this

This is the code of the xml layout

<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/Theme.AppCompat.DayNight.DarkActionBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            app:title=" "
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginBottom="20dp"
                android:fontFamily="@font/satisfy_regular"
                android:text="CodeRem"
                android:textColor="#3C4A63"
                android:textSize="35sp"

                />
        </androidx.appcompat.widget.Toolbar>

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/frag"
            android:layout_below="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:name="com.example.coderem.Home"

            />

    </RelativeLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/nav_menu" />

</androidx.drawerlayout.widget.DrawerLayout>


text:
Q: Why %USERDOMAIN% is not "NT AUTHORITY" for SYSTEM user? Running the following command
set USERDOMAIN
set USERNAME

in a Windows service will return
USERDOMAIN=MY_CORPORATE_DOMAIN
USERNAME=SYSTEM

But my service was running in "NT AUTHORITY\SYSTEM".
My Questions are:

*

*Why is USERDOMAIN is "MY_CORPORATE_DOMAIN" not "NT AUTHORITY"?

*If I want to run taskkill as shown below to kill my process under the current user.

*

*It won't run correctly in SYSTEM user, because userdomain
return MY_CORPORATE_DOMAIN, which should return NT AUTHORITY.

How
    can I rewrite the command?
 taskkill /F /FI "USERNAME eq %userdomain%\%username%" /IM my_process.exe

A: On a domain, the SYSTEM user uses the credentials of the Active Directory machine account under some circumstances, this being one of them. Computers have accounts too; their SAM names are just the computer name with an extra $ at the end. Therefore, a computer named CATACLYSM in the INFERNO domain would get INFERNO\CATACLYSM$ in response to echo %userdomain%\%username%.
If you want to get NT AUTHORITY\SYSTEM for programs running as SYSTEM, use the whoami utility. Sadly, there's not a nice way in Windows batch to put the output of a command in a variable. This Stack Overflow answer would suggest you do something like this:
whoami > tmp-whoami
set /p currentuser= < tmp-whoami
del tmp-whoami

You would then be able to use %currentuser% in place of %userdomain%\%username%.


text:
Q: how to delete specific map keys from a button Flutter/Dart I have a Map of string and doubles. I am creating a button for each key. This works fine (see photo).  On long press, I would like to delete that key/button. The issue I am having is that the key that gets deleted is always the last entered regardless if you press the first or any other key. This is a for fun project and I am willing to rewrite all of this if there is a better way. The goal for the map is to keep track of how many of that string there are. EX: "pencils":2 etc
for ( name in materialMap.keys)
            Container(
              child:ElevatedButton(
                child: Text(name),
                onPressed: () {},
                onLongPress: () {

                  displayDeleteDialog(context,name );
                },
              ),
            ),

The delete dialog
Future<void> displayDeleteDialog(BuildContext context, String name ) async {
  //this brings up an alert dialog to input material

   name=name;

  return showDialog(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: Text('Are you sure you would like to remove material'),
        actions: <Widget>[
          TextButton(
            child: Text('OK'),
            onPressed: () {
              materialMap.removeWhere((key, value) => key == name);
              //materialList.remove(materialList[indexDeleteM]);
              Navigator.push(
                context,```

  [1]: https://i.stack.imgur.com/wQ0lN.png

A: If I understand correctly, you are having trouble updating materialMap within the presentation layer.  The first thing would be that I would change the Map into an Iterable data structure, like List, so you can have indexes to make it easier to remove.  Then this sounds like a state management problem, which you can use a variety of libraries or methodologies such as Bloc/Cubit, Riverpod, Provider, or Stateful Widget.
The broad strokes are that you will store the materialMap as a List high in the Widget tree and then use some kind of builder each time you update the state.
Cubit
class MyCubit extends Cubit<int> {
  /// Your initial list of material
  MyCubit() : super([{"pencil":2},{"paper":1,}]);

  /// event to remove item by index
  void remove(int index) => emit(state.remoteAt(index));
}

class ButtonList extends StatelessWidget {
    const ButtonList({ Key? key }) : super(key: key);

    @override
    Widget build(BuildContext context) {
      return BlocProvider(
      create: (_) => MyCubit(),
      child: BlocBuilder<MyCubit, List<Map<String,double>>(
          builder: (context, state) => state.asMap().entries.map((entry) {
             int idx = entry.key;
             Map<String, double> val = entry.value;
             return TextButton(
               child: Text(val.keys.first ?? "missing"),
               onPressed: () => context.read<MyCubit>().remove(idx),,
               );
            }
         ).toList(),
      );
    }
  }

Stateful Widget
class ButtonList extends StatefulWidget {
  const ButtonList({Key? key}) : super(key: key);

  @override
  _ButtonListState createState() => _ButtonListState();
}

class _ButtonListState extends State<ButtonList> {
  final List<Map<String, double>> material = [{"pencil": 2},{"paper": 1,}];

  @override
  Widget build(BuildContext context) {
    return Column(
        children: material.asMap().entries.map((entry) {
      int idx = entry.key;
      Map<String, double> val = entry.value;
      return TextButton(
        child: Text(val.keys.first),
        onPressed: () {
          setState(() {
            material.removeAt(idx);
          });
        },
      );
    }).toList());
  }
}


text:
Q: Why doesnt confirmation box come up? JavaScript

function AdultNumber(){              /* Ticket Number Validation   */
    var AdInput = parseInt($("#adult").val());    //Declare it as an Integer
    var ChildInput = parseInt ($("#child").val());

    if (ChildInput >=0 && ChildInput <= 50  && AdInput > 0 && AdInput <= 50 || AdInput > 0 && AdInput <= 50 && !ChildInput   ){   //If passengers are between 0 to 10
        document.getElementById("AdTickError").textContent = "";
        document.getElementById("ChildTickError").textContent = "";
        return true;

    }

   else if( AdInput >= 10 ) {  //If user input is greater than 10
        confirm("Are you sure you want 10+ Passengers?");
        document.getElementById("AdTickError").textContent = "";
        return true;
    }

    else{
        document.getElementById("AdTickError").textContent = "Incorrect Enter Correct Number Of Passengers";

        return false;
    }

}

HTML:

        <Form action="#" class="group" name="form2" id="Form-2" method="post">
        <legend id="fixed">2Tickets</legend>

        Adults(+16)
        <input type="number" id="adult" name="user_adult">

        Child
        <input type="number" id="child" name="user_child">

     <button type = "button" value="checkout" id="checkoutbtn" onclick="AdultNumber(); calculateFare(); " >CHECKOUT</button>

Why doesnt the confirmation box show up after choosing+10 for the number type input fields (Child) and (Adult) ID's? It should be displayed twice if choosing +10 for both boxes. Currently nothing happens. Plus would it be more appropiate if I chose alert box or confirmation box?

A: Your if statement has a max for ChildInput and AdInput of 50 instead of 10. It's never hitting the else if statement which shows the alert boxes.
if (ChildInput >=0 && ChildInput <= 50  && AdInput > 0 && AdInput <= 50 || AdInput > 0 && AdInput <= 50 && !ChildInput   ){   //If passengers are between 0 to 10
        document.getElementById("AdTickError").textContent = "";

A: Try with this, it would be easier with JQuery:
$('#checkoutbtn').on('click',function(){

    var AdInput = parseInt($("#adult").val());    //Declare it as an Integer
    var ChildInput = parseInt ($("#child").val());

    if (ChildInput >=0 && ChildInput <= 50  && AdInput > 0 && AdInput <= 50 || AdInput > 0 && AdInput <= 50 && !ChildInput   ){   //If passengers are between 0 to 10
        document.getElementById("AdTickError").textContent = "";
        document.getElementById("ChildTickError").textContent = "";
        return true;

    }

   else if( AdInput >= 10 || ChildInput>=10) {  //If user input is greater than 10
        confirm("Are you sure you want 10+ Passengers?");
        document.getElementById("AdTickError").textContent = "";
        return true;
    }

    else{
        document.getElementById("AdTickError").textContent = "Incorrect Enter Correct Number Of Passengers";
        return false;
    }
});

Of course, remove the "onclick" actions on the HTML button tag.


text:
Q: Avoid creating multiple files with wget I use wget to call a link every 10 seconds like this:
#/bin/sh
while true; do
    wget http://www.some.random.link/to/some/PHP/script
    sleep 10
done

This produces empty files called script_name.# where # is incremented on every run.
Why does this happen?

A: That's because wget downloads the output of your script (which, presumably, is empty) and saves it to a file, appending a number each time so as not to overwrite the previously downloaded file.
There's a couple of options for how to prevent this.

*

*Prevent wget from downloading anything at all, using the --spider option:
wget --spider http://www.some.random.link/to/some/PHP/script
However, this may cause your script not to work since, IIRC, it only issues a HEAD request.

*Download the output, but discard it by sending it to /dev/null:
wget -O /dev/null http://www.some.random.link/to/some/PHP/script

*Download the output, but delete if afterwards, using the --delete-after option:
wget --delete-after http://www.some.random.link/to/some/PHP/script

*For the sake of completeness, if you can live with one file, use the -nc option to prevent wget from downloading files that already exist locally:
wget -nc http://www.some.random.link/to/some/PHP/script

A: As an alternative fix, you could avoid using wget — which, as its name implies, is intended for getting web content from a given URL. In other words, it's built to be a "download" tool. (It is, of course, very flexible, as Indrek demonstrated in his answer. But its defaults work against your purposes.)
Since you don't need or want to actually download anything (you're just accessing the URL to fire off a server-side script), the curl command is a bit more appropriate for your script. It will write the results of its requests to stdout by default, instead of to a file.
So, replacing wget with curl  in your code above should fix the file-creation problem without any further work.


text:
Q: Does pump durability affects Blight rewards? Does the durability of the pump affect the rewards you get from the chests afterwards? Obviously, the goal is to prevent the pump from reaching 0 durability and being ultimately destroyed -- but what happens to the rewards if I finish a pump with only a sliver of durability left vs no damage to the pump at all?

A:
Does the durability of the pump affect the rewards you get from the chests afterwards?

No. It can't -- the reward nodes at the end of each lane appear, and can be looted, as soon as the lane is completed. This can occur while monsters are still active in other lanes, and are thus still able to damage the pump.


text:
Q: Customizing Label Fonts in Swing In my swing application, I have different types of text I'd like to display. For example, I want to display a heading text before a list of choices, something like:

    Select choice:
     a
     b

I want the "Select Choice" label to use the "Heading" font (something I define), and the choices to use the "Choice" font. This pattern will occur multiple places in my application, so ideally I'd like to centralize where the fonts are set.
My current approach is to use a factory to create the different label types:
LabelFactory.createHeadingLabel("LabelText");
LabelFactory.createChoiceLabel("ChoiceText");

The factory reads in a properties file specifying the fonts and I customize the labels when they are created in the factory. I know that using a factory like this works, but I'm not sure if there is a standard Swing convention for doing something like this. Any input would be appreciated.

A: One other approach would be to extend JLabel.
You could still read the fonts in from a configuration file, but this way, you can create labels in a much more similar way to a regular JLabel.
private JLabel header = new HeaderJLabel("Header text");

All you would have to do is override the constructor for your custom labels.
Also, you should only read in the configuration file once.  Load it into memory, and access it from memory from then on.

A: You can use limited html inside of many Swing components, so you may be able to use html to give your text different styles.
For instance, headingLabel.setText("< html><b>This text will be bold</b>< /html>");
Will give you a label with bold text.
Note: you have to remove the extra space from < html> and < /html>


text:
Q: listview onClick return wrong result I have custom listview with data from SQLite database. I can add and edit items. Also I have SearchVIew in toolbar to serch items by name.
The problem is that when I want to edit item, and use SearchView to find it, onClick method returns wrong id (item of the first in the list).
If I do not use the search, then everything is fine. For example:

My class code:
public class ProductCategoryActivity extends AppCompatActivity {

private ListView myProductsList;
private DataBaseHelper dataBaseHelper;
private SQLiteDatabase db;
private Cursor productCursor;
private ArrayList<Product> productList;
private int tableId;
private String dbName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_products);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent idOfGroup = new Intent(getIntent());
    tableId = idOfGroup.getIntExtra("table_id", 0);

    myProductsList = (ListView) findViewById(R.id.lvMyProducts);

    switch (tableId) {
        case 1:
            dbName = DataBaseHelper.TABLE_MY_PRODUCTS;
            break;
    }

    //allow adding and editing products if tableId == 1
    if (tableId == 1) {
        myProductsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //get id by click on list view item
                String sql = "SELECT " + DataBaseHelper.COLUMN_ID + "  FROM " + dbName;
                productCursor = db.rawQuery(sql, null);
                ArrayList<Long> arrayList = new ArrayList<>();
                if (productCursor.moveToFirst()) {
                    do {
                        arrayList.add(Long.parseLong(productCursor.getString(0)));
                    } while (productCursor.moveToNext());
                } else {
                    throw new NullPointerException();
                }
                //sending id to another activity
                Intent intent = new Intent(ProductCategoryActivity.this, ProductAddEditActivity.class);
                intent.putExtra("id", arrayList.get(position));
                startActivity(intent);
            }
        });
    }
    dataBaseHelper = new DataBaseHelper(getApplicationContext());
    //creating db
    dataBaseHelper.create_db();

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.newProduct:
            Intent intent = new Intent(ProductCategoryActivity.this, ProductAddEditActivity.class);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onResume() {
    super.onResume();
    productList = new ArrayList<>();
    productList.clear();
    db = dataBaseHelper.open();
    //get data from db
    productCursor = db.rawQuery("select * from " + dbName, null);
    setProduct();
}

//product search by name
public Cursor getProductListByKeyword(String search) {
    productList = new ArrayList<>();
    productList.clear();
    db = dataBaseHelper.open();
    //get data from db by word
    productCursor = db.rawQuery("SELECT * FROM " + dbName + " WHERE "
            + DataBaseHelper.COLUMN_NAME + "  LIKE  '%" + search + "%' ", null);
    setProduct();
    return productCursor;
}

private void setProduct() {
    //select  required columns
    if (productCursor != null && productCursor.getCount() != 0) {
        if (productCursor.moveToFirst()) {
            do {
                Product product = new Product();
                product.setProductName(productCursor.getString(productCursor.getColumnIndex(DataBaseHelper.COLUMN_NAME)));

                productList.add(product);
            } while (productCursor.moveToNext());
        }
    }
    productCursor.close();
    ProductListAdapter productListAdapter = new ProductListAdapter(this, productList);
    myProductsList.setAdapter(productListAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    //the add button is hidden if tableId != 1
    if (tableId != 1) {
        MenuItem menuItem = menu.findItem(R.id.newProduct);
        menuItem.setVisible(false);
    }
    SearchView searchView = (SearchView) menu.findItem(R.id.searchForSee).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            productCursor = getProductListByKeyword(s);
            Toast.makeText(ProductCategoryActivity.this, productCursor.getCount() + " " +
                            getString(R.string.txt_products_found),
                    Toast.LENGTH_LONG)
                    .show();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            productCursor = getProductListByKeyword(s);
            return false;
        }
    });
    return true;

}
@Override
public void onDestroy() {
    super.onDestroy();
    db.close();
    productCursor.close();
}

A: I think your problem is how you are getting that id. You first get all column IDs from the table, then create an array of IDs and then choose an entry from there based on position.
Irrespective of your search results, your arrayList variable will always contain all IDs from the table. So when you access arrayList.get(position), it will return the object on that position in the table, not in the list.
You should either use long id or change your SQL query such that you only get entries such that your search test is honored in the SQL results.
Somethign like this perhaps
String sql = "SELECT " + DataBaseHelper.COLUMN_ID + "  FROM " + dbName + " WHERE " + DataBaseHelper.COLUMN_NAME + "=" + searchText;

Change the vars accordingly.
Even easier than that, You can simply use the long id passed in params.

A: I solved my problem in onClick method:
 myProductsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //get id by click on list view item
                long productId;
                if (productCursor.moveToPosition(position)) {
                    productId = Long.parseLong(productCursor.getString(0));
                } else {
                    throw new NullPointerException();
                }
                //sending id to another activity
                Intent intent = new Intent(ProductCategoryActivity.this, ProductAddEditActivity.class);
                intent.putExtra("id", productId);
                startActivity(intent);
            }
        });


text:
Q: Spatial dimension of a finite graph If $(X,d)$ is a metric space, we associate with it a simple, undirected graph, called its proximity graph $G(X,d)$ given by $V(G(X,d)) = X$ and $$E(G(X,d)) = \big\{\{x,y\}:x\neq y\in X \text{ and } d(x,y)\leq 1\big\}.$$
As MO user @YCor pointed out in a comment to a recent deleted question, given any (not necessarily finite) simple, undirected graph $G=(V,E)$, the map $d:V\times V\to \mathbb{R}$ given by $d(v,v) = 0$ for $v\in V$, $d(v,w)=1$ iff $\{v,w\}\in E$ and $d(v,w) = 2$ otherwise gives a metric on $V$ such that $G\cong G(V,d)$.
If $G=(V,E)$ is a finite graph we define its spatial dimension $\text{dim}_s(G)$ to be the smallest non-negative integer $n$ such that there is $S\subseteq\mathbb{R}^n$ with $G \cong G(S,||\cdot||)$, where $||\cdot||$ denotes the Euclidean metric that $S$ inherits from $\mathbb{R}^n$.
Question. Given any integer $n\geq 1$, what is an example of a finite graph $G=(V,E)$ with $\text{dim}_s(G)=n$?

A: If $s$ obeys $k_{n-1}<s$, where $k_n$ is the kissing number of $n$-dimensional Euclidean space, then the star $K_{1,s}$ has dimension at least $n$. For instance, $K_{1,7}$ has dimension 3.
(In most cases where $s\le k_n$, $K_{1,s}$ has dimension exactly $n$, but there are exceptions. For instance $K_{1,6}$ has dimension 3, even though $6\le k_2$, because it turns out not to be possible for six unit disks in the plane to all touch a central disk without touching each other.)


text:
Q: Ubuntu 15.10, logitech mx anywhere mouse pairs but doesn't do anything When I used Ubuntu 15.04 with bluez5 from PPA installed, the mouse works. But after installing Ubuntu 15.04, the mouse doesn't work.
[bluetooth]# info XX:XX:XX:XX:XX
Device XX:XX:XX:XX:XX
Name: MX Anywhere 2
Alias: MX Anywhere 2
Icon: input-mouse
Paired: yes
Trusted: yes
Blocked: no
Connected: yes
LegacyPairing: no

bluez5 have already included in ubuntu 15.10.
The mouse paring and connecting seem fine but the mouse doesn't do anything.
$dpkg -l | grep bluez
ii  bluez                                         5.35-0ubuntu2                              amd64        Bluetooth tools and daemons

A: In a related thread the user Tobi just updated his answer for Ubuntu 15.10, which worked for me perfectly: Logitech MX Anywhere 2 mouse pairs but doesn't do anything
In fact the PIN-less pairing method of the MX Anywhere 2 is not very well implemented in Ubuntu 15.10.
This commands have to be run to make the pairing work:
hciconfig hci0 sspmode 1
hciconfig hci0 down
hciconfig hci0 up


text:
Q: How can we create custom template using grmm inbuilt class in mallet? I am new to mallet and currently working on Sparql query optimization using template based model. For this i wanted to create a template model from RDf graph. The three templates which i want to create is class, attribute and relation. i have come across this tool called mallet which can help me to create a template. but still i am not getting an idea how can i do so using ACRF.Template in grmm.Can someone please give me guidelines about the template creation using mallet.
See the below image. I want a (1) class template for example movie all entities belonging to movie are included. (2) an attribute template suppose attribute edge "title" in which all entities belonging to that title are include. (3) Relation template which have source and target relation for example "Spouse".
My Use case:
1) I want a Bayesian Network model using Template(Predefine Class is available in Mallet).
2) fire a sparql query on that Model.
Can any one help me reach my goal?


text:
Q: $\sum a+b+c \sum \frac{ab+bc+ca}{a+b+c} \sum \frac{abc}{ab+bc+ca} \leq \sum a \sum b \sum c$ Let $a_i,b_i,c_i$ be $>0$ ($1 \leq i \leq n$). Then we have
$$ \sum (a_i+b_i+c_i) \sum \frac{a_i b_i + b_i c_i + c_i a_i}{a_i+b_i+c_i} \sum \frac{a_i b_i c_i}{a_i b_i+b_i c_i + c_i a_i} \leq \sum a_i \sum b_i \sum c_i $$
This is problem #68 in Hardy, Polya and Littlewood's Inequality. It can be proved by using convexity (see e.g. http://www.win.tue.nl/~gwoegi/papers/cauchy.pdf) but I would like to see an elementary proof of this inequality. The problem is found in the chapter which deals with elementary means and associated inequality (such as arithmetic-geometric mean, Hölder and Minkowski's inequalities, ...). So there should be an elementary derivation of this inequality from some other well-known result. Of course we can rewrite the proof which relies on convexity but this is cheating. For example it is easy to prove by induction that
$$ \sum \frac{a_i b_i + b_i c_i + c_i a_i}{a_i+b_i+c_i} \leq \frac{\sum a_i \sum b_i+ \sum b_i \sum c_i + \sum c_i \sum a_i}{\sum a_i+b_i+c_i}$$
and
$$ \sum \frac{a_i b_i c_i}{a_i b_i+b_i c_i+c_i a_i} \leq \frac{\sum a_i \sum b_i \sum c_i}{\sum a_i \sum b_i+ \sum b_i \sum c_i + \sum c_i \sum a_i}$$
so we get the result, but we knew these inequalities were true in the first place thanks to convexity.

A: Lemma 1:
\begin{equation}
\sum_{i=1}^{n}(a_{i}+b_{i})\sum_{i=1}^{n}\dfrac{a_{i}b_{i}}{a_{i}+b_{i}}\le\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}b_{i}
\tag{1}\end{equation}
proof:
$$
\Longleftrightarrow \sum_{i=1}^{n}\left(a_{i}+b_{i}-\dfrac{4a_{i}b_{i}}{a_{i}+b_{i}}\right)\ge\sum_{i=1}^{n}a_{i}+\sum_{i=1}^{n}b_{i}-\dfrac{4\displaystyle\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}b_{i}}{\displaystyle\sum_{i=1}^{n}a_{i}+\sum_{i=1}^{n}b_{i}}
$$
$$\Longleftrightarrow \sum_{i=1}^{n}\dfrac{(a_{i}-b_{i})^2}{a_{i}+b_{i}}\ge\dfrac{(\displaystyle\sum_{i=1}^{n}(a_{i}-b_{i}))^2}{\displaystyle\sum_{i=1}^{n}(a_{i}+b_{i})}
$$
It's easy use of $Cauchy-Schwarz$ inequality!
Lemma 2:
\begin{equation}
\sum_{i=1}^{n}(a_{i}+b_{i}+c_{i})\sum_{i=1}^{n}\dfrac{a_{i}b_{i}+a_{i}c_{i}+b_{i}c_{i}}{a_{i}+b_{i}+c_{i}}\le\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}b_{i}+\sum_{i=1}^{n}b_{i}\sum_{i=1}^{n}c_{i}+\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}c_{i}
\tag{2}\end{equation}
proof:
use Lemma 1, we have
$$\sum_{i=1}^{n}((a_{i}+b_{i})+c_{i})\sum_{i=1}^{n}\dfrac{(a_{i}+b_{i})c_{i}}{a_{i}+b_{i}+c_{i}}\le(\sum_{i=1}^{n}a_{i}+\sum_{i=1}^{n}b_{i})\sum_{i=1}^{n}c_{i}$$
and same as other two inequality, and add this three inequality by done!
Lemma 3:
\begin{equation}
\left(\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}b_{i}+\sum_{i=1}^{n}c_{i}\sum_{i=1}^{n}b_{i}+\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}c_{i}\right)\sum_{i=1}^{n}\dfrac{a_{i}b_{i}c_{i}}{a_{i}b_{i}+a_{i}c_{i}+b_{i}c_{i}}\le \sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}b_{i}\sum_{i=1}^{n}c_{i}
\tag{3}\end{equation}
proof:
let $t_{i}=\dfrac{c_{i}b_{i}}{b_{i}+c_{i}}$, and use Lemma 1, we have
$$\sum_{i=1}^{n}(a_{i}+t_{i})\sum_{i=1}^{n}\dfrac{a_{i}t_{i}}{a_{i}+t_{i}}\le\sum_{i=1}^{n}a_{i}\sum_{i=1}^{n}t_{i}$$
and
$$\sum_{i=1}^{n}(c_{i}+b_{i})\sum_{i=1}^{n}\dfrac{c_{i}b_{i}}{c_{i}+b_{i}}\le\sum_{i=1}^{n}c_{i}\sum_{i=1}^{n}b_{i}$$
Now It's easy prove it!
and you can $(1)\times (2)\times (3)$, that equality prove it by done!


text:
Q: How to pull values by reference number I have a df of paired values and I want to be able to subset it by accessing only one value. This is my data:
df1 %>% head()
  values    pair_num
   <ch>     <int>
1  apple      1
2  pb         1
3  apple      2
4  ranch      2
5  apple      3
6  sauce      3
7  orange     4
8  soda       4
9  grape      5
10 juice      5

So for example I would like to access all values associated with apple without knowing what they are and end up with something like this:
df1 %>% head()
  values    pair_num
   <ch>     <int>
1  apple      1
2  pb         1
3  apple      2
4  ranch      2
5  apple      3
6  sauce      3

A: I'm not sure I understand the question, as I would have thought this would be the output (with row 6) that you'd want.
library(dplyr)
df1 %>%
  filter(values == "apple") %>%
  select(pair_num) %>%
  left_join(df1)

Joining, by = "pair_num"
  pair_num values
1        1  apple
2        1     pb
3        2  apple
4        2  ranch
5        3  apple
6        3  sauce


text:
Q: asp:ListBox or TextBox Width is capped, but HTML table width is not I'm experiencing a very strange behavior that I can't really reproduce except in my main application: I use an Infragistics WebSplitter component that splits the page into two panes. On the right side of the pane, there are some grids (aligned inside HTML tables, and sometimes without); if the grid Width is set to 100%, the grid takes the whole width of the splitter pane as desired. The same goes for any <table> with width:100% set.
But: any asp:ListBox or asp:TextBox that uses Width="100%" is somehow capped at a certain fixed amount. That is, the control scales if I decrease the splitter pane size dynamically, and increases again, but then caps out again at the same amount (which seems arbitrary, but is always the same). It also doesn't matter if I set the Width attribute or do it via css (width: 100% !important;). The same goes for the editors inside the grid; if I edit a cell, a text box opens (happens with the ASP.NET TextBox variant of the Infragistics grid, but also with their own editor provider control) that has the same width as the current column width. But if I increase the column size, it is capped out at the same amount.
It is important to note that the amount also stays the same no matter how/where I align the control. If I, e.g., center it horizontally inside the pane, the size is still at the same cap, but it is centered correctly. Setting the width to a fixed amount instead of 100%, but greater than the visual cap, still makes it cap out.
I apologize for the vague formulation and lack of code, but I'm at a loss here since I cannot reproduce it so far; so I just ask and hope that anyone has encountered a similar issue at some point and may push me in the right direction to look.
Edit: It seems only form controls are affected. For example, asp:Label with Width="100%" works fine as well, but asp:TextBox, asp:ListBox don't. For some reason, asp:DetailsView does work, but I assume it's because it is using an HTML table underneath.

A: It was indeed a stupid CSS restriction that I didn't see in the first place. In the Visual Studio 2013 template for an ASP.NET application with a master page, a Site.css file is references which has code similar to the following:
input,
select,
textarea
{
  max-width: 280px;
}

Which makes for that strange behaviour (well, not really strange per se, but it occurred to me as strange because I encountered the issue initially only in edit fields of the Infragistics grids, since there were no other input controls of that width anywhere).