Q: In Java, how do I create a bitmap to solve "knapsack quandary" I'm in my first programming course and I'm quite stuck right now. Basically, what we are doing is we take 16 values from a text file (on the first line of code) and there is a single value on the second line of code. We read those 16 values into an array, and we set that 2nd line value as our target. I had no problem with that part.
But, where I'm having trouble is creating a bitmap to test every possible subset of the 16 values, that equal the target number.
IE, say we had these numbers:
12   15   20   4   3   10   17   12   24   21   19   33   27   11   25   32

We then correspond each value to a bitmap
 0    1    1   0   0    0    0    1    1    1    0    1    0    0    1    0

Then we only accept the values predicated with "1"
     15   20                     12   24   21        33             25

Then we test that subset to see if it equals the "target" number.
We are only allowed to use one array in the problem, and we aren't allowed to use the math class (haven't gotten to it yet).
I understand the concept, and I know that I need to implement shifting operators and the logical & sign, but I'm truly at a loss. I'm very frustrated, and I just was wondering if anybody could give me any tips.

A: To generate all possible bit patterns inside an int and thus all possible subsets defined by that bit map would simply require you to start your int at 1 and keep incrementing it to the highest possible value an unsigned short int can hold (all 1s). At the end of each inner loop, compare the sum to the target. If it matches, you got a solution subset - print it out. If not, try the next subset.
Can someone help to explain how to go about doing this? I understand the concept but lack the knowledge of how to implement it.

A: OK, so you are allowed one array. Presumably, that array holds the first set of data.
So your approach needs to not have any additional arrays.
The bit-vector is simply a mental model construct in this case. The idea is this: if you try every possible combination (note, NOT permutation), then you are going to find the closest sum to your target. So lets say you have N numbers. That means you have 2^N possible combinations.
The bit-vector approach is to number each combination with 0 to 2^N - 1, and try each one.
Assuming you have less that 32 numbers in the array, you essentially have an outer loop like this:
int numberOfCombinations = (1 << numbers.length - 1) - 1;
for (int i = 0; i < numberOfCombinations; ++i) { ... }

for each value of i, you need to go over each number in numbers, deciding to add or skip based on shifts and bitmasks of i.

A: So the task is to what an algorithm that, given a set A of non-negative numbers and a goal value k, determines whether there is a subset of A such that the sum of its elements is k.
I'd approach this using induction over A, keeping track of which numbers <= k are sums of a subset of the set of elements processed so far. That is:
boolean[] reachable = new boolean[k+1];
reachable[0] = true;
for (int a : A) {
    // compute the new reachable
    // hint: what's the relationship between subsets of S and S \/ {a} ?
}
return reachable[k];

A bitmap is, mathematically speaking, a function mapping a range of numbers onto {0, 1}. A boolean[] maps array indices to booleans. So one could call a boolean[] a bitmap.
One disadvanatage of using a boolean[] is that you must process each array element individually. Instead, one could use that a long holds 64 bits, and use bitshifting and masking operations to process 64 "array" elements at a time. But that sort of microoptimization is error-prone and rather involved, so not commonly done in code that should be reliable and maintainable.

A: I think you need something like this:
public boolean equalsTarget( int bitmap, int [] numbers, int target ) {
  int sum = 0; // this is the variable we're storing the running sum of our numbers
  int mask = 1; // this is the bitmask that we're using to query the bitmap
  for( int i = 0; i < numbers.length; i++ ) { // for each number in our array
    if( bitmap & mask > 0 ) { // test if the ith bit is 1
        sum += numbers[ i ]; // and add the ith number to the sum if it is
    }
    mask <<= 1; // shift the mask bit left by 1
  }
  return sum == target; //if the sum equals the target, this bitmap is a match
}

The rest of your code is fairly simple, you just feed every possible value of your bitmap (1..65535) into this method and act on the result.
P.s.: Please make sure that you fully understand the solution and not just copy it, otherwise you're just cheating yourself. :)
P.p.s: Using int works in this case, as int is 32 bit wide and we only need 16. Be careful with bitwise operations though if you need all the bits, as all primitive integer types (byte, short, int, long) are signed in Java.

A: There are a couple steps in solving this.  First you need to enumerate all the possible bit maps.  As others have pointed out you can do this easily by incrementing an integer from 0 to 2^n - 1.
Once you have that, you can iterate over all the possible bit maps you just need a way to take that bit map and "apply" it to an array to generate the sum of the elements at all indexes represented by the map.  The following method is an example of how to do that:
private static int bitmapSum(int[] input, int bitmap) {
    // a variable for holding the running total
    int sum = 0;

    // iterate over each element in our array
    // adding only the values specified by the bitmap
    for (int i = 0; i < input.length; i++) {
        int mask = 1 << i;
        if ((bitmap & mask) != 0) {
            // If the index is part of the bitmap, add it to the total;
            sum += input[i];
        }
    }

    return sum;
}

This function will take an integer array and a bit map (represented as an integer) and return the sum of all the elements in the array whose index are present in the mask.
The key to this function is the ability to determine if a given index is in fact in the bit map.  That is accomplished by first creating a bit mask for the desired index and then applying that mask to the bit map to test if that value is set.
Basically we want to build an integer where only one bit is set and all the others are zero.  We can then bitwise AND that mask with the bit map and test if a particular position is set by comparing the result to 0.
Lets say we have an 8-bit map like the following:
map:       1 0 0 1 1 1 0 1
           ---------------
indexes:   7 6 5 4 3 2 1 0

To test the value for index 4 we would need a bit mask that looks like the following:
mask:      0 0 0 1 0 0 0 0
           ---------------
indexes:   7 6 5 4 3 2 1 0

To build the mask we simply start with 1 and shift it by N:
1:            0 0 0 0 0 0 0 1
shift by 1:   0 0 0 0 0 0 1 0
shift by 2:   0 0 0 0 0 1 0 0
shift by 3:   0 0 0 0 1 0 0 0
shift by 4:   0 0 0 1 0 0 0 0

Once we have this we can apply the mask to the map and see if the value is set:
map:             1 0 0 1 1 1 0 1
mask:            0 0 0 1 0 0 0 0
                 ---------------
result of AND:   0 0 0 1 0 0 0 0

Since the result is != 0 we can tell that index 4 is included in the map.


Q: É possível instanciar uma conexão com o banco de dados manualmente usando o Entity Framework? Eu gostaria de gerenciar minhas conexões manualmente, para que os usuários pudessem informar o endereço do servidor, porém o Entity cria a string de conexão diretamente no arquivo de config, o único modo seria alterar aquele arquivo todas as vezes.
Porém eu queria fazer isso através de código, como se estivesse instanciando uma conexão manualmente ou apenas informando a string de conexão via código sem modificar o arquivo de configurações. É possível?

A: Sim, é possível.
Uma forma de se fazer isso é passando como parâmetro do construtor do contexto. Uma das sobrecargas do construtor aceita uma string.
Com esta abordagem é possível trabalhar de duas maneiras: 1) mantendo todas as conexões no arquivo web.config e construir o contexto passando o nome da conexão como parâmetro; e 2) passar como parâmetro do construtor a string de conexão completa.
public class SeuContexto : DbContext
{
    public SeuContexto(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }
}

E o uso poderia ser algo como
var context = new SeuContexto("uma string de conexao gigante aqui");


Q: Map String to Object using Jackson with inheritance I have the QueueContent class that it has is a superclass of two others.
I get a String in JSON format that contains the information I need to extract. The super class is:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class QueueContent {

    private String empresa;
    private String empresa_cor;
    private String empresa_contato;
    private String empresa_url;
    private String empresa_telefone;
    private String empresa_idioma;

    public QueueContent(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma) {
        this.empresa = empresa;
        this.empresa_cor = empresa_cor;
        this.empresa_contato = empresa_contato;
        this.empresa_url = empresa_url;
        this.empresa_telefone = empresa_telefone;
        this.empresa_idioma = empresa_idioma;
    }

    public QueueContent() {
    }
}

I'm using Lombok to generate Getters / Setters)
This is the child class:
@Data
public class EmailCameraOffline extends  QueueContent {
    private Timestamp camera_last_online;
    private String camera_nome;
    private String empresa_url_plataforma;

    public EmailCameraOffline(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma, Timestamp camera_last_online, String camera_nome, String empresa_url_plataforma) {
        super(empresa, empresa_cor, empresa_contato, empresa_url, empresa_telefone, empresa_idioma);
        this.camera_last_online = camera_last_online;
        this.camera_nome = camera_nome;
        this.empresa_url_plataforma = empresa_url_plataforma;
    }

    public EmailCameraOffline() {
    }
}

So I've done:

 EmailCameraOffline infosEmail = new ObjectMapper().readValue(content, EmailCameraOffline.class);
                System.out.println(infosEmail);

And the output is:
 EmailCameraOffline (camera_last_online = 2020-03-12 03: 01: 45.0, camera_nome = Pier Cam 1, empresa_url_platform = null)

How do I get my EmailCameraOffline object to have the superclass attributes initialized?

A: Everything should be loaded and initialized just fine, so calling:
System.out.println(infosEmail.getEmpresa());

should give expected value.
Problem
The problem is in the default implementation of toString() method (done via @Data) at EmailCameraOffline class, which does not include inherited fields.
Solution
To fix this you can "override" @Data's toString() implementation to include inherited fields as well using Lombok as:
@Data
@ToString(callSuper = true)
public class EmailCameraOffline extends QueueContent {
...
}


Q: Can we have such an external function on some $L(A)$?
Working within $\sf ZF-Reg.$, is there anything that forbids having a set $A$ and a transitive model $M$ of $\sf ZF+ V=L(A)$, that admits an external bijection $j$ between two limit stages $L_\alpha(A), L_\beta(A)$ of $M$, where $|\beta|=|\alpha|^+$, and such that both relations $J,J^{-1}$ are set like?

Where for any function $f$, by relation $F$ we mean:
$$y  \ F \ x \iff  \exists z \in x : y= f[z] $$
where $f[z]=\{f(m) \mid m \in z\}$
This comes within the context of proving $\sf Con(NF)$, since if we can get to have $\mathcal P(L_\alpha(A)) \subset L_\beta(A)$, then we get to interpret $\sf NFU+ |Set|=|Ur|$, through membership relation $\in^*$ defined on $L_\alpha(A)$ as:
$$x \in^* y \iff x \in j^{-1}(y) \land j^{-1}(y) \subseteq L_\alpha(A)$$
where $j: L_\beta(A) \to L_\alpha(A)$.


Q: SOLR - DataImportHandler - how to map multiple objects inside one list of json objects I am new to SOLR,I am trying to index oracle DB query results using SOLR. I have written config.xml and added indexes in schema.xml as well.
I have multiple queries as sub-entities(with child=true) in my config.xml file. Many of the queries are returning multiple rows. For example I have one entity as
<entity name="example_subentity" child="true" query="SELECT A,B from table_temp">
    <field column="A" name="a" />
    <field column="B" name="b" />
</entity>

which returns output as
"response":{"numFound":1,"start":0,"docs":[
      {
        "unique_key":"4493234234",
        "_version_":1560479076226957312,
        "_childDocuments_":[
        {
          "a" : "value_a_1",
          "b" : "value_b_1",
        },
        {
          "a" : "value_a_2",
          "b" : "value_b_2",
        }]
      }]}

what I am trying to achieve here is, something like
 "_childDocuments_":[
      {"table_temp_response" :[
        {
          "a" : "value_a_1",
          "b" : "value_b_1",
        },
        {
          "a" : "value_a_2",
          "b" : "value_b_2",
        }]
        }]

Can anyone guide me, how I can get this kind of output using DIH?
Just a update I am looking for a server side solution, I can do this using java or SOLRJ in client side. But I have multiple client which are going to consume SOLR query response.

A: if you use Solrj
JSONArray jArray = new JSONArray();

        for (int i = 0; i < docList.size(); i++) {
            JSONObject json = new JSONObject(docList.get(i));
            jArray.put(json);
        }

>

for (int i = 0; i < jArray.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);
            obj.getString("a"));


Q: how to detect execution environment? I would like to have a pair ofdb-specmaps with my database configuration for development and production.
But I can't find an easy way to detect the current execution environment. Need something like (defn db-spec [] (if (is-dev?) { dev-spec-here } { prod-spec-here })).
Maybe it can detect the current lein profile. No matter how I ask to google. Can't find how.

A: I'm fond of using environment variables for this (which can be set system wide for example in /etc/profile amongst other places). others prefer to pass a -D definition to the JVM

A: your code is okay, detect it depend your environment, like hostname, IP arrdress, global variable etc.


Q: why do i get a circular import error on whichever module that comes first but not on the second? I am making a simple inventory program for college assignment. however i keep getting a circular import error on one of the module. i get the error on the module import that comes first and not on the second. but the strange thing is, if i were to switch the import order, the previous erroneous import works and the previously working import returns an error.
Elaboration:
when running as this, import A has circular import error and import B works fine.
import A
import B

But if i run the program as this, import B has circular import error and import A works fine
import B
import A

why is this happening? what is the problem here?
This is the main module.
import purchase
import addition

def choices():
    print("Press any of following number for a course of action")
    print("1. To Purchase Bikes")
    print("2. To Add Bikes in the Stock")
    print("3. Exit the program\n")
    value = 0

    while not value in range(1, 5):
        try:
            value = int(input("Enter your desired number: "))
        except:
            print("\n\nPlease enter a valid number between 1-5:\n")

    if value > 3 or value < 1:
        print("\nInvalid Input!! Please select from the given.\n")
        choices()

    elif(value == 1):
        purchase.purBikes()

    elif(value == 2):
        addition.addStock()

    elif(value == 3):
        quit()

choices()

The whole program is available here. i know its a lot to look through but i didn't know what parts to remove to make a minimalized reproduceable example.
https://filebin.net/zgr985zo5wao5c0e

A: You have to rethink the design.
addition.py:
import Main
def addStock():
    # The 2 last lines
    Main.choices()
    return shipCost

A module is a library of reusable components, so they can not depend on some "Main", they must work anyhere, specially on unit tests.
Also, you call addition.addStock() in Main.choices(), so there is a circular call. When does it return shipCost?

A: First off, your welcome function is not defined(I dont see it if it is)
Second, module purchase doesnt exist publicly so it may be the problem


Q: ggplot/qqplotr returns error on data format I am trying to create a QQ and/or PP plot from the air_time data inside the flights data frame belonging to the nycflights13 package. I am using ggplot with qqplotr.
This is my code:
library(nycflights13)
library(qqplotr)

ggplot(data = flights$air_time, mapping = aes(sample = norm)) +
  stat_qq_band() +
  stat_qq_line() +
  stat_qq_point() +
  labs(x = "Theoretical Quantiles", y = "Sample Quantiles")

When I try to run this I get the error:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a numeric vector

What is causing this error and how do I fix it? I normally call ggplot as follows so I do not know if there could be issues there:
ggplot(flights, air_time, aes(sample = norm))

A: Change the sample argument to reflect the variable inside the data.
Air_time <- flights[, "air_time"] # Or select a random sample to save time
ggplot(data = Air_time, mapping = aes(sample = air_time)) +
  stat_qq_band() +
  stat_qq_line() +
  stat_qq_point()


Q: "Fragment file is not indexed" in Signac/R I am currently running an snATAC-seq analysis and performed the following command:
chrom_assay <- CreateChromatinAssay(
   counts = counts,
   sep = c(":", "-"),
   genome = 'mm10',
   fragments = '../vignette_data/atac_v1_pbmc_10k_fragments.tsv',
   min.cells = 10,
   min.features = 200
)

Now, my error comes out as
Error in CreateFragmentObject(path = fragments, cells = cells,
validate.fragments = validate.fragments,
:Fragment file is not indexed.

Could someone provide possible solutions to mitigate this?

A: As written in the documentation of the function CreateChromatinAssay, the fragments =  file should be a tabix file (ending in .tbi) containing the index with fragments of your data, or a Fragments object in R.
Apparently, first you will need to create the Fragments object in R from your tsv data, using the function CreateFragmentObject(). Take a look at: https://satijalab.org/signac/reference/fragments .

A: Based on the advise from the Signac developer in https://github.com/timoast/signac/issues/7#issuecomment-513934624 , the folder with the fragments file should also contain the fragment index file (.tbi). For example, for the human 10X PBMC vignette data (https://satijalab.org/signac/articles/pbmc_vignette.html): atac_v1_pbmc_10k/atac_v1_pbmc_10k_fragments.tsv.gz and
atac_v1_pbmc_10k/atac_v1_pbmc_10k_fragments.tsv.gz.tbi should be in the same folder. Hope this helps. Thanks.

A: Please see this Github issue to regenerate .tbi file
Briefly, run the following cmds in linux/unix terminal :

*

*gzip -d <fragment.tsv.gz>

*bgzip <fragment.tsv>

*tabix -p bed <fragment.tsv.gz>


Q: When i press Stop and then Play the sound dont works i have a simple app with 2 buttons. When i press Play, the sound run correctly, but when i press Pause and then play, the sound don´t works.
Why?
Here my code:
    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
public class MainActivity extends Activity {

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

final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);

 Button Play = (Button) findViewById(R.id.button1);
    Play.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v) {
        mp.start();
    }});

    final Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

         mp.stop();
         //mp.reset();

        }
    });

}
}

A: change to this:
button2.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    if (mp != null) {
         mp.stop();
         mp.release();
    }
    }
});

A: Don't use stop() for pausing media. Use pause() and check isPlaying() or not before pausing() it.


Q: How to round up a floating variable in c upto 2/3/4....n digits precision without using  and printf(".n%f") float f = 2.8386483,g ;
//Suppose I am having f = 2.8386483..... I want to store k = 2.8.... to n positions where n=a natural //number
//e.g. g= 2.83 to 2 decimal precision/n=2
    //   g = 2.838 to 3 decimal precision/n=3

A: Without using math.h, or printf(“.n%f”), the other answer will work for you.
But regarding your phrase I want to store k = 2.8.... to n positions.  It may be interesting to you that this has less to do with rounding than it has to do with type, and how much memory is required to store each type.
float, double and long double require differing amounts of memory to store the precision (numbers to the right of ".") required by the type, regardless of how you format them for display.   That is:
A displayed representation of a float may look like 2.83
while in memory, a float will contain memory sufficient to 7 digits precision 2.8368361 (on 32 bit system)
And for a type double representation of the same number might stored as 2.836836100000001.
Again, the way a number has little to do with how it is stored.
Edit: (Rounding a float to n decimal places)
#include <ansi_c.h>//I did not realized that this header INCLUDEs math.h, oops
int main(void)
{
    int p;

    float a,c;

    printf("Enter the floating point value:-");

    scanf("%f",&a);

    printf("Enter the precision value:-");

    scanf("%d",&p);

    if(a>0)
    {
        c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
        printf("Value Rounding Off:-%f",c);
    }

    else

    {
        c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
        printf("Value Rounding Off:-%f",c);
    }
    getchar();
    getchar();
}

From HERE (thanks to H. Gupta)

A: If you want to have n digits, then you can first start with multiplying your number f with 10^n. After that you can turn it into an integer so that the rest of the decimals "disappear" - turn it again into an float and divide by 10^n
However, remember to check for if the number needs to be rounded up or down :)

*

*2 places = 10^2

*2.836836 * 10^2 = 283.6836

*rounding rules: add 0.5 to the number

*283.6836 + 0.5 = 284.1836

*(int) 284.1836 = 284

*284 * 1.0 / 10^2 = 2.84

=>
float f = 10^2 * f + 0.5
int newint = (int) f f = newint * 1.0 / 10^2

A: Scale x and then round.  Make sure to deal with negative numbers correctly if rounding to nearest.
Thanks to @David Heffernan C : x to the power n using repeated squaring without recursive function
float pow10f(unsigned exponent) {
  float base = 10.0;
  float result = 1.0;
  while (exponent > 0) {
    while ((exponent & 1) == 0) {
      exponent /= 2;
      base *= base;
    }
    exponent--;
    result *= base;
  }
  return result;
}

float RoundToNPlaces(float x, unsigned n) {
  if (x < 0.0) {
    return -RoundToNPlaces(-x, n);
  }
  float scale = pow10f(n);  // fix per @Michael Burr
  x *= scale;
  uintmax_t u = (uintmax_t) (x + 0.5);  // Add 0.5 if rounding to nearest.
  x = (float) u;
  x /= scale;
  return x;
}

Does have a range limit though but likely wider than int.

[Edit] per @Michael Burr comment
(int) (RoundToNPlaces( 2.8386483, 2) * 100) --> 283 rather than the expected 284.  What happened though, is correct.  Rounded to 2 places the result of 2.8386483 is mathematically 2.84 but is not representable with typical float.  The 2 closest float to 2.84 are
2.8399999141693115234375000
2.8400001525878906250000000

and RoundToNPlaces( 2.8386483, 2) resulted in the closer one: 2.8399999141693115234375.
Now performing (int) (2.8399999141693115234375f * 100) --> (int) 283.99999141693115234375f --> 283.
This exhibits the necessary compromise to the OP's original goal, finding 2.8386483f rounded to 2 decimal places does not typically lead to an exact answer.  Hence subsequent operations like * 100 and then int conversion lead to unexpected results, not because the best answer was not found in the round to 2 decimal places step, but because the best answer still will not exhibit all the properties of the mathematical exact answer.


Q: Regex return all characters I was using the (.) to match all characters but it return back too with too many matches. How do i make it so it only 1 match?
 private MatchCollection RegexMatchingV2(string data, string regex)
    {
        MatchCollection col = null;
        try
        {
            col = Regex.Matches(data, regex, RegexOptions.IgnoreCase);
        }
        catch (Exception ex)
        {
            Response.Write("RegexMatching ERROR:" + ex.Message);
        }
        return col;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       MatchCollection col= RegexMatchingV2("return all of this data in 1 match", "(.)");
       Response.Write(col.Count);//Too much matches
    }

A: To make it a single match use (.*)
The single . matches a single character.  The additional * means "zero or more".
Edit In response to the comment about two matches (the first match contains the string, and the second is an empty match):  The Matches documentation indicates that it gives empty matches special treatment.  There is a good example on that page to show the behavior.  But the end result is that after the match, it does not do forward movement, so it picks up an empty match.  To prevent that, you could use beginning of line and end of line anchors:  (^.*$) or use the + to force at least one character to be included:  (.+).

A: Since you want to match any number of any characters, change the . to .* to match zero or more, or .+ to match one or more.


Q: Adding TextView to content_main in Navigation Drawer Template I'm trying to add a TextView to the content_main layout while the setContentView is at activity_main. I am currently using the Navigation Drawer template when you create a new project in Android Studio. Activity_main includes app_bar_main which includes content_main.
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="org.test.testy.test"
    tools:showIn="@layout/app_bar_main"
    android:weightSum="1">

</LinearLayout>

The code I'm trying to use is this:
    LayoutInflater inflater;
    inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = (View) inflater.inflate(R.layout.content_main, null);
    LinearLayout layout = (LinearLayout) view.findViewById(R.id.content_main);
    //Card view create
    CardView cv = new CardView(layout.getContext());
    cv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    cv.setVisibility(View.VISIBLE);
    TextView tv = new TextView(layout.getContext());
    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    tv.setText("Test");
    tv.setVisibility(View.VISIBLE);
    cv.addView(tv);
    layout.addView(cv);

Everything below //Card view create was tested in a blank app, which worked perfectly fine. I also tried to put a TextView in the xml of content_main with an id and trying to read the text, which also returned the correct text. If I am able to access the layout and the code for adding to view is fine, then why is it not working?

A: Two things I was doing wrong:

*

*I had to id each of the <include>s with the EXACT name that it was going to and

*I had to go through each includes because I had two:
LinearLayout layout = (LinearLayout) findViewById(R.id.app_bar_main).findViewById(R.id.content_main);


Q: What is the difference between WPF and Silverlight application? What is the difference between WPF and Silverlight application? Are they the same?

A: Silverlight is a subset of WPF. Once it was known as WPF/E (WPF everywhere). In fact, the base framework is similar, but not the same.
See this for further information:  Silverlight "WPF/E" first steps: Getting started with simple analog clock, Introduction - What is WPF/E?

A: Silverlight is Microsoft’s latest development platform for building next-generation Web client applications
(WPF) is Microsoft’slatest development platform forbuilding next-generation Windows client applications
Silverlight is generally considered to be a subset of
WPF, and is a XAML
WPF is generally considered to be a subset of .NET Framework
Silverlight Support Cross OS, cross browser, cross device
WPF for Windows client users.
in order to run Silverlight applications at client machines, we need to install Silverlight
software on the client machine once
WPF, on the other hand, does notsupport any plug-in mechanism;instead, we need to install a
completed WPF client application
Silverlight applications are hosted within a webserver and a web page.
WPF applications can be deployed as standalone applications,

A: WPF is based off of the desktop CLR which is the full version of the CLR.
Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth of CLR features.  It also has a much smaller version of the BCL.

A:
Silverlight (codenamed WPF/E) is a cross-platform, cross-browser, browser plugin which contains WPF-based technology (including XAML)[17] that provides features such as video, vector graphics, and animations to multiple operating systems including Windows Vista, Windows XP, and Mac OS X, with Microsoft sanctioned 3rd party developers working ports for Linux distributions.[18] Specifically, it is currently provided as an add-on for Mozilla Firefox, Internet Explorer 6 and above, and Apple Safari. Silverlight and WPF only share the XAML presentation layer.

WIKI

A: WPF is essentially the replacement to Winforms in that it is a desktop application platform built on the .Net (3+) platform.
Silverlight represents a subset of WPF that is delivered through a browser plug-in, much like Flash/Flex.

A: Silverlight is a subset of WPF and therefore has fewer features but is more portable.  WPF can be ran in both a browser or as a WinForms style application in Windows while Silverlight can only be ran in a browser.  WPF is intended to run on Windows systems while Silverlight runs on Windows or Mac, also Linux via Moonlight.
If confused on when to use each, I found a useful blog better explaining this: http://blogs.msdn.com/b/jennifer/archive/2008/05/06/when-should-i-use-wpf-vs-silverlight.aspx

A: wpf is window application and  Silverlight  is web application

A: A detailed comparison can be found here: http://wpfslguidance.codeplex.com/


Q: Vertically aligning block element to image? I'm looking for a way to vertically align a block element to an image. On my site this image would dynamically change in height and width so I'd need the vertical alignment to adapt for whatever the image size is. For example:

img { float: left; }

#box { float: right; width: 200px; height: 150px; background-color: #666; }

So I'd want this div to vertically align itself to the image. How can this be done?
Thanks.

A: The trick is to add a couple layers of wrapper-divs. The first layer is set to white-space: nowrap and max-width:50% which means that the elements inside can't wrap, and are constrained to 50% of the width of the parent.
Then you set the white space back to normal, and make the second layer display:inline-block so that these divs have to play by text alignment rules. Then you set both of them to vertical-align:middle; Just one won't work because vertical align is relative to the baseline of the text, not the containing block element.
So in this way we have constrained ourselves to one line of "text", composed of two div elements both aligned such their middle is at the text baseline, and ensured that their size must be no more than 50% of the parent container.
EDIT: I discovered after little more playing that you need to add some max-width:100% to keep the image from pushing the text out the right hand side.
EDIT 2: I should have mentioned that this requires IE-8 standards mode, added meta-equiv to tell IE-8 to behave itself, but giving a proper doctype or sending an http response header can achieve the same thing google IE8 standards mode for all that stuff.

    <title>Test</title>
    <meta http-equiv="X-UA-Compatible" content="IE=8" />

        Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit
        esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia
        deserunt mollit anim id est laborum


Q: Taking 4-5 second to visible view with big ArrayList data to RecyclerView inside NestedScrollView I have three RecyclerView in NestedScrollView, 2 RecyclerView having approx 100 items and third having approx 400 items. Then it takes 4-5 seconds to render the view after adding data to arraylist and notifiedDataSetChanged(). Every RecyclerView is in vertical. So if there any solution for this please explain
if(!itemsList.isEmpty()) {itemsList.clear();}
itemsList.addAll(itemData);
itemAdapter.notifyDataSetChanged();

A: Recyclerview inside nested scrollview does complete layout at a single load rather than usual recyclerview behaviour, try to remove nested scrollview from layout, use recyclerview with different view types.


Q: nginx basic auth permissions for user Можно ли сделать ограничение пользователям к ресурсам приложения используя nginx + basic auth. Я хочу сделать что бы юзер client после авторизации имел доступ только к некоторым ресурсам, /wp/modules, /wp/desi, /wp/assets. А пользователь admin имел доступ ко всему.

A: А если попробовать использовать для разных location разные файлы с паролями?
Например вот такой конфиг у меня прекрасно сработал в тестовой песочнице. В корень пускает и admin и user, а в /test_admin при попытке войти user-ом запрашивает пароль.
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        auth_basic  "rootdir";
        auth_basic_user_file "/usr/share/nginx/root.auth";
        }

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        location /test_admin {
            root   /usr/share/nginx;
            index  index.html index.htm;
            auth_basic  "admindir";
            auth_basic_user_file "/usr/share/nginx/admin.auth";
        }
    }

Соответственно содержимое /usr/share/nginx/root.auth:
admin:yIFz/FsHJVxBA
user:ywRtY7HxsLbzk

И содержимое /usr/share/nginx/admin.auth:
admin:yIFz/FsHJVxBA

Пароль admin: 12345, user: 67890


Q: python xml elementtree wrap text by number of characters I'm wondering in xml elementtree how to wrap the text?
For instance, I have the following text
4324OO234324O234O32O423423OO23O432O4OO23O4O32O423O423O4O234OO234234O234OO324O234

And I need to make sure that it wraps the text for every 10 characters e.g.
However, I also need to preserve the tabs/whitespace that is happening after each line.
<mydata>
        4324OO2343
        24O234O32O
        423423OO23
        O432O4OO2
        3O4O32O42
        3O423O4O2
        34OO234234
        O234OO324
        O234
</mydata>

Any idea of any easy way to do this in python 2.5.2?
This is not a replicate question, because this is xml elementtree specific... It might be possible to break the chars up into chunks, but then I have to use minidom.parseString and toprettyxml, to get the tabs - but I havent found a way to do it yet –

A: The poster that voted to close this question was not correct and didn't provide help towards a solution. The duplicate thread only provided part of the solution, which is not useful in this case.
In the end I resolved it the following way:
hexerre = re.sub("(.{80})", "\1\n\t\t\t\t\t\t\t", hexer, 0)
By adding the tabs into the regex expression I was able to get the indentation needed.


Q: Sencha Extjs 6.2 : Edit object values in cell grid I have a grid and in the last two columns (Chourly and Cdaily), each cell contains an object.
Example of data :
{
    data: [{
        Date: "2018/01/11 21:00:00",
        Ahourly: "1",
        Chourly: {
            val: 2,
            status: "Low",
            color: "#ffff00"
        }
    }, ...
    success: true
}

Here is my fiddle, see Chourly and Cdaily columns.
I need to edit data of this object and display the new values.
I tried to use beforeedit end validateedit but for now no success !
Any help ?
Thanks,
mpe

A: First thing to do is to adjust your data model in the store.
Use "mapping" to accommodate all the fields in object field into individual fields,
like that:
 var store = Ext.create('Ext.data.JsonStore', {
        fields: [
            'Date',
            'Ahourly',
            {name:'ChourlyVal',mapping:'Chourly.val'},
            {name:'ChourlyColor',mapping:'Chourly.color'},
            {name:'ChourlyStatus',mapping:'Chourly.status'},
            {name:'CdailyVal' ,mapping:'Cdaily.val'},
            {name:'CdailyColor' ,mapping:'Cdaily.color'},
            {name:'CdailyStatus' ,mapping:'Cdaily.status'}
            ],
        proxy: {
            type: 'ajax',
            url: 'data1.json',
            reader: {
                type: 'json',
                rootProperty: 'data'
            }
        },
        autoLoad: true
    });

And than, adjust the column and the renderer to use the mapped fields:
 {
            text: 'Chourly',
            dataIndex: 'ChourlyVal',
            flex: 1,
            renderer: function (a, meta, record) {
                console.log(record);
                meta.tdStyle = "background-color:" + record.data.ChourlyColor + ";";
                var cellText = a + " " + record.data.ChourlyStatus;
                return cellText;
            },
            editor: 'textfield'
        }

I hope that helps

A: Thanks for your reply. I think its the good way.
Then I think I have to use the serialize function to put the object back together with the modified value(s) to send back to the server like this :
fields: ['Date', {
                name: 'Chourly',
                serialize: function (val, rec) {
                    return {
                        'val': rec.get('val'),
                        'status': rec.get('status'),
                        'color': rec.get('color')
                    };
                }
            }, {
                name: 'val',
                mapping: 'Chourly.val',
                persist: false //Do not write back to server
            }, {
                name: 'status',
                mapping: 'Chourly.status',
                persist: false

            }, {
                name: 'color',
                mapping: 'Chourly.color',
                persist: false

            },
            ...
        ]...

Now I have to do that dynamically because I don't know in advance which data the user will consult (Chourly, Dhourly, Ehourly ....). Any idea to modify the model on the load callback ?


Q: Windows Live Messenger stops space bar working On Windows Vista, the included Windows Live Messenger frequently stops the space bar working after a long period (or is it after I put the computer into standby).
It is frustrating to have to exit Windows Live Messenger and re-start just so I can type spaces in conversations.
Anybody else have this problem?

A: The modifier keys might affect the behavior of the space bar, try to play with them to see if it resolves.


Q: Limit root node processing in CPLEX Python I have a very large problem (1m variables, 3m constraints) that I'm trying to solve using CPLEX in Python. Obviously, solving it optimally is out of the question, so I have implemented a time limit so I could get the best solution within that time.
c.timelimit.set(7200)

However, when the time was up, it hadn't even finished processing the root node:
        Nodes                                         Cuts/
 Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

  0     0       10.0070  2177                     10.0070    65714
  0     0       10.0070  1793                    Cuts: 29    80275
  0     0       10.0070  2427                  Cuts: 6928   101277
  0     0       10.0070  2061                  Cuts: 4737   122524
Implied bound cuts applied:  485
Flow cuts applied:  68
Mixed integer rounding cuts applied:  12019
Zero-half cuts applied:  193

Root node processing (before b&c):
  Real time             = 7200.47 sec. (2762999.79 ticks)
Parallel b&c, 112 threads:
  Real time             =    0.00 sec. (0.00 ticks)
  Sync time (average)   =    0.00 sec.
  Wait time (average)   =    0.00 sec.
                          ------------
Total (root+branch&cut) = 7200.47 sec. (2762999.79 ticks)
Solution status =  108 :
MIP_time_limit_infeasible
Exception raised during solve

Is there any way to limit the time spent on the root node so it at least starts the b&c method? Would that even be advantageous at all?


Q: HSQL database user lacks privilege or object not found error I am trying to use hsqldb-2.3.4 to connect from Spring applicastion.
I created data base using the following details
Type : HSQL Database Engine Standalone
Driver: org.hsqldb.jdbcDriver
URL: jdbc:hsqldb:file:mydb
UserName: SA
Password: SA

I created a table named ALBUM under "MYDB" schema
In spring configuration file:
<bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dbcpDataSource" />
</bean>

<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:file:mydb" />
    <property name="username" value="SA" />
    <property name="password" value="SA" />
</bean>

And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper());
And It gives me exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

If I execute same query through SQL editor of hsqldb it executes fine.  Can you please help me with this.

A: I had the error user lacks privilege or object not found while trying to create a table in an empty in-memory database.
I used spring.datasource.schema and the problem was that I missed a semicolon in my SQL file after the "CREATE TABLE"-Statement (which was followed by "CREATE INDEX").

A: As said by a previous response there is many possible causes. One of them is that the table isn't created because of syntax incompatibility. If specific DB vendor syntax or specific capability is used,  HSQLDB will not recognize it. Then while the creation code is executed you could see that the table is not created for this syntax reason. For exemple if the entity is annoted with @Column(columnDefinition = "TEXT") the creation of the table will fail.
There is a work around which tell to HSQLDB to be in a compatible mode
for pgsl you should append your connection url with that
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true"

and for mysql with
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_mys=true"

oracle
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_ora=true"

note there is variant depending on your configuration
it could be hibernate.connection.url= or spring.datasource.url=
for those who don't use the hibernate schema creation but a SQL script you should use this kind of syntax in your script
SET DATABASE SQL SYNTAX ORA TRUE;

It will also fix issues due to vendor specific syntax in SQL request such as array_agg for posgresql
Nota bene : The the problem occurs very early when the code parse the model to create the schema and then is hidden in many lines of logs, then the unitTested code crash with a confusing and obscure exception "user lacks privilege or object not found error" which does not point the real problem at all. So make sure to read all the trace from the beginning and fix all possible issues

A: If you've tried all the other answers on this question, then it is most likely that you are facing a case-sensitivity issue.
HSQLDB is case-sensitive by default. If you don't specify the double quotes around the name of a schema or column or table, then it will by default convert that to uppercase. If your object has been created in uppercase, then you are in luck. If it is in lowercase, then you will have to surround your object name with double quotes.
For example:
CREATE MEMORY TABLE "t1"("product_id" INTEGER NOT NULL)

To select from this table you will have to use the following query
select "product_id" from "t1"

A: user lacks privilege or object not found can have multiple causes, the most obvious being you're accessing a table that does not exist. A less evident reason is that, when you run your code, the connection to a file database URL actually can create a DB. The scenario you're experiencing might be you've set up a DB using HSQL Database Manager, added tables and rows, but it's not this specific instance your Java code is using. You may want to check that you don't have multiple copies of these files: mydb.log, mydb.lck, mydb.properties, etc in your workspace. In the case your Java code did create those files, the location depends on how you run your program. In a Maven project run inside Netbeans for example, the files are stored alongside the pom.xml.

A: I had similar issue with the error 'org.hsqldb.HsqlException: user lacks privilege or object not found: DAYS_BETWEEN' turned out DAYS_BETWEEN is not recognized by hsqldb as a function. use DATEDIFF instead.
DATEDIFF ( <datetime value expr 1>, <datetime value expr 2> )

A: When running a HSWLDB server. for example your java config file has:
hsql.jdbc.url = jdbc:hsqldb:hsql://localhost:9005/YOURDB;sql.enforce_strict_size=true;hsqldb.tx=mvcc
check to make sure that your set a server.dbname.#. for example my server.properties file:
    server.database.0=eventsdb
    server.dbname.0=eventsdb
    server.port=9005

A: I was inserting the data in hsql db using following script
INSERT INTO Greeting (text) VALUES ("Hello World");

I was getting issue related to the Hello World object not found and HSQL database user lacks privilege or object not found error
which I changed into the below script
INSERT INTO Greeting (text) VALUES ('Hello World');

And now it is working fine.

A: Add these two extra properties:
spring.jpa.hibernate.naming.implicit-strategy=
org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

spring.jpa.hibernate.naming.physical-strategy=
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

A: I bumped into kind of the same problem recently. We are running a grails application and someone inserted a SQL script into the BootStrap file (that's the entry point for grails). That script was supposed to be run only in the production environment, however because of bad logic it was running in test as well. So the error I got was:
User lacks privilege or object not found:

without any more clarification...
I just had to make sure the script was not run in the test environment and it fixed the problem for me, though it took me 3 hours to figure it out. I know it is very, very specific issue but still if I can save someone a couple of hours of code digging that would be great.

A: I was having the same mistake. In my case I was forgetting to put the apas in the strings.
I was doing String test = "inputTest";
The correct one is String test = "'inputTest'";
The error was occurring when I was trying to put something in the database
connection.createStatement.execute("INSERT INTO tableTest values(" + test +")";

In my case, just put the quotation marks ' to correct the error.

A: In my case the error occured because i did NOT put the TABLE_NAME into double quotes "TABLE_NAME" and had the oracle schema prefix.
Not working:
SELECT * FROM FOOSCHEMA.BAR_TABLE

Working:
SELECT * FROM "BAR_TABLE"

A: had this issue with concatenating variables in insert statement. this worked
// var1, var3, var4 are String variables
// var2 and var5 are Integer variables
result = statement.executeUpdate("INSERT INTO newTable VALUES ('"+var1+"',"+var2+",'"+var3+"','"+var4+"',"+var5 +")");

A: In my case the issue was caused by the absence (I'd commented it out by mistake) of the following line in persistence.xml:
<property name="hibernate.hbm2ddl.auto" value="update"/>

which prevented Hibernate from emitting the DDL to create the required schema elements...
(different Hibernate wrappers will have different mechanisms to specify properties; I'm using JPA here)

A: I had this error while trying to run my application without specifying the "Path" field in Intellij IDEA data source (database) properties. Everything else was configured correctly.
I was able to run scripts in IDEA database console and they executed correctly, but without giving a path to the IDEA, it was unable to identify where to connect, which caused errors.

A: You have to run the Database in server mode and connect.Otherwise it wont connect from external application and give error similar to user lacks privilege.
Also change the url of database in spring configuration file accordingly when running DB in server mode.
Sample command to run DB in server mode
$java -cp lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:data/mydb --dbname.0 Test
Format of URL in configuration file
jdbc:hsqldb:hsql://localhost/Test

A: In my case, one of the columns had the name 'key' with the missing @Column(name = "key") annotation so that in the logs you could see the query that created the table but in fact it was not there. So be careful with column names

A: For what it's worth - I had this same problem.  I had a column named 'TYPE', which I renamed to 'XTYPE' and a column named ORDER which I renamed to 'XORDER' and the problem went away.

A: Yet another reason could be a misspelt field name. If your actual table has an id column named albumid and you'd used album_id, then too this could occur.
As another anwer remarked, case differences in field names too need to be taken care of.

A: I faced the same issue and found there was more than one PersistenceUnit (ReadOnly and ReadWrite) , So the tables in HSQLDDB created using a schema from one persistence unit resulted in exception(HSQL database user lacks privilege or object not found error) being thrown when accessed from other persistence unit .It happens when tables are created from one session in JPA and accessed from another session

A: In my case the table MY_TABLE was in the schema SOME_SCHEMA. So calling select/insert etc. directly didn't work. To fix:

*

*add file schema.sql to the resources folder

*in this file add the line CREATE SCHEMA YOUR_SCHEMA_NAME;


Q: How to handle a GET request in python I have some microservices running in kubernetes, and they need to pass some data among each other, but I can't handle the GET request from the server side.
The docs I found are very focused on how to make the GET request on python, but not how to handle it.
So, this is what I tried:
from flask import Flask
from flask import request
import requests

app = Flask(__name__)

@app.route('/<trace_id>')
def root():
    return trace_id

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8080, debug=True)

From the client, I do the request like this:
>>> trace_id = '54b012b2767e7b21321ca649872913c5'
>>> requests.get('http://my-service', params=trace_id)
<Response [404]>

And on my server I get this dumped:
/# python3 app.py
 * Serving Flask app "app" (lazy loading)
 ...
10.52.2.29 - - [29/Nov/2019 18:41:23] "GET /?54b012b2767e7b21321ca649872913c5 HTTP/1.1" 404 -

I would like to know how to handle the request on the server side. Also, it would be nice to get some suggestions of what's the best way of dealing with this.

Note: there is a k8s service in front of the server that gets the
  requests on port 80 and forward them to 8080.

A: You need to pass trace_id as input argument
def root(trace_id):
    return trace_id

And trace_id is part of the url, not the query part:
requests.get('http://my-service/' + trace_id)

A: We have to look closer at your code.
@app.route('/<trace_id>')

String argument inside brackets is a path part after 'http://my_service/'.
Full path of this API endpoint will be 'http://my_service/value_of_trace_id'.
And this part 'value_of_trace_id' will be stored as 'trace_id' variable and passed to function body so you have to pass it as function (API endpoint) arg.
@app.route('/<trace_id>')
def api_endpoint(trace_id):
    return trace_id

So, you have to use:
requests.get('http://my-service/' + trace_id)

I highly recommend read that or that.


Q: modifying softmax function in tensorflow I started using tensorflow about a week ago, so I'm not sure what API can I use.
Currently I'm using basic mnist number recognition code.
I want to test how recognition precision of this code changes if I modify the softmax function from floating point calculation to fixed point calculation.
At first I tried to modify the library but it was too complicated to do so. So I  think I have to read tensors and modify(calculate) it in the form of array and change it to the tensor using tf.Session().eval() function.
Which function should I use?
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

import tensorflow as tf

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
#temp = tf.Variable(tf.zeros([784, 10]))
temp = tf.Variable(tf.matmul(x, W) + b)
#temp = tf.add(tf.matmul(x, W),b)

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#print(temp[500])

for i in range(100):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


Q: Start Segue After Completion Of Social Sharing I want to let users share some posts from my app with the help of the social framework. But after the post button in the social framework, the segue is not starting. How can I handle this?
var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
shareToFacebook.addImage(self.Img.image)
self.presentViewController(shareToFacebook, animated: true, completion: nil)
self.performSegueWithIdentifier("goToStarting", sender: self)

A: You have to present the view controller in this method
var completionHandler: SLComposeViewControllerCompletionHandler!

You can use the above method like this
var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
shareToFacebook.addImage(self.Img.image)
shareToFacebook.completionHandler = {
    (result:SLComposeViewControllerResult) in

    }
self.presentViewController(shareToFacebook, animated: true, completion: nil)
self.performSegueWithIdentifier("goToStarting", sender: self)


Q: How to store HTML form value for other pages in PHP and MySQLi? I have created a database in phpMyAdmin with table for topics such as Math, Physics etc. Each topic has a topic_id as primary key in table tb_topic. Each topic can have multiple videos. Admin can add videos to each topic which requires topic_id as foreign key in table tb_video_management to store videos against a topic.
Backend:
There is a button to add videos in form.php
form.php:
<?php
    $query = "SELECT topic_id, topic_name,aid FROM tb_topic";
    $result = $con->query($query);
    while($query_row = mysqli_fetch_assoc($result)) {?>

            <form action='edit.php' method='get'>
                <button type='submit' name='edit' id = 'edit' value='<?php echo $query_row['topic_id'];?>' class='btn btn-success'>EDIT</button>

            </form>

    <?php
    } ?>

When this button is clicked, page is navigated to another page "edit.php" which has 2 buttons, one for add new video and second for viewing video gallery.
edit.php:
$id = $_GET['edit'];
echo 'topic id----> ' . $id;

<form action='add_video.php' method='get'>
    <button type='submit' name='add' id = 'add' value='<?php echo $id;?>' class='btn btn-success'>ADD NEW VIDEO</button>
</form>
<form action="video.php" method="get">
    <button type="submit" name="goback" id="goback" value="submit" class="btn btn-primary">VIEW GALLERY</button>
</form>

The class where videos are added has a form for topic name, details etc.
add_video.php
$id = $_GET['add'];
echo 'topic id----> ' . $id;

<form action="add_video.php" method="post">
        Video Title: <input type="text" name="video_name">

        Video Detail: <input type="text" name="video_detail">

        Video Question: <input type="text" name="video_question">

        Video Link: <input type="text" name="video_link">

        <input type="submit" name="submit" value = "Submit">

</form>

When "submit" button is clicked, following code executes:
if(isset($_POST['submit'])) {

    if(!(empty($_POST['video_name']) || empty($_POST['video_detail']) || empty($_POST['video_question']) || empty($_POST['video_link']))) {
        $name = $_POST['video_name'];
        $detail = $_POST['video_detail'];
        $question = $_POST['video_question'];
        $link = $_POST['video_link'];
        $insert = "INSERT INTO tb_video_management(topic_id, video_name, video_detail, video_question,video_link) VALUES ('$id','$name','$detail', '$question','$link')";
        if(!mysqli_query($con,$insert))
            echo "error";
        header('location:edit.php');
    }
}

The problem I am facing is, when I click submit button, the value in $id is lost (may be because another button (submit) is pressed) and it fails to insert the record as there is no value for "topic_id" anymore. I cannot resolve this issue of keeping foreign key value even after pressing submit button.
So far I have been creating extra table to hold value for topic_id which is definitely not the right approach.

A: To use the $id into another page, you must have to store that in such a way that it will be remain exist after submit.That can be done by using the hidden field.
You may set the value of $id like:
<input type="hidden" name="topic_id" value="<?php echo $id?>">

Once you submit and redirect to add_video.php, you may get the value of $id same as another field video_detail.
On submit look like:
if(isset($_POST['submit'])) {
    $topic_id = $_POST['topic_id'];
}


Q: sum of stochastically continuous processes Hallo,
is the sum of two stochastically continuous processes again a stochastically continuous process? why?
Thank you very much,
Paolo.

A: Yes. A stochastically continuous process is a mapping $t \mapsto X_t \in L^0$ into the space of random variables that is continuous with $L^0$ given the topology of convergence in probability. Since $L^0$ is a topological vector space for this topology - in particular, addition is continuous - it is clear that $t \mapsto (X_t, Y_t) \mapsto X_t + Y_t$ is continuous as a composition of continuous mappings.


Q: Proof of why multiplication between a matrix and its eigenvector equals the eigenvalue times its eigenvector Why is the following true?
$$\lambda \vec{x} = P \vec{x} \: \: \: \lambda \:\: \text{is the eigenvalue of P} $$
If the column vectors are the input space, and the row vectors are the output space, why are they related in such a way that the input space is a constant multiple of output space when acting on a eigenvector?
Thanks

A: You view a $n \times n$ matrix as a linear application $f:\mathbb{R}^n\to \mathbb{R}^n$, so "row" and "columns" have no meaning here.
The rest is a definition


Q: Сколько есть способов передачи аргументов в функцию? Как по мне, то в С есть передача аргументов в функцию только по значению, а в С++ по факту тоже только передача по значению. То есть, передачи по указателю не может быть, потому что указатель содержит адрес, а это тоже значение. Так что правильней говорить, что передача по значению. Ну а насчет ссылок, то это те же указатели с константным адресом и которые неявно преобразуются к указателю, так что тоже передача по значению.
То есть, есть только передача по значению. А когда говорят о передаче по указателю и ссылке, то это скорей для того, чтобы внести ясность о том, будет ли переменная копирована или взят её адрес или так же неявно взят адрес с невозможностью заменить его на другой адрес.

В общем, условно(для упрощения понимания) есть 2 способа передачи аргументов в функцию в Си :
по значению,
по указателю.
И 3 способа в C++:
по значению,
по указателю,
по ссылке.

А по факту везде передается по значению и только.
В тесте по Си были 2 ответа : по значению, и по указателю. Но вопрос там был другой "Какими способами можно передавать параметры в функцию?". То есть, не аргументы, а параметры. Не совсем понимаю этот момент, но если предположить, что аргументы передаются в параметры, а потом параметры в тело функции, то параметры вполне могут передаваться по значению или указателю или по ссылке( в C++). И будет выглядеть как -
void func1 ( int   arg );
void func2 ( int * arg );
void func3 ( int & arg );

Из кода видно, что сами параметры могут быть и ссылкой и указателем, но тем не менее во всех трех случаях инициализированы они будут аргументами, которые передаются только по значению.
Что-то мне кажется, что скорей всего не правильно был сформулирован вопрос теста и параметры не передаются в функцию, так как они и так в её сигнатуре, а передаются аргументы, ну а параметры просто инициализируются где-то между сигнатурой и телом в области видимости под которую попадает тело функции.
A: Насколько я понимаю, в C ровно один способ передачи аргументов: по значению. Передаёте ли вы по значению число или указатель, вы получаете с той стороны копию этого числа/указателя: если вы меняете число внутри функции, с его «внешним прообразом» (который может, кстати, быть и выражением) ничего не случается; если внешний прообраз меняется в течение выполнения функции, на значении аргумента это никак не отражается.
Иногда говорят, что передавая указатель на объект в функцию, вы как бы тем самым неявно передаёте сам объект в функцию «по указателю». Это на самом деле не вполне верный подход.
Давайте я приведу пример: представьте себе, что вам передали число. Вы использовали это число как индекс в глобальном массиве, и изменили элемент этого массива. Можно ли сказать, что вам был передан этот элемент? Нет, вы получили лишь число.
Точно так же можно смотреть на указатель как на индекс в памяти, рассматриваемой как массив байт. Доступ к объекту через указатель ничем не лучше и не хуже доступа к ячейке массива по индексу.

В C++ появился новый вид передачи параметров: по ссылке. По существу, передача «по ссылке» ничем не отличается от передачи указателя кроме того, что (1) ссылка не может соответствовать NULL-указателю в корректной программе, (2) ссылка синтаксически ведёт себя как разыменованный указатель.
Однако, разработчики C++ советуют всё же видеть в передачу по ссылке другую семантику: ссылка является «алиасом», другими именем объекта. Хотя такая семантика и более привлекательна с точки зрения ясности программ, всё же ссылка на объект и сам объект — не одно и то же. В частности, ссылка может пережить объект, и вы получите при попытке обратиться к ней undefined behaviour. Если бы ссылка была самим объектом (как это часто пытаются подать), такого произойти бы не смогло.
Следовать ли совету разработчиков или думать о передаче по ссылке как о синтаксическом сахаре для передачи по указателю — личное дело каждого. Я бы всё же советовал думать так, как советуют разработчики, но не упускать из виду, что эта абстракция «протекает».

ЗЫ: Пример кода без явных ошибок (наподобие возврата ссылки на локальную переменную), в котором ссылка на объект переживает сам объект:
class X
{
    struct C { int x; };
    C* pc;

    void f(int& x) { g(); cout << x << endl; }
    void g() { delete pc; }

public:
    X() : pc(new C()) {}
    void run() { f(pc->x); }
};

A: при передачи по значению передаваемое значение не меняется, а внутри функции создается временная переменная.
при передачи по указателю или ссылки передается только адрес, передаваемый объект можно изменить изнутри функции и не создается локальной (временной) переменной внутри функции. разница между передачи ссылкой и указателем в удобстве употребления (не надо писать звездочку каждый раз внутри функции).
ниже пример:
#include <iostream>

using namespace std;

void f_value(int a){ // значение
    a = 10; // изменяем параметр
}

void f_poiner(int * a){ // указатель
    *a = 10; // изменяем параметр
}

void f_reference(int & a){ // ссылка
    a = 20; // изменяем параметр
}

int main(){
    int a = 0;
    cout << "a = " << a << endl;
    f_value(a); // значение переменной (а) НЕ изменится после выполнения
    cout << "a = " << a << endl;
    f_poiner(&a); // значение переменной (а) изменится после выполнения
    cout << "a = " << a << endl;
    f_reference(a); // значение переменной (а) изменится после выполнения
    cout << "a = " << a << endl;

    return 0;
}

---------------------------------------------------

a = 0
a = 0
a = 10
a = 20
Press <RETURN> to close this window...

A: пока читал вопрос несколько раз запустался :))
int foo(int a);//"a" это параметр функции

int foo(int a){//между "){" произойдёт присвоение a="значение из аргумента"
    return a+10;
}

int main(){
    int c=100,g;
    g=foo(c);// "c" это аргумент функции
             //тут выполнится такой порядок действий:
             //временная_переменная="то что возвращает foo"
             //очистка того что занимала foo
             //g=временная_переменная
    return 0;
}

вот тут пример с ссылками тык.
Так что всё "передаётся по значению" но надо же как то отличать передачу указателя, ссылки и объекта, ведь если объект занимает 1гб то при передачи самого объекта  копироваться будет 1гб (того нужно 2 гб), а при передачи через указатель\ссылку нужно будет только пару байт. Потому такие передачи и называют по разному...
так что да "некорректно задан вопрос"!

A: Есть два способа, причем мы рассматриваем C++, а не си и не ассеблер( где можно говорить через стек или через регистры )

*

*Передача по значению, где значение объекта копируется в стек или адресс объекта копируется в стек....

*По ссылке, где в теле функции просто непосредственно обращаются к
объекту, например сегменту данных, где была определега глобальная
переменная, которая передается по ссылке. То есть, тут подменить
адрес переданного объекта по ссылке нельзя в отличии от от передачи
по указателю. Это просто как алиас объекта.


Q: Data structure and algorithms: Should one use OOP to program algorithms? I have seen people code for example, say a quicksort algorithm without using OOP. I have also seen the identical algorithm in Robert Lafore's data structure and algorithm textbook written under OOP framework.
Is it better to do it using OOP  ? What are the advantages or disadvantages?
Suppose I know how to write an algorithm in both ways, should I always do it the OOP way ? Or does it depend on the algorithm itself ? If yes, then what algorithms would using OOP be beneficial ?


Q: Can't get TinyMCE 4.0.6 to work This is driving me crazy....
I'm trying to get TinyMCE v4.0.6 to work, and I'm probably doing something very dumb, since I can't get the editor to display at all.
I could get a v3.5.8 editor to show in a page similar to what follows, but no joy with this:
<!DOCTYPE html>
<html>
<head>
<title>TinyMCE Test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="tinymce/tinymce.min.js"></script>
<script type="text/javascript">
    tinymce.init({
        selector: "textarea"
    });
</script>
</head>
<body>
<form method="post" action="something">
    <textarea name="content" cols="100" rows="15">content</textarea>
    <input type="submit" value="Save" />
</form>
</body>
</html>

I've verified (using FireBug) that the path to the tinymce JavaScript file is correct, but other than that, I'm completely at a loss.
Thanks for any suggestions..

A: After your comment, I took your HTML and checked it with a CDN copy of tinyMCE and it work fine: http://codepen.io/anon/pen/mIvFg so I can only assume it's an error with your tinymce.min.js file.


Q: New notation yielded new insights into identities It is well known that using different notation can significantly reduce the proof of identities or other properties. Has there been cases of using a new notation led to new insights to yet unknown identities or properties?

A: There are a few examples of important notational changes which come to mind. I'll put them all in separate sections, in various levels of fleshed out description. Keep in mind, notation typically comes after mathematics. Oftentimes we choose a certain notation because it fits a form we are used to, or in order to simplify a proof. With that caveat out of the way...

One fairly recent example that comes to mind is this paper ("Extending the Algebraic Manipulability of Differentials", Bartlett and Khurshudyan).
In it, the authors notice the typical (second) differential notion $\frac{d^2f}{dx^2}$ is not ideal, because it obscures what algebraic manipulations are permitted. One basic example they give is that $\frac{dy}{dx} \cdot \frac{dx}{dt} = \frac{dy}{dt}$, but $\frac{d^2 y}{dx^2} \cdot \frac{dx^2}{dt^2} = \frac{d^2 y}{dx^2} \left ( \frac{dx}{dt} \right )^2 \not = \frac{d^2 y}{dt^2}$.
The authors argue that the notation is confusing, and misleads students into trying to perform illegal algebraic manipulations. Their solution is to reform the notation for higher derivatives into something which can be algebraically manipulated. They have a simple methodology for figuring out what the correct notion is, but it is in the paper and this answer is already quite long.
Suffice to say, using $\frac{d^2 y}{dx^2} - \frac{dy}{dx} \frac{d^2 x}{dx^2}$ allows us to algebraically manipulate second derivatives as well. (Note - they do not suggest actually using this notation, instead they suggest we use $D^2_x y$ for this. It is just useful to be able to expand it when need arises, much like foiling a polynomial).
This notation, while more cumbersome to write out, bears fruits somewhat immediately.
Just as we can show $\frac{dx}{dy} = \frac{1}{\frac{dy}{dx}}$ by algebraic manipulation, we can show a similar formula for the second derivative using the new notation:
$- D^2_x y = \left ( \frac{1}{D^1_x y} \right )^3 = D^2_y x$
In traditional notation, this says
$- \frac{d^2 y}{dx^2} \left ( \frac{1}{\frac{dy}{dx}} \right )^3 = \frac{d^2 x}{dy^2}$, a formula which is widely unknown.
The proof is nothing but algebraic manipulation, and is in the linked paper. Indeed
the authors of the paper thought that nobody had proven this before! (As with most things in basic calculus, somebody had already done it. That said the original proof was almost certainly less clear than the one in the paper.)

As a potentially controversial point, using $\tau = 2 \pi$ as the fundamental circle constant is, at its core, a notational change. The arguments are well documented, but the gist is that it makes many identities and patterns involving circles seem more natural. While this is not responsible for proving new results, it could be responsible for making the concepts seem simpler, which I think is worth mentioning.

A (negative) anecdote comes from mathematical logic, where we really dodged a bullet fired by Frege. The way we typically write formulas nowadays (using symbols like $\forall$, and $\exists$, $\land$, $\lor$, $\lnot$, $\to$, etc.) was not the first notation tried. Indeed Frege invented a notation for logical formulas called Begriffsschrift, which would have completely killed logic if it had been adopted widely. It is 2 dimensional, and here's an example of it in use:
$[\forall a. (P(x,a) \to Q(a)) \to P(x,y) \to Q(y)] \to
[\forall b . Q(b) \to \forall a . P(b,a) \to Q(a)] \to
Q(x) \to P(x,y) \to Q(y)$
(I grant you, this is a complicated formula, but I bet you can read it fairly quickly. Look what it becomes):

While you could make an argument saying we read the first one faster because it's what we're used to, it is objectively more compact. Imagine writing formulas at a blackboard, or deriving things with proof trees using Frege's notation. I shudder at the thought.

Back to calculus for a moment, one piece of notation that you probably don't even notice is the integral! The fact that we use the same notation to refer to antiderivatives and areas under curves from the start clues students into the fact that they are the same concept! This falls into the $\tau$ vs $\pi$ camp again, as it is primarily a didactic argument instead of a research-focused one, but students can see the connection much quicker than the inventors of calculus because our notation emphasizes it! A priori, it is extremely unclear that these two topics should have anything to do with each other, and yet students tend to grasp this quite quickly nowadays. I think that the notation is a big part of this, and while I have no direct results to cite, I'm sure this was responsible for countless results after its adoption.

Categorically, we use $X \times Y$ and $X + Y$ to denote product and coproduct, and we use $X^Y$ to denote an internal hom object. Why do we use this notation? Because (in many important categories) all of the standard rules work. For example, $(X \times Y)^Z \cong X^Z \times Y^Z$, $X^{Y + Z} \cong X^Y \times X^Z$, $X \times (Y + Z) \cong X \times Y + X \times Z$, etc.
Knowing only the notation, one might conjecture that some of the above results are true, and then try to prove them! Even without having seen the proof, and without me telling you, I bet you can already guess other identities that hold between these constructions. That is the power of good notation!

One last proposed change in notation is the Triangle of Power, popularized by this youtube video. The idea is to better relate three connected topics (exponentiation, radicals, and logrithms) by giving them a more related notation.
Instead of summarizing the notation here, I'll link to the original mse post,
which makes a good argument for how it clarifies pre-existing theorems (as most new notation does).
To whet your appetite, it makes the following results seem obvious: $\log_{\sqrt[y]{z}}(z)=y$, and $\sqrt[\log_x(z)]{z} = x$.

Again, I'm not sure if this is exactly what you're looking for, but finding examples of genuinely "new" notation which prove genuinely new results is hard. Oftentimes we change the notation to make results we already know seem more obvious, as in the case of the integral and the triangle above. Sometimes, however, we get lucky, and our new (clearer) notation lets us prove new results related to the topic which we have clarified, as in the case of the algebraic notation for iterated derivatives. Of course, just because the result was already known doesn't mean that changing notation is worthless -- as mathematicians it is in part our job to make mathematics easier for future generations to do. Progress is not just made by geniuses seeing patterns with their amazing intuition, progress can also be made by taking the patterns we found hard to see, and making them easy to see. In this way, our students can spend less time rediscovering what we have found, and spend more time pushing into new areas of math.
I hope this was interesting ^_^

A: Three other examples :

*

*The dot-notation for ... dot-product (or scalar product, or "interior product" by contrast with "outer product"), making notations using vectors like this one

$$(\vec{u}+\vec{v})^2=\vec{u}^2+\vec{v}^2+2 \vec{u} \cdot \vec{v}$$
analogous to their algebraic computation counterpart rules on numbers
$$(a+b)^2=a^2+b^2+2a . b.$$
This analogy helps to find new identities : for example, we are fully confident that
$$\vec{u}^2-\vec{v}^2=(\vec{u}+\vec{v}) \cdot (\vec{u}-\vec{v})$$
holds because its ordinary algebraic analog is true.

*Quaternions' multiplication:

Instead of the detailed development
$$qq'=(a+a_1i+a_2j+a_3k)(a'+a'_1i+a'_2j+a'_3k)=aa'+...+a_3a'_3k^2$$
one can group the "real" and "vector" part under the form,
$$qq'=(a+V)(a'+V')$$
$$qq'=(aa'-\underbrace{V \cdot V'}_{\text{dot product}})+(aV'+a'V+\underbrace{\color{red}{V \times V'}}_{\text{cross product}})$$
underlining a close analogy with multiplication of two complex numbers (set apart the red term accounting for the non-commutativity of quaternion product). See formulas (4) and (5) in this answer.
A big thank to Mr. Gibbs, the physicist who introduced the dot product and the cross product notations around 1900.

*The blocks notation for matrices.

Let us for example a $2 \times 2$ block decomposition :
$$M=\begin{pmatrix}A&B\\C&D\end{pmatrix}$$
where the only condition is that blocks $A,B,C,D$ must have compatible dimensions.
This notation helps to simplify the description of many matrix operations, and provides often deep hints.
For example, if $A$,$B$,$C$,$D$ are all square blocks:
$$\det(M)=\det(A)\det(D)-\det(B)\det(C)$$
is true under a certain condition ($C$ and $D$ have to commute).
Another example, the "augmentation" of a quadratic form :
If $A$ is an $n \times n$ matrix, if $U,X \in \mathbb{R^n}$ and $b,y \in \mathbb{R}$, we can expand the following quadratic form  :
$$(X,y)^T\begin{pmatrix}A&U\\ U^T&b\end{pmatrix}\binom{X}{y}=X^TAX+2 y X^T U+by^2$$
in the way we would do it using numbers... only taking care of the respective dimensions.
Edit: an interesting transcription of a conference made by S. Wolfram here that I found referenced in a students' report.


Q: Problems with an extra space when redirecting variables into a text file When I run the following lines:
set "Loc=%~dp0"
echo %Loc% > C:\PLACE\LOCFILE.txt

I receive the following in the LOCFILE:
C:\BATCHLOC
           ^
       Note Space

I am trying to use %Loc% like this in a separate batch file:
(
set /p Loc=
)<C:\PLACE\LOCFILE.txt
)
call "%Loc%\FILENAME.bat"

But the space ruins the path, and so then the call command doesn't work. Does anyone know how to fix this, (Stop it from creating the space at the end)?

A: echo %Loc% > C:\PLACE\LOCFILE.txt
          ↑
     This space is written to the file.

Fix:
echo %Loc%> C:\PLACE\LOCFILE.txt

A: This is more robust.
>"C:\PLACE\LOCFILE.txt" echo(%Loc%

The redirection at the starts stops numbers like 3,4,5 in %loc% from breaking your code when redirection is directly at the end (such as shown below).
When using the technique below then constructs like test 2 in %loc% will also fail.
This is because single digit numbers at the end are interpreted as stream designators, so numerals 0 to 9 are all problems when placed directly before a redirection character (> or >>).
do not use this: echo %Loc%> C:\PLACE\LOCFILE.txt
Extra tips:
The echo( protects from other failures in the echo command and the ( character has been tested as the least problematic character when used in this way.
The double quotes around the "drive:\path\filename" also protect against long filename elements such as spaces, as well as the & character.


Q: Как в Git посмотреть список задач с ревизия1 до ревизия2 Есть ли простой способ получить список задач из Git от одной ревизии до другой, когда известно, что в комментарии к комитам указываются номера задач, к примеру по такому шаблону:
[TASK-NNN]:
Мне хочется извлечь все TASK-NNN и оставить уникальные.

A: Можно сделать так:
git log <rev_from>..<rev_to> | grep TASK-


Q: TextView.setMaxLines not working? In my app I have a screen where I display some text and then a photo. The text is variable in length (sometimes none at all, sometimes a lot), so I wanted to have it set up so the text never takes up more than a few lines (but can be scrolled) leaving enough room for the image below.
My view component for this part is created programatically, and I've adjusted the code to have the following (currently in my text-setting method, but the same thing happens if it's in the initial view-create code)
public void SetDescription(String description)
{
    mTxtDescription.setText(Html.fromHtml(description));
    mTxtDescription.setClickable(true);
    mTxtDescription.setMaxLines(5);
    mTxtDescription.setLines(5); //this makes no difference either!
    mTxtDescription.setSingleLine(false);
    mTxtDescription.setScrollbarFadingEnabled(true);
    mTxtDescription.setScrollBarStyle(VERTICAL);
    mTxtDescription.setMovementMethod(ScrollingMovementMethod.getInstance());
    mTxtDescription.invalidate(); //adding this made no difference...
}

However it doesn't work- long text still fills the whole screen and the image has vanished due to being pushed down to a height of 0. How can I get the text to never be more than 5 lines?

A: Try removing the call to setSingleLine. And use setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE). It'd also put this call before the setMaxLines and setLines call to be sure.
Note: setLines overrides the settings of setMaxLines and setMinLines.
The TextView has many issues surrounding the various calls to how it should display multiple, ellipses, etc.

A: The setSingleLine(false) seemes to reset the setMaxLines command. Try to move the setSingleLine command before the setText. That worked for me.

A: The below code is working fine for me
   txt = (TextView)findViewById(R.id.textview);
   txt.setMaxLines(5);
   txt.setMovementMethod(new ScrollingMovementMethod());

   txt.setScrollContainer(true);
   txt.setText("Example Text");
   txt.setTextColor(Color.WHITE);
   txt.setScrollbarFadingEnabled(true);

in xml inside textview
   android:scrollbars="vertical"


Q: Variable Scopes Within PowerShell Nested Functions I was given this extensive PowerShell script from a major/reputable corporation which was supposed to work flawlessly. Well, it didn't.
The script is composed of numerous nested functions with lots of variables passed to the main parent function and then to all of its children. Children who use and modify all these variables.
Why is it that all these variables do not contain the correct data?
Here's the structure I'm talking about:
f1 {
     f2 {
          v #prints 0
          v = 1
          f3
     }
     f3 {
          v #prints 1
          v = 2
     }
     v = 0
     f2
     v #should print 2 but prints 0
}

A: Note:
This was tested with PowerShell 3.0 and 4.0.
Within nested functions, all child functions have access to all of the parent functions' variables. Any changes to the variables are visible within the local scope of the current function and all the nested child functions called afterwards. When the child function has finished execution, the variables will return to the original values before the child function was called.
In order to apply the variable changes throughout all the nested functions scopes, the variable scope type needs to be changed to AllScope:
Set-Variable -Name varName -Option AllScope

This way, no matter at what level within the nested functions the variable gets modified, the change is persistent even after the child function terminates and the parent will see the new updated value.

Normal behavior of variable scopes within Nested Functions:
function f1 ($f1v1 , $f1v2 )
{
        function f2 ()
       {
               $f2v = 2
               $f1v1 = $f2v #local modification visible within this scope and to all its children
               f3
               "f2 -> f1v2 -- " + $f1v2 #f3's change is not visible here
       }
        function f3 ()
       {
               "f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
               $f3v = 3
               $f1v2 = $f3v #local assignment will not be visible to f2
               "f3 -> f1v2 -- " + $f1v2
       }

        f2
        "f1 -> f1v1 -- " + $f1v1 #the changes from f2 are not visible
        "f1 -> f1v2 -- " + $f1v2 #the changes from f3 are not visible
}

f1 1 0

Printout:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 0
f1 -> f1v1 -- 1
f1 -> f1v2 -- 0

Nested Functions with AllScope variables:
function f1($f1v1, $f1v2)
{
    Set-Variable -Name f1v1,f1v2 -Option AllScope
    function f2()
    {
        $f2v = 2
        $f1v1 = $f2v #modification visible throughout all nested functions
        f3
        "f2 -> f1v2 -- " + $f1v2 #f3's change is visible here
    }
    function f3()
    {
        "f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
        $f3v = 3
        $f1v2 = $f3v #assignment visible throughout all nested functions
        "f3 -> f1v2 -- " + $f1v2
    }

    f2
    "f1 -> f1v1 -- " + $f1v1 #reflects the changes from f2
    "f1 -> f1v2 -- " + $f1v2 #reflects the changes from f3
}

f1 1 0

Printout:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 3
f1 -> f1v1 -- 2
f1 -> f1v2 -- 3


Q: One to one function in R to change number to text I have quite long list of postal codes with corresponding name of city or town. I just want to write a R program that has postal code as input variable and returns the name of the location (city or town). The list will be finite in length and has about 40 different pairs of postal code and location name. What is the best way to do this?

A: myProg<-function(code) db$city[db$code==code]

A: This is a filtering question. There are a number of ways to filter data in R. Here's what you need to do:

*

*Put your data in a data.frame

*Try filtering it:

*Now make it a function (this is your program)

*Use the function

postal_codes <- data.frame(code = c(78754, 84606), location = c("Austin", "Provo"))
postal_codes[postal_codes$code %in% 78754, ]
postal_finder <- function(mycode) {
  postal_codes$location[postal_codes$code %in% mycode]
}

postal_finder(78754)


Q: ExpressJS app.use("/" router) router.get("/") Breaks I'm not sure how to phrase this, but part of the following code, for lack of an appropriate term, doesn't work. If I try to go to localhost:3000/ it doesn't send back a response. I'm using Express 4.7.4 and the latest node available on the Ubuntu Trusty repository.
app.js

///// Dependencies & config
var express = require('express');

///// Bootstrapping
//// Prepare Express
var server = express();

/// Configure Express
server.set('views', __dirname + '/views');

/// Routers
var infoR = express.Router();

// This doesn't send anything back
infoR.get("/", function(req, res) {
  res.render('common/home');
});
// This works perfectly
infoR.get("/something", function(req, res) {
  res.render('info/something');
});

// Routes that work
server.use('/admin', require('./routes/admin'));
server.use('/account', require('./routes/account'));
server.use('/', infoR); // This is where the problem starts

///// Start the server
server.listen(3000, function() {
  console.log('Server started on port 3000');
});

A: Fixed by updating Express to version 4.9.
Edit: Turns out I've been doing it wrong, as noted in the documentation.


Q: EXC_BREAKPOINT in Swift I set up a var tagTextField: UITextField in the a set up method. Later when I call a method where I want to do something with this var tagTextField: UITextField, namely:
var pos1 = tagTextField.positionFromPosition(tagTextField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 0)

I get the following Error:
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1000e4280)

I tried to just see if the var tagTextField: UITextField == nil, but then I get the same Error. Any suggestions why this is? If you need more code, let me know.
Thanks in advance
edit:
here is the error. no breakpoint

A: You set a breakpoint on Xcode (probably by mistake when trying to access to a specific line).
Breakpoints are represented by blue tabs and allow you to stop the execution of your code to check some variable states for instance. Just click on it again to deactivate it (it will turn light blue).

A: You've set some sort of user-breakpoint.
All user-set breakpoints show up in the Breakpoint Navigator:

If your Xcode doesn't say "No Breakpoints" here, you have breakpoints.  Good news is, you can manage all your breakpoints from this tab.  You can delete them, or create new ones.
Click the plus sign at the bottom lets you add different sorts of breakpoints here.


Q: using #define to substitute in a continuous string I am trying to write a Macro for certain read/write functions. The functions are in the form
k_target_socket.write8(address,val);

When I tried #define Wx(add,val) k_target_socket.writex(address,val) I got   W8(0x100,0x120); for   W8(0x100,0x120); then I replace the macro with  #define W(x,add,val) & then got k_target_socket.writex(0x100,0x120); Is there a way to substitute for x in the above two examples?

A: What you need is token pasting. try the following:
#define W(x,ad,val) k_target_socket.write##x(ad,val)

The ## will paste the x with the function name.
More details here


Q: Movable Panel control using C# I'm trying to make my panel control movable using c#, but my main form moves along with the panel control when dragging. Is there a better code for this?
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCaptre();

public static void _MOVE_PANEL(IntPtr Handle, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
       ReleaseCaptre();
       SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

private void sub_inv_pcount_edit_MouseMove(object sender, MouseEventArgs e) //panel move
{
    _MOVE_PANEL(Handle, e);
}

see sample: see screenshot

A: I'm afraid this is not an approach you can tweak to get the result you want. WM_NCLBUTTONDOWN is essentially how the window manager decides how to handle mouse events on a top-level window. It allows you to make windows that have custom chrome, but it doesn't allow you to do anything about non-top-level windows (such as your panel).
You can get a reasonably nice-working dragging doing the obvious thing - in MouseMove, handle moving the control yourself. It's not going to be as well behaved as moving the entire window, though.


Q: Как понять, сколько CPU потребляет zram для своей работы? Насколько я знаю, zram сжимает данные в ОЗУ, и из-за этого повышается нагрузка на CPU.
И как понять, сколько CPU потребляет zram в данный момент времени?
В списке процессов я не вижу zram. Как тогда это понять?


Q: Proving that (0,1) and [0,1] are numerically equivalent. as the title suggests, I need help proving that the cardinality of $(0,1)$ and $[0,1]$ are the same.
Here is my work:
$f:[0,1] \rightarrow (0,1)$
Let $n\in N$
Let $A=\{\frac{1}{2}, \frac{1}{3}, \frac{1}{4}....\}\cup \{0\}$
On $[0,1]\in A: f(x)=x$
On $A: f(0)=\frac{1}{3}$
$f(1)=\frac{1}{2}$
$f(\frac{1}{n})=\frac{1}{n+2}, n>2$
Now I will prove that $f$ is a bijective function.
Let $f(n)=f(m)$ for $n,m \in N$ and $n,m>2$. Then $\frac{1}{n+2}=\frac{1}{m+2}$. We multiply both sides of the equation by $(n+2)(m+2)$ and obtain $m+2=n+2 \rightarrow m=n$. Thus $f$ is injective.
From here on out, I am kind of shakey. I know the gist of this proof, but I don't know how to set up the sequencing correctly. For instance, I know that I need to map $x_1$ to $0$ and $x_2$ to $1$ and $x_{n}$ to $x_{n+2}$, but I am confused on how to do so.

A: Your proof has some problems.

*

*You haven't defined $A$. I suppose it should denote some subset of $[0,1]$.

*If $A$ is a subset of $[0,1]$ then it's not the case that $[0,1]\in A$. Perhaps you meant $[0,1]\setminus A$?

*The idea is that $A$ can be "easily described" as a sequence $a_n$ for $n\in\Bbb N$, preferably such that $a_0=0$ and $a_1=1$. Then you can define a function which maps $a_n\mapsto a_{n+2}$, and $x$ for those not in $A$ (as you did).

Then to show that the map is a bijection you need to show that if $x,y\in[0,1]$ are distinct then $f(x)\neq f(y)$. This is done by dividing into cases, both $x,y\in A$, both $x,y\notin A$ and the case that $x\in A$ and $y\notin A$ (there's a fourth case which is similar to this one).
Then you have to show that every $y\in(0,1)$ is in the range, which is also done by dividing into cases, if $y\notin A$ then $f(y)=y$; and if $y\in A$, then you have to do some work.

A: I think you're getting a little too bogged down in the details. The basic idea is that the sets $$A_0=\{a_0,a_1,a_2\ldots,a_n,\ldots\}\text{ and }A_1=\{a_1,a_2,a_3\ldots,a_n,\ldots\}$$ have the same cardinality, where $\{a_0,a_1,a_2\ldots\}$ is any sequence of distinct numbers. So $$B\cup A_0\text{ and }B\cup A_1$$ have the same cardinality, where $B$ is any set disjoint from $A_0$ (and hence also disjoint from $A_1$). This shows that adding one element to the set $B\cup A_1$ doesn't change the cardinality.
So if you start with some infinite set $S$ and some element $a_0$ not in the set, the trick is to express $S$ as $B\cup A_1$. Well, just pick an infinite sequence in $S$ to serve as $A_1$, and let $B=S-A_1$.
The sets $(0,1)$ is an example of such an infinite set $S$, so it follows that $[0,1)$ has the same cardinality as $(0,1)$. Repeat to get $[0,1]$ with the same cardinality. Or modify the previous argument to show that adding two elements doesn't change the cardinality of an infinite set: $$A_0=\{a_0,a_1,a_2\ldots,a_n,\ldots\}\text{ and }A_2=\{a_2,a_3,a_4\ldots,a_n,\ldots\}$$ have the same cardinality, etc.
Now your proof follows this idea; you've just made a particular choice for the sequence $\{a_2,a_3,\ldots\}$, namely $\{\tfrac{1}{2}, \tfrac{1}{3},\ldots\}$. Also you are trying to construction the one-one correspondence explicitly.
This isn't hard. We want $f:B\cup A_0\rightarrow B\cup A_2$ one-one and onto. To begin with, as you indicated, we want $f(a_0)=a_2$, $f(a_1)=a_3$, etc.; i.e., $f(0)=\tfrac{1}{2}$, $f(1)=\tfrac{1}{3}$, and $f(\tfrac{1}{n})=\tfrac{1}{n+2}$ for $n\geq 2$. Then for $x\not\in \{a_0,a_1,\ldots\}$, let $f(x)=x$.
(I'm assuming when you wrote "On $[0,1]\in A$", that was a typo for "On $[0,1]-A$". Also, I'm using $-$ for set-difference, what some people denote by $\smallsetminus$.)


Q: Error with primary key in one-to-one relationship using Entity Framework I've created a database according to which the user profile is formed by the following two classes:
public class Usr
{
    [Key()]
    public int UsrID { get; set; }

    public virtual UsrType UsrType { get; set; }

    public virtual UsrStatus UsrStatus { get; set; }

    [Required]
    [MaxLength(100, ErrorMessage = "Email can only contain {0} characters")]
    public string UsrEmail { get; set; }

    [Required]
    [MaxLength(32, ErrorMessage = "Password can only contain {0} characters")]
    [MinLength(8, ErrorMessage = "Password must be at least {0} characters")]
    public string UsrPassword { get; set; }
}

public class UsrDetails
{
    [ForeignKey("UsrID")]
    [Required]
    public virtual Usr Usr { get; set; }

    [Required]
    [MaxLength(40, ErrorMessage = "Name can only contain {0} characters")]
    public string UsrName { get; set; }

    [Required]
    [MaxLength(40, ErrorMessage = "Surname can only contain {0} characters")]
    public string UsrSurname { get; set; }

    [Required]
    [MaxLength(20, ErrorMessage = "Country can only contain {0} characters")]
    public string UsrCountry { get; set; }

    [Required]
    [MaxLength(20, ErrorMessage = "City can only contain {0} characters")]
    public string UsrCity { get; set; }

    [Required]
    [MaxLength(40, ErrorMessage = "Street can only contain {0} characters")]
    public string UsrStreet { get; set; }

    [Required]
    public int UsrNum { get; set; }

    [Required]
    public int UsrPostalCode { get; set; }
}

I want to connect them by having both as primary key the UsrID and I get an error that UsrDetails don't have a primary key because I'm using the foreign key attribute. Any ideas?

A: You need to declare a key property in UserDetails with the same name that you declare in the ForeignKey attribute:
public class UsrDetails
{
    [Key]
    public int UsrID{ get; set; }

    [ForeignKey("UsrID")]
    public virtual Usr Usr { get; set; }
}

All your entities must have a PK property. In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK. You can check this tutorial in case you need more info.